Search in sources :

Example 51 with AdWordsSession

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

the class AdWordsJaxWsSoapCompressionIntegrationTest method testGoldenSoap_oauth2.

/**
 * Tests making a JAX-WS AdWords API call with OAuth2 and compression enabled.
 */
@Test
public void testGoldenSoap_oauth2() throws Exception {
    testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
    credential.setAccessToken("TEST_ACCESS_TOKEN");
    AdWordsSession session = new AdWordsSession.Builder().withUserAgent("TEST_APP").withOAuth2Credential(credential).withEndpoint(testHttpServer.getServerUrl()).withDeveloperToken("TEST_DEVELOPER_TOKEN").withClientCustomerId("TEST_CLIENT_CUSTOMER_ID").build();
    BudgetServiceInterface budgetService = new AdWordsServices().get(session, BudgetServiceInterface.class);
    Budget budget = new Budget();
    budget.setName("Test Budget Name");
    Money money = new Money();
    money.setMicroAmount(50000000L);
    budget.setAmount(money);
    budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);
    BudgetOperation operation = new BudgetOperation();
    operation.setOperand(budget);
    operation.setOperator(Operator.ADD);
    Budget responseBudget = budgetService.mutate(Lists.newArrayList(operation)).getValue().get(0);
    assertEquals("Budget ID does not match", 251877074L, responseBudget.getBudgetId().longValue());
    assertEquals("Budget name does not match", budget.getName(), responseBudget.getName());
    assertEquals("Budget amount does not match", budget.getAmount().getMicroAmount(), responseBudget.getAmount().getMicroAmount());
    assertEquals("Budget delivery method does not match", budget.getDeliveryMethod(), responseBudget.getDeliveryMethod());
    assertTrue("Compression was enabled but the last request body was not compressed", testHttpServer.wasLastRequestBodyCompressed());
    Diff diff = DiffBuilder.compare(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION)).withTest(testHttpServer.getLastRequestBody()).checkForSimilar().build();
    assertFalse(diff.hasDifferences());
    assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
}
Also used : Money(com.google.api.ads.adwords.jaxws.v201809.cm.Money) Diff(org.xmlunit.diff.Diff) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) DiffBuilder(org.xmlunit.builder.DiffBuilder) BudgetOperation(com.google.api.ads.adwords.jaxws.v201809.cm.BudgetOperation) BudgetServiceInterface(com.google.api.ads.adwords.jaxws.v201809.cm.BudgetServiceInterface) Budget(com.google.api.ads.adwords.jaxws.v201809.cm.Budget) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) AdWordsServices(com.google.api.ads.adwords.jaxws.factory.AdWordsServices) Test(org.junit.Test) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)

Example 52 with AdWordsSession

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

the class AddDynamicPageFeed 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();
    AddDynamicPageFeedParams params = new AddDynamicPageFeedParams();
    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.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
        params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    }
    try {
        runExample(adWordsServices, session, params.campaignId, 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) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) 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 53 with AdWordsSession

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

the class AddExpandedTextAdWithUpgradedUrls 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();
    AddExpandedTextAdWithUpgradedUrlsParams params = new AddExpandedTextAdWithUpgradedUrlsParams();
    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 54 with AdWordsSession

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

the class AdvancedCreateCredentialFromScratch method createAdWordsSession.

private static AdWordsSession createAdWordsSession(String userId, DataStoreFactory storeFactory) throws IOException, ValidationException, ConfigurationLoadException {
    // Create a GoogleCredential with minimal information.
    GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, Arrays.asList(SCOPE)).setDataStoreFactory(storeFactory).build();
    // Load the credential.
    Credential credential = authorizationFlow.loadCredential(userId);
    // developer token, client customer ID, etc., but use the credentials created above.
    return new AdWordsSession.Builder().fromFile().withOAuth2Credential(credential).build();
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory)

Example 55 with AdWordsSession

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

the class AdvancedCreateCredentialFromScratch method main.

public static void main(String[] args) {
    if (CLIENT_ID.equals("INSERT_CLIENT_ID_HERE") || CLIENT_SECRET.equals("INSERT_CLIENT_SECRET_HERE")) {
        throw new IllegalArgumentException("Please input your client IDs or secret. " + "See https://console.developers.google.com/project");
    }
    // It is highly recommended that you use a credential store in your
    // application to store a per-user Credential.
    // See: https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#data_store
    DataStoreFactory storeFactory = new MemoryDataStoreFactory();
    // Authorize and store your credential.
    try {
        authorize(storeFactory, USER_ID);
    } catch (Exception e) {
        System.err.printf("Failed to authorize credentials: %s%n", e);
        return;
    }
    // Create a AdWordsSession from the credential store. You will typically do this
    // in a servlet interceptor for a web application or per separate thread
    // of your offline application.
    AdWordsSession adWordsSession;
    try {
        adWordsSession = createAdWordsSession(USER_ID, storeFactory);
    } 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 (IOException ioe) {
        System.err.printf("Failed to load OAuth credentials from local data store. Exception: %s%n", ioe);
        return;
    }
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    // Location to download report to.
    String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";
    try {
        runExample(adWordsServices, adWordsSession, reportFile);
    } catch (ReportDownloadResponseException rde) {
        // A ReportDownloadResponseException will be thrown if the HTTP status code in the response
        // indicates an error occurred, but the response did not contain further details.
        System.err.printf("Report was not downloaded due to: %s%n", rde);
    } catch (ReportException re) {
        // A ReportException will be thrown if the download failed due to a transport layer exception.
        System.err.printf("Report was not downloaded due to transport layer exception: %s%n", re);
    } catch (IOException ioe) {
        // An IOException in this example indicates that the report's contents could not be read from
        // the response.
        System.err.printf("Report was not read due to an IOException: %s%n", ioe);
    }
}
Also used : MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) 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) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ReportException(com.google.api.ads.adwords.lib.utils.ReportException) IOException(java.io.IOException) DetailedReportDownloadResponseException(com.google.api.ads.adwords.lib.utils.DetailedReportDownloadResponseException) ReportDownloadResponseException(com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException) DetailedReportDownloadResponseException(com.google.api.ads.adwords.lib.utils.DetailedReportDownloadResponseException) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) IOException(java.io.IOException) ReportDownloadResponseException(com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) ReportException(com.google.api.ads.adwords.lib.utils.ReportException) DataStoreFactory(com.google.api.client.util.store.DataStoreFactory) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory)

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