I have the following code to build a Google calendar service with the Java API (using a service account):
/**
* Return a google Calendar object for interacting with the calendar API.
* Return null if it can't be built for any reason
*/
private Calendar buildGoogleCalendarService() throws GeneralSecurityException, IOException {
String googleUsername = this.getGoogleUsername();
if (googleUsername == null) {
return null;
}
String path = AuthManager.class.getClassLoader().getResource("").getPath();
File privateKey = new File(path + "/google_key.p12");
if (!privateKey.exists()) {
logger.error("Google private key not found at " + privateKey.getAbsolutePath());
return null;
}
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(AppProperties.googleAppEmailAddress)
.setServiceAccountPrivateKeyFromP12File(privateKey)
.setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
.setServiceAccountUser(googleUsername).build();
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(AppProperties.appName).build();
return service;
}
It works fine with some basic testing, the question is how long will the credentials / service be able to be re-used for? i.e. how many API requests can you make using it before regenerating? This server application may process a high volume of API calls and last for some months between reboots.
Doing some timing, the credential building stage (GoogleCredential credential = new GoogleCredential.Builder()...) takes the most time, approx. a quarter of a second, I'll try caching that to start with and see how it goes but any answers appreciated.
Aucun commentaire:
Enregistrer un commentaire