public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the ContentMetadataKeyHierarchy service.
    ContentMetadataKeyHierarchyServiceInterface contentMetadataKeyHierarchyService =
        dfpServices.get(session, ContentMetadataKeyHierarchyServiceInterface.class);

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

    int totalResultSetSize = 0;

    do {
      // Get content metadata key hierarchies by statement.
      ContentMetadataKeyHierarchyPage page =
          contentMetadataKeyHierarchyService.getContentMetadataKeyHierarchiesByStatement(
              statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %d\n", totalResultSetSize);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the CompanyService.
    CompanyServiceInterface companyService =
        dfpServices.get(session, CompanyServiceInterface.class);

    // Create a statement to only select companies that are advertisers.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("type = :type")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("type", CompanyType.ADVERTISER.toString());

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

    do {
      // Get companies by statement.
      CompanyPage page = companyService.getCompaniesByStatement(statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %s\n", totalResultSetSize);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long lineItemId)
      throws Exception {
    // Get the ForecastService.
    ForecastServiceInterface forecastService =
        dfpServices.get(session, ForecastServiceInterface.class);

    // Get forecast for line item.
    AvailabilityForecastOptions options = new AvailabilityForecastOptions();
    options.setIncludeContendingLineItems(true);
    options.setIncludeTargetingCriteriaBreakdown(true);
    AvailabilityForecast forecast =
        forecastService.getAvailabilityForecastById(lineItemId, options);

    long matched = forecast.getMatchedUnits();
    double availablePercent = (forecast.getAvailableUnits() / (matched * 1.0)) * 100;
    String unitType = forecast.getUnitType().toString().toLowerCase();

    System.out.printf("%d %s matched.\n", matched, unitType);
    System.out.printf("%.2f%% %s available.\n", availablePercent, unitType);

    if (forecast.getPossibleUnits() != null) {
      double possiblePercent = (forecast.getPossibleUnits() / (matched * 1.0)) * 100;
      System.out.printf("%.2f%% %s possible.\n", possiblePercent, unitType);
    }

    System.out.printf(
        "%d contending line items.\n",
        forecast.getContendingLineItems() == null ? 0 : forecast.getContendingLineItems().length);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the UserService.
    UserServiceInterface userService = dfpServices.get(session, UserServiceInterface.class);

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

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

    do {
      // Get users by statement.
      UserPage page = userService.getUsersByStatement(statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %d\n", totalResultSetSize);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long packageId)
      throws Exception {
    // Get the PackageService.
    PackageServiceInterface packageService =
        dfpServices.get(session, PackageServiceInterface.class);

    // Create a statement to select a single package.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("id = :id")
            .orderBy("id ASC")
            .limit(1)
            .withBindVariableValue("id", packageId);

    // Get the package.
    PackagePage page = packageService.getPackagesByStatement(statementBuilder.toStatement());

    Package pkg = Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    // Update the comments of the package.
    pkg.setComments("This package is ready to be made into proposal line items.");

    // Update the package on the server.
    Package[] packages = packageService.updatePackages(new Package[] {pkg});

    for (Package updatedPackage : packages) {
      System.out.printf(
          "Package with ID %d and name '%s' was updated.%n",
          updatedPackage.getId(), updatedPackage.getName());
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, String emailAddress, String name)
      throws Exception {
    // Get the UserService.
    UserServiceInterface userService = dfpServices.get(session, UserServiceInterface.class);

    // Create a user.
    User traffickerUser = new User();
    traffickerUser.setEmail(emailAddress);
    traffickerUser.setName(name);
    traffickerUser.setPreferredLocale("en_US");

    // Set the system defined ID of the trafficker role.
    // To determine what other roles exist, run GetAllRoles.java.
    traffickerUser.setRoleId(-7L);

    // Create the user on the server.
    User[] users = userService.createUsers(new User[] {traffickerUser});

    for (User createdUser : users) {
      System.out.printf(
          "A user with ID \"%d\" and name \"%s\" was created.\n",
          createdUser.getId(), createdUser.getName());
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the PublisherQueryLanguageService.
    PublisherQueryLanguageServiceInterface pqlService =
        dfpServices.get(session, PublisherQueryLanguageServiceInterface.class);

    // Create statement to select all line items.
    StatementBuilder lineItemStatementBuilder =
        new StatementBuilder()
            .select("Id, Name, Status")
            .from("Line_Item")
            .orderBy("Id ASC")
            .offset(0)
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Create statement to select all ad units.
    StatementBuilder adUnitStatementBuilder =
        new StatementBuilder()
            .select("Id, Name")
            .from("Ad_Unit")
            .orderBy("Id ASC")
            .offset(0)
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    String lineItemFilePath =
        fetchMatchTable(lineItemStatementBuilder, pqlService, "Line-Item-Matchtable");
    String adUnitFilePath =
        fetchMatchTable(adUnitStatementBuilder, pqlService, "Ad-Unit-Matchtable");

    System.out.printf("Ad units saved to %s\n", adUnitFilePath);
    System.out.printf("Line items saved to %s\n", lineItemFilePath);
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long rateCardId, long productTemplateId)
      throws Exception {
    // Get the BaseRateService.
    BaseRateServiceInterface baseRateService =
        dfpServices.get(session, BaseRateServiceInterface.class);

    // Create a base rate for a product template.
    ProductTemplateBaseRate productTemplateBaseRate = new ProductTemplateBaseRate();

    // Set the rate card ID that the product template base rate belongs to.
    productTemplateBaseRate.setRateCardId(rateCardId);

    // Set the product template the base rate will be applied to.
    productTemplateBaseRate.setProductTemplateId(productTemplateId);

    // Create a rate worth $2 and set that on the product template base rate.
    Money rate = new Money();
    rate.setCurrencyCode("USD");
    rate.setMicroAmount(2000000L);
    productTemplateBaseRate.setRate(rate);

    // Create the product template base rate on the server.
    BaseRate[] baseRates =
        baseRateService.createBaseRates(new BaseRate[] {productTemplateBaseRate});

    for (BaseRate createdBaseRate : baseRates) {
      System.out.printf(
          "A product template base rate with ID %d and rate %.4f %s " + "was created.%n",
          createdBaseRate.getId(),
          (((ProductTemplateBaseRate) createdBaseRate).getRate().getMicroAmount() / 1000000f),
          ((ProductTemplateBaseRate) createdBaseRate).getRate().getCurrencyCode());
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long advertiserCompanyId) throws Exception {
    // Get the ActivityGroupService.
    ActivityGroupServiceInterface activityGroupService =
        dfpServices.get(session, ActivityGroupServiceInterface.class);

    // Create a short-term activity group.
    ActivityGroup shortTermActivityGroup = new ActivityGroup();
    shortTermActivityGroup.setName(
        "Short-term activity group #" + new Random().nextInt(Integer.MAX_VALUE));
    shortTermActivityGroup.setCompanyIds(new long[] {advertiserCompanyId});
    shortTermActivityGroup.setClicksLookback(1);
    shortTermActivityGroup.setImpressionsLookback(1);

    // Create a long-term activity group.
    ActivityGroup longTermActivityGroup = new ActivityGroup();
    longTermActivityGroup.setName(
        "Long-term activity group #" + new Random().nextInt(Integer.MAX_VALUE));
    longTermActivityGroup.setCompanyIds(new long[] {advertiserCompanyId});
    longTermActivityGroup.setClicksLookback(30);
    longTermActivityGroup.setImpressionsLookback(30);

    // Create the activity groups on the server.
    ActivityGroup[] activityGroups =
        activityGroupService.createActivityGroups(
            new ActivityGroup[] {shortTermActivityGroup, longTermActivityGroup});

    for (ActivityGroup createdActivityGroup : activityGroups) {
      System.out.printf(
          "An activity group with ID \"%d\" and name \"%s\" was created.\n",
          createdActivityGroup.getId(), createdActivityGroup.getName());
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the ReconciliationReportService.
    ReconciliationReportServiceInterface reconciliationReportService =
        dfpServices.get(session, ReconciliationReportServiceInterface.class);

    // Get the first day of last month.
    DateTime lastMonth = new DateTime().minusMonths(1).dayOfMonth().withMinimumValue();

    // Create a statement to select the last month's reconciliation report.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("startDate = :startDate")
            .orderBy("id ASC")
            .limit(1)
            .withBindVariableValue("startDate", lastMonth.toString("YYYY-MM-dd"));

    // Get the reconciliation report.
    ReconciliationReportPage page =
        reconciliationReportService.getReconciliationReportsByStatement(
            statementBuilder.toStatement());

    ReconciliationReport reconciliationReport =
        Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    System.out.printf(
        "Reconciliation report with ID \"%d\" for month %s/%s was found.%n",
        reconciliationReport.getId(),
        reconciliationReport.getStartDate().getMonth(),
        reconciliationReport.getStartDate().getYear());
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the CreativeService.
    CreativeServiceInterface creativeService =
        dfpServices.get(session, CreativeServiceInterface.class);

    // Create a statement to only select image creatives.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("creativeType = :creativeType")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("creativeType", ImageCreative.class.getSimpleName());

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

    do {
      // Get creatives by statement.
      CreativePage page = creativeService.getCreativesByStatement(statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %d\n", totalResultSetSize);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the PackageService.
    PackageServiceInterface packageService =
        dfpServices.get(session, PackageServiceInterface.class);

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

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

    do {
      // Get packages by statement.
      PackagePage page = packageService.getPackagesByStatement(statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the ExchangeRateService.
    ExchangeRateServiceInterface exchangeRateService =
        dfpServices.get(session, ExchangeRateServiceInterface.class);

    // Create an exchange rate.
    ExchangeRate exchangeRate = new ExchangeRate();

    // Set the currency code.
    exchangeRate.setCurrencyCode("AUD");

    // Set the direction of the conversion (from the network currency).
    exchangeRate.setDirection(ExchangeRateDirection.FROM_NETWORK);

    // Set the conversion value as 1.5 (this value is multiplied by 10,000,000,000)
    exchangeRate.setExchangeRate(15000000000L);

    // Do not refresh exchange rate from Google data. Update manually only.
    exchangeRate.setRefreshRate(ExchangeRateRefreshRate.FIXED);

    // Create the exchange rate on the server.
    ExchangeRate[] exchangeRates =
        exchangeRateService.createExchangeRates(new ExchangeRate[] {exchangeRate});

    for (ExchangeRate createdExchangeRate : exchangeRates) {
      System.out.printf(
          "An exchange rate with ID \"%d,\" currency code \"%s,\""
              + " direction \"%s,\" and exchange rate \"%.2f\" was created.%n",
          createdExchangeRate.getId(),
          createdExchangeRate.getCurrencyCode(),
          createdExchangeRate.getDirection().getValue(),
          (createdExchangeRate.getExchangeRate() / 10000000000f));
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, String currencyCode, long[] teamIds)
      throws Exception {
    // Get the RateCardService.
    RateCardServiceInterface rateCardService =
        dfpServices.get(session, RateCardServiceInterface.class);

    // Create a rate card.
    RateCard rateCard = new RateCard();
    rateCard.setName("RateCard #" + new Random().nextInt(Integer.MAX_VALUE));
    rateCard.setCurrencyCode(currencyCode);

    if (teamIds.length != 0) {
      rateCard.setAppliedTeamIds(teamIds);
    }

    // Create the rate card on the server.
    RateCard[] rateCards = rateCardService.createRateCards(new RateCard[] {rateCard});

    for (RateCard createdRateCard : rateCards) {
      System.out.printf(
          "A rate card with ID %d, name '%s', and currency code " + "'%s' was created.%n",
          createdRateCard.getId(), createdRateCard.getName(), createdRateCard.getCurrencyCode());
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long proposalLineItemId) throws Exception {
    // Get the ProposalLineItemService.
    ProposalLineItemServiceInterface proposalLineItemService =
        dfpServices.get(session, ProposalLineItemServiceInterface.class);

    // Create a statement to select a proposal line item.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("WHERE id = :id")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("id", proposalLineItemId);

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

    do {
      // Get proposal line items by statement.
      ProposalLineItemPage page =
          proposalLineItemService.getProposalLineItemsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (ProposalLineItem proposalLineItem : page.getResults()) {
          System.out.printf(
              "%d) Proposal line item with ID \"%d\" will be archived.%n",
              i++, proposalLineItem.getId());
        }
      }

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

    System.out.printf("Number of proposal line items to be archived: %d%n", totalResultSetSize);

    if (totalResultSetSize > 0) {
      // Remove limit and offset from statement.
      statementBuilder.removeLimitAndOffset();

      // Create action.
      com.google.api.ads.dfp.axis.v201505.ArchiveProposalLineItems action =
          new com.google.api.ads.dfp.axis.v201505.ArchiveProposalLineItems();

      // Perform action.
      UpdateResult result =
          proposalLineItemService.performProposalLineItemAction(
              action, statementBuilder.toStatement());

      if (result != null && result.getNumChanges() > 0) {
        System.out.printf("Number of proposal line items archived: %d%n", result.getNumChanges());
      } else {
        System.out.println("No proposal line items were archived.");
      }
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long customFieldId)
      throws Exception {
    // Get the CustomFieldService.
    CustomFieldServiceInterface customFieldService =
        dfpServices.get(session, CustomFieldServiceInterface.class);

    // Create a statement to select a custom field.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("WHERE id = :id")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("id", customFieldId);

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

    do {
      // Get custom fields by statement.
      CustomFieldPage page =
          customFieldService.getCustomFieldsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (CustomField customField : page.getResults()) {
          System.out.printf(
              "%d) Custom field with ID \"%d\" will be deactivated.\n", i++, customField.getId());
        }
      }

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

    System.out.printf("Number of custom fields to be deactivated: %d\n", totalResultSetSize);

    if (totalResultSetSize > 0) {
      // Remove limit and offset from statement.
      statementBuilder.removeLimitAndOffset();

      // Create action.
      com.google.api.ads.dfp.axis.v201511.DeactivateCustomFields action =
          new com.google.api.ads.dfp.axis.v201511.DeactivateCustomFields();

      // Perform action.
      UpdateResult result =
          customFieldService.performCustomFieldAction(action, statementBuilder.toStatement());

      if (result != null && result.getNumChanges() > 0) {
        System.out.printf("Number of custom fields deactivated: %d\n", result.getNumChanges());
      } else {
        System.out.println("No custom fields were deactivated.");
      }
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the InventoryService.
    InventoryServiceInterface inventoryService =
        dfpServices.get(session, InventoryServiceInterface.class);

    // Get the NetworkService.
    NetworkServiceInterface networkService =
        dfpServices.get(session, NetworkServiceInterface.class);

    // Set the parent ad unit's ID for all children ad units to be fetched from.
    String parentAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();

    // Create a statement to select ad units under the parent ad unit.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("parentId = :parentId")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("parentId", parentAdUnitId);

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

    do {
      // Get ad units by statement.
      AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %d\n", totalResultSetSize);
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long customTargetingValueId) throws Exception {
    // Get the CustomTargetingService.
    CustomTargetingServiceInterface customTargetingService =
        dfpServices.get(session, CustomTargetingServiceInterface.class);

    // Create a statement to get custom targeting values.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("WHERE id = :id")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("id", customTargetingValueId);

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

    do {
      // Get custom targeting values by statement.
      CustomTargetingValuePage page =
          customTargetingService.getCustomTargetingValuesByStatement(
              statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        CustomTargetingValue[] customTargetingValues = page.getResults();

        // Update each local custom targeting value object by changing its display
        // name.
        for (CustomTargetingValue customTargetingValue : customTargetingValues) {
          if (customTargetingValue.getDisplayName() == null) {
            customTargetingValue.setDisplayName(customTargetingValue.getName());
          }
          customTargetingValue.setDisplayName(
              customTargetingValue.getDisplayName() + " (Deprecated)");
        }

        // Update the custom targeting values on the server.
        customTargetingValues =
            customTargetingService.updateCustomTargetingValues(customTargetingValues);

        for (CustomTargetingValue updatedCustomTargetingValue : customTargetingValues) {
          System.out.printf(
              "Custom targeting value with ID %d, name '%s', and display name "
                  + "'%s' was updated.%n",
              updatedCustomTargetingValue.getId(),
              updatedCustomTargetingValue.getName(),
              updatedCustomTargetingValue.getDisplayName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the CustomTargetingService.
    CustomTargetingServiceInterface customTargetingService =
        dfpServices.get(session, CustomTargetingServiceInterface.class);

    // Get all custom targeting keys.
    List<Long> customTargetingKeyIds = getAllCustomTargetingKeyIds(dfpServices, session);

    // Create a statement to get all custom targeting values for a custom
    // targeting key.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("customTargetingKeyId = :customTargetingKeyId")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    int totalResultsCounter = 0;

    for (Long customTargetingKeyId : customTargetingKeyIds) {
      // Set the custom targeting key ID to select from.
      statementBuilder.withBindVariableValue("customTargetingKeyId", customTargetingKeyId);

      // Default for total result set size and offset.
      int totalResultSetSize = 0;
      statementBuilder.offset(0);

      do {
        // Get custom targeting values by statement.
        CustomTargetingValuePage page =
            customTargetingService.getCustomTargetingValuesByStatement(
                statementBuilder.toStatement());

        if (page.getResults() != null) {
          totalResultSetSize = page.getTotalResultSetSize();
          for (CustomTargetingValue customTargetingValue : page.getResults()) {
            System.out.printf(
                "%d) Custom targeting value with ID \"%d\", belonging to key "
                    + "with ID \"%d\", name \"%s\" and display name \"%s\" was found.\n",
                totalResultsCounter++,
                customTargetingValue.getId(),
                customTargetingValue.getCustomTargetingKeyId(),
                customTargetingValue.getName(),
                customTargetingValue.getDisplayName());
          }
        }

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

    System.out.printf("Number of results found: %d\n", totalResultsCounter);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long advertiserId)
      throws Exception {
    // Get the CreativeService.
    CreativeServiceInterface creativeService =
        dfpServices.get(session, CreativeServiceInterface.class);

    // Create creative size.
    Size size = new Size();
    size.setWidth(300);
    size.setHeight(250);
    size.setIsAspectRatio(false);

    // Create a custom creative.
    CustomCreative customCreative = new CustomCreative();
    customCreative.setName("Custom creative #" + new Random().nextInt(Integer.MAX_VALUE));
    customCreative.setAdvertiserId(advertiserId);
    customCreative.setDestinationUrl("http://google.com");
    customCreative.setSize(size);

    // Set the custom creative image asset.
    CustomCreativeAsset customCreativeAsset = new CustomCreativeAsset();
    customCreativeAsset.setMacroName("IMAGE_ASSET");
    customCreativeAsset.setAssetByteArray(
        Media.getMediaDataFromUrl(
            "http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg"));
    // Filenames must be unique.
    customCreativeAsset.setFileName(
        String.format("image%s.jpg", new Random().nextInt(Integer.MAX_VALUE)));
    customCreative.setCustomCreativeAssets(new CustomCreativeAsset[] {customCreativeAsset});

    // Set the HTML snippet using the custom creative asset macro.
    customCreative.setHtmlSnippet(
        "<a href='%%CLICK_URL_UNESC%%%%DEST_URL%%'>"
            + "<img src='%%FILE:"
            + customCreativeAsset.getMacroName()
            + "%%'/>"
            + "</a><br>Click above for great deals!");

    // Create the creative on the server.
    Creative[] creatives = creativeService.createCreatives(new Creative[] {customCreative});

    for (Creative createdCreative : creatives) {
      System.out.printf(
          "A creative with ID \"%d\", name \"%s\", and type \"%s\""
              + " was created and can be previewed at: %s\n",
          createdCreative.getId(),
          createdCreative.getName(),
          createdCreative.getCreativeType(),
          createdCreative.getPreviewUrl());
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long reconciliationReportId, long lineItemId)
      throws Exception {
    // Get the ReconciliationLineItemReportService.
    ReconciliationLineItemReportServiceInterface reconciliationLineItemReportService =
        dfpServices.get(session, ReconciliationLineItemReportServiceInterface.class);

    // Create a statement to select a reconciliation line item report.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("reconciliationReportId = :reconciliationReportId AND lineItemId = :lineItemId")
            .orderBy("lineItemId ASC")
            .limit(1)
            .withBindVariableValue("reconciliationReportId", reconciliationReportId)
            .withBindVariableValue("lineItemId", lineItemId);

    // Get reconciliation line item reports by statement.
    ReconciliationLineItemReportPage page =
        reconciliationLineItemReportService.getReconciliationLineItemReportsByStatement(
            statementBuilder.toStatement());

    ReconciliationLineItemReport lineItemReport =
        Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    // Add $10 to the computed billable revenue as an override.
    Money billableRevenue;
    if (PricingModel.NET.equals(lineItemReport.getPricingModel())) {
      billableRevenue = lineItemReport.getNetBillableRevenue();
    } else {
      billableRevenue = lineItemReport.getGrossBillableRevenue();
    }
    billableRevenue.setMicroAmount(billableRevenue.getMicroAmount() + 10000000L);

    BillableRevenueOverrides billableRevenueOverrides = new BillableRevenueOverrides();
    billableRevenueOverrides.setBillableRevenueOverride(billableRevenue);

    lineItemReport.setBillableRevenueOverrides(billableRevenueOverrides);

    ReconciliationLineItemReport[] updatedLineItemReports =
        reconciliationLineItemReportService.updateReconciliationLineItemReports(
            new ReconciliationLineItemReport[] {lineItemReport});

    for (ReconciliationLineItemReport updatedLineItemReport : updatedLineItemReports) {
      System.out.printf(
          "Reconciliation line item report for line item ID \"%d\" was "
              + "updated, with net billable revenue \"%.2f\" and reconciled volume \"%d\".%n",
          updatedLineItemReport.getLineItemId(),
          updatedLineItemReport.getNetBillableRevenue().getMicroAmount() / 1000000f,
          updatedLineItemReport.getReconciledVolume());
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the UserService.
    UserServiceInterface userService = dfpServices.get(session, UserServiceInterface.class);

    // Get all roles.
    Role[] roles = userService.getAllRoles();

    int i = 0;
    for (Role role : roles) {
      System.out.printf(
          "%d) Role with ID \"%d\" and name \"%s\" was found.\n",
          i++, role.getId(), role.getName());
    }

    System.out.printf("Number of results found: %d\n", roles.length);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
    // Get the PublisherQueryLanguageService.
    PublisherQueryLanguageServiceInterface pqlService =
        dfpServices.get(session, PublisherQueryLanguageServiceInterface.class);

    // Create statement to select all line items.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .select("Id, Name, Status")
            .from("Line_Item")
            .orderBy("Id ASC")
            .offset(0)
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

    // Default for result sets.
    ResultSet combinedResultSet = null;
    ResultSet resultSet;
    int i = 0;

    do {
      // Get all line items.
      resultSet = pqlService.select(statementBuilder.toStatement());

      // Combine result sets with previous ones.
      combinedResultSet =
          combinedResultSet == null
              ? resultSet
              : Pql.combineResultSets(combinedResultSet, resultSet);

      System.out.printf(
          "%d) %d line items beginning at offset %d were found.%n",
          i++,
          resultSet.getRows() == null ? 0 : resultSet.getRows().length,
          statementBuilder.getOffset());

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (resultSet.getRows() != null && resultSet.getRows().length > 0);

    // Change to your file location.
    String filePath = File.createTempFile("Line-Items-", ".csv").toString();

    // Write the result set to a CSV.
    CsvFiles.writeCsv(Pql.resultSetToStringArrayList(combinedResultSet), filePath);

    System.out.printf("Line items saved to: %s%n", filePath);
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long premiumRateId)
      throws Exception {
    // Get the PremiumRateService.
    PremiumRateServiceInterface premiumRateService =
        dfpServices.get(session, PremiumRateServiceInterface.class);

    // Create a statement to get a single premium rate.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("id = :id")
            .orderBy("id ASC")
            .limit(1)
            .withBindVariableValue("id", premiumRateId);

    // Get the premium rate.
    PremiumRatePage page =
        premiumRateService.getPremiumRatesByStatement(statementBuilder.toStatement());

    PremiumRate premiumRate = Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    // Create a flat fee based premium rate value with a 10% increase.
    PremiumRateValue flatFeePremiumRateValue = new PremiumRateValue();
    flatFeePremiumRateValue.setPremiumFeature(premiumRate.getPremiumFeature());
    flatFeePremiumRateValue.setRateType(RateType.CPM);
    flatFeePremiumRateValue.setAdjustmentSize(10000L);
    flatFeePremiumRateValue.setAdjustmentType(PremiumAdjustmentType.PERCENTAGE);

    // Update the premium rate's premiumRateValues to include a flat fee premium rate.
    List<PremiumRateValue> existingPremiumRateValues =
        ((premiumRate.getPremiumRateValues() != null)
            ? Lists.<PremiumRateValue>newArrayList(premiumRate.getPremiumRateValues())
            : Lists.<PremiumRateValue>newArrayList());

    existingPremiumRateValues.add(flatFeePremiumRateValue);
    premiumRate.setPremiumRateValues(existingPremiumRateValues.toArray(new PremiumRateValue[] {}));

    // Update the premium rate on the server.
    PremiumRate[] premiumRates =
        premiumRateService.updatePremiumRates(new PremiumRate[] {premiumRate});

    for (PremiumRate updatedPremiumRate : premiumRates) {
      System.out.printf(
          "Premium rate with ID \"%d\" associated with rate card id " + "\"%d\" was updated.%n",
          updatedPremiumRate.getId(), updatedPremiumRate.getRateCardId());
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long reconciliationLineItemReportId)
      throws Exception {
    // Get the ReconciliationLineItemReportService.
    ReconciliationLineItemReportServiceInterface reconciliationLineItemReportService =
        dfpServices.get(session, ReconciliationLineItemReportServiceInterface.class);

    // Create a statement to select a reconciliation line item report.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("id = :lineItemReportId")
            .orderBy("id ASC")
            .limit(1)
            .withBindVariableValue("lineItemReportId", reconciliationLineItemReportId);

    // Get reconciliation line item reports by statement.
    ReconciliationLineItemReportPage page =
        reconciliationLineItemReportService.getReconciliationLineItemReportsByStatement(
            statementBuilder.toStatement());

    ReconciliationLineItemReport lineItemReport =
        Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    // Set and use a manual volume for billing. This example splits the difference between DFP
    // and the third party volume.
    lineItemReport.setManualVolume(
        (lineItemReport.getDfpVolume() + lineItemReport.getThirdPartyVolume()) / 2);
    lineItemReport.setReconciliationSource(BillFrom.MANUAL);

    ReconciliationLineItemReport[] updatedLineItemReports =
        reconciliationLineItemReportService.updateReconciliationLineItemReports(
            new ReconciliationLineItemReport[] {lineItemReport});

    for (ReconciliationLineItemReport updatedLineItemReport : updatedLineItemReports) {
      System.out.printf(
          "Reconciliation line item report with ID \"%d\" for line item ID \"%d\" was "
              + "updated, with manual volume \"%d\".%n",
          updatedLineItemReport.getId(),
          updatedLineItemReport.getLineItemId(),
          updatedLineItemReport.getManualVolume());
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, int activityId)
      throws Exception {
    // Get the ActivityService.
    ActivityServiceInterface activityService =
        dfpServices.get(session, ActivityServiceInterface.class);

    // Get the activity.
    Activity activity = activityService.getActivity(activityId);

    // Update the expected URL.
    activity.setExpectedURL("http://google.com");

    // Update the activity on the server.
    Activity[] activities = activityService.updateActivities(new Activity[] {activity});

    for (Activity updatedActivity : activities) {
      System.out.printf(
          "Activity with ID \"%d\" and name \"%s\" was updated.\n",
          updatedActivity.getId(), updatedActivity.getName());
    }
  }
  /** Gets all custom targeting key IDs. */
  private static List<Long> getAllCustomTargetingKeyIds(DfpServices dfpServices, DfpSession session)
      throws RemoteException {
    List<Long> customTargetingKeyIds = Lists.newArrayList();

    // Get the CustomTargetingService.
    CustomTargetingServiceInterface customTargetingService =
        dfpServices.get(session, CustomTargetingServiceInterface.class);

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

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

    do {
      // Get custom targeting keys by statement.
      CustomTargetingKeyPage page =
          customTargetingService.getCustomTargetingKeysByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (CustomTargetingKey customTargetingKey : page.getResults()) {
          System.out.printf(
              "%d) Custom targeting key with ID \"%d\", name \"%s\", and "
                  + "display name \"%s\" was found.\n",
              i++,
              customTargetingKey.getId(),
              customTargetingKey.getName(),
              customTargetingKey.getDisplayName());
          customTargetingKeyIds.add(customTargetingKey.getId());
        }
      }

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

    return customTargetingKeyIds;
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long userId, long teamId) throws Exception {
    // Get the UserTeamAssociationService.
    UserTeamAssociationServiceInterface userTeamAssociationService =
        dfpServices.get(session, UserTeamAssociationServiceInterface.class);

    // Create a user team association.
    UserTeamAssociation userTeamAssociation = new UserTeamAssociation();
    userTeamAssociation.setUserId(userId);
    userTeamAssociation.setTeamId(teamId);

    // Create the user team association on the server.
    UserTeamAssociation[] userTeamAssociations =
        userTeamAssociationService.createUserTeamAssociations(
            new UserTeamAssociation[] {userTeamAssociation});

    for (UserTeamAssociation createdUserTeamAssociation : userTeamAssociations) {
      System.out.printf(
          "A user team association with user ID %d and team ID %d was created.%n",
          createdUserTeamAssociation.getUserId(), createdUserTeamAssociation.getTeamId());
    }
  }
  public static void runExample(
      DfpServices dfpServices, DfpSession session, long lineItemId, long creativeId)
      throws Exception {
    // Get the LineItemCreativeAssociationService.
    LineItemCreativeAssociationServiceInterface licaService =
        dfpServices.get(session, LineItemCreativeAssociationServiceInterface.class);

    // Create a line item creative association.
    LineItemCreativeAssociation lica = new LineItemCreativeAssociation();
    lica.setLineItemId(lineItemId);
    lica.setCreativeId(creativeId);

    // Create the line item creative association on the server.
    LineItemCreativeAssociation[] licas =
        licaService.createLineItemCreativeAssociations(new LineItemCreativeAssociation[] {lica});

    for (LineItemCreativeAssociation createdLica : licas) {
      System.out.printf(
          "A LICA with line item ID \"%d\" and creative ID \"%d\" was created.\n",
          createdLica.getLineItemId(), createdLica.getCreativeId());
    }
  }
  public static void runExample(DfpServices dfpServices, DfpSession session, long productPackageId)
      throws Exception {
    // Get the ProductPackageService.
    ProductPackageServiceInterface productPackageService =
        dfpServices.get(session, ProductPackageServiceInterface.class);

    // Create a statement to select a single product package.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("id = :id")
            .orderBy("id ASC")
            .limit(1)
            .withBindVariableValue("id", productPackageId);

    // Get the product package.
    ProductPackagePage page =
        productPackageService.getProductPackagesByStatement(statementBuilder.toStatement());

    ProductPackage productPackage = Iterables.getOnlyElement(Arrays.asList(page.getResults()));

    System.out.printf("Product package with ID %d will be activated.%n", productPackage.getId());

    // Remove limit and offset from statement.
    statementBuilder.removeLimitAndOffset();

    // Create action to activate product packages.
    com.google.api.ads.dfp.axis.v201508.ActivateProductPackages action =
        new com.google.api.ads.dfp.axis.v201508.ActivateProductPackages();

    // Perform action.
    UpdateResult result =
        productPackageService.performProductPackageAction(action, statementBuilder.toStatement());

    if (result != null && result.getNumChanges() > 0) {
      System.out.printf("Number of product packages activated: %d%n", result.getNumChanges());
    } else {
      System.out.println("No product packages were deactivated.");
    }
  }