use of com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed in project googleads-java-lib by googleads.
the class MigrateToExtensionSettings 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 all of the feeds for the session's account.
List<Feed> feeds = getFeeds(adWordsServices, session);
for (Feed feed : feeds) {
// Retrieve all the sitelinks from the current feed.
Map<Long, SiteLinkFromFeed> feedItems = getSiteLinksFromFeed(adWordsServices, session, feed);
// Get all the instances where a sitelink from this feed has been added to a campaign.
List<CampaignFeed> campaignFeeds = getCampaignFeeds(adWordsServices, session, feed, PLACEHOLDER_SITELINKS);
Set<Long> allFeedItemsToDelete = Sets.newHashSet();
for (CampaignFeed campaignFeed : campaignFeeds) {
// Retrieve the sitelinks that have been associated with this campaign.
Set<Long> feedItemIds = getFeedItemIdsForCampaign(campaignFeed);
ExtensionSettingPlatform platformRestrictions = getPlatformRestictionsForCampaign(campaignFeed);
if (feedItemIds.isEmpty()) {
System.out.printf("Migration skipped for campaign feed with campaign ID %d " + "and feed ID %d because no mapped feed item IDs were found in the " + "campaign feed's matching function.%n", campaignFeed.getCampaignId(), campaignFeed.getFeedId());
} else {
// Delete the campaign feed that associates the sitelinks from the feed to the campaign.
deleteCampaignFeed(adWordsServices, session, campaignFeed);
// Create extension settings instead of sitelinks.
createExtensionSetting(adWordsServices, session, feedItems, campaignFeed, feedItemIds, platformRestrictions);
// Mark the sitelinks from the feed for deletion.
allFeedItemsToDelete.addAll(feedItemIds);
}
}
// Delete all the sitelinks from the feed.
deleteOldFeedItems(adWordsServices, session, allFeedItemsToDelete, feed);
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed in project googleads-java-lib by googleads.
the class MigrateToExtensionSettings method createExtensionSetting.
/**
* Creates the extension setting for a list of feed items.
*
* @param adWordsServices the AdWordsServices
* @param session the AdWordsSession
* @param feedItems the list of all feed items
* @param campaignFeed the original campaign feed
* @param feedItemIds IDs of the feed items for which extension settings should be created
* @param platformRestrictions the platform restrictions for the new campaign extension setting
*/
private static void createExtensionSetting(AdWordsServicesInterface adWordsServices, AdWordsSession session, Map<Long, SiteLinkFromFeed> feedItems, CampaignFeed campaignFeed, Set<Long> feedItemIds, ExtensionSettingPlatform platformRestrictions) throws RemoteException {
// Get the CampaignExtensionSettingService.
CampaignExtensionSettingServiceInterface campaignExtensionSettingService = adWordsServices.get(session, CampaignExtensionSettingServiceInterface.class);
CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting();
campaignExtensionSetting.setCampaignId(campaignFeed.getCampaignId());
campaignExtensionSetting.setExtensionType(FeedType.SITELINK);
ExtensionSetting extensionSetting = new ExtensionSetting();
List<ExtensionFeedItem> extensionFeedItems = new ArrayList<>();
for (Long feedItemId : feedItemIds) {
SiteLinkFromFeed siteLinkFromFeed = feedItems.get(feedItemId);
SitelinkFeedItem siteLinkFeedItem = new SitelinkFeedItem();
siteLinkFeedItem.setSitelinkText(siteLinkFromFeed.text);
if (siteLinkFromFeed.finalUrls != null && siteLinkFromFeed.finalUrls.length > 0) {
siteLinkFeedItem.setSitelinkFinalUrls(new UrlList(siteLinkFromFeed.finalUrls));
if (siteLinkFromFeed.finalMobileUrls != null && siteLinkFromFeed.finalMobileUrls.length > 0) {
siteLinkFeedItem.setSitelinkFinalMobileUrls(new UrlList(siteLinkFromFeed.finalMobileUrls));
}
siteLinkFeedItem.setSitelinkTrackingUrlTemplate(siteLinkFromFeed.trackingUrlTemplate);
} else {
siteLinkFeedItem.setSitelinkUrl(siteLinkFromFeed.url);
}
siteLinkFeedItem.setSitelinkLine2(siteLinkFromFeed.line2);
siteLinkFeedItem.setSitelinkLine3(siteLinkFromFeed.line3);
extensionFeedItems.add(siteLinkFeedItem);
}
extensionSetting.setExtensions(extensionFeedItems.toArray(new ExtensionFeedItem[extensionFeedItems.size()]));
extensionSetting.setPlatformRestrictions(platformRestrictions);
campaignExtensionSetting.setExtensionSetting(extensionSetting);
CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation();
operation.setOperand(campaignExtensionSetting);
operation.setOperator(Operator.ADD);
campaignExtensionSettingService.mutate(new CampaignExtensionSettingOperation[] { operation });
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed in project googleads-java-lib by googleads.
the class MigrateToExtensionSettings method getFeedItemIdsForCampaign.
/**
* Returns the list of feed item IDs that are used by a campaign through a given campaign feed.
*/
private static Set<Long> getFeedItemIdsForCampaign(CampaignFeed campaignFeed) throws RemoteException {
Set<Long> feedItemIds = Sets.newHashSet();
FunctionOperator functionOperator = campaignFeed.getMatchingFunction().getOperator();
if (FunctionOperator.IN.equals(functionOperator)) {
// Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}).
// Extract feed items if applicable.
feedItemIds.addAll(getFeedItemIdsFromArgument(campaignFeed.getMatchingFunction()));
} else if (FunctionOperator.AND.equals(functionOperator)) {
// Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}).
// Extract feed items if applicable.
Arrays.stream(campaignFeed.getMatchingFunction().getLhsOperand()).filter(FunctionOperand.class::isInstance).map(argument -> (FunctionOperand) argument).filter(operand -> FunctionOperator.IN.equals(operand.getValue().getOperator())).forEach(operand -> feedItemIds.addAll(getFeedItemIdsFromArgument(operand.getValue())));
} else {
// There are no other matching functions involving feed item IDs.
}
return feedItemIds;
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed in project googleads-java-lib by googleads.
the class MigrateToExtensionSettings method getCampaignFeeds.
/**
* Returns the campaign feeds that use a particular feed for a particular placeholder type.
*/
private static List<CampaignFeed> getCampaignFeeds(AdWordsServicesInterface adWordsServices, AdWordsSession session, Feed feed, int placeholderType) throws RemoteException {
// Get the CampaignFeedService.
CampaignFeedServiceInterface campaignFeedService = adWordsServices.get(session, CampaignFeedServiceInterface.class);
String query = String.format("SELECT CampaignId, MatchingFunction, PlaceholderTypes WHERE Status = 'ENABLED' " + "AND FeedId = %d AND PlaceholderTypes CONTAINS_ANY [%d]", feed.getId(), placeholderType);
List<CampaignFeed> campaignFeeds = new ArrayList<>();
int offset = 0;
CampaignFeedPage campaignFeedPage;
do {
String pageQuery = String.format(query + " LIMIT %d, %d", offset, PAGE_SIZE);
campaignFeedPage = campaignFeedService.query(pageQuery);
if (campaignFeedPage.getEntries() != null) {
campaignFeeds.addAll(Arrays.asList(campaignFeedPage.getEntries()));
}
offset += PAGE_SIZE;
} while (offset < campaignFeedPage.getTotalNumEntries());
return campaignFeeds;
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignFeed in project googleads-java-lib by googleads.
the class AddGoogleMyBusinessLocationExtensions method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param gmbEmailAddress the email address of the owner or manager of the GMB account.
* @param gmbAccessToken the OAuth2 access token for GMB.
* @param businessAccountIdentifier optional identifier of the Google My Business account. This is
* required when the {@code gmbEmailAddress} is a GMB manager.
* @throws ApiException if the API request failed with one or more service errors.
* @throws RemoteException if the API request failed due to other errors.
* @throws InterruptedException if the thread was interrupted while sleeping between retries.
*/
private static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, String gmbEmailAddress, String gmbAccessToken, @Nullable String businessAccountIdentifier) throws RemoteException, InterruptedException {
FeedServiceInterface feedService = adWordsServices.get(session, FeedServiceInterface.class);
// Create a feed that will sync to the Google My Business account specified
// by gmbEmailAddress. Do not add FeedAttributes to this object,
// as AdWords will add them automatically because this will be a
// system generated feed.
Feed gmbFeed = new Feed();
gmbFeed.setName("Google My Business feed #" + System.currentTimeMillis());
PlacesLocationFeedData feedData = new PlacesLocationFeedData();
feedData.setEmailAddress(gmbEmailAddress);
feedData.setBusinessAccountIdentifier(businessAccountIdentifier);
// Optional: specify labels to filter Google My Business listings. If
// specified, only listings that have any of the labels set are
// synchronized into FeedItems.
feedData.setLabelFilters(new String[] { "Stores in New York City" });
OAuthInfo oAuthInfo = new OAuthInfo();
oAuthInfo.setHttpMethod("GET");
oAuthInfo.setHttpRequestUrl(GetRefreshToken.ADWORDS_API_SCOPE);
oAuthInfo.setHttpAuthorizationHeader(String.format("Bearer %s", gmbAccessToken));
feedData.setOAuthInfo(oAuthInfo);
gmbFeed.setSystemFeedGenerationData(feedData);
// Since this feed's feed items will be managed by AdWords,
// you must set its origin to ADWORDS.
gmbFeed.setOrigin(FeedOrigin.ADWORDS);
// Create an operation to add the feed.
FeedOperation feedOperation = new FeedOperation();
feedOperation.setOperand(gmbFeed);
feedOperation.setOperator(Operator.ADD);
// Add the feed. Since it is a system generated feed, AdWords will automatically:
// 1. Set up the FeedAttributes on the feed.
// 2. Set up a FeedMapping that associates the FeedAttributes of the feed
// with the placeholder fields of the LOCATION placeholder type.
FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation });
Feed addedFeed = addFeedResult.getValue(0);
System.out.printf("Added GMB feed with ID %d%n", addedFeed.getId());
// Add a CustomerFeed that associates the feed with this customer for
// the LOCATION placeholder type.
CustomerFeed customerFeed = new CustomerFeed();
customerFeed.setFeedId(addedFeed.getId());
customerFeed.setPlaceholderTypes(new int[] { PLACEHOLDER_LOCATION });
// Create a matching function that will always evaluate to true.
Function customerMatchingFunction = new Function();
ConstantOperand constOperand = new ConstantOperand();
constOperand.setType(ConstantOperandConstantType.BOOLEAN);
constOperand.setBooleanValue(true);
customerMatchingFunction.setLhsOperand(new FunctionArgumentOperand[] { constOperand });
customerMatchingFunction.setOperator(FunctionOperator.IDENTITY);
customerFeed.setMatchingFunction(customerMatchingFunction);
// Create an operation to add the customer feed.
CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
customerFeedOperation.setOperand(customerFeed);
customerFeedOperation.setOperator(Operator.ADD);
CustomerFeedServiceInterface customerFeedService = adWordsServices.get(session, CustomerFeedServiceInterface.class);
// After the completion of the Feed ADD operation above the added feed will not be available
// for usage in a CustomerFeed until the sync between the AdWords and GMB accounts
// completes. The loop below will retry adding the CustomerFeed up to ten times with an
// exponential back-off policy.
CustomerFeed addedCustomerFeed = null;
int numberOfAttempts = 0;
do {
numberOfAttempts++;
try {
CustomerFeedReturnValue customerFeedResult = customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation });
addedCustomerFeed = customerFeedResult.getValue(0);
System.out.printf("Attempt #%d to add the CustomerFeed was successful%n", numberOfAttempts);
} catch (Exception e) {
// Wait using exponential backoff policy
long sleepSeconds = (long) Math.scalb(5, numberOfAttempts);
System.out.printf("Attempt #%d to add the CustomerFeed was not successful. " + "Waiting %d seconds before trying again.%n", numberOfAttempts, sleepSeconds);
Thread.sleep(sleepSeconds * 1000);
}
} while (numberOfAttempts < MAX_CUSTOMER_FEED_ADD_ATTEMPTS && addedCustomerFeed == null);
if (addedCustomerFeed == null) {
throw new RuntimeException("Could not create the CustomerFeed after " + MAX_CUSTOMER_FEED_ADD_ATTEMPTS + " attempts. Please retry " + "the CustomerFeed ADD operation later.");
}
System.out.printf("Added CustomerFeed for feed ID %d and placeholder type %d%n", addedCustomerFeed.getFeedId(), addedCustomerFeed.getPlaceholderTypes()[0]);
// OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at the Campaign
// level. This will be similar to the CampaignFeed in the AddSiteLinks example, except
// you can also filter based on the business name and category of each FeedItem
// by using a FeedAttributeOperand in your matching function.
// OPTIONAL: Create an AdGroupFeed for even more fine grained control over
// which feed items are used at the AdGroup level.
}
Aggregations