com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface Java Examples

The following examples show how to use com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AddMultiAssetResponsiveDisplayAd.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and uploads an {@link ImageAsset} for the specified URL.
 *
 * @return the ID of the {@link ImageAsset}.
 * @throws IOException if unable to read the image from the specified URL.
 */
private static long uploadImageAsset(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, String url)
    throws IOException {

  AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);

  // Create the image asset.
  ImageAsset image = new ImageAsset();
  // Optional: Provide a unique friendly name to identify your asset. If you specify the assetName
  // field, then both the asset name and the image being uploaded should be unique, and should not
  // match another ACTIVE asset in this customer account.
  // image.setAssetName("Image asset #" + System.currentTimeMillis());
  image.setImageData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));

  // Create the operation.
  AssetOperation operation = new AssetOperation();
  operation.setOperator(Operator.ADD);
  operation.setOperand(image);

  // Create the asset and return the ID.
  return assetService.mutate(new AssetOperation[] {operation}).getValue(0).getAssetId();
}
 
Example #2
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Uploads an image. */
private static long uploadImage(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, String url)
    throws IOException {
  MediaServiceInterface mediaService = adWordsServices.get(session, MediaServiceInterface.class);

  // Create image.
  Image image = new Image();
  image.setData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));
  image.setType(MediaMediaType.IMAGE);

  Media[] media = new Media[] {image};

  // Upload image.
  Media[] result = mediaService.upload(media);

  return result[0].getMediaId();
}
 
Example #3
Source File: AddSmartShoppingAd.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Creates a default product partition as an ad group criterion. */
private static void createDefaultPartition(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, long adGroupId)
    throws RemoteException {
  // Create an ad group criterion for 'All products' using the ProductPartitionTree utility.
  ProductPartitionTree productPartitionTree =
      ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroupId);
  List<AdGroupCriterionOperation> mutateOperations = productPartitionTree.getMutateOperations();

  // Make the mutate request.
  AdGroupCriterionServiceInterface adGroupCriterionService =
      adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
  AdGroupCriterionReturnValue adGroupCriterionResult =
      adGroupCriterionService.mutate(mutateOperations.toArray(new AdGroupCriterionOperation[0]));

  // Display result.
  for (AdGroupCriterion adGroupCriterion : adGroupCriterionResult.getValue()) {
    System.out.printf(
        "Ad group criterion with ID %d in ad group with ID %d was added.%n",
        adGroupCriterion.getCriterion().getId(), adGroupCriterion.getAdGroupId());
  }
}
 
Example #4
Source File: AddDynamicSearchAdsCampaign.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Creates the budget. */
private static Budget createBudget(
    AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException, ApiException {
  // Get the BudgetService.
  BudgetServiceInterface budgetService =
      adWordsServices.get(session, BudgetServiceInterface.class);

  // Create a budget, which can be shared by multiple campaigns.
  Budget sharedBudget = new Budget();
  sharedBudget.setName("Interplanetary Cruise #" + System.currentTimeMillis());
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(50000000L);
  sharedBudget.setAmount(budgetAmount);
  sharedBudget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(sharedBudget);
  budgetOperation.setOperator(Operator.ADD);

  // Add the budget
  Budget budget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
  return budget;
}
 
Example #5
Source File: UploadImage.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 * @throws IOException if unable to get media data from the URL.
 */
public static void runExample(
    AdWordsServicesInterface adWordsServices, AdWordsSession session) throws IOException {
  // Get the MediaService.
  MediaServiceInterface mediaService =
      adWordsServices.get(session, MediaServiceInterface.class);

  // Create image.
  Image image = new Image();
  image.setData(
      com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/3b9Wfh"));
  image.setType(MediaMediaType.IMAGE);

  Media[] media = new Media[] {image};

  // Upload image.
  Media[] result = mediaService.upload(media);

  // Display images.
  image = (Image) result[0];
  Map<MediaSize, Dimensions> dimensions = Maps.toMap(image.getDimensions());
  System.out.printf("Image with ID %d, dimensions %dx%d, and MIME type '%s' was "
      + "uploaded.%n", image.getMediaId(), dimensions.get(MediaSize.FULL).getWidth(),
      dimensions.get(MediaSize.FULL).getHeight(), image.getMediaType());
}
 
Example #6
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param budgetId the budget ID to use for the new campaign.
 * @param merchantId the Merchant Center ID for the new campaign.
 * @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 IOException if unable to get media data from the URL.
 */
public static void runExample(
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    Long budgetId,
    Long merchantId)
    throws IOException {
  Campaign campaign = createCampaign(adWordsServices, session, budgetId, merchantId);
  System.out.printf(
      "Campaign with name '%s' and ID %d was added.%n", campaign.getName(), campaign.getId());

  AdGroup adGroup = createAdGroup(adWordsServices, session, campaign);
  System.out.printf(
      "Ad group with name '%s' and ID %d was added.%n", adGroup.getName(), adGroup.getId());

  AdGroupAd adGroupAd = createShowcaseAd(adWordsServices, session, adGroup);
  System.out.printf("Showcase ad with ID %d was added.%n", adGroupAd.getAd().getId());

  ProductPartitionTree partitionTree =
      createProductPartitions(adWordsServices, session, adGroup.getId());
  System.out.printf("Final tree: %s%n", partitionTree);
}
 
Example #7
Source File: AddShoppingDynamicRemarketingCampaign.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the example.
 *
 * @param services the services factory.
 * @param session the session.
 * @param merchantId the ID of the merchant center account from which to source product feed data.
 * @param budgetId the ID of a shared budget to associate with the campaign.
 * @param userListId the ID of a user list to target.
 * @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 IOException if the ad images failed to load.
 */
private static void runExample(
    AdWordsServicesInterface services,
    AdWordsSession session,
    long merchantId,
    long budgetId,
    long userListId)
    throws IOException {
  Campaign campaign = createCampaign(services, session, merchantId, budgetId);
  System.out.printf(
      "Campaign with name '%s' and ID %d was added.%n", campaign.getName(), campaign.getId());

  AdGroup adGroup = createAdGroup(services, session, campaign);
  System.out.printf(
      "Ad group with name '%s' and ID %d was added.%n", adGroup.getName(), adGroup.getId());

  AdGroupAd adGroupAd = createAd(services, session, adGroup);
  System.out.printf("Responsive display ad with ID %d was added.%n", adGroupAd.getAd().getId());

  attachUserList(services, session, adGroup, userListId);
  System.out.printf(
      "User list with ID %d was attached to ad group with ID %d.%n", userListId, adGroup.getId());
}
 
Example #8
Source File: AddDynamicPageFeed.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param campaignId the ID of the campaign where the dynamic page feed will be added.
 * @param adGroupId the ID of the ad group where web page targeting will be added.
 * @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,
    Long adGroupId)
    throws RemoteException {
  String dsaPageUrlLabel = "discounts";

  // Get the page feed details. This code example creates a new feed, but you can
  // fetch and re-use an existing feed.
  DSAFeedDetails feedDetails = createFeed(adWordsServices, session);
  createFeedMapping(adWordsServices, session, feedDetails);
  createFeedItems(adWordsServices, session, feedDetails, dsaPageUrlLabel);

  // Associate the page feed with the campaign.
  updateCampaignDsaSetting(adWordsServices, session, campaignId, feedDetails);

  // Optional: Target web pages matching the feed's label in the ad group.
  addDsaTargeting(adWordsServices, session, adGroupId, dsaPageUrlLabel);

  System.out.printf("Dynamic page feed setup is complete for campaign ID %s.%n", campaignId);
}
 
Example #9
Source File: MigrateToExtensionSettings.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the feed items for a feed.
 */
private static List<FeedItem> getFeedItems(AdWordsServicesInterface adWordsServices,
    AdWordsSession session, Feed feed) throws RemoteException {
  // Get the FeedItemService.
  FeedItemServiceInterface feedItemService =
      adWordsServices.get(session, FeedItemServiceInterface.class);
  String query = String.format(
      "SELECT FeedItemId, AttributeValues WHERE Status = 'ENABLED' AND FeedId = %d",
      feed.getId());

  List<FeedItem> feedItems = new ArrayList<>();
  int offset = 0;
  FeedItemPage feedItemPage;

  do {
    String pageQuery = String.format(query + " LIMIT %d, %d", offset, PAGE_SIZE);
    feedItemPage = feedItemService.query(pageQuery);
    if (feedItemPage.getEntries() != null) {
      feedItems.addAll(Arrays.asList(feedItemPage.getEntries()));
    }
    offset += PAGE_SIZE;
  } while (offset < feedItemPage.getTotalNumEntries());

  return feedItems;
}
 
Example #10
Source File: MigrateToExtensionSettings.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Deletes the old feed items for which extension settings have been created. */
private static void deleteOldFeedItems(
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    Set<Long> feedItemIds,
    Feed feed)
    throws RemoteException {
  // Get the FeedItemService.
  FeedItemServiceInterface feedItemService =
      adWordsServices.get(session, FeedItemServiceInterface.class);

  if (feedItemIds.isEmpty()) {
    return;
  }

  List<FeedItemOperation> operations = new ArrayList<>();
  for (Long feedItemId : feedItemIds) {
    FeedItemOperation operation = new FeedItemOperation();

    FeedItem feedItem = new FeedItem();
    feedItem.setFeedId(feed.getId());
    feedItem.setFeedItemId(feedItemId);

    operation.setOperand(feedItem);
    operation.setOperator(Operator.REMOVE);

    operations.add(operation);
  }

  feedItemService.mutate(operations.toArray(new FeedItemOperation[operations.size()]));
}
 
Example #11
Source File: RemoveAdGroup.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group to remove.
 * @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 adGroupId)
    throws RemoteException {
  // Get the AdGroupService.
  AdGroupServiceInterface adGroupService =
      adWordsServices.get(session, AdGroupServiceInterface.class);

  // Create ad group with REMOVED status.
  AdGroup adGroup = new AdGroup();
  adGroup.setId(adGroupId);
  adGroup.setStatus(AdGroupStatus.REMOVED);

  // Create operations.
  AdGroupOperation operation = new AdGroupOperation();
  operation.setOperand(adGroup);
  operation.setOperator(Operator.SET);

  AdGroupOperation[] operations = new AdGroupOperation[] {operation};

  // Remove ad group.
  AdGroupReturnValue result = adGroupService.mutate(operations);

  // Display ad groups.
  for (AdGroup adGroupResult : result.getValue()) {
    System.out.printf("Ad group with name '%s' and ID %d was removed.%n",
        adGroupResult.getName(), adGroupResult.getId());
  }
}
 
Example #12
Source File: UploadOfflineConversions.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param conversionName the name of the conversion tracker.
 * @param gClid the GCLID for the conversion.
 * @param conversionTime the date and time of the conversion.
 * @param conversionValue the value of the conversion.
 * @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,
    String conversionName, String gClid, String conversionTime,
    double conversionValue) throws RemoteException {

  // Get the OfflineConversionFeedService.
  OfflineConversionFeedServiceInterface offlineConversionFeedService =
      adWordsServices.get(session, OfflineConversionFeedServiceInterface.class);

  // Associate offline conversions with the existing named conversion tracker. If this tracker
  // was newly created, it may be a few hours before it can accept conversions.
  OfflineConversionFeed feed = new OfflineConversionFeed();
  feed.setConversionName(conversionName);
  feed.setConversionTime(conversionTime);
  feed.setConversionValue(conversionValue);
  feed.setGoogleClickId(gClid);

  OfflineConversionFeedOperation offlineConversionOperation =
      new OfflineConversionFeedOperation();
  offlineConversionOperation.setOperator(Operator.ADD);
  offlineConversionOperation.setOperand(feed);

  OfflineConversionFeedReturnValue offlineConversionReturnValue = offlineConversionFeedService
      .mutate(new OfflineConversionFeedOperation[] {offlineConversionOperation});

  OfflineConversionFeed newFeed = offlineConversionReturnValue.getValue(0);

  System.out.printf(
      "Uploaded offline conversion value of %.4f for Google Click ID '%s' to '%s'.%n",
      newFeed.getConversionValue(), newFeed.getGoogleClickId(), newFeed.getConversionName());
}
 
Example #13
Source File: AddSiteLinksUsingFeeds.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private static void createSiteLinksFeedItems(AdWordsServicesInterface adWordsServices,
    AdWordsSession session, SiteLinksDataHolder siteLinksData) throws RemoteException {
  // Get the FeedItemService.
  FeedItemServiceInterface feedItemService =
      adWordsServices.get(session, FeedItemServiceInterface.class);

  // Create operations to add FeedItems.
  FeedItemOperation home = newSiteLinkFeedItemAddOperation(siteLinksData, "Home",
      "http://www.example.com", "Home line 2", "Home line 3");
  FeedItemOperation stores = newSiteLinkFeedItemAddOperation(siteLinksData, "Stores",
      "http://www.example.com/stores", "Stores line 2", "Stores line 3");
  FeedItemOperation onSale = newSiteLinkFeedItemAddOperation(siteLinksData, "On Sale",
      "http://www.example.com/sale", "On Sale line 2", "On Sale line 3");
  FeedItemOperation support = newSiteLinkFeedItemAddOperation(siteLinksData, "Support",
      "http://www.example.com/support", "Support line 2", "Support line 3");
  FeedItemOperation products = newSiteLinkFeedItemAddOperation(siteLinksData, "Products",
      "http://www.example.com/prods", "Products line 2", "Products line 3");
  // This site link is using geographical targeting to use LOCATION_OF_PRESENCE.
  FeedItemOperation aboutUs = newSiteLinkFeedItemAddOperation(siteLinksData, "About Us",
      "http://www.example.com/about", "About Us line 2", "About Us line 3", true);

  FeedItemOperation[] operations =
      new FeedItemOperation[] {home, stores, onSale, support, products, aboutUs};

  FeedItemReturnValue result = feedItemService.mutate(operations);
  for (FeedItem item : result.getValue()) {
    System.out.printf("FeedItem with feedItemId %d was added.%n", item.getFeedItemId());
    siteLinksData.siteLinkFeedItemIds.add(item.getFeedItemId());
  }

  // Target the "aboutUs" sitelink to geographically target California.
  // See https://developers.google.com/adwords/api/docs/appendix/geotargeting for
  // location criteria for supported locations.
  restrictFeedItemToGeoTarget(adWordsServices, session, result.getValue(5), 21137L);
}
 
Example #14
Source File: CreateCompleteCampaignBothApisPhase1.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private void runExample(
    GoogleAdsClient googleAdsClient,
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    long customerId)
    throws RemoteException, UnsupportedEncodingException {
  CampaignBudget budget = createBudget(googleAdsClient, customerId);
  Campaign campaign = createCampaign(adWordsServices, session, budget);
  AdGroup adGroup = createAdGroup(adWordsServices, session, campaign);
  createTextAds(adWordsServices, session, adGroup, NUMBER_OF_ADS);
  createKeywords(adWordsServices, session, adGroup, KEYWORDS_TO_ADD);
}
 
Example #15
Source File: AddAdCustomizer.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Restricts the feed item to an ad group. */
private static void restrictFeedItemToAdGroup(
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    FeedItem feedItem,
    long adGroupId)
    throws RemoteException {
  // Get the FeedItemTargetingService.
  FeedItemTargetServiceInterface feedItemTargetService =
      adWordsServices.get(session, FeedItemTargetServiceInterface.class);
  FeedItemAdGroupTarget adGroupTarget = new FeedItemAdGroupTarget();
  adGroupTarget.setFeedId(feedItem.getFeedId());
  adGroupTarget.setFeedItemId(feedItem.getFeedItemId());
  adGroupTarget.setAdGroupId(adGroupId);

  FeedItemTargetOperation operation = new FeedItemTargetOperation();
  operation.setOperator(Operator.ADD);
  operation.setOperand(adGroupTarget);

  FeedItemTargetReturnValue returnValue =
      feedItemTargetService.mutate(new FeedItemTargetOperation[] {operation});
  FeedItemAdGroupTarget addedAdGroupTarget = (FeedItemAdGroupTarget) returnValue.getValue(0);
  System.out.printf(
      "Feed item target for feed ID %d and feed item ID %d "
          + "was created to restrict serving to ad group ID %d.%n",
      addedAdGroupTarget.getFeedId(),
      addedAdGroupTarget.getFeedItemId(),
      addedAdGroupTarget.getAdGroupId());
}
 
Example #16
Source File: UpdateExpandedTextAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adId the ID of the ad to update.
 * @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 adId)
    throws RemoteException {
  // Get the AdService.
  AdServiceInterface adService = adWordsServices.get(session, AdServiceInterface.class);

  // Creates an expanded text ad using the provided ad ID.
  ExpandedTextAd expandedTextAd = new ExpandedTextAd();
  expandedTextAd.setId(adId);
  // Updates some properties of the expanded text ad.
  expandedTextAd.setHeadlinePart1("Cruise to Pluto #" + System.currentTimeMillis());
  expandedTextAd.setHeadlinePart2("Tickets on sale now");
  expandedTextAd.setDescription("Best space cruise ever.");
  expandedTextAd.setFinalUrls(new String[] {"http://www.example.com/"});
  expandedTextAd.setFinalMobileUrls(new String[] {"http://www.example.com/mobile"});

  // Creates ad group ad operation and adds it to the list.
  AdOperation operation = new AdOperation();
  operation.setOperator(Operator.SET);
  operation.setOperand(expandedTextAd);

  // Updates the ad on the server.
  ExpandedTextAd updatedAd =
      (ExpandedTextAd) adService.mutate(new AdOperation[] {operation}).getValue(0);

  // Prints out some information.
  System.out.printf("Expanded text ad with ID %d was updated.%n", updatedAd.getId());
  System.out.printf(
      "Headline part 1 is '%s'.%nHeadline part 2 is '%s'.%nDescription is '%s'.%n",
      updatedAd.getHeadlinePart1(), updatedAd.getHeadlinePart2(), updatedAd.getDescription());
  System.out.printf(
      "Final URL is '%s'.%nFinal mobile URL is '%s'.%n",
      updatedAd.getFinalUrls()[0], updatedAd.getFinalMobileUrls()[0]);
}
 
Example #17
Source File: RemoveAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group for the ad.
 * @param adId the ID of the ad to remove.
 * @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 adGroupId, long adId)
    throws RemoteException {
  // Get the AdGroupAdService.
  AdGroupAdServiceInterface adGroupAdService =
      adWordsServices.get(session, AdGroupAdServiceInterface.class);

  // Create base class ad to avoid setting type specific fields.
  Ad ad = new Ad();
  ad.setId(adId);

  // Create ad group ad.
  AdGroupAd adGroupAd = new AdGroupAd();
  adGroupAd.setAdGroupId(adGroupId);
  adGroupAd.setAd(ad);

  // Create operations.
  AdGroupAdOperation operation = new AdGroupAdOperation();
  operation.setOperand(adGroupAd);
  operation.setOperator(Operator.REMOVE);

  AdGroupAdOperation[] operations = new AdGroupAdOperation[] {operation};

  // Remove ad.
  AdGroupAdReturnValue result = adGroupAdService.mutate(operations);

  // Display ads.
  for (AdGroupAd adGroupAdResult : result.getValue()) {
    System.out.printf("Ad with ID %d and type '%s' was removed.%n",
        adGroupAdResult.getAd().getId(), adGroupAdResult.getAd().getAdType());
  }
}
 
Example #18
Source File: AddSiteLinksUsingFeeds.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Restricts the first feed item in {@code siteLinksData} to only serve with ads for the specified
 * location ID.
 */
private static void restrictFeedItemToGeoTarget(
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    FeedItem feedItem,
    Long locationId)
    throws RemoteException {
  FeedItemTargetServiceInterface feedItemTargetService =
      adWordsServices.get(session, FeedItemTargetServiceInterface.class);
  // Optional: Restrict the feed item to only serve with ads for the specified geo target.
  FeedItemCriterionTarget feedItemCriterionTarget = new FeedItemCriterionTarget();
  feedItemCriterionTarget.setFeedId(feedItem.getFeedId());
  feedItemCriterionTarget.setFeedItemId(feedItem.getFeedItemId());
  Location location = new Location();
  // The IDs can be found in the documentation or retrieved with the LocationCriterionService.
  location.setId(locationId);
  feedItemCriterionTarget.setCriterion(location);

  FeedItemTargetOperation operation = new FeedItemTargetOperation();
  operation.setOperand(feedItemCriterionTarget);
  operation.setOperator(Operator.ADD);

  feedItemCriterionTarget =
      (FeedItemCriterionTarget)
          feedItemTargetService.mutate(new FeedItemTargetOperation[] {operation}).getValue(0);
  System.out.printf(
      "Feed item target for feed ID %d and feed item ID %d was created to restrict serving to "
          + "location ID %d'.%n",
      feedItemCriterionTarget.getFeedId(),
      feedItemCriterionTarget.getFeedItemId(),
      feedItemCriterionTarget.getCriterion().getId());
}
 
Example #19
Source File: CreateCompleteCampaignAdWordsApiOnly.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
  throws RemoteException, UnsupportedEncodingException {
  Budget budget = createBudget(adWordsServices, session);
  Campaign campaign = createCampaign(adWordsServices, session, budget);
  AdGroup adGroup = createAdGroup(adWordsServices, session, campaign);
  createTextAds(adWordsServices, session, adGroup, NUMBER_OF_ADS);
  createKeywords(adWordsServices, session, adGroup, KEYWORDS_TO_ADD);
}
 
Example #20
Source File: AddSmartShoppingAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a non-shared budget for a Smart Shopping campaign. Smart Shopping campaigns support
 * only non-shared budgets.
 */
private static Budget createBudget(
    AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
  BudgetServiceInterface budgetService =
      adWordsServices.get(session, BudgetServiceInterface.class);

  // Create a budget.
  Budget budget = new Budget();
  budget.setName("Interplanetary Cruise #" + System.currentTimeMillis());
  Money budgetAmount = new Money();
  // This budget equals 50.00 units of your account's currency, e.g.,
  // 50 USD if your currency is USD.
  budgetAmount.setMicroAmount(50_000_000L);
  budget.setAmount(budgetAmount);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);
  // Non-shared budgets are required for Smart Shopping campaigns.
  budget.setIsExplicitlyShared(false);

  // Create operation.
  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(budget);
  budgetOperation.setOperator(Operator.ADD);

  // Add the budget.
  Budget newBudget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
  System.out.printf(
      "Budget with name '%s' and ID %d was added.%n",
      newBudget.getName(), newBudget.getBudgetId());
  return newBudget;
}
 
Example #21
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Creates an ad group in the Shopping campaign. */
private static AdGroup createAdGroup(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, Campaign campaign)
    throws RemoteException {
  // Get the AdGroupService.
  AdGroupServiceInterface adGroupService =
      adWordsServices.get(session, AdGroupServiceInterface.class);

  // Create ad group.
  AdGroup adGroup = new AdGroup();
  adGroup.setCampaignId(campaign.getId());
  adGroup.setName("Ad Group #" + System.currentTimeMillis());

  // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
  adGroup.setAdGroupType(AdGroupType.SHOPPING_SHOWCASE_ADS);

  // Required: Set the ad group's bidding strategy configuration.
  // Note: Showcase ads require that the campaign has a ManualCpc BiddingStrategyConfiguration.
  BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();

  // Optional: Set the bids.
  Money bidAmount = new Money();
  bidAmount.setMicroAmount(100000L);
  CpcBid cpcBid = new CpcBid();
  cpcBid.setBid(bidAmount);
  biddingStrategyConfiguration.setBids(new Bids[] {cpcBid});

  adGroup.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

  // Create operation.
  AdGroupOperation adGroupOperation = new AdGroupOperation();
  adGroupOperation.setOperand(adGroup);
  adGroupOperation.setOperator(Operator.ADD);

  // Make the mutate request.
  AdGroupReturnValue adGroupAddResult =
      adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});

  return adGroupAddResult.getValue(0);
}
 
Example #22
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Creates a Showcase ad. */
private static AdGroupAd createShowcaseAd(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, AdGroup adGroup)
    throws IOException {
  // Create the Showcase ad.
  AdGroupAdServiceInterface adGroupAdService =
      adWordsServices.get(session, AdGroupAdServiceInterface.class);
  ShowcaseAd showcaseAd = new ShowcaseAd();
  showcaseAd.setName("Showcase ad #" + System.currentTimeMillis());
  showcaseAd.setFinalUrls(new String[] {"http://example.com/showcase"});
  showcaseAd.setDisplayUrl("example.com");

  // Required: Set the ad's expanded image.
  Image expandedImage = new Image();
  expandedImage.setMediaId(uploadImage(adWordsServices, session, "https://goo.gl/IfVlpF"));
  showcaseAd.setExpandedImage(expandedImage);

  // Optional: Set the collapsed image.
  Image collapsedImage = new Image();
  collapsedImage.setMediaId(uploadImage(adWordsServices, session, "https://goo.gl/NqTxAE"));
  showcaseAd.setCollapsedImage(collapsedImage);

  // Create ad group ad.
  AdGroupAd adGroupAd = new AdGroupAd();
  adGroupAd.setAdGroupId(adGroup.getId());
  adGroupAd.setAd(showcaseAd);

  // Create operation.
  AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
  adGroupAdOperation.setOperand(adGroupAd);
  adGroupAdOperation.setOperator(Operator.ADD);

  // Make the mutate request.
  AdGroupAdReturnValue adGroupAdAddResult =
      adGroupAdService.mutate(new AdGroupAdOperation[] {adGroupAdOperation});

  return adGroupAdAddResult.getValue(0);
}
 
Example #23
Source File: AddUniversalAppCampaign.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the budget for the campaign.
 *
 * @return the new budget.
 */
private static Long createBudget(AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException, ApiException {
  // Get the BudgetService.
  BudgetServiceInterface budgetService =
      adWordsServices.get(session, BudgetServiceInterface.class);

  // Create the campaign budget.
  Budget budget = new Budget();
  budget.setName("Interplanetary Cruise App Budget #" + System.currentTimeMillis());
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(50000000L);
  budget.setAmount(budgetAmount);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  // Universal app campaigns don't support shared budgets.
  budget.setIsExplicitlyShared(false);
  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(budget);
  budgetOperation.setOperator(Operator.ADD);

  // Add the budget
  Budget addedBudget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
  System.out.printf(
      "Budget with name '%s' and ID %d was created.%n",
      addedBudget.getName(), addedBudget.getBudgetId());
  return addedBudget.getBudgetId();
}
 
Example #24
Source File: AddSmartShoppingAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Smart Shopping ad group by setting the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.
 */
private static AdGroup createSmartShoppingAdGroup(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, long campaignId)
    throws RemoteException {
  // Get the AdGroupService.
  AdGroupServiceInterface adGroupService =
      adWordsServices.get(session, AdGroupServiceInterface.class);

  // Create ad group.
  AdGroup adGroup = new AdGroup();
  adGroup.setCampaignId(campaignId);
  adGroup.setName("Smart Shopping ad group #" + System.currentTimeMillis());

  // Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.
  adGroup.setAdGroupType(AdGroupType.SHOPPING_GOAL_OPTIMIZED_ADS);

  // Create operation.
  AdGroupOperation adGroupOperation = new AdGroupOperation();
  adGroupOperation.setOperand(adGroup);
  adGroupOperation.setOperator(Operator.ADD);

  // Make the mutate request.
  AdGroupReturnValue adGroupAddResult =
      adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});

  // Display result.
  adGroup = adGroupAddResult.getValue(0);
  System.out.printf(
      "Smart Shopping ad group with name '%s' and ID %d was added.%n",
      adGroup.getName(), adGroup.getId());

  return adGroup;
}
 
Example #25
Source File: ParallelReportDownload.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private ReportDownloadCallable(
    ImmutableAdWordsSession session,
    AdWordsServicesInterface adWordsServices,
    ReportDefinition reportDefinition,
    File reportOutputFile,
    ExponentialBackOff backOff) {
  this.session = session;
  this.adWordsServices = adWordsServices;
  this.reportDefinition = reportDefinition;
  this.reportOutputFile = reportOutputFile;
  this.backOff = backOff;
}
 
Example #26
Source File: UsePortfolioBiddingStrategy.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the bidding strategy object.
 *
 * @param adWordsServices the user to run the example with
 * @param session the AdWordsSession
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
private static SharedBiddingStrategy createBiddingStrategy(
    AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
  // Get the BiddingStrategyService, which loads the required classes.
  BiddingStrategyServiceInterface biddingStrategyService =
      adWordsServices.get(session, BiddingStrategyServiceInterface.class);

  // Create a portfolio bidding strategy.
  SharedBiddingStrategy portfolioBiddingStrategy = new SharedBiddingStrategy();
  portfolioBiddingStrategy.setName("Maximize Clicks" + System.currentTimeMillis());

  TargetSpendBiddingScheme biddingScheme = new TargetSpendBiddingScheme();
  // Optionally set additional bidding scheme parameters.
  biddingScheme.setBidCeiling(new Money(null, 2000000L));
  biddingScheme.setSpendTarget(new Money(null, 20000000L));

  portfolioBiddingStrategy.setBiddingScheme(biddingScheme);

  // Create operation.
  BiddingStrategyOperation operation = new BiddingStrategyOperation();
  operation.setOperand(portfolioBiddingStrategy);
  operation.setOperator(Operator.ADD);

  BiddingStrategyOperation[] operations = new BiddingStrategyOperation[] {operation};
  BiddingStrategyReturnValue result = biddingStrategyService.mutate(operations);

  SharedBiddingStrategy newBiddingStrategy = result.getValue(0);

  System.out.printf(
      "Portfolio bidding strategy with name '%s' and ID %d of type '%s' was created.%n",
      newBiddingStrategy.getName(), newBiddingStrategy.getId(),
      newBiddingStrategy.getBiddingScheme().getBiddingSchemeType());

  return newBiddingStrategy;
}
 
Example #27
Source File: CreateCompleteCampaignBothApisPhase3.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private void runExample(
    GoogleAdsClient googleAdsClient,
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    long customerId)
    throws RemoteException, UnsupportedEncodingException {
  CampaignBudget budget = createBudget(googleAdsClient, customerId);
  Campaign campaign = createCampaign(googleAdsClient, customerId, budget);
  AdGroup adGroup = createAdGroup(googleAdsClient, customerId, campaign);
  createTextAds(adWordsServices, session, adGroup, NUMBER_OF_ADS);
  createKeywords(adWordsServices, session, adGroup, KEYWORDS_TO_ADD);
}
 
Example #28
Source File: GetCampaignsByLabel.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param labelId the ID of the label.
 * @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 labelId)
    throws RemoteException {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  int offset = 0;

  // Create selector.
  SelectorBuilder builder = new SelectorBuilder();
  Selector selector = builder
      .fields(CampaignField.Id, CampaignField.Name, CampaignField.Labels)
      // Labels filtering is performed by ID. You can use containsAny to select campaigns with
      // any of the label IDs, containsAll to select campaigns with all of the label IDs, or
      // containsNone to select campaigns with none of the label IDs.
      .containsAny(CampaignField.Labels, labelId.toString())
      .orderAscBy(CampaignField.Name)
      .offset(offset)
      .limit(PAGE_SIZE)
      .build();

  CampaignPage page = null;
  do {
    // Get all campaigns.
    page = campaignService.get(selector);

    // Display campaigns.
    if (page.getEntries() != null) {
      for (Campaign campaign : page.getEntries()) {
        String labels =
            Joiner.on(", ")
                .join(
                    Lists.transform(
                        Lists.newArrayList(campaign.getLabels()),
                        label -> String.format("%d/%s", label.getId(), label.getName())));
        System.out.printf("Campaign found with name '%s' and ID %d and labels: %s.%n",
            campaign.getName(), campaign.getId(), labels);
      }
    } else {
      System.out.println("No campaigns were found.");
    }

    offset += PAGE_SIZE;
    selector = builder.increaseOffsetBy(PAGE_SIZE).build();
  } while (offset < page.getTotalNumEntries());
}
 
Example #29
Source File: AddCampaignLabels.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
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();

  AddCampaignLabelsParams params = new AddCampaignLabelsParams();
  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.campaignIds = Arrays.asList(
        Long.valueOf("INSERT_CAMPAIGN_ID_HERE"),
        Long.valueOf("INSERT_CAMPAIGN_ID_HERE"));
    params.labelId = Long.parseLong("INSERT_LABEL_ID_HERE");
  }

  try {
    runExample(adWordsServices, session, params.campaignIds, params.labelId);
  } 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);
  }
}
 
Example #30
Source File: SetAdParameters.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group of the keyword.
 * @param keywordId the ID of the keyword.
 * @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 adGroupId,
    Long keywordId)
    throws RemoteException {
  // Get the AdParamService.
  AdParamServiceInterface adParamService =
      adWordsServices.get(session, AdParamServiceInterface.class);

  // Create ad params.
  AdParam adParam1 = new AdParam();
  adParam1.setAdGroupId(adGroupId);
  adParam1.setCriterionId(keywordId);
  adParam1.setInsertionText("100");
  adParam1.setParamIndex(1);

  AdParam adParam2 = new AdParam();
  adParam2.setAdGroupId(adGroupId);
  adParam2.setCriterionId(keywordId);
  adParam2.setInsertionText("$40");
  adParam2.setParamIndex(2);

  // Create operations.
  AdParamOperation adParamOperation1 = new AdParamOperation();
  adParamOperation1.setOperand(adParam1);
  adParamOperation1.setOperator(Operator.SET);

  AdParamOperation adParamOperation2 = new AdParamOperation();
  adParamOperation2.setOperand(adParam2);
  adParamOperation2.setOperator(Operator.SET);

  AdParamOperation[] operations = new AdParamOperation[] {adParamOperation1, adParamOperation2};

  // Set ad parameters.
  AdParam[] adParams = adParamService.mutate(operations);

  // Display ad parameters.
  for (AdParam adParam : adParams) {
    System.out.printf("Ad parameter with ad group ID %d, criterion ID %d, insertion text "
        + "'%s', and parameter index %d was set.%n", adParam.getAdGroupId(), 
        adParam.getCriterionId(), adParam.getInsertionText(), adParam.getParamIndex());
  }
}