Search in sources :

Example 1 with Builder

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());
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest) Test(org.junit.Test)

Example 2 with Builder

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());
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest) Test(org.junit.Test)

Example 3 with Builder

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());
}
Also used : GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) Credential(com.google.api.client.auth.oauth2.Credential) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) DiffBuilder(org.xmlunit.builder.DiffBuilder) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest) Test(org.junit.Test)

Example 4 with Builder

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);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) Builder(com.google.api.ads.adwords.lib.client.AdWordsSession.Builder) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) IOException(java.io.IOException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 5 with Builder

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();
    }
}
Also used : OAuthException(com.google.api.ads.common.lib.exception.OAuthException) Arrays(java.util.Arrays) Parameter(com.beust.jcommander.Parameter) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) AdGroupCriterionPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage) AdGroupCriterionServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) CodeSampleParams(com.google.api.ads.common.lib.utils.examples.CodeSampleParams) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector) ArgumentNames(com.google.api.ads.adwords.lib.utils.examples.ArgumentNames) Credential(com.google.api.client.auth.oauth2.Credential) AdGroupCriterionField(com.google.api.ads.adwords.lib.selectorfields.v201809.cm.AdGroupCriterionField) AdGroupCriterionServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) AdGroupCriterionPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Aggregations

Credential (com.google.api.client.auth.oauth2.Credential)16 IOException (java.io.IOException)7 OfflineCredentials (com.google.api.ads.common.lib.auth.OfflineCredentials)5 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)5 AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)4 MockHttpIntegrationTest (com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)4 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)4 AuthorizationCodeInstalledApp (com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp)4 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)4 Test (org.junit.Test)4 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)3 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)3 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)3 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)3 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)3 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)3 AuthorizationCodeTokenRequest (com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)3 LocalServerReceiver (com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver)3 GoogleAuthorizationCodeFlow (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow)3 GoogleNetHttpTransport (com.google.api.client.googleapis.javanet.GoogleNetHttpTransport)3