private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets)
throws Exception {
GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(),
new JacksonFactory(),
clientSecrets,
Lists.newArrayList(SCOPE))
// Set the access type to offline so that the token can be refreshed.
// By default, the library will automatically refresh tokens when it
// can, but this can be turned off by setting
// api.adwords.refreshOAuth2Token=false in your ads.properties file.
.setAccessType("offline").build();
String authorizeUrl =
authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
System.out.println("Paste this url in your browser: \n" + authorizeUrl + '\n');
// Wait for the authorization code.
System.out.println("Type the code you received here: ");
String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();
// Authorize the OAuth2 token.
GoogleAuthorizationCodeTokenRequest tokenRequest =
authorizationFlow.newTokenRequest(authorizationCode);
tokenRequest.setRedirectUri(CALLBACK_URL);
GoogleTokenResponse tokenResponse = tokenRequest.execute();
// Create the OAuth2 credential.
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setClientSecrets(clientSecrets)
.build();
// Set authorized credentials.
credential.setFromTokenResponse(tokenResponse);