Search in sources :

Example 91 with AdWordsSession

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

the class AddMultiAssetResponsiveDisplayAd 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();
    AddMultiAssetResponsiveDisplayAdParams params = new AddMultiAssetResponsiveDisplayAdParams();
    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);
    } catch (IOException ioe) {
        System.err.printf("Example failed unexpectedly due to IOException: %s%n", ioe);
    }
}
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) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 92 with AdWordsSession

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

the class AddUniversalAppCampaign 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();
    try {
        runExample(adWordsServices, session);
    } 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 93 with AdWordsSession

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

the class AddHtml5Ad 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();
    AddHtml5AdParams params = new AddHtml5AdParams();
    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);
    } catch (IOException ioe) {
        System.err.printf("Example failed due to IOException: %s%n", ioe);
    }
}
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) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 94 with AdWordsSession

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

the class AdHocReportDownloadHelperTest method setUp.

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    Enum<?> downloadFormat = TestDownloadFormat.CSV;
    Mockito.<Enum<?>>when(reportRequest.getDownloadFormat()).thenReturn(downloadFormat);
    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();
    helper = new GenericAdWordsServices().getBootstrapper().getInstanceOf(session, AdHocReportDownloadHelper.class);
    exceptionBuilder = DetailedReportDownloadResponseException::new;
}
Also used : GenericAdWordsServices(com.google.api.ads.adwords.lib.utils.testing.GenericAdWordsServices) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Builder(com.google.api.ads.adwords.lib.utils.DetailedReportDownloadResponseException.Builder) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) Before(org.junit.Before)

Example 95 with AdWordsSession

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

the class ReportRequestFactoryHelperTest method testGetHttpRequestFactory.

/**
 * Tests the factory builds the request properly for this test's attributes.
 */
@Test
public void testGetHttpRequestFactory() throws ValidationException, AuthenticationException, IOException {
    final int timeoutFromLibConfig = 42;
    when(adWordsLibConfiguration.getReportDownloadTimeout()).thenReturn(timeoutFromLibConfig);
    AdWordsSession session = new AdWordsSession.Builder().withDeveloperToken("foodevtoken").withClientCustomerId("fooclientcustomerid").withOAuth2Credential(credential).withUserAgent("userAgent").withReportingConfiguration(reportingConfiguration).build();
    when(authorizationHeaderProvider.getAuthorizationHeader(session, ENDPOINT_URL.build())).thenReturn("fooauthheader");
    when(userAgentCombiner.getUserAgent(anyString())).thenReturn("foouseragent");
    ReportRequestFactoryHelper helper = new ReportRequestFactoryHelper(session, authorizationHeaderProvider, userAgentCombiner, transport, adWordsLibConfiguration, reportResponseInterceptor);
    HttpRequestFactory requestFactory = helper.getHttpRequestFactory(ENDPOINT_URL.build(), version);
    HttpRequest request = requestFactory.buildPostRequest(ENDPOINT_URL, new AwqlReportBodyProvider("select 1", "csv").getHttpContent());
    HttpHeaders headers = request.getHeaders();
    assertEquals("foodevtoken", headers.get("developerToken"));
    assertEquals("fooauthheader", headers.getAuthorization());
    assertEquals("fooclientcustomerid", headers.get("clientCustomerId"));
    assertTrue((headers.getUserAgent()).contains("foouseragent"));
    if (reportingConfiguration == null) {
        assertFalse("skipReportHeader should not be in the header if no reporting config is set", headers.containsKey("skipReportHeader"));
        assertFalse("skipReportSummary should not be in the header if no reporting config is set", headers.containsKey("skipReportSummary"));
        assertEquals("connect timeout is incorrect", timeoutFromLibConfig, request.getConnectTimeout());
        assertEquals("read timeout is incorrect", timeoutFromLibConfig, request.getReadTimeout());
    } else {
        Integer expectedTimeout = reportingConfiguration.getReportDownloadTimeout();
        if (expectedTimeout == null) {
            // Should fall back to the library level config value if the reporting config does not have
            // a timeout set.
            expectedTimeout = timeoutFromLibConfig;
        }
        assertEquals("connect timeout is incorrect", expectedTimeout.intValue(), request.getConnectTimeout());
        assertEquals("read timeout is incorrect", expectedTimeout.intValue(), request.getReadTimeout());
        assertEquals("skipReportHeader not equal to the reporting config setting", toStringBoolean(reportingConfiguration.isSkipReportHeader()), headers.get("skipReportHeader"));
        assertEquals("skipColumnHeader not equal to the reporting config setting", toStringBoolean(reportingConfiguration.isSkipColumnHeader()), headers.get("skipColumnHeader"));
        assertEquals("skipReportSummary not equal to the reporting config setting", toStringBoolean(reportingConfiguration.isSkipReportSummary()), headers.get("skipReportSummary"));
        assertEquals("includeZeroImpressions not equal to the reporting config setting", toStringBoolean(reportingConfiguration.isIncludeZeroImpressions()), headers.get("includeZeroImpressions"));
        assertEquals("useRawEnumValues not equal to the reporting config setting", toStringBoolean(reportingConfiguration.isUseRawEnumValues()), headers.get("useRawEnumValues"));
    }
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) Test(org.junit.Test)

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