Search in sources :

Example 31 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession 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)

Example 32 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class RemoveAdGroup method main.

public static void main(String[] args) {
    AdWordsSession session;
    try {
        // Generate a refreshable OAuth2 credential.
        Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS).fromFile().build().generateCredential();
        // Construct an AdWordsSession.
        session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
        System.err.printf("Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle);
        return;
    } catch (ValidationException ve) {
        System.err.printf("Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve);
        return;
    } catch (OAuthException oe) {
        System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe);
        return;
    }
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    RemoveAdGroupParams params = new RemoveAdGroupParams();
    if (!params.parseArguments(args)) {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the code here. See the parameter class definition above for descriptions.
        params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    }
    try {
        runExample(adWordsServices, session, params.adGroupId);
    } 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.println("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);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) 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 33 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class RemoveKeyword method main.

public static void main(String[] args) {
    AdWordsSession session;
    try {
        // Generate a refreshable OAuth2 credential.
        Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS).fromFile().build().generateCredential();
        // Construct an AdWordsSession.
        session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
        System.err.printf("Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle);
        return;
    } catch (ValidationException ve) {
        System.err.printf("Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve);
        return;
    } catch (OAuthException oe) {
        System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe);
        return;
    }
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    RemoveKeywordParams params = new RemoveKeywordParams();
    if (!params.parseArguments(args)) {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the code here. See the parameter class definition above for descriptions.
        params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
        params.criterionId = Long.parseLong("INSERT_CRITERION_ID_HERE");
    }
    try {
        runExample(adWordsServices, session, params.adGroupId, params.criterionId);
    } 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.println("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);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) 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 34 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession 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 35 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class UploadOfflineData method main.

public static void main(String[] args) {
    AdWordsSession session;
    try {
        // Generate a refreshable OAuth2 credential.
        Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS).fromFile().build().generateCredential();
        // Construct an AdWordsSession.
        session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
        System.err.printf("Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle);
        return;
    } catch (ValidationException ve) {
        System.err.printf("Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve);
        return;
    } catch (OAuthException oe) {
        System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe);
        return;
    }
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    UploadOfflineDataParams params = new UploadOfflineDataParams();
    if (!params.parseArguments(args)) {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the code here. See the parameter class definition above for descriptions.
        params.emailAddresses = Arrays.asList("INSERT_EMAIL_ADDRESS_1_HERE", "INSERT_EMAIL_ADDRESS_2_HERE");
        params.conversionName = "INSERT_CONVERSION_NAME_HERE";
        params.externalUploadId = Long.valueOf("INSERT_EXTERNAL_UPLOAD_ID_HERE");
        // Change the enum below to STORE_SALES_UPLOAD_THIRD_PARTY if uploading third party data.
        params.offlineDataUploadType = OfflineDataUploadType.STORE_SALES_UPLOAD_FIRST_PARTY.getValue();
        // The three constants below are needed when uploading third party data.
        // You can safely ignore them if you are uploading first party data.
        // For times, use the format yyyyMMdd HHmmss tz. For more details on formats, see:
        // https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats
        // For time zones, see:
        // https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
        params.advertiserUploadTime = "INSERT_ADVERTISER_UPLOAD_TIME";
        params.bridgeMapVersionId = "INSERT_BRIDGE_MAP_VERSION_ID";
        params.partnerId = Integer.valueOf("INSERT_PARTNER_ID");
    }
    OfflineDataUploadType uploadTypeEnum = OfflineDataUploadType.fromString(params.offlineDataUploadType);
    // Set partial failure to true since this example demonstrates how to handle partial
    // failure errors.
    session.setPartialFailure(true);
    try {
        runExample(adWordsServices, session, params.conversionName, params.externalUploadId, params.emailAddresses, uploadTypeEnum, params.advertiserUploadTime, params.bridgeMapVersionId, params.partnerId);
    } 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.println("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 (UnsupportedEncodingException ue) {
        System.err.printf("Example failed due to encoding exception: %s%n", ue);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OfflineDataUploadType(com.google.api.ads.adwords.axis.v201809.rm.OfflineDataUploadType) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Aggregations

AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)121 Credential (com.google.api.client.auth.oauth2.Credential)104 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)102 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)101 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)100 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)100 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)97 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)97 RemoteException (java.rmi.RemoteException)97 SelectorBuilder (com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder)24 Test (org.junit.Test)15 IOException (java.io.IOException)14 OfflineCredentials (com.google.api.ads.common.lib.auth.OfflineCredentials)12 AdWordsServices (com.google.api.ads.adwords.axis.factory.AdWordsServices)10 Api (com.google.api.ads.common.lib.auth.OfflineCredentials.Api)9 DEFAULT_CONFIGURATION_FILENAME (com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME)9 MockHttpIntegrationTest (com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)8 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)7 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)7 List (java.util.List)7