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.
420380
public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
    // Get the TrafficEstimatorService.
    TrafficEstimatorServiceInterface trafficEstimatorService =
        adWordsServices.get(session, TrafficEstimatorServiceInterface.class);

    // Create keywords. Refer to the TrafficEstimatorService documentation for the maximum
    // number of keywords that can be passed in a single request.
    //   https://developers.google.com/adwords/api/docs/reference/latest/TrafficEstimatorService
    List<Keyword> keywords = new ArrayList<Keyword>();

    Keyword marsCruiseKeyword = new Keyword();
    marsCruiseKeyword.setText("mars cruise");
    marsCruiseKeyword.setMatchType(KeywordMatchType.BROAD);
    keywords.add(marsCruiseKeyword);

    Keyword cheapCruiseKeyword = new Keyword();
    cheapCruiseKeyword.setText("cheap cruise");
    cheapCruiseKeyword.setMatchType(KeywordMatchType.PHRASE);
    keywords.add(cheapCruiseKeyword);

    Keyword cruiseKeyword = new Keyword();
    cruiseKeyword.setText("cruise");
    cruiseKeyword.setMatchType(KeywordMatchType.EXACT);
    keywords.add(cruiseKeyword);

    // Create a keyword estimate request for each keyword.
    List<KeywordEstimateRequest> keywordEstimateRequests =
        keywords.stream()
            .map(
                keyword -> {
                  KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest();
                  keywordEstimateRequest.setKeyword(keyword);
                  return keywordEstimateRequest;
                })
            .collect(Collectors.toList());

    // Add a negative keyword to the traffic estimate.
    KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest();
    negativeKeywordEstimateRequest.setKeyword(new Keyword(null, null, null, "hiking tour",
        KeywordMatchType.BROAD));
    negativeKeywordEstimateRequest.setIsNegative(true);
    keywordEstimateRequests.add(negativeKeywordEstimateRequest);

    // Create ad group estimate requests.
    List<AdGroupEstimateRequest> adGroupEstimateRequests = new ArrayList<AdGroupEstimateRequest>();
    AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest();
    adGroupEstimateRequest.setKeywordEstimateRequests(keywordEstimateRequests
        .toArray(new KeywordEstimateRequest[] {}));
    adGroupEstimateRequest.setMaxCpc(new Money(null, 1000000L));
    adGroupEstimateRequests.add(adGroupEstimateRequest);

    // Create campaign estimate requests.
    List<CampaignEstimateRequest> campaignEstimateRequests =
        new ArrayList<CampaignEstimateRequest>();
    CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest();
    campaignEstimateRequest.setAdGroupEstimateRequests(adGroupEstimateRequests
        .toArray(new AdGroupEstimateRequest[] {}));

    Location unitedStates = new Location();
    unitedStates.setId(2840L);
    Language english = new Language();
    english.setId(1000L);
    campaignEstimateRequest.setCriteria(new Criterion[] {unitedStates, english});
    campaignEstimateRequests.add(campaignEstimateRequest);

    // Create selector.
    TrafficEstimatorSelector selector = new TrafficEstimatorSelector();
    selector.setCampaignEstimateRequests(campaignEstimateRequests
        .toArray(new CampaignEstimateRequest[] {}));

    // Optional: Request a list of campaign level estimates segmented by platform.
    selector.setPlatformEstimateRequested(true);

    // Get traffic estimates.
    TrafficEstimatorResult result = trafficEstimatorService.get(selector);

    // Display traffic estimates.
    if (result != null
        && result.getCampaignEstimates() != null
        && result.getCampaignEstimates().length > 0) {
      CampaignEstimate campaignEstimate = result.getCampaignEstimates()[0];

      // Display the campaign level estimates segmented by platform.
      if (campaignEstimate.getPlatformEstimates() != null) {
        for (PlatformCampaignEstimate platformEstimate : campaignEstimate.getPlatformEstimates()) {
          String platformMessage =
              String.format(
                  "Results for the platform with ID %d and name '%s':%n",
                  platformEstimate.getPlatform().getId(),
                  platformEstimate.getPlatform().getPlatformName());
          displayMeanEstimates(
              platformMessage,
              platformEstimate.getMinEstimate(),
              platformEstimate.getMaxEstimate());
        }
      }

      // Display the keyword estimates.
      KeywordEstimate[] keywordEstimates =
          campaignEstimate.getAdGroupEstimates()[0].getKeywordEstimates();
      for (int i = 0; i < keywordEstimates.length; i++) {
        if (Boolean.TRUE.equals(keywordEstimateRequests.get(i).getIsNegative())) {
          continue;
        }

        Keyword keyword = keywordEstimateRequests.get(i).getKeyword();
        KeywordEstimate keywordEstimate = keywordEstimates[i];

        String keywordMessage =
            String.format(
                "Results for the keyword with text '%s' and match type '%s':%n",
                keyword.getText(), keyword.getMatchType());
        displayMeanEstimates(keywordMessage, keywordEstimate.getMin(), keywordEstimate.getMax());
      }
    } else {
      System.out.println("No traffic estimates were returned.");
    }
  }
462345
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, "");
  }
1038961
public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
    // Get the CampaignService.
    CampaignCriterionServiceInterface campaignCriterionService =
        adWordsServices.get(session, CampaignCriterionServiceInterface.class);

    int offset = 0;

    // Create selector.
    SelectorBuilder builder = new SelectorBuilder();
    Selector selector = builder
        .fields(
            CampaignCriterionField.CampaignId,
            CampaignCriterionField.Id,
            CampaignCriterionField.CriteriaType,
            CampaignCriterionField.PlatformName,
            CampaignCriterionField.LanguageName,
            CampaignCriterionField.LocationName,
            CampaignCriterionField.KeywordText)
        .in(CampaignCriterionField.CriteriaType, "KEYWORD", "LANGUAGE", "LOCATION", "PLATFORM")
        .offset(0)
        .limit(PAGE_SIZE)
        .build();

    CampaignCriterionPage page = null;
    do {
      page = campaignCriterionService.get(selector);

      if (page.getEntries() != null) {
        // Display campaigns.
        for (CampaignCriterion campaignCriterion : page.getEntries()) {
          System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, "
              + "and type '%s' was found.%n", campaignCriterion.getCampaignId(), campaignCriterion
              .getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType());
        }
      } else {
        System.out.println("No campaign criteria were found.");
      }
      offset += PAGE_SIZE;
      selector = builder.increaseOffsetBy(PAGE_SIZE).build();
    } while (offset < page.getTotalNumEntries());
  }
300318
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    ProposalServiceInterface proposalService =
        adManagerServices.get(session, ProposalServiceInterface.class);

    // Create a statement to select proposals.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("status = :status")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("status", ProposalStatus.PENDING_APPROVAL.toString());

    // Retrieve a small amount of proposals at a time, paging through
    // until all proposals have been retrieved.
    int totalResultSetSize = 0;
    do {
      ProposalPage page =
          proposalService.getProposalsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each proposal.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (Proposal proposal : page.getResults()) {
          System.out.printf(
              "%d) Proposal with ID %d and name '%s' was found.%n",
              i++,
              proposal.getId(),
              proposal.getName()
          );
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
1020389
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    ContactServiceInterface contactService =
        adManagerServices.get(session, ContactServiceInterface.class);

    // Create a statement to select contacts.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("status = :status")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("status", ContactStatus.UNINVITED.toString());

    // Retrieve a small amount of contacts at a time, paging through
    // until all contacts have been retrieved.
    int totalResultSetSize = 0;
    do {
      ContactPage page =
          contactService.getContactsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each contact.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (Contact contact : page.getResults()) {
          System.out.printf(
              "%d) Contact with ID %d and name '%s' was found.%n",
              i++,
              contact.getId(),
              contact.getName()
          );
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
356993
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the LabelService.
    LabelServiceInterface labelService =
        adManagerServices.get(session, LabelServiceInterface.class);

    // Create a competitive exclusion label.
    Label competitiveExclusionLabel = new Label();
    competitiveExclusionLabel.setName(
        "Car company label #" + new Random().nextInt(Integer.MAX_VALUE));
    competitiveExclusionLabel.setTypes(new LabelType[] {LabelType.COMPETITIVE_EXCLUSION});

    // Create an ad unit frequency cap label.
    Label adUnitFrequencyCapLabel = new Label();
    adUnitFrequencyCapLabel.setName(
        "Don't run too often label #" + new Random().nextInt(Integer.MAX_VALUE));
    adUnitFrequencyCapLabel.setTypes(new LabelType[] {LabelType.AD_UNIT_FREQUENCY_CAP});

    // Create the labels on the server.
    Label[] labels =
        labelService.createLabels(new Label[] {competitiveExclusionLabel, adUnitFrequencyCapLabel});

    for (Label createdLabel : labels) {
      System.out.printf("A label with ID %d and name '%s' was created.%n",
          createdLabel.getId(), createdLabel.getName());
    }
  }
32034
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);
    }
  }
798022
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the BaseRateService.
    BaseRateServiceInterface baseRateService =
        adManagerServices.get(session, BaseRateServiceInterface.class);

    // Create a statement to select all base rates.
    StatementBuilder statementBuilder = new StatementBuilder()
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Default for total result set size.
    int totalResultSetSize = 0;

    do {
      // Get base rates by statement.
      BaseRatePage page =
          baseRateService.getBaseRatesByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (BaseRate baseRate : page.getResults()) {
          System.out.printf("%d) Base rate with ID %d and type '%s',"
              + " belonging to rate card ID %d was found.%n", i++,
              baseRate.getId(), baseRate.getClass().getSimpleName(),
              baseRate.getRateCardId());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
398600
private static function createBudget(
        AdWordsServices $adWordsServices,
        AdWordsSession $session
    ) {
        $budgetService = $adWordsServices->get($session, BudgetService::class);

        // Create the shared budget (required).
        $budget = new Budget();
        $budget->setName('Interplanetary Cruise Budget #' . uniqid());
        $money = new Money();
        $money->setMicroAmount(50000000);
        $budget->setAmount($money);
        $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

        // Universal App campaigns don't support shared budgets.
        $budget->setIsExplicitlyShared(false);
        $operations = [];

        // Create a budget operation.
        $operation = new BudgetOperation();
        $operation->setOperand($budget);
        $operation->setOperator(Operator::ADD);
        $operations[] = $operation;

        // Create the budget on the server.
        $result = $budgetService->mutate($operations);
        $budget = $result->getValue()[0];

        printf(
            "Budget with name '%s' and ID %d was created.\n",
            $budget->getName(),
            $budget->getBudgetId()
        );


        return $budget->getBudgetId();
    }
821676
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the CmsMetadataService.
    CmsMetadataServiceInterface cmsMetadataService =
        adManagerServices.get(session, CmsMetadataServiceInterface.class);

    // Create a statement to select all CMS metadata keys.
    StatementBuilder statementBuilder =
        new StatementBuilder().orderBy("id ASC").limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Default for total result set size.
    int totalResultSetSize = 0;

    do {
      // Get CMS metadata keys by statement.
      CmsMetadataKeyPage page =
          cmsMetadataService.getCmsMetadataKeysByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (CmsMetadataKey cmsMetadataKey : page.getResults()) {
          System.out.printf(
              "%d) CMS metadata key with ID %d and name '%s' was found.%n",
              i++, cmsMetadataKey.getId(), cmsMetadataKey.getName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
418097
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the ContentService.
    ContentServiceInterface contentService =
        adManagerServices.get(session, ContentServiceInterface.class);

    // Create a statement to get all content.
    StatementBuilder statementBuilder =
        new StatementBuilder().orderBy("id ASC").limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Default for total result set size.
    int totalResultSetSize = 0;

    do {
      // Get content by statement.
      ContentPage page = contentService.getContentByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (Content content : page.getResults()) {
          System.out.printf(
              "%d) Content with ID %d and name '%s' was found.%n",
              i++, content.getId(), content.getName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
272350
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the ProductTemplateService.
    ProductTemplateServiceInterface productTemplateService =
        adManagerServices.get(session, ProductTemplateServiceInterface.class);

    // Create a statement to select all product templates.
    StatementBuilder statementBuilder = new StatementBuilder()
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Default for total result set size.
    int totalResultSetSize = 0;

    do {
      // Get product templates by statement.
      ProductTemplatePage page =
          productTemplateService.getProductTemplatesByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (ProductTemplate productTemplate : page.getResults()) {
          System.out.printf(
              "%d) Product template with ID %d and name '%s' was found.%n", i++,
              productTemplate.getId(), productTemplate.getName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
1123764
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the ProductPackageService.
    ProductPackageServiceInterface productPackageService =
        adManagerServices.get(session, ProductPackageServiceInterface.class);

    // Create a statement to select all product packages.
    StatementBuilder statementBuilder = new StatementBuilder()
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Default for total result set size.
    int totalResultSetSize = 0;

    do {
      // Get product packages by statement.
      ProductPackagePage page =
          productPackageService.getProductPackagesByStatement(
              statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (ProductPackage productPackage : page.getResults()) {
          System.out.printf(
              "%d) Product package with ID %d and name '%s' was found.%n",
              i++, productPackage.getId(), productPackage.getName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
1253795
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
      throws RemoteException {
    // Get the CustomerNegativeCriterionService.
    CustomerNegativeCriterionServiceInterface customerNegativeCriterionService =
        adWordsServices.get(session, CustomerNegativeCriterionServiceInterface.class);

    List<Criterion> criteria = new ArrayList<>();

    // Exclude tragedy & conflict content.
    ContentLabel tragedyContentLabel = new ContentLabel();
    tragedyContentLabel.setContentLabelType(ContentLabelType.TRAGEDY);
    criteria.add(tragedyContentLabel);

    // Exclude a specific placement.
    Placement placement = new Placement();
    placement.setUrl("http://www.example.com");
    criteria.add(placement);

    // Additional criteria types are available for this service. See the types listed
    // under Criterion here:
    // https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion

    // Create operations to add each of the criteria above.
    List<CustomerNegativeCriterionOperation> operations = new ArrayList<>();
    for (Criterion criterion : criteria) {
      CustomerNegativeCriterion negativeCriterion = new CustomerNegativeCriterion();
      negativeCriterion.setCriterion(criterion);
      CustomerNegativeCriterionOperation operation = new CustomerNegativeCriterionOperation();
      operation.setOperator(Operator.ADD);
      operation.setOperand(negativeCriterion);
      operations.add(operation);
    }

    // Send the request to add the criteria.
    CustomerNegativeCriterionReturnValue result =
        customerNegativeCriterionService.mutate(
            operations.toArray(new CustomerNegativeCriterionOperation[operations.size()]));

    // Display the results.
    for (CustomerNegativeCriterion negativeCriterion : result.getValue()) {
      System.out.printf(
          "Customer negative criterion with criterion ID %d and type '%s' was added.%n",
          negativeCriterion.getCriterion().getId(),
          negativeCriterion.getCriterion().getCriterionType());
    }
  }
950328
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;
  }
1319153
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    ActivityGroupServiceInterface activityGroupService =
        adManagerServices.get(session, ActivityGroupServiceInterface.class);

    // Create a statement to select activity groups.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("status = :status")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("status", ActivityGroupStatus.ACTIVE.toString());

    // Retrieve a small amount of activity groups at a time, paging through
    // until all activity groups have been retrieved.
    int totalResultSetSize = 0;
    do {
      ActivityGroupPage page =
          activityGroupService.getActivityGroupsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each activity group.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (ActivityGroup activityGroup : page.getResults()) {
          System.out.printf(
              "%d) Activity group with ID %d and name '%s' was found.%n",
              i++, activityGroup.getId(), activityGroup.getName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
1259052
private static void updateCampaignDsaSetting(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      Long campaignId,
      DSAFeedDetails feedDetails)
      throws ApiException, RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    Selector selector =
        new SelectorBuilder()
            .fields(CampaignField.Id, CampaignField.Settings)
            .equalsId(campaignId)
            .build();

    CampaignPage campaignPage = campaignService.get(selector);
    if (campaignPage.getEntries() == null || campaignPage.getTotalNumEntries() == 0) {
      throw new IllegalArgumentException("No campaign found with ID: " + campaignId);
    }
    Campaign campaign = campaignPage.getEntries(0);

    if (campaign.getSettings() == null) {
      throw new IllegalArgumentException(
          "Campaign with ID " + campaignId + " is not a DSA campaign.");
    }

    DynamicSearchAdsSetting dsaSetting =
        (DynamicSearchAdsSetting)
            Arrays.stream(campaign.getSettings())
                .filter(DynamicSearchAdsSetting.class::isInstance)
                .findFirst()
                .orElse(null);

    if (dsaSetting == null) {
      throw new IllegalArgumentException(
          "Campaign with ID " + campaignId + " is not a DSA campaign.");
    }

    // Use a page feed to specify precisely which URLs to use with your
    // Dynamic Search Ads.
    PageFeed pageFeed = new PageFeed();
    pageFeed.setFeedIds(new long[] {feedDetails.feedId});
    dsaSetting.setPageFeed(pageFeed);

    // Optional: Specify whether only the supplied URLs should be used with your
    // Dynamic Search Ads.
    dsaSetting.setUseSuppliedUrlsOnly(true);

    Campaign updatedCampaign = new Campaign();
    updatedCampaign.setId(campaignId);
    updatedCampaign.setSettings(campaign.getSettings());

    CampaignOperation operation = new CampaignOperation();
    operation.setOperand(updatedCampaign);
    operation.setOperator(Operator.SET);

    updatedCampaign = campaignService.mutate(new CampaignOperation[] {operation}).getValue(0);
    System.out.printf(
        "DSA page feed for campaign ID %d was updated with feed ID %d.%n",
        updatedCampaign.getId(), feedDetails.feedId);
  }