Sparkles

that were shone when I got tempered!

Archive for the ‘Google API’ Category

Manage Google Calendars in Java

leave a comment »

Do Step 1 as mentioned in [developers.google.com]

Step 1: Turn on the Google Calendar API

  1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API.
  2. Click Continue, then Go to credentials.
  3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button. (These are the options you will display to the user when you asking for the permission for the app via consent screen).
  4. Select the Credentials tab, click the Add credentials button and select OAuth 2.0 client ID.
  5. Select the application type Other, enter the name of the app “eg : Google Calendar API Quickstart”, and click the Create button.
  6. Click OK to dismiss the resulting dialog.
  7. Click the (Download JSON) button to the right of the client ID.
  8. Move this file to your working directory and rename it client_secret.json. This is the one that you will use to communicate with the Google app via Java program.

 

This is the Java class that you can use to manage the Calenders.

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.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class CalendarQuickstart {

private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";

private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/calendar-java-quickstart-1.0.0");

private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

private static HttpTransport HTTP_TRANSPORT;

private static final List<String> SCOPES = Arrays.asList(CalendarScopes.CALENDAR);

static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}

/**
* Creates an authorized Credential object.
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {

InputStream in = CalendarQuickstart.class.getResourceAsStream("/client_secret_1.0.0.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();

Credential credential = null;
try { credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("namal");} catch (Exception e) {}

System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());

return credential;
}

/**
* Build and return an authorized Calendar client service.
* @return an authorized Calendar client service
* @throws IOException
*/
public static com.google.api.services.calendar.Calendar getCalendarService() throws IOException {

Credential credential = authorize();

return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}

private static void viewCalenders() throws IOException {

com.google.api.services.calendar.Calendar service = getCalendarService();

String pageToken = null;

do {
CalendarList calendarList = service.calendarList().list().setPageToken(pageToken).execute();
List<CalendarListEntry> items = calendarList.getItems();

for (CalendarListEntry calendarListEntry : items) {
System.out.println("viewCalenders()." + calendarListEntry.getSummary() + " --> " + calendarListEntry.getId() + " --> " + calendarListEntry.getAccessRole());
}

pageToken = calendarList.getNextPageToken();

} while (pageToken != null);

}

private static void insertEvent() throws IOException {

com.google.api.services.calendar.Calendar service = getCalendarService();

Event event = new Event()
.setSummary("Google I/O 2 2016/15")
.setLocation("800 Howard St., San Francisco, CA 94103")
.setDescription("A chance to hear more about Google's developer products.");

DateTime startDateTime = new DateTime("2015-12-15T09:00:00-07:00");

EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("America/Los_Angeles");

event.setStart(start);
DateTime endDateTime = new DateTime("2015-12-16T17:00:00-07:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("America/Los_Angeles");
event.setEnd(end);

String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));
EventAttendee[] attendees = new EventAttendee[] {
new EventAttendee().setEmail("lwepage@example.com"),
new EventAttendee().setEmail("swebrin@example.com"),
};

event.setAttendees(Arrays.asList(attendees));
EventReminder[] reminderOverrides = new EventReminder[] {
new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};

Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));

event.setReminders(reminders);

String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();

System.out.printf("Event created: %s\n", event.getHtmlLink());

}

private static void viewEvents() throws IOException {

// Build a new authorized API client service.
// Note: Do not confuse this class with the
// com.google.api.services.calendar.model.Calendar class.

com.google.api.services.calendar.Calendar service = getCalendarService();

// 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.size() == 0) {
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);
}
}
}

public static void main(String[] args) throws IOException {
// viewCalenders();
viewEvents();
// insertEvent();
}

}

Dependencies :
You must download all the dependencies (eg : google client, google 0auth client etc) for this. There are 49 jars so far.
<dependencies>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.20.0</version>
</dependency>

<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-calendar</artifactId>
<version>v3-rev125-1.20.0</version>
</dependency>

<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.20.0</version>
</dependency>
</dependencies>

Here is the list of jars.

commons-cli-1.0.jar
commons-codec-1.3.jar
commons-lang-2.1.jar
commons-logging-1.1.1.jar
doxia-sink-api-1.0-alpha-7.jar
fit-google-calander-1.0.0.jar
google-api-client-1.20.0.jar
google-api-services-calendar-v3-rev125-1.20.0.jar
google-http-client-1.20.0.jar
google-http-client-jackson2-1.20.0.jar
google-oauth-client-1.20.0.jar
google-oauth-client-java6-1.20.0.jar
google-oauth-client-jetty-1.20.0.jar
guava-jdk5-13.0.jar
httpclient-4.0.1.jar
httpcore-4.0.1.jar
jackson-core-2.1.3.jar
jetty-6.1.26.jar
jetty-util-6.1.26.jar
jsr305-1.3.9.jar
junit-3.8.1.jar
maven-archiver-2.4.2.jar
maven-clean-plugin-2.4.1.jar
maven-common-artifact-filters-1.3.jar
maven-compiler-plugin-2.3.2.jar
maven-filtering-1.0.jar
maven-install-plugin-2.3.1.jar
maven-jar-plugin-2.3.2.jar
maven-reporting-api-2.0.6.jar
maven-reporting-api-2.0.9.jar
maven-resources-plugin-2.5.jar
maven-surefire-common-2.10.jar
maven-surefire-plugin-2.10.jar
plexus-archiver-2.0.1.jar
plexus-build-api-0.0.4.jar
plexus-compiler-api-1.8.1.jar
plexus-compiler-javac-1.8.1.jar
plexus-compiler-manager-1.8.1.jar
plexus-digest-1.0.jar
plexus-interactivity-api-1.0-alpha-4.jar
plexus-interpolation-1.13.jar
plexus-io-2.0.1.jar
plexus-utils-2.0.5.jar
plexus-utils-2.1.jar
plexus-utils-3.0.jar
servlet-api-2.5-20081211.jar
surefire-api-2.10.jar
surefire-booter-2.10.jar
surefire-junit3-2.10.jar

Here’s the interesting part – MY FINDINGS –

APPLICATION_NAME –
This should be the same name that you used for the OAuth 2.0 client ID.

DATA_STORE_DIR –
This is the directory where data (credentials etc) retrieved from the authorized users from the consent screen.

SCOPES –
There are two main scopes here.
1. CalendarScopes.CALENDAR : This is used to Manage the Calendar (Read, Insert, Delete, Update etc) data
2. CalendarScopes.CALENDAR_READONLY : This is used to only Read the Calender data
These scopes are very important when you grant the App permission from a user through the consent screen. It says you are asking the permission to Manage the Calendar or only Read the Calendar.
client_secret_1.0.0.json
This is the client secret that you have downloaded from the OAuth 2.0 client ID setup. This is Used to communicate with the Google App you have created as mentioned earlier. In this example it should be in the root folder. Anyway the path and name must be provided as below.

InputStream in = CalendarQuickstart.class.getResourceAsStream("/client_secret_1.0.0.json");

Grant the permission and credenials for a user.

Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("namal");

In this case when you are run the authorize method for the first time on each user (eg : namal as per .authorize(“namal”) ), iit will provide you a URL to display the consent screen

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=123456789101-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://localhost:12345/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar

Then once run that on a browser you will be requested for permission for currently logged-in google account. If you haven’t logged-in yet you will be asked to log-in then will be requested for permission. Here, the consent screen contains the information you provided when you set-up it as mentioned earlier (eg : Developer’s email address, Product Name, Logo, URL for your site, Policies, Terms of Service, Permission you are requesting as mentioned in the SCOPE etc).

ConsentScreen

Then when you are Allowed, it will display the success message as mentioned below.

http://localhost:12345/Callback?code=1/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#
Received verification code. You may now close this window…

Here, in this case, the credentials (of the google account used to allow the app) will be stored against the mentioned user (eg : “namal”) in DATA_STORE_DIR. So, you can use that user as the key to access the Google Calender (s) belongs to the Google account that allowed the app. This way you can manage Google Calender(s) of multiple Google Accounts using the keys.

View Calendar events

In this case, the Calender for the user’s email address will be mentioned as the “primary” one.

Events events = service.events().list("primary")
.setMaxResults(10)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();

You can specify the Calender ID -as mentioned in the viewCalenders() method- to obtain events in a perticular caleder. You can get this Calender ID from the Calendar Setting’s Calendar Address area.

Events events = service.events().list("xxxxxxxxxxxxxxxxxxxxxxxxxx@group.calendar.google.com")
.setMaxResults(10)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();

You can check the applications enabled for your google account via :
https://security.google.com/settings/security/permissions

References :

Advertisements

Written by Namal Fernando

December 15, 2015 at 6:48 am

Ruth's Reflections

Contemplations from quakey quirky Christchurch

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.

Ziplok

Learn and discover simple things

Meihta Dwiguna Saputra's Knowledge Base

~In learning you will teach and in teaching you will (re)learn~

The Java Blog

Thoughts, tips and tricks about the Java programming language

Sparkles

that were shone when I got tempered!