use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project googleads-java-lib by googleads.
the class OfflineCredentialsIntegrationTest method testGenerateCredentialFromFile.
/**
* Tests that the builder builds and gets an OAuth2 token correctly from a
* file.
*/
@Test
public void testGenerateCredentialFromFile() throws Exception {
testHttpServer.setMockResponseBody("{\"access_token\" : \"accessToken\"," + "\"token_type\" : \"Bearer\"," + "\"expires_in\" : 3600," + "\"refresh_token\" : \"newRefreshToken\"}");
OfflineCredentials offlineCredentials = new OfflineCredentials.Builder().forApi(OfflineCredentials.Api.AD_MANAGER).withTokenUrlServer(testHttpServer.getServerUrl()).fromFile(OfflineCredentialsIntegrationTest.class.getResource("props/ads-test.properties")).build();
Credential credential = offlineCredentials.generateCredential();
assertTrue(testHttpServer.getLastRequestBody().contains("grant_type=refresh_token"));
assertTrue(testHttpServer.getLastRequestBody().contains("refresh_token=refreshToken"));
assertTrue(testHttpServer.getLastRequestBody().contains("client_id=clientId"));
assertTrue(testHttpServer.getLastRequestBody().contains("client_secret=clientSecret"));
assertEquals("accessToken", credential.getAccessToken());
assertEquals("newRefreshToken", credential.getRefreshToken());
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project googleads-java-lib by googleads.
the class OfflineCredentialsIntegrationTest method testGenerateCredential.
/**
* Tests that the builder builds and gets an OAuth2 token correctly.
*/
@Test
public void testGenerateCredential() throws Exception {
testHttpServer.setMockResponseBody("{\"access_token\" : \"accessToken\"," + "\"token_type\" : \"Bearer\"," + "\"expires_in\" : 3600," + "\"refresh_token\" : \"newRefreshToken\"}");
OfflineCredentials offlineCredentials = new OfflineCredentials.Builder().forApi(OfflineCredentials.Api.AD_MANAGER).withTokenUrlServer(testHttpServer.getServerUrl()).withClientSecrets("clientId", "clientSecret").withRefreshToken("refreshToken").build();
Credential credential = offlineCredentials.generateCredential();
assertTrue(testHttpServer.getLastRequestBody().contains("grant_type=refresh_token"));
assertTrue(testHttpServer.getLastRequestBody().contains("refresh_token=refreshToken"));
assertTrue(testHttpServer.getLastRequestBody().contains("client_id=clientId"));
assertTrue(testHttpServer.getLastRequestBody().contains("client_secret=clientSecret"));
assertEquals("accessToken", credential.getAccessToken());
assertEquals("newRefreshToken", credential.getRefreshToken());
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project googleads-java-lib by googleads.
the class AddShoppingDynamicRemarketingCampaign method main.
public static void main(String[] args) {
final AdWordsServicesInterface services = AdWordsServices.getInstance();
AdWordsSession session;
try {
Credential oAuth2Credential;
oAuth2Credential = new OfflineCredentials.Builder().forApi(OfflineCredentials.Api.ADWORDS).fromFile().build().generateCredential();
session = new Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
} catch (ConfigurationLoadException cle) {
System.err.printf("Failed to load configuration from the %s file%n", DEFAULT_CONFIGURATION_FILENAME);
return;
} catch (ValidationException ve) {
System.err.printf("Invalid configuration in the %s file%n", DEFAULT_CONFIGURATION_FILENAME);
return;
} catch (OAuthException oe) {
System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file%n", DEFAULT_CONFIGURATION_FILENAME);
return;
}
final AddShoppingDynamicRemarketingCampaignParams params = new AddShoppingDynamicRemarketingCampaignParams();
if (!params.parseArguments(args)) {
params.merchantId = Long.parseLong("INSERT_MERCHANT_ID");
params.budgetId = Long.parseLong("INSERT_BUDGET_ID");
params.userListId = Long.parseLong("INSERT_USER_LIST_ID");
}
try {
runExample(services, session, params.merchantId, params.budgetId, params.userListId);
} catch (ApiException apiException) {
// ApiException is the base class for most exceptions thrown by an API request. Instances
// of this exception have a message and a collection of ApiErrors that indicate the
// type and underlying cause of the exception. Every exception object in the adwords.axis
// packages will return a meaningful value from toString.
//
// ApiException extends RemoteException, so this catch block must appear before the
// catch block for RemoteException.
System.err.print("Request failed due to ApiException. Underlying ApiErrors:");
if (apiException.getErrors() != null) {
int i = 0;
for (ApiError apiError : apiException.getErrors()) {
System.err.printf(" Error %d: %s%n", i++, apiError);
}
}
} catch (RemoteException re) {
System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
} catch (IOException e) {
System.err.printf("Request failed unexpectedly due to IOException: %s%n", e);
}
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project googleads-java-lib by googleads.
the class GetKeywords method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param adGroupId the ID of the ad group to use to find keywords.
* @throws ApiException if the API request failed with one or more service errors.
* @throws RemoteException if the API request failed due to other errors.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId) throws RemoteException {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
int offset = 0;
boolean morePages = true;
// Create selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder.fields(AdGroupCriterionField.Id, AdGroupCriterionField.CriteriaType, AdGroupCriterionField.KeywordMatchType, AdGroupCriterionField.KeywordText).orderAscBy(AdGroupCriterionField.KeywordText).offset(offset).limit(PAGE_SIZE).in(AdGroupCriterionField.AdGroupId, adGroupId.toString()).in(AdGroupCriterionField.CriteriaType, "KEYWORD").build();
while (morePages) {
// Get all ad group criteria.
AdGroupCriterionPage page = adGroupCriterionService.get(selector);
// Display ad group criteria.
if (page.getEntries() != null && page.getEntries().length > 0) {
// Display results.
Arrays.stream(page.getEntries()).map(adGroupCriterionResult -> (Keyword) adGroupCriterionResult.getCriterion()).forEach(keyword -> System.out.printf("Keyword with text '%s', match type '%s', criteria type '%s'," + " and ID %d was found.%n", keyword.getText(), keyword.getMatchType(), keyword.getType(), keyword.getId()));
} else {
System.out.println("No ad group criteria were found.");
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
morePages = offset < page.getTotalNumEntries();
}
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project googleads-java-lib by googleads.
the class AdWordsAxisSoapIntegrationTest method testGoldenSoap_oauth2_offlineCredentials.
@Test
public void testGoldenSoap_oauth2_offlineCredentials() throws Exception {
testHttpServer.setMockResponseBodies(Lists.newArrayList(AuthResponseProvider.getTestOAuthResponse("TEST_ACCESS_TOKEN_1", 1L, "newRefreshToken1"), AuthResponseProvider.getTestOAuthResponse("TEST_ACCESS_TOKEN_2", 3600L, "newRefreshToken2"), SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)));
OfflineCredentials offlineCredentials = new OfflineCredentials.Builder().forApi(OfflineCredentials.Api.ADWORDS).withTokenUrlServer(testHttpServer.getServerUrl()).fromFile(AdWordsAxisSoapIntegrationTest.class.getResource("props/ads-test.properties")).build();
Credential credential = offlineCredentials.generateCredential();
assertTrue(testHttpServer.getLastRequestBody().contains("grant_type=refresh_token"));
assertTrue(testHttpServer.getLastRequestBody().contains("refresh_token=refreshToken"));
assertTrue(testHttpServer.getLastRequestBody().contains("client_id=clientId"));
assertTrue(testHttpServer.getLastRequestBody().contains("client_secret=clientSecret"));
// Make sure the old token expires - the session builder should issue a request
// for another access token.
Thread.sleep(1000);
assertEquals("TEST_ACCESS_TOKEN_1", credential.getAccessToken());
AdWordsSession session = new AdWordsSession.Builder().withUserAgent("TEST_APP").withOAuth2Credential(credential).withEndpoint(testHttpServer.getServerUrl()).withDeveloperToken("TEST_DEVELOPER_TOKEN").withClientCustomerId("TEST_CLIENT_CUSTOMER_ID").build();
testBudgetServiceMutateRequest(session);
assertEquals("Bearer TEST_ACCESS_TOKEN_2", testHttpServer.getLastAuthorizationHttpHeader());
}
Aggregations