Search in sources :

Example 6 with AdWordsServices

use of com.google.api.ads.adwords.axis.factory.AdWordsServices in project googleads-java-lib by googleads.

the class AddConversionTrackers method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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) throws RemoteException {
    // Get the ConversionTrackerService.
    ConversionTrackerServiceInterface service = adWordsServices.get(session, ConversionTrackerServiceInterface.class);
    List<ConversionTracker> conversionTrackers = new ArrayList<>();
    // Create an AdWords conversion tracker.
    AdWordsConversionTracker adWordsConversionTracker = new AdWordsConversionTracker();
    adWordsConversionTracker.setName("Earth to Mars Cruises Conversion # " + System.currentTimeMillis());
    adWordsConversionTracker.setCategory(ConversionTrackerCategory.DEFAULT);
    // You can optionally provide these field(s).
    adWordsConversionTracker.setStatus(ConversionTrackerStatus.ENABLED);
    adWordsConversionTracker.setViewthroughLookbackWindow(15);
    adWordsConversionTracker.setDefaultRevenueValue(1d);
    adWordsConversionTracker.setAlwaysUseDefaultRevenueValue(Boolean.TRUE);
    conversionTrackers.add(adWordsConversionTracker);
    // Create an upload conversion for offline conversion imports.
    UploadConversion uploadConversion = new UploadConversion();
    // Set an appropriate category. This field is optional, and will be set to
    // DEFAULT if not mentioned.
    uploadConversion.setCategory(ConversionTrackerCategory.LEAD);
    uploadConversion.setName("Upload Conversion #" + System.currentTimeMillis());
    uploadConversion.setViewthroughLookbackWindow(30);
    uploadConversion.setCtcLookbackWindow(90);
    // Optional: Set the default currency code to use for conversions
    // that do not specify a conversion currency. This must be an ISO 4217
    // 3-character currency code such as "EUR" or "USD".
    // If this field is not set on this UploadConversion, AdWords will use
    // the account's currency.
    uploadConversion.setDefaultRevenueCurrencyCode("EUR");
    // Optional: Set the default revenue value to use for conversions
    // that do not specify a conversion value. Note that this value
    // should NOT be in micros.
    uploadConversion.setDefaultRevenueValue(2.50);
    // Optional: To upload fractional conversion credits, mark the upload conversion
    // as externally attributed. See
    // https://developers.google.com/adwords/api/docs/guides/conversion-tracking#importing_externally_attributed_conversions
    // to learn more about importing externally attributed conversions.
    // uploadConversion.setIsExternallyAttributed(true);
    conversionTrackers.add(uploadConversion);
    // Create operations.
    List<ConversionTrackerOperation> operations = conversionTrackers.stream().map(conversionTracker -> {
        ConversionTrackerOperation operation = new ConversionTrackerOperation();
        operation.setOperator(Operator.ADD);
        operation.setOperand(conversionTracker);
        return operation;
    }).collect(Collectors.toList());
    // Add the conversions.
    ConversionTrackerReturnValue result = service.mutate(operations.toArray(new ConversionTrackerOperation[operations.size()]));
    // Display conversion.
    for (ConversionTracker conversionTracker : result.getValue()) {
        System.out.printf("Conversion with ID %d, name '%s', status '%s', " + "category '%s' was added.%n", conversionTracker.getId(), conversionTracker.getName(), conversionTracker.getStatus(), conversionTracker.getCategory());
        if (conversionTracker instanceof AdWordsConversionTracker) {
            System.out.printf("Google global site tag:%n%s%n%n", conversionTracker.getGoogleGlobalSiteTag());
            System.out.printf("Google event snippet:%n%s%n%n", conversionTracker.getGoogleEventSnippet());
        }
    }
}
Also used : ConversionTrackerCategory(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerCategory) ConversionTrackerReturnValue(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerReturnValue) ArrayList(java.util.ArrayList) ConversionTracker(com.google.api.ads.adwords.axis.v201809.cm.ConversionTracker) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) Credential(com.google.api.client.auth.oauth2.Credential) ConversionTrackerOperation(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerOperation) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) ConversionTrackerServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerServiceInterface) ConversionTrackerStatus(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerStatus) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Operator(com.google.api.ads.adwords.axis.v201809.cm.Operator) Collectors(java.util.stream.Collectors) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdWordsConversionTracker(com.google.api.ads.adwords.axis.v201809.cm.AdWordsConversionTracker) List(java.util.List) 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) UploadConversion(com.google.api.ads.adwords.axis.v201809.cm.UploadConversion) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) ConversionTracker(com.google.api.ads.adwords.axis.v201809.cm.ConversionTracker) AdWordsConversionTracker(com.google.api.ads.adwords.axis.v201809.cm.AdWordsConversionTracker) AdWordsConversionTracker(com.google.api.ads.adwords.axis.v201809.cm.AdWordsConversionTracker) ConversionTrackerOperation(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerOperation) ArrayList(java.util.ArrayList) ConversionTrackerServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerServiceInterface) UploadConversion(com.google.api.ads.adwords.axis.v201809.cm.UploadConversion) ConversionTrackerReturnValue(com.google.api.ads.adwords.axis.v201809.cm.ConversionTrackerReturnValue)

Example 7 with AdWordsServices

use of com.google.api.ads.adwords.axis.factory.AdWordsServices in project googleads-java-lib by googleads.

the class AddRuleBasedUserLists method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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) throws RemoteException {
    // Get the AdwordsUserListService.
    AdwordsUserListServiceInterface userListService = adWordsServices.get(session, AdwordsUserListServiceInterface.class);
    // First rule item group - users who visited the checkout page and had more than one item
    // in their shopping cart.
    StringKey pageTypeKey = new StringKey("ecomm_pagetype");
    StringRuleItem checkoutStringRuleItem = new StringRuleItem();
    checkoutStringRuleItem.setKey(pageTypeKey);
    checkoutStringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    checkoutStringRuleItem.setValue("checkout");
    RuleItem checkoutRuleItem = new RuleItem();
    checkoutRuleItem.setStringRuleItem(checkoutStringRuleItem);
    NumberKey cartSizeKey = new NumberKey("cartsize");
    NumberRuleItem cartSizeNumberRuleItem = new NumberRuleItem();
    cartSizeNumberRuleItem.setKey(cartSizeKey);
    cartSizeNumberRuleItem.setOp(NumberRuleItemNumberOperator.GREATER_THAN);
    cartSizeNumberRuleItem.setValue(1.0);
    RuleItem cartSizeRuleItem = new RuleItem();
    cartSizeRuleItem.setNumberRuleItem(cartSizeNumberRuleItem);
    // Combine the two rule items into a RuleItemGroup so AdWords will AND their rules
    // together.
    RuleItemGroup checkoutMultipleItemGroup = new RuleItemGroup();
    checkoutMultipleItemGroup.setItems(new RuleItem[] { checkoutRuleItem, cartSizeRuleItem });
    // Second rule item group - users who checked out within the next 3 months.
    DateKey checkoutDateKey = new DateKey("checkoutdate");
    DateRuleItem startDateDateRuleItem = new DateRuleItem();
    startDateDateRuleItem.setKey(checkoutDateKey);
    startDateDateRuleItem.setOp(DateRuleItemDateOperator.AFTER);
    startDateDateRuleItem.setValue(DateTime.now().toString(DATE_FORMAT_STRING));
    RuleItem startDateRuleItem = new RuleItem();
    startDateRuleItem.setDateRuleItem(startDateDateRuleItem);
    DateRuleItem endDateDateRuleItem = new DateRuleItem();
    endDateDateRuleItem.setKey(checkoutDateKey);
    endDateDateRuleItem.setOp(DateRuleItemDateOperator.BEFORE);
    endDateDateRuleItem.setValue(DateTime.now().plusMonths(3).toString(DATE_FORMAT_STRING));
    RuleItem endDateRuleItem = new RuleItem();
    endDateRuleItem.setDateRuleItem(endDateDateRuleItem);
    // Combine the date rule items into a RuleItemGroup.
    RuleItemGroup checkedOutNextThreeMonthsItemGroup = new RuleItemGroup();
    checkedOutNextThreeMonthsItemGroup.setItems(new RuleItem[] { startDateRuleItem, endDateRuleItem });
    // Combine the rule item groups into a Rule so AdWords knows how to apply the rules.
    Rule rule = new Rule();
    rule.setGroups(new RuleItemGroup[] { checkoutMultipleItemGroup, checkedOutNextThreeMonthsItemGroup });
    // ExpressionRuleUserLists can use either CNF or DNF for matching. CNF means 'at least one item
    // in each rule item group must match', and DNF means 'at least one entire rule item group must
    // match'. DateSpecificRuleUserList only supports DNF. You can also omit the rule type
    // altogether to default to DNF.
    rule.setRuleType(UserListRuleTypeEnumsEnum.DNF);
    // Third and fourth rule item groups.
    // Visitors of a page who visited another page.
    StringKey urlStringKey = new StringKey("url__");
    StringRuleItem site1StringRuleItem = new StringRuleItem();
    site1StringRuleItem.setKey(urlStringKey);
    site1StringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    site1StringRuleItem.setValue("example.com/example1");
    RuleItem site1RuleItem = new RuleItem();
    site1RuleItem.setStringRuleItem(site1StringRuleItem);
    StringRuleItem site2StringRuleItem = new StringRuleItem();
    site2StringRuleItem.setKey(urlStringKey);
    site2StringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    site2StringRuleItem.setValue("example.com/example2");
    RuleItem site2RuleItem = new RuleItem();
    site2RuleItem.setStringRuleItem(site2StringRuleItem);
    // Create two RuleItemGroups to show that a visitor browsed two sites.
    RuleItemGroup site1RuleItemGroup = new RuleItemGroup();
    site1RuleItemGroup.setItems(new RuleItem[] { site1RuleItem });
    RuleItemGroup site2RuleItemGroup = new RuleItemGroup();
    site2RuleItemGroup.setItems(new RuleItem[] { site2RuleItem });
    // Create two rules to show that a visitor browsed two sites.
    Rule userVisitedSite1Rule = new Rule();
    userVisitedSite1Rule.setGroups(new RuleItemGroup[] { site1RuleItemGroup });
    Rule userVisitedSite2Rule = new Rule();
    userVisitedSite2Rule.setGroups(new RuleItemGroup[] { site2RuleItemGroup });
    // Create the user list with no restrictions on site visit date.
    ExpressionRuleUserList expressionUserList = new ExpressionRuleUserList();
    String creationTimeString = DateTime.now().toString("yyyyMMdd_HHmmss");
    expressionUserList.setName("Expression based user list created at " + creationTimeString);
    expressionUserList.setDescription("Users who checked out in three month window OR visited the checkout page " + "with more than one item in their cart");
    expressionUserList.setRule(rule);
    // Optional: Set the prepopulationStatus to REQUESTED to include past users in the user list.
    expressionUserList.setPrepopulationStatus(RuleBasedUserListPrepopulationStatus.REQUESTED);
    // Create the user list restricted to users who visit your site within the next six months.
    DateTime startDate = DateTime.now();
    DateTime endDate = startDate.plusMonths(6);
    DateSpecificRuleUserList dateUserList = new DateSpecificRuleUserList();
    dateUserList.setName("Date rule user list created at " + creationTimeString);
    dateUserList.setDescription(String.format("Users who visited the site between %s and %s and " + "checked out in three month window OR visited the checkout page " + "with more than one item in their cart", startDate.toString(DATE_FORMAT_STRING), endDate.toString(DATE_FORMAT_STRING)));
    dateUserList.setRule(rule);
    // Set the start and end dates of the user list.
    dateUserList.setStartDate(startDate.toString(DATE_FORMAT_STRING));
    dateUserList.setEndDate(endDate.toString(DATE_FORMAT_STRING));
    // Create the user list where "Visitors of a page who did visit another page".
    // To create a user list where "Visitors of a page who did not visit another
    // page", change the ruleOperator from AND to AND_NOT.
    CombinedRuleUserList combinedRuleUserList = new CombinedRuleUserList();
    combinedRuleUserList.setName("Combined rule user list created at " + creationTimeString);
    combinedRuleUserList.setDescription("Users who visited two sites.");
    combinedRuleUserList.setLeftOperand(userVisitedSite1Rule);
    combinedRuleUserList.setRightOperand(userVisitedSite2Rule);
    combinedRuleUserList.setRuleOperator(CombinedRuleUserListRuleOperator.AND);
    // Create operations to add the user lists.
    List<UserListOperation> operations = Stream.of(expressionUserList, dateUserList, combinedRuleUserList).map(userList -> {
        UserListOperation operation = new UserListOperation();
        operation.setOperand(userList);
        operation.setOperator(Operator.ADD);
        return operation;
    }).collect(Collectors.toList());
    // Submit the operations.
    UserListReturnValue result = userListService.mutate(operations.toArray(new UserListOperation[operations.size()]));
    // Display the results.
    for (UserList userListResult : result.getValue()) {
        System.out.printf("User list added with ID %d, name '%s', status '%s', list type '%s'," + " accountUserListStatus '%s', description '%s'.%n", userListResult.getId(), userListResult.getName(), userListResult.getStatus().getValue(), userListResult.getListType() == null ? null : userListResult.getListType().getValue(), userListResult.getAccountUserListStatus().getValue(), userListResult.getDescription());
    }
}
Also used : DateKey(com.google.api.ads.adwords.axis.v201809.rm.DateKey) ExpressionRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.ExpressionRuleUserList) DateSpecificRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.DateSpecificRuleUserList) UserList(com.google.api.ads.adwords.axis.v201809.rm.UserList) UserListRuleTypeEnumsEnum(com.google.api.ads.adwords.axis.v201809.rm.UserListRuleTypeEnumsEnum) DateRuleItemDateOperator(com.google.api.ads.adwords.axis.v201809.rm.DateRuleItemDateOperator) NumberRuleItemNumberOperator(com.google.api.ads.adwords.axis.v201809.rm.NumberRuleItemNumberOperator) RuleItemGroup(com.google.api.ads.adwords.axis.v201809.rm.RuleItemGroup) UserListReturnValue(com.google.api.ads.adwords.axis.v201809.rm.UserListReturnValue) CombinedRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.CombinedRuleUserList) NumberKey(com.google.api.ads.adwords.axis.v201809.rm.NumberKey) CombinedRuleUserListRuleOperator(com.google.api.ads.adwords.axis.v201809.rm.CombinedRuleUserListRuleOperator) Rule(com.google.api.ads.adwords.axis.v201809.rm.Rule) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) DateRuleItem(com.google.api.ads.adwords.axis.v201809.rm.DateRuleItem) Credential(com.google.api.client.auth.oauth2.Credential) RuleItem(com.google.api.ads.adwords.axis.v201809.rm.RuleItem) RuleBasedUserListPrepopulationStatus(com.google.api.ads.adwords.axis.v201809.rm.RuleBasedUserListPrepopulationStatus) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) AdwordsUserListServiceInterface(com.google.api.ads.adwords.axis.v201809.rm.AdwordsUserListServiceInterface) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) DateTime(org.joda.time.DateTime) Operator(com.google.api.ads.adwords.axis.v201809.cm.Operator) UserListOperation(com.google.api.ads.adwords.axis.v201809.rm.UserListOperation) NumberRuleItem(com.google.api.ads.adwords.axis.v201809.rm.NumberRuleItem) StringRuleItemStringOperator(com.google.api.ads.adwords.axis.v201809.rm.StringRuleItemStringOperator) Collectors(java.util.stream.Collectors) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) List(java.util.List) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) Stream(java.util.stream.Stream) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) StringRuleItem(com.google.api.ads.adwords.axis.v201809.rm.StringRuleItem) StringKey(com.google.api.ads.adwords.axis.v201809.rm.StringKey) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) AdwordsUserListServiceInterface(com.google.api.ads.adwords.axis.v201809.rm.AdwordsUserListServiceInterface) StringKey(com.google.api.ads.adwords.axis.v201809.rm.StringKey) DateRuleItem(com.google.api.ads.adwords.axis.v201809.rm.DateRuleItem) UserListOperation(com.google.api.ads.adwords.axis.v201809.rm.UserListOperation) DateSpecificRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.DateSpecificRuleUserList) RuleItemGroup(com.google.api.ads.adwords.axis.v201809.rm.RuleItemGroup) CombinedRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.CombinedRuleUserList) DateKey(com.google.api.ads.adwords.axis.v201809.rm.DateKey) DateTime(org.joda.time.DateTime) UserListReturnValue(com.google.api.ads.adwords.axis.v201809.rm.UserListReturnValue) NumberRuleItem(com.google.api.ads.adwords.axis.v201809.rm.NumberRuleItem) DateRuleItem(com.google.api.ads.adwords.axis.v201809.rm.DateRuleItem) RuleItem(com.google.api.ads.adwords.axis.v201809.rm.RuleItem) NumberRuleItem(com.google.api.ads.adwords.axis.v201809.rm.NumberRuleItem) StringRuleItem(com.google.api.ads.adwords.axis.v201809.rm.StringRuleItem) Rule(com.google.api.ads.adwords.axis.v201809.rm.Rule) ExpressionRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.ExpressionRuleUserList) ExpressionRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.ExpressionRuleUserList) DateSpecificRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.DateSpecificRuleUserList) UserList(com.google.api.ads.adwords.axis.v201809.rm.UserList) CombinedRuleUserList(com.google.api.ads.adwords.axis.v201809.rm.CombinedRuleUserList) StringRuleItem(com.google.api.ads.adwords.axis.v201809.rm.StringRuleItem) NumberKey(com.google.api.ads.adwords.axis.v201809.rm.NumberKey)

Example 8 with AdWordsServices

use of com.google.api.ads.adwords.axis.factory.AdWordsServices in project googleads-java-lib by googleads.

the class AdWordsAxisSoapCompressionIntegrationTest method testGoldenSoap_oauth2_compressionEnabled.

/**
 * Tests making an Axis AdWords API call with OAuth2 and compression enabled.
 */
@Test
public void testGoldenSoap_oauth2_compressionEnabled() 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 companyService = 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 = companyService.mutate(new BudgetOperation[] { operation }).getValue(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.axis.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.axis.v201809.cm.BudgetOperation) BudgetServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.BudgetServiceInterface) Budget(com.google.api.ads.adwords.axis.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.axis.factory.AdWordsServices) Test(org.junit.Test) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)

Example 9 with AdWordsServices

use of com.google.api.ads.adwords.axis.factory.AdWordsServices in project googleads-java-lib by googleads.

the class AdWordsAxisSoapIntegrationTest method testBudgetServiceMutateRequest.

/**
 * Submits a BudgetService.mutate call to the test server and asserts that the response contains
 * expected values.
 */
private void testBudgetServiceMutateRequest(AdWordsSession session) throws RemoteException, ApiException, IOException, SAXException {
    BudgetServiceInterface companyService = 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 = companyService.mutate(new BudgetOperation[] { operation }).getValue(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());
    assertFalse("Did not request compression but request was compressed", testHttpServer.wasLastRequestBodyCompressed());
    Diff diff = DiffBuilder.compare(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION)).withTest(testHttpServer.getLastRequestBody()).checkForSimilar().build();
    assertFalse(diff.hasDifferences());
}
Also used : Money(com.google.api.ads.adwords.axis.v201809.cm.Money) Diff(org.xmlunit.diff.Diff) BudgetOperation(com.google.api.ads.adwords.axis.v201809.cm.BudgetOperation) BudgetServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.BudgetServiceInterface) Budget(com.google.api.ads.adwords.axis.v201809.cm.Budget) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices)

Example 10 with AdWordsServices

use of com.google.api.ads.adwords.axis.factory.AdWordsServices in project googleads-java-lib by googleads.

the class EstimateKeywordTraffic method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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) throws RemoteException {
    // Get the TrafficEstimatorService.
    TrafficEstimatorServiceInterface trafficEstimatorService = adWordsServices.get(session, TrafficEstimatorServiceInterface.class);
    // Create keywords. Refer to the TrafficEstimatorService documentation for the maximum
    // number of keywords that can be passed in a single request.
    // https://developers.google.com/adwords/api/docs/reference/latest/TrafficEstimatorService
    List<Keyword> keywords = new ArrayList<Keyword>();
    Keyword marsCruiseKeyword = new Keyword();
    marsCruiseKeyword.setText("mars cruise");
    marsCruiseKeyword.setMatchType(KeywordMatchType.BROAD);
    keywords.add(marsCruiseKeyword);
    Keyword cheapCruiseKeyword = new Keyword();
    cheapCruiseKeyword.setText("cheap cruise");
    cheapCruiseKeyword.setMatchType(KeywordMatchType.PHRASE);
    keywords.add(cheapCruiseKeyword);
    Keyword cruiseKeyword = new Keyword();
    cruiseKeyword.setText("cruise");
    cruiseKeyword.setMatchType(KeywordMatchType.EXACT);
    keywords.add(cruiseKeyword);
    // Create a keyword estimate request for each keyword.
    List<KeywordEstimateRequest> keywordEstimateRequests = keywords.stream().map(keyword -> {
        KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest();
        keywordEstimateRequest.setKeyword(keyword);
        return keywordEstimateRequest;
    }).collect(Collectors.toList());
    // Add a negative keyword to the traffic estimate.
    KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest();
    negativeKeywordEstimateRequest.setKeyword(new Keyword(null, null, null, "hiking tour", KeywordMatchType.BROAD));
    negativeKeywordEstimateRequest.setIsNegative(true);
    keywordEstimateRequests.add(negativeKeywordEstimateRequest);
    // Create ad group estimate requests.
    List<AdGroupEstimateRequest> adGroupEstimateRequests = new ArrayList<AdGroupEstimateRequest>();
    AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest();
    adGroupEstimateRequest.setKeywordEstimateRequests(keywordEstimateRequests.toArray(new KeywordEstimateRequest[] {}));
    adGroupEstimateRequest.setMaxCpc(new Money(null, 1000000L));
    adGroupEstimateRequests.add(adGroupEstimateRequest);
    // Create campaign estimate requests.
    List<CampaignEstimateRequest> campaignEstimateRequests = new ArrayList<CampaignEstimateRequest>();
    CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest();
    campaignEstimateRequest.setAdGroupEstimateRequests(adGroupEstimateRequests.toArray(new AdGroupEstimateRequest[] {}));
    Location unitedStates = new Location();
    unitedStates.setId(2840L);
    Language english = new Language();
    english.setId(1000L);
    campaignEstimateRequest.setCriteria(new Criterion[] { unitedStates, english });
    campaignEstimateRequests.add(campaignEstimateRequest);
    // Create selector.
    TrafficEstimatorSelector selector = new TrafficEstimatorSelector();
    selector.setCampaignEstimateRequests(campaignEstimateRequests.toArray(new CampaignEstimateRequest[] {}));
    // Optional: Request a list of campaign level estimates segmented by platform.
    selector.setPlatformEstimateRequested(true);
    // Get traffic estimates.
    TrafficEstimatorResult result = trafficEstimatorService.get(selector);
    // Display traffic estimates.
    if (result != null && result.getCampaignEstimates() != null && result.getCampaignEstimates().length > 0) {
        CampaignEstimate campaignEstimate = result.getCampaignEstimates()[0];
        // Display the campaign level estimates segmented by platform.
        if (campaignEstimate.getPlatformEstimates() != null) {
            for (PlatformCampaignEstimate platformEstimate : campaignEstimate.getPlatformEstimates()) {
                String platformMessage = String.format("Results for the platform with ID %d and name '%s':%n", platformEstimate.getPlatform().getId(), platformEstimate.getPlatform().getPlatformName());
                displayMeanEstimates(platformMessage, platformEstimate.getMinEstimate(), platformEstimate.getMaxEstimate());
            }
        }
        // Display the keyword estimates.
        KeywordEstimate[] keywordEstimates = campaignEstimate.getAdGroupEstimates()[0].getKeywordEstimates();
        for (int i = 0; i < keywordEstimates.length; i++) {
            if (Boolean.TRUE.equals(keywordEstimateRequests.get(i).getIsNegative())) {
                continue;
            }
            Keyword keyword = keywordEstimateRequests.get(i).getKeyword();
            KeywordEstimate keywordEstimate = keywordEstimates[i];
            String keywordMessage = String.format("Results for the keyword with text '%s' and match type '%s':%n", keyword.getText(), keyword.getMatchType());
            displayMeanEstimates(keywordMessage, keywordEstimate.getMin(), keywordEstimate.getMax());
        }
    } else {
        System.out.println("No traffic estimates were returned.");
    }
}
Also used : TrafficEstimatorServiceInterface(com.google.api.ads.adwords.axis.v201809.o.TrafficEstimatorServiceInterface) TrafficEstimatorResult(com.google.api.ads.adwords.axis.v201809.o.TrafficEstimatorResult) KeywordMatchType(com.google.api.ads.adwords.axis.v201809.cm.KeywordMatchType) AdGroupEstimateRequest(com.google.api.ads.adwords.axis.v201809.o.AdGroupEstimateRequest) ArrayList(java.util.ArrayList) CampaignEstimate(com.google.api.ads.adwords.axis.v201809.o.CampaignEstimate) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) Money(com.google.api.ads.adwords.axis.v201809.cm.Money) Credential(com.google.api.client.auth.oauth2.Credential) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) Language(com.google.api.ads.adwords.axis.v201809.cm.Language) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) Collectors(java.util.stream.Collectors) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) List(java.util.List) 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) CampaignEstimateRequest(com.google.api.ads.adwords.axis.v201809.o.CampaignEstimateRequest) KeywordEstimate(com.google.api.ads.adwords.axis.v201809.o.KeywordEstimate) Criterion(com.google.api.ads.adwords.axis.v201809.cm.Criterion) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) Location(com.google.api.ads.adwords.axis.v201809.cm.Location) KeywordEstimateRequest(com.google.api.ads.adwords.axis.v201809.o.KeywordEstimateRequest) PlatformCampaignEstimate(com.google.api.ads.adwords.axis.v201809.o.PlatformCampaignEstimate) TrafficEstimatorSelector(com.google.api.ads.adwords.axis.v201809.o.TrafficEstimatorSelector) StatsEstimate(com.google.api.ads.adwords.axis.v201809.o.StatsEstimate) CampaignEstimateRequest(com.google.api.ads.adwords.axis.v201809.o.CampaignEstimateRequest) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) ArrayList(java.util.ArrayList) AdGroupEstimateRequest(com.google.api.ads.adwords.axis.v201809.o.AdGroupEstimateRequest) KeywordEstimateRequest(com.google.api.ads.adwords.axis.v201809.o.KeywordEstimateRequest) Money(com.google.api.ads.adwords.axis.v201809.cm.Money) PlatformCampaignEstimate(com.google.api.ads.adwords.axis.v201809.o.PlatformCampaignEstimate) Language(com.google.api.ads.adwords.axis.v201809.cm.Language) CampaignEstimate(com.google.api.ads.adwords.axis.v201809.o.CampaignEstimate) PlatformCampaignEstimate(com.google.api.ads.adwords.axis.v201809.o.PlatformCampaignEstimate) TrafficEstimatorServiceInterface(com.google.api.ads.adwords.axis.v201809.o.TrafficEstimatorServiceInterface) TrafficEstimatorResult(com.google.api.ads.adwords.axis.v201809.o.TrafficEstimatorResult) TrafficEstimatorSelector(com.google.api.ads.adwords.axis.v201809.o.TrafficEstimatorSelector) Location(com.google.api.ads.adwords.axis.v201809.cm.Location) KeywordEstimate(com.google.api.ads.adwords.axis.v201809.o.KeywordEstimate)

Aggregations

AdWordsServices (com.google.api.ads.adwords.axis.factory.AdWordsServices)11 AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)10 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)9 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)9 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)9 OfflineCredentials (com.google.api.ads.common.lib.auth.OfflineCredentials)9 Api (com.google.api.ads.common.lib.auth.OfflineCredentials.Api)9 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)9 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)9 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)9 DEFAULT_CONFIGURATION_FILENAME (com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME)9 Credential (com.google.api.client.auth.oauth2.Credential)9 RemoteException (java.rmi.RemoteException)9 Parameter (com.beust.jcommander.Parameter)6 Operator (com.google.api.ads.adwords.axis.v201809.cm.Operator)6 List (java.util.List)6 ArgumentNames (com.google.api.ads.adwords.lib.utils.examples.ArgumentNames)5 CodeSampleParams (com.google.api.ads.common.lib.utils.examples.CodeSampleParams)5 ArrayList (java.util.ArrayList)5 Arrays (java.util.Arrays)5