use of com.google.api.ads.adwords.axis.v201809.cm.Operation in project googleads-java-lib by googleads.
the class AddAudience 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 UserListService.
AdwordsUserListServiceInterface userListService = adWordsServices.get(session, AdwordsUserListServiceInterface.class);
// Get the ConversionTrackerService.
ConversionTrackerServiceInterface conversionTrackerService = adWordsServices.get(session, ConversionTrackerServiceInterface.class);
// Create conversion type (tag).
UserListConversionType conversionType = new UserListConversionType();
conversionType.setName("Mars cruise customers #" + System.currentTimeMillis());
// Create remarketing user list.
BasicUserList userList = new BasicUserList();
userList.setName("Mars cruise customers #" + System.currentTimeMillis());
userList.setDescription("A list of mars cruise customers in the last year");
userList.setMembershipLifeSpan(365L);
userList.setConversionTypes(new UserListConversionType[] { conversionType });
// You can optionally provide these field(s).
userList.setStatus(UserListMembershipStatus.OPEN);
// Create operations.
UserListOperation operation = new UserListOperation();
operation.setOperand(userList);
operation.setOperator(Operator.ADD);
UserListOperation[] operations = new UserListOperation[] { operation };
// Add user list.
UserListReturnValue result = userListService.mutate(operations);
// Display results.
// Capture the ID(s) of the conversion.
List<String> conversionIds = new ArrayList<>();
for (UserList userListResult : result.getValue()) {
if (userListResult instanceof BasicUserList) {
BasicUserList remarketingUserList = (BasicUserList) userListResult;
for (UserListConversionType userListConversionType : remarketingUserList.getConversionTypes()) {
conversionIds.add(userListConversionType.getId().toString());
}
}
}
// Create predicate and selector.
Selector selector = new SelectorBuilder().fields("Id", "GoogleGlobalSiteTag", "GoogleEventSnippet").in(AdwordsUserListField.Id, conversionIds.toArray(new String[0])).build();
// Get all conversion trackers.
Map<Long, AdWordsConversionTracker> conversionTrackers = new HashMap<Long, AdWordsConversionTracker>();
ConversionTrackerPage page = conversionTrackerService.get(selector);
if (page != null && page.getEntries() != null) {
conversionTrackers = Arrays.stream(page.getEntries()).collect(Collectors.toMap(conversionTracker -> conversionTracker.getId(), conversionTracker -> (AdWordsConversionTracker) conversionTracker));
}
// Display user lists.
for (UserList userListResult : result.getValue()) {
System.out.printf("User list with name '%s' and ID %d was added.%n", userListResult.getName(), userListResult.getId());
// Display user list associated conversion code snippets.
if (userListResult instanceof BasicUserList) {
BasicUserList remarketingUserList = (BasicUserList) userListResult;
for (UserListConversionType userListConversionType : remarketingUserList.getConversionTypes()) {
ConversionTracker conversionTracker = conversionTrackers.get(userListConversionType.getId());
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());
}
}
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.Operation 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());
}
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.Operation 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());
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.Operation in project googleads-java-lib by googleads.
the class AddSmartShoppingAd method createSmartShoppingCampaign.
/**
* Creates a Smart Shopping campaign.
*/
private static Campaign createSmartShoppingCampaign(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long budgetId, long merchantId) throws RemoteException {
CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
// Create a campaign with required and optional settings.
Campaign campaign = new Campaign();
campaign.setName("Smart Shopping campaign #" + System.currentTimeMillis());
// The advertisingChannelType is what makes this a Shopping campaign.
campaign.setAdvertisingChannelType(AdvertisingChannelType.SHOPPING);
// Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to
// make this a Smart Shopping campaign.
campaign.setAdvertisingChannelSubType(AdvertisingChannelSubType.SHOPPING_GOAL_OPTIMIZED_ADS);
// Recommendation: Set the campaign to PAUSED when creating it to stop
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
campaign.setStatus(CampaignStatus.PAUSED);
// Set a budget.
Budget budget = new Budget();
budget.setBudgetId(budgetId);
campaign.setBudget(budget);
// Set bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported.
BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MAXIMIZE_CONVERSION_VALUE);
campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
// All Shopping campaigns need a ShoppingSetting.
ShoppingSetting shoppingSetting = new ShoppingSetting();
shoppingSetting.setSalesCountry("US");
shoppingSetting.setMerchantId(merchantId);
campaign.setSettings(new Setting[] { shoppingSetting });
// Create operation.
CampaignOperation campaignOperation = new CampaignOperation();
campaignOperation.setOperand(campaign);
campaignOperation.setOperator(Operator.ADD);
// Make the mutate request.
CampaignReturnValue campaignAddResult = campaignService.mutate(new CampaignOperation[] { campaignOperation });
// Display result.
campaign = campaignAddResult.getValue(0);
System.out.printf("Smart Shopping campaign with name '%s' and ID %d was added.%n", campaign.getName(), campaign.getId());
return campaign;
}
use of com.google.api.ads.adwords.axis.v201809.cm.Operation in project googleads-java-lib by googleads.
the class AddCampaignTargetingCriteria method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param campaignId the ID of the campaign where targeting criteria will be added.
* @param locationFeedId optional ID of a location targeting feed.
* @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 campaignId, @Nullable Long locationFeedId) throws RemoteException {
// Get the CampaignService.
CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session, CampaignCriterionServiceInterface.class);
// Create locations. The IDs can be found in the documentation or
// retrieved with the LocationCriterionService.
Location california = new Location();
california.setId(21137L);
Location mexico = new Location();
mexico.setId(2484L);
// Create languages. The IDs can be found in the documentation or
// retrieved with the ConstantDataService.
Language english = new Language();
english.setId(1000L);
Language spanish = new Language();
spanish.setId(1003L);
List<Criterion> criteria = new ArrayList<>(Arrays.asList(california, mexico, english, spanish));
// Distance targeting. Area of 10 miles around the locations in the location feed.
if (locationFeedId != null) {
LocationGroups radiusLocationGroup = new LocationGroups();
radiusLocationGroup.setFeedId(locationFeedId);
ConstantOperand radius = new ConstantOperand();
radius.setType(ConstantOperandConstantType.DOUBLE);
radius.setUnit(ConstantOperandUnit.MILES);
radius.setDoubleValue(10d);
LocationExtensionOperand distance = new LocationExtensionOperand();
distance.setRadius(radius);
Function radiusMatchingFunction = new Function();
radiusMatchingFunction.setOperator(FunctionOperator.IDENTITY);
radiusMatchingFunction.setLhsOperand(new FunctionArgumentOperand[] { distance });
radiusLocationGroup.setMatchingFunction(radiusMatchingFunction);
criteria.add(radiusLocationGroup);
}
// Create operations to add each of the criteria above.
List<CampaignCriterionOperation> operations = new ArrayList<>();
for (Criterion criterion : criteria) {
CampaignCriterionOperation operation = new CampaignCriterionOperation();
CampaignCriterion campaignCriterion = new CampaignCriterion();
campaignCriterion.setCampaignId(campaignId);
campaignCriterion.setCriterion(criterion);
operation.setOperand(campaignCriterion);
operation.setOperator(Operator.ADD);
operations.add(operation);
}
// Add a negative campaign criterion.
Keyword negativeKeyword = new Keyword();
negativeKeyword.setText("jupiter cruise");
negativeKeyword.setMatchType(KeywordMatchType.BROAD);
CampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
negativeCriterion.setCampaignId(campaignId);
negativeCriterion.setCriterion(negativeKeyword);
CampaignCriterionOperation operation = new CampaignCriterionOperation();
operation.setOperand(negativeCriterion);
operation.setOperator(Operator.ADD);
operations.add(operation);
CampaignCriterionReturnValue result = campaignCriterionService.mutate(operations.toArray(new CampaignCriterionOperation[operations.size()]));
// Display campaigns.
for (CampaignCriterion campaignCriterion : result.getValue()) {
System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, " + "and type '%s' was added.%n", campaignCriterion.getCampaignId(), campaignCriterion.getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType());
}
}
Aggregations