private static void authorize(DataStoreFactory storeFactory, String userName) throws Exception {
// Depending on your application, there may be more appropriate ways of
// performing the authorization flow (such as on a servlet), see
// https://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow
// for more information.
GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(),
new JacksonFactory(),
CLIENT_ID,
CLIENT_SECRET,
Lists.newArrayList(SCOPE))
.setDataStoreFactory(storeFactory)
// 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.dfa.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();
// Store the credential for the user.
authorizationFlow.createAndStoreCredential(tokenResponse, userName);
}