I\'m working on a project where I have to access a set of Google Calendars using REST and working with Java.
The program, situated on a private non-Google server, pe
If you just need to access a particular set of calendars, I would create a service account and share the necessary calendars with that account.
To do so:
Then you should be able to use the following code:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.json.gson.GsonFactory;
import java.io.File;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import java.util.Arrays;
import com.google.api.services.calendar.Calendar;
GoogleCredential credentials = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport())
.setJsonFactory(new GsonFactory())
.setServiceAccountId("<service account email address>@developer.gserviceaccount.com")
.setServiceAccountScopes(Arrays.asList("https://www.googleapis.com/auth/calendar.readonly"))
.setServiceAccountPrivateKeyFromP12File(new File("<private key for service account in P12 format>-privatekey.p12"))
.build();
Calendar client = new Calendar.Builder(GoogleNetHttpTransport.newTrustedTransport(), new GsonFactory(), credentials).build();
client.<do calendar stuff>.execute();
If instead you are a domain administrator who needs to access calendars for all Google Apps accounts that are part of your domain without consent from individual users, then instead of step 4 above:
You should now be able to write code like the following:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.json.gson.GsonFactory;
import java.io.File;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import java.util.Arrays;
import com.google.api.services.calendar.Calendar;
GoogleCredential credentials = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport())
.setJsonFactory(new GsonFactory())
.setServiceAccountId("<service account email address>@developer.gserviceaccount.com")
.setServiceAccountScopes(Arrays.asList("https://www.googleapis.com/auth/calendar"))
.setServiceAccountPrivateKeyFromP12File(new File("<private key for service account in P12 format>-privatekey.p12"))
.setServiceAccountUser("<domain user whose data you need>@yourdomain.com")
.build();
Calendar client = new Calendar.Builder(GoogleNetHttpTransport.newTrustedTransport(), new GsonFactory(), credentials).build();
client.<do calendar stuff as that user>()
In addition to the steps mentioned in @aeijdenberg's answer, the Service Account now needs to explicitly accept the shared calendar by adding it to its CalendarList via CalendarList.insert. See:
Service Accounts don't accept automatically shared calendars anymore [148804709] https://issuetracker.google.com/issues/148804709