1
votes

I would like to retrieve all the events within a calendar, then categorize them by calendar.

Here is what I have so far.

public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME =
    "Google Calendar API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
    System.getProperty("user.home"), ".credentials/calendar-java-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

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

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/calendar-java-quickstart
 */
private static final List<String> SCOPES =
    Arrays.asList(CalendarScopes.CALENDAR_READONLY);

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 {
    // Load client secrets.
   BufferedReader br = new BufferedReader( new FileReader("C:\\Users\\User\\.credentials\\calendar-java-quickstart\\client_secret.json"));
   GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, br);

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("user");
    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();
}


public static void main(String[] args) 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();
    String pageToken = null;
    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    Events events = service.events().list("primary")
        .setPageToken(pageToken)
        .setMaxResults(10)
        .setTimeMin(now)
        .setOrderBy("startTime")
        .setSingleEvents(true)
        .execute();
    List<Event> items = events.getItems();
    do 
    {
        CalendarList calendarList = service.calendarList().list().setPageToken(pageToken).execute();
        List<CalendarListEntry> items2 = calendarList.getItems();

        for (CalendarListEntry calendarListEntry : items2)
        {
             System.out.println(calendarListEntry.getSummary());
        }//for
          while(pageToken != null)
          pageToken = calendarList.getNextPageToken();
    }//do
    while (pageToken != null);
    System.out.println("------------------------------");
    if (items.size() == 0) 
    {
        System.out.println("No upcoming events found.");
    }//if
    else 
    {
        for (Event event : items) 
        {
            DateTime start = event.getStart().getDateTime();
            if (start == null) 
            {
                start = event.getStart().getDate();
            }//if
            System.out.println(event.getSummary());
        }//for
    }//else
}//main

As you can see, I can get all the events (from the primary calendar) and all the names of the available calendars.

How can I fetch the calendarId so I can sort the events by Calendar?

1

1 Answers

2
votes

Calendar list returns a clandarListResponse

{
  "kind": "calendar#calendarList",
  "etag": etag,
  "nextPageToken": string,
  "nextSyncToken": string,
  "items": [
    calendarList Resource
  ]
}

You are already looping tough each calendarListEntry but instead of doing your summary you should just request the fields you want in this case id.

Each calendar#calendarListEntry has an id value which is the calendar id you are looking for.

I am not a java developer but I would guess something ike

for (CalendarListEntry calendarListEntry : items) {
    System.out.println(calendarListEntry.getId());
 }