Java Code Examples for com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface#get()

The following examples show how to use com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface#get() . 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: 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 2
Source File: AddGmailAd.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: 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 5
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 6
Source File: UpdateCampaign.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 campaignId the ID of the campaign 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 campaignId)
    throws RemoteException {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  // Create campaign with updated status.
  Campaign campaign = new Campaign();
  campaign.setId(campaignId);
  campaign.setStatus(CampaignStatus.PAUSED);

  // Create operations.
  CampaignOperation operation = new CampaignOperation();
  operation.setOperand(campaign);
  operation.setOperator(Operator.SET);

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

  // Update campaign.
  CampaignReturnValue result = campaignService.mutate(operations);

  // Display campaigns.
  for (Campaign campaignResult : result.getValue()) {
    System.out.printf("Campaign with name '%s', ID %d, and budget delivery method '%s' "
        + "was updated.%n", campaignResult.getName(), campaignResult.getId(),
        campaignResult.getBudget().getDeliveryMethod());
  }
}
 
Example 7
Source File: AddAdCustomizer.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates expanded text ads that use ad customizations for the specified ad group IDs.
 */
private static void createAdsWithCustomizations(AdWordsServicesInterface adWordsServices,
    AdWordsSession session, List<Long> adGroupIds, String feedName) throws RemoteException {
  // Get the AdGroupAdService.
  AdGroupAdServiceInterface adGroupAdService =
      adWordsServices.get(session, AdGroupAdServiceInterface.class);

  ExpandedTextAd textAd = new ExpandedTextAd();
  textAd.setHeadlinePart1(String.format("Luxury Cruise to {=%s.Name}", feedName));
  textAd.setHeadlinePart2(String.format("Only {=%s.Price}", feedName));
  textAd.setDescription(String.format("Offer ends in {=countdown(%s.Date)}!", feedName));
  textAd.setFinalUrls(new String[] {"http://www.example.com"});

  // We add the same ad to both ad groups. When they serve, they will show different values, since
  // they match different feed items.
  List<AdGroupAdOperation> adGroupAdOperations = new ArrayList<>();
  for (Long adGroupId : adGroupIds) {
    AdGroupAd adGroupAd = new AdGroupAd();
    adGroupAd.setAdGroupId(adGroupId);
    adGroupAd.setAd(textAd);

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

    adGroupAdOperations.add(adGroupAdOperation);
  }

  AdGroupAdReturnValue adGroupAdReturnValue = adGroupAdService.mutate(
      adGroupAdOperations.toArray(new AdGroupAdOperation[adGroupAdOperations.size()]));

  for (AdGroupAd addedAd : adGroupAdReturnValue.getValue()) {
    System.out.printf("Created an ad with ID %d, type '%s' and status '%s'.%n",
        addedAd.getAd().getId(), addedAd.getAd().getAdType(), addedAd.getStatus());
  }
}
 
Example 8
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 9
Source File: AddAdGroupBidModifier.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 where bid modifiers 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 adGroupId) throws RemoteException {
  // Get the AdGroupBidModifierService.
  AdGroupBidModifierServiceInterface adGroupBidModifierService =
      adWordsServices.get(session, AdGroupBidModifierServiceInterface.class);

  // Create mobile platform. The ID can be found in the documentation.
  // https://developers.google.com/adwords/api/docs/appendix/platforms
  Platform mobile = new Platform();
  mobile.setId(30001L);

  AdGroupBidModifier adGroupBidModifier = new AdGroupBidModifier();
  adGroupBidModifier.setAdGroupId(adGroupId);
  adGroupBidModifier.setBidModifier(BID_MODIFIER);
  adGroupBidModifier.setCriterion(mobile);

  // Create ADD operation.
  AdGroupBidModifierOperation operation = new AdGroupBidModifierOperation();
  operation.setOperand(adGroupBidModifier);
  // Use 'ADD' to add a new modifier and 'SET' to update an existing one. A
  // modifier can be removed with the 'REMOVE' operator.
  operation.setOperator(Operator.ADD);

  // Update ad group bid modifier.
  AdGroupBidModifierReturnValue result =
      adGroupBidModifierService.mutate(new AdGroupBidModifierOperation[] {operation});
  for (AdGroupBidModifier bidModifierResult : result.getValue()) {
    System.out.printf(
        "Campaign ID %d, ad group ID %d was updated with ad group level modifier: %.4f%n",
        bidModifierResult.getCampaignId(), bidModifierResult.getAdGroupId(),
        bidModifierResult.getBidModifier());
  }
}
 
Example 10
Source File: AddSmartShoppingAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Creates a Smart Shopping ad. */
private static void createSmartShoppingAd(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, long adGroupId)
    throws RemoteException {
  AdGroupAdServiceInterface adGroupAdService =
      adWordsServices.get(session, AdGroupAdServiceInterface.class);

  // Create a Smart Shopping ad (Goal-optimized Shopping ad).
  GoalOptimizedShoppingAd smartShoppingAd = new GoalOptimizedShoppingAd();

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

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

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

  // Display result.
  adGroupAd = adGroupAdAddResult.getValue(0);

  System.out.printf("Smart Shopping ad with ID %d was added.%n", adGroupAd.getAd().getId());
}
 
Example 11
Source File: AddDynamicSearchAdsCampaign.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Creates the campaign. */
private static Campaign createCampaign(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, Budget budget)
    throws RemoteException, ApiException {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  // Create campaign.
  Campaign campaign = new Campaign();
  campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis());
  campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);

  // Recommendation: Set the campaign to PAUSED when creating it to prevent
  // the ads from immediately serving. Set to ENABLED once you've added
  // targeting and the ads are ready to serve.
  campaign.setStatus(CampaignStatus.PAUSED);

  BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
  biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
  campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

  // Only the budgetId should be sent, all other fields will be ignored by CampaignService.
  Budget campaignBudget = new Budget();
  campaignBudget.setBudgetId(budget.getBudgetId());
  campaign.setBudget(campaignBudget);

  // Required: Set the campaign's Dynamic Search Ads settings.
  DynamicSearchAdsSetting dynamicSearchAdsSetting = new DynamicSearchAdsSetting();
  // Required: Set the domain name and language.
  dynamicSearchAdsSetting.setDomainName("example.com");
  dynamicSearchAdsSetting.setLanguageCode("en");

  // Set the campaign settings.
  campaign.setSettings(new Setting[] {dynamicSearchAdsSetting});

  // Optional: Set the start date.
  campaign.setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"));
  // Optional: Set the end date.
  campaign.setEndDate(new DateTime().plusYears(1).toString("yyyyMMdd"));

  // Create the operation.
  CampaignOperation operation = new CampaignOperation();
  operation.setOperand(campaign);
  operation.setOperator(Operator.ADD);

  // Add the campaign.
  Campaign newCampaign = campaignService.mutate(new CampaignOperation[] {operation}).getValue(0);

  // Display the results.
  System.out.printf(
      "Campaign with name '%s' and ID %d was added.%n",
      newCampaign.getName(), newCampaign.getId());

  return newCampaign;
}
 
Example 12
Source File: GetCampaignCriterionBidModifierSimulations.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 campaignId the ID of the 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.
 */
public static void runExample(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId)
    throws RemoteException {
  // Get the DataService.
  DataServiceInterface dataService = adWordsServices.get(session, DataServiceInterface.class);

  // Create selector.
  Selector selector =
      new SelectorBuilder()
          .fields(
              DataField.BidModifier,
              DataField.CampaignId,
              DataField.CriterionId,
              DataField.StartDate,
              DataField.EndDate,
              DataField.LocalClicks,
              DataField.LocalCost,
              DataField.LocalImpressions,
              DataField.TotalLocalClicks,
              DataField.TotalLocalCost,
              DataField.TotalLocalImpressions,
              DataField.RequiredBudget)
          .equals(DataField.CampaignId, campaignId.toString())
          .limit(PAGE_SIZE)
          .build();

  // Display bid landscapes.
  int landscapePointsInPreviousPage = 0;
  int startIndex = 0;
  do {
    // Offset the start index by the number of landscape points in the last retrieved page,
    // NOT the number of entries (bid landscapes) in the page.
    startIndex += landscapePointsInPreviousPage;
    selector.getPaging().setStartIndex(startIndex);

    // Reset the count of landscape points in preparation for processing the next page.
    landscapePointsInPreviousPage = 0;

    // Request the next page of bid landscapes.
    CriterionBidLandscapePage page = dataService.getCampaignCriterionBidLandscape(selector);

    if (page.getEntries() != null) {
      for (CriterionBidLandscape criterionBidLandscape : page.getEntries()) {
        System.out.printf(
            "Found campaign-level criterion bid modifier landscape for"
                + " criterion with ID %d, start date '%s', end date '%s', and"
                + " landscape points:%n",
            criterionBidLandscape.getCriterionId(),
            criterionBidLandscape.getStartDate(),
            criterionBidLandscape.getEndDate());

        for (BidLandscapeLandscapePoint bidLandscapePoint :
            criterionBidLandscape.getLandscapePoints()) {
          landscapePointsInPreviousPage++;
          System.out.printf(
              "  {bid modifier: %.2f => clicks: %d, cost: %d, impressions: %d, "
                  + "total clicks: %d, total cost: %d, total impressions: %d, and "
                  + "required budget: %d%n",
              bidLandscapePoint.getBidModifier(),
              bidLandscapePoint.getClicks(),
              bidLandscapePoint.getCost().getMicroAmount(),
              bidLandscapePoint.getImpressions(),
              bidLandscapePoint.getTotalLocalClicks(),
              bidLandscapePoint.getTotalLocalCost().getMicroAmount(),
              bidLandscapePoint.getTotalLocalImpressions(),
              bidLandscapePoint.getRequiredBudget().getMicroAmount());
        }
      }
    }
  } while (landscapePointsInPreviousPage >= PAGE_SIZE);
}
 
Example 13
Source File: ProductPartitionTreeImpl.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new instance of this class by retrieving the product partitions of the
 * specified ad group. All parameters are required.
 */
static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services,
    AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
  // Get the AdGroupCriterionService.
  AdGroupCriterionServiceInterface criterionService =
      services.get(session, AdGroupCriterionServiceInterface.class);

  SelectorBuilder selectorBuilder = new SelectorBuilder()
      .fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(
          new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()]))
      .equals(AdGroupCriterionField.AdGroupId, adGroupId.toString())
      .equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION")
      .in(
          AdGroupCriterionField.Status,
          UserStatus.ENABLED.getValue(),
          UserStatus.PAUSED.getValue())
      .limit(PAGE_SIZE);

  AdGroupCriterionPage adGroupCriterionPage;

  // A multimap from each product partition ID to its direct children.
  ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
  int offset = 0;
  do {
    // Get the next page of results.
    adGroupCriterionPage = criterionService.get(selectorBuilder.build());

    if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
      for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
        ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
        parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
      }
      offset += adGroupCriterionPage.getEntries().length;
      selectorBuilder.increaseOffsetBy(PAGE_SIZE);
    }
  } while (offset < adGroupCriterionPage.getTotalNumEntries());

  // Construct the ProductPartitionTree from the parentIdMap.
  if (!parentIdMap.containsKey(null)) {
    Preconditions.checkState(parentIdMap.isEmpty(),
        "No root criterion found in the tree but the tree is not empty");
    return createEmptyAdGroupTree(adGroupId,
        getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
  }

  return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
}
 
Example 14
Source File: AddDynamicPageFeed.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Creates the feed for DSA page URLs. */
private static DSAFeedDetails createFeed(
    AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws ApiException, RemoteException {
  // Get the FeedService.
  FeedServiceInterface feedService = adWordsServices.get(session, FeedServiceInterface.class);

  // Create attributes.
  FeedAttribute urlAttribute = new FeedAttribute();
  urlAttribute.setType(FeedAttributeType.URL_LIST);
  urlAttribute.setName("Page URL");

  FeedAttribute labelAttribute = new FeedAttribute();
  labelAttribute.setType(FeedAttributeType.STRING_LIST);
  labelAttribute.setName("Label");

  // Create the feed.
  Feed dsaPageFeed = new Feed();
  dsaPageFeed.setName("DSA Feed #" + System.currentTimeMillis());
  dsaPageFeed.setAttributes(new FeedAttribute[] {urlAttribute, labelAttribute});
  dsaPageFeed.setOrigin(FeedOrigin.USER);

  // Create operation.
  FeedOperation operation = new FeedOperation();
  operation.setOperand(dsaPageFeed);
  operation.setOperator(Operator.ADD);

  // Add the feed.
  Feed newFeed = feedService.mutate(new FeedOperation[] {operation}).getValue(0);

  DSAFeedDetails feedDetails = new DSAFeedDetails();
  feedDetails.feedId = newFeed.getId();
  FeedAttribute[] savedAttributes = newFeed.getAttributes();
  feedDetails.urlAttributeId = savedAttributes[0].getId();
  feedDetails.labelAttributeId = savedAttributes[1].getId();
  System.out.printf(
      "Feed with name '%s' and ID %d with urlAttributeId %d"
          + " and labelAttributeId %d was created.%n",
      newFeed.getName(),
      feedDetails.feedId,
      feedDetails.urlAttributeId,
      feedDetails.labelAttributeId);
  return feedDetails;
}
 
Example 15
Source File: GetProductCategoryTaxonomy.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.
 * @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 constant data service.
  ConstantDataServiceInterface constantDataService =
      adWordsServices.get(session, ConstantDataServiceInterface.class);
  
  Selector selector = new SelectorBuilder()
    .equals(ConstantDataField.Country, "US")
    .build();
  
  ProductBiddingCategoryData[] results =
      constantDataService.getProductBiddingCategoryData(selector);
  
  // List of top level category nodes.
  List<CategoryNode> rootCategories = new ArrayList<>();
  // Map of category ID to category node for all categories found in the results.
  Map<Long, CategoryNode> biddingCategories = Maps.newHashMap();
  
  for (ProductBiddingCategoryData productBiddingCategoryData : results) {
    Long id = productBiddingCategoryData.getDimensionValue().getValue();
    String name = productBiddingCategoryData.getDisplayValue(0).getValue();
    CategoryNode node = biddingCategories.get(id);
    if (node == null) {
      node = new CategoryNode(id, name);
      biddingCategories.put(id, node);
    } else if (node.name == null) {
      // Ensure that the name attribute for the node is set. Name will be null for nodes added
      // to biddingCategories as a result of being a parentNode below.
      node.name = name;
    }

    if (productBiddingCategoryData.getParentDimensionValue() != null
        && productBiddingCategoryData.getParentDimensionValue().getValue() != null) {
      Long parentId = productBiddingCategoryData.getParentDimensionValue().getValue();
      CategoryNode parentNode = biddingCategories.get(parentId);
      if (parentNode == null) {
        parentNode = new CategoryNode(parentId);
        biddingCategories.put(parentId, parentNode);
      }
      parentNode.children.add(node);
    } else {
      rootCategories.add(node);
    }
  }
  displayCategories(rootCategories, "");
}
 
Example 16
Source File: AddProductScope.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 campaignId the ID of the shopping 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.
 */
public static void runExample(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId)
    throws RemoteException {
  // Get the campaign criterion service.
  CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session,
      CampaignCriterionServiceInterface.class);
  
  ProductScope productScope = new ProductScope();

  // This set of dimensions is for demonstration purposes only. It would be
  // extremely unlikely that you want to include so many dimensions in your
  // product scope.
  ProductBrand productBrand = new ProductBrand();
  productBrand.setValue("Nexus");

  ProductCanonicalCondition productCanonicalCondition = new ProductCanonicalCondition();
  productCanonicalCondition.setCondition(ProductCanonicalConditionCondition.NEW);

  ProductCustomAttribute productCustomAttribute = new ProductCustomAttribute();
  productCustomAttribute.setType(ProductDimensionType.CUSTOM_ATTRIBUTE_0);
  productCustomAttribute.setValue("my attribute value");

  ProductOfferId productOfferId = new ProductOfferId();
  productOfferId.setValue("book1");

  ProductType productTypeLevel1Media = new ProductType();
  productTypeLevel1Media.setType(ProductDimensionType.PRODUCT_TYPE_L1);
  productTypeLevel1Media.setValue("Media");

  ProductType productTypeLevel2Books = new ProductType();
  productTypeLevel2Books.setType(ProductDimensionType.PRODUCT_TYPE_L2);
  productTypeLevel2Books.setValue("Books");

  // The value for the bidding category is a fixed ID for the 'Luggage & Bags'
  // category. You can retrieve IDs for categories from the ConstantDataService.
  // See the 'GetProductCategoryTaxonomy' example for more details.
  ProductBiddingCategory productBiddingCategory = new ProductBiddingCategory();
  productBiddingCategory.setType(ProductDimensionType.BIDDING_CATEGORY_L1);
  productBiddingCategory.setValue(-5914235892932915235L);
  
  productScope.setDimensions(new ProductDimension[]{ productBrand, productCanonicalCondition,
      productCustomAttribute, productOfferId, productTypeLevel1Media, productTypeLevel2Books,
      productBiddingCategory});

  CampaignCriterion campaignCriterion = new CampaignCriterion();
  campaignCriterion.setCampaignId(campaignId);
  campaignCriterion.setCriterion(productScope);
  
  // Create operation.
  CampaignCriterionOperation criterionOperation = new CampaignCriterionOperation();
  criterionOperation.setOperand(campaignCriterion);
  criterionOperation.setOperator(Operator.ADD);
  
  // Make the mutate request.
  CampaignCriterionReturnValue result =
      campaignCriterionService.mutate(new CampaignCriterionOperation[] {criterionOperation});

  // Display the result.
  System.out.printf("Created a ProductScope criterion with ID %d.%n",
      result.getValue(0).getCriterion().getId());
}
 
Example 17
Source File: CreateAndAttachSharedKeywordSet.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 campaignId the ID of the campaign that will use the shared set.
 * @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) throws RemoteException {
  // Get the SharedSetService.
  SharedSetServiceInterface sharedSetService =
      adWordsServices.get(session, SharedSetServiceInterface.class);

  // Keywords to include in the shared set.
  List<String> keywords = Arrays.asList("mars cruise", "mars hotels");

  // Create the shared negative keyword set.
  SharedSet sharedSet = new SharedSet();
  sharedSet.setName("Negative keyword list #" + System.currentTimeMillis());
  sharedSet.setType(SharedSetType.NEGATIVE_KEYWORDS);

  SharedSetOperation sharedSetOperation = new SharedSetOperation();
  sharedSetOperation.setOperator(Operator.ADD);
  sharedSetOperation.setOperand(sharedSet);

  // Add the shared set.
  sharedSet = sharedSetService.mutate(new SharedSetOperation[] {sharedSetOperation}).getValue(0);

  System.out.printf("Shared set with ID %d and name '%s' was successfully added.%n",
      sharedSet.getSharedSetId(), sharedSet.getName());

  // Add negative keywords to the shared set.
  List<SharedCriterionOperation> sharedCriterionOperations = new ArrayList<>();
  for (String keyword : keywords) {
    Keyword keywordCriterion = new Keyword();
    keywordCriterion.setText(keyword);
    keywordCriterion.setMatchType(KeywordMatchType.BROAD);

    SharedCriterion sharedCriterion = new SharedCriterion();
    sharedCriterion.setCriterion(keywordCriterion);
    sharedCriterion.setNegative(true);
    sharedCriterion.setSharedSetId(sharedSet.getSharedSetId());

    SharedCriterionOperation sharedCriterionOperation = new SharedCriterionOperation();
    sharedCriterionOperation.setOperator(Operator.ADD);
    sharedCriterionOperation.setOperand(sharedCriterion);

    sharedCriterionOperations.add(sharedCriterionOperation);
  }

  // Get the SharedCriterionService.
  SharedCriterionServiceInterface sharedCriterionService =
      adWordsServices.get(session, SharedCriterionServiceInterface.class);

  SharedCriterionReturnValue sharedCriterionReturnValue =
      sharedCriterionService.mutate(sharedCriterionOperations.toArray(
          new SharedCriterionOperation[sharedCriterionOperations.size()]));

  for (SharedCriterion addedCriterion : sharedCriterionReturnValue.getValue()) {
    System.out.printf("Added shared criterion ID %d with text '%s' to shared set with ID %d.%n",
        addedCriterion.getCriterion().getId(),
        ((Keyword) addedCriterion.getCriterion()).getText(), addedCriterion.getSharedSetId());
  }

  // Attach the negative keyword shared set to the campaign.
  CampaignSharedSetServiceInterface campaignSharedSetService =
      adWordsServices.get(session, CampaignSharedSetServiceInterface.class);

  CampaignSharedSet campaignSharedSet = new CampaignSharedSet();
  campaignSharedSet.setCampaignId(campaignId);
  campaignSharedSet.setSharedSetId(sharedSet.getSharedSetId());

  CampaignSharedSetOperation campaignSharedSetOperation = new CampaignSharedSetOperation();
  campaignSharedSetOperation.setOperator(Operator.ADD);
  campaignSharedSetOperation.setOperand(campaignSharedSet);

  campaignSharedSet = campaignSharedSetService.mutate(
      new CampaignSharedSetOperation[] {campaignSharedSetOperation}).getValue(0);

  System.out.printf("Shared set ID %d was attached to campaign ID %d.%n",
      campaignSharedSet.getSharedSetId(), campaignSharedSet.getCampaignId());
}
 
Example 18
Source File: GetAllDisapprovedAdsWithAwql.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 to search for disapproved ads.
 * @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 AdGroupAdService.
  AdGroupAdServiceInterface adGroupAdService =
      adWordsServices.get(session, AdGroupAdServiceInterface.class);

  ServiceQuery serviceQuery =
      new ServiceQuery.Builder()
          .fields(AdGroupAdField.Id, AdGroupAdField.PolicySummary)
          .where(AdGroupAdField.AdGroupId).equalTo(adGroupId)
          .where(AdGroupAdField.CombinedApprovalStatus)
          .equalTo(PolicyApprovalStatus.DISAPPROVED.getValue())
          .orderBy(AdGroupAdField.Id, SortOrder.ASCENDING)
          .limit(0, PAGE_SIZE)
          .build();

  // Get all disapproved ads.
  AdGroupAdPage page = null;
  int disapprovedAdsCount = 0;
  do {
    serviceQuery.nextPage(page);
    page = adGroupAdService.query(serviceQuery.toString());

    // Display ads.
    for (AdGroupAd adGroupAd : page) {
      disapprovedAdsCount++;
      AdGroupAdPolicySummary policySummary = adGroupAd.getPolicySummary();
      System.out.printf(
          "Ad with ID %d and type '%s' was disapproved with the following "
              + "policy topic entries:%n",
          adGroupAd.getAd().getId(), adGroupAd.getAd().getAdType());
      // Display the policy topic entries related to the ad disapproval.
      for (PolicyTopicEntry policyTopicEntry : policySummary.getPolicyTopicEntries()) {
        System.out.printf(
            "  topic id: %s, topic name: '%s'%n",
            policyTopicEntry.getPolicyTopicId(), policyTopicEntry.getPolicyTopicName());
        // Display the attributes and values that triggered the policy topic.
        if (policyTopicEntry.getPolicyTopicEvidences() != null) {
          for (PolicyTopicEvidence evidence : policyTopicEntry.getPolicyTopicEvidences()) {
            System.out.printf("    evidence type: %s%n", evidence.getPolicyTopicEvidenceType());
            if (evidence.getEvidenceTextList() != null) {
              for (int i = 0; i < evidence.getEvidenceTextList().length; i++) {
                System.out.printf(
                    "      evidence text[%d]: %s%n", i, evidence.getEvidenceTextList(i));
              }
            }
          }
        }
      }
    }
  } while (serviceQuery.hasNext(page));

  System.out.printf("%d disapproved ads were found.%n", disapprovedAdsCount);
}
 
Example 19
Source File: CreateCompleteCampaignBothApisPhase3.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates text ads.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @param adGroup the ad group for the text ad.
 * @throws RemoteException if the API request failed due to other errors.
 */
private AdGroupAd[] createTextAds(
  AdWordsServicesInterface adWordsServices,
  AdWordsSession session,
  AdGroup adGroup,
  int numberOfAds)
  throws RemoteException {

  // Gets the AdGroupAdService.
  AdGroupAdServiceInterface adGroupAdService =
    adWordsServices.get(session, AdGroupAdServiceInterface.class);

  List<AdGroupAdOperation> operations = new ArrayList<>();

  for (int i = 0; i < numberOfAds; i++) {
    // Creates the expanded text ad.
    ExpandedTextAd expandedTextAd = new ExpandedTextAd();
    expandedTextAd.setDescription("Buy your tickets now!");
    expandedTextAd.setHeadlinePart1(String.format("Cruise #%d to Mars", i));
    expandedTextAd.setHeadlinePart2("Best Space Cruise Line");
    expandedTextAd.setFinalUrls(new String[] {"http://www.example.com/" + i});

    // Creates the ad group ad.
    AdGroupAd expandedTextAdGroupAd = new AdGroupAd();
    expandedTextAdGroupAd.setAdGroupId(adGroup.getId().getValue());
    expandedTextAdGroupAd.setAd(expandedTextAd);

    // Optional: sets the status.
    expandedTextAdGroupAd.setStatus(AdGroupAdStatus.PAUSED);

    // Creates the operation.
    AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
    adGroupAdOperation.setOperand(expandedTextAdGroupAd);
    adGroupAdOperation.setOperator(Operator.ADD);

    operations.add(adGroupAdOperation);
  }

  // Adds the ads.
  AdGroupAdReturnValue result =
    adGroupAdService.mutate(operations.toArray(new AdGroupAdOperation[0]));

  // Displays the ads.
  for (AdGroupAd adGroupAdResult : result.getValue()) {
    ExpandedTextAd newAd = (ExpandedTextAd) adGroupAdResult.getAd();
    System.out.printf(
      "Expanded text ad with ID %d "
        + "and headline '%s - %s' was created in ad group with ID %d.%n",
      newAd.getId(),
      newAd.getHeadlinePart1(),
      newAd.getHeadlinePart2(),
      adGroup.getId().getValue());
  }
  return result.getValue();
}
 
Example 20
Source File: AddSmartShoppingAd.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** 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;
}