Runs the example.

@param adManagerServices 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.
6297
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the NativeStyleService.
    NativeStyleServiceInterface nativeStyleService =
        adManagerServices.get(session, NativeStyleServiceInterface.class);

    String htmlSnippet =
            "<div id=\"adunit\" style=\"overflow: hidden;\">\n"
            + "  <img src='[%Thirdpartyimpressiontracker%]' style='display:none'>\n"
            + "  <div class='attribution'>Ad</div>\n"
            + "  <div class='image'>\n"
            + "    <a class='image-link' "
            + "href='%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%' target='_top'>"
            + "<img src=\"[%Image%]\"></a>\n"
            + "  </div>\n"
            + "  <div class='app-icon'><img src=\"[%Appicon%]\"/></div>\n"
            + "  <div class='title'>\n"
            + "    <a class='title-link' "
            + "href='%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%' "
            + "target='_top'>[%Headline%]</a>\n"
            + "  </div>\n"
            + "  <div class='reviews'></div>\n"
            + "  <div class='body'>\n"
            + "    <a class='body-link' "
            + "href='%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%' "
            + "target='_top'>[%Body%]</a>\n"
            + "  </div>\n"
            + "  <div class='price'>[%Price%]</div>\n"
            + "  <div class='button'>\n"
            + "    <a class='button-link' "
            + "href='%%CLICK_URL_UNESC%%[%Thirdpartyclicktracker%]%%DEST_URL%%' "
            + "target='_top'>[%Calltoaction%]</a>\n"
            + "  </div>\n"
            + "</div>\n";

    String cssSnippet =
        "body {"
            + "    background-color: rgba(255, 255, 255, 1);"
            + "    font-family: \"Roboto-Regular\", sans-serif;"
            + "    font-weight: normal;"
            + "    font-size: 12px;"
            + "    line-height: 14px;"
            + "}"
            + ".attribution {"
            + "    background-color: rgba(236, 182, 0, 1);"
            + "    color: rgba(255, 255, 255, 1);"
            + "    font-size: 13px;"
            + "    display: table;"
            + "    margin: 4px 8px;"
            + "    padding: 0 3px;"
            + "    border-radius: 2px;"
            + "}"
            + ".image {"
            + "    text-align: center;"
            + "    margin: 8px;"
            + "}"
            + ".image img,"
            + ".image-link {"
            + "    width: 100%;"
            + "}"
            + ".app-icon {"
            + "    float: left;"
            + "    margin: 0 8px 4px 8px;"
            + "    height: 40px;"
            + "    width: 40px;"
            + "    background-color: transparent;"
            + "}"
            + ".app-icon img {"
            + "    height: 100%;"
            + "    width: 100%;"
            + "    border-radius: 20%;"
            + "}"
            + ".title {"
            + "    font-weight: bold;"
            + "    font-size: 14px;"
            + "    line-height: 20px;"
            + "    margin: 8px 8px 4px 8px;"
            + "}"
            + ".title a {"
            + "    color: rgba(112, 112, 112, 1);"
            + "    text-decoration: none;"
            + "}"
            + ".reviews {"
            + "    float: left;"
            + "}"
            + ".reviews svg {"
            + "    fill: rgba(0, 0, 0, 0.7);"
            + "}"
            + ".body {"
            + "    clear: left;"
            + "    margin: 8px;"
            + "}"
            + ".body a {"
            + "    color: rgba(110, 110, 110, 1);"
            + "    text-decoration: none;"
            + "}"
            + ".price {"
            + "    display: none;"
            + "}"
            + ".button {"
            + "    font-size: 14px;"
            + "    font-weight: bold;"
            + "    float: right;"
            + "    margin: 0px 16px 16px 0px;"
            + "    white-space: nowrap;"
            + "}"
            + ".button a {"
            + "    color: #2196F3;"
            + "    text-decoration: none;"
            + "}"
            + ".button svg {"
            + "    display: none;"
            + "}";

    // This is the creative template ID for the system-defined native app
    // install ad format, which we will create the native style from. Use
    // CreativeTemplateService.getCreativeTemplatesByStatement() and
    // CreativeTemplate.isNativeEligible to get other native ad formats
    // available in your network.
    long nativeAppInstallTemplateId = 10004400L;

    // Set the size for the native style.
    Size size = new Size();
    size.setWidth(300);
    size.setHeight(250);
    size.setIsAspectRatio(false);

    // Create a style for native app install ads.
    NativeStyle nativeStyle = new NativeStyle();
    nativeStyle.setName("Native style #" + new Random().nextInt(Integer.MAX_VALUE));
    nativeStyle.setCreativeTemplateId(nativeAppInstallTemplateId);
    nativeStyle.setSize(size);
    nativeStyle.setHtmlSnippet(htmlSnippet);
    nativeStyle.setCssSnippet(cssSnippet);

    // Create the native style on the server.
    NativeStyle[] nativeStyles =
        nativeStyleService.createNativeStyles(new NativeStyle[] {nativeStyle});

    for (NativeStyle createdNativeStyle : nativeStyles) {
      System.out.printf(
          "A native style with ID %d and name '%s' was created.%n",
          createdNativeStyle.getId(), createdNativeStyle.getName());
    }
  }
763817
public void doProcess(InputStream in, PrintWriter out, Map<String, Object> properties)
        throws RemoteException
    {
        String strCommand = this.getProperty(REMOTE_COMMAND, properties);
        if (RECEIVE_REMOTE_MESSAGE.equals(strCommand))
        {
            Message message = ((RemoteReceiveQueue)m_remoteObject).receiveRemoteMessage();
            if (message != null)	// If the client quits, this is freed and I get a null message (which I don't need to return)
            	this.setReturnObject(out, message);
        }
        else if (ADD_REMOTE_MESSAGE_FILTER.equals(strCommand))
        {
            BaseMessageFilter messageFilter = (BaseMessageFilter)this.getNextObjectParam(in, FILTER, properties);
            String strSessionPathID = this.getNextStringParam(in, SESSION, properties);
            BaseHolder sessionHolder = this.getSessionFromPath(strSessionPathID);
            BaseMessageFilter objReturn = null;
            if (sessionHolder instanceof SessionHolder)
            {       // Always
                RemoteSession remoteSession = (RemoteSession)sessionHolder.getRemoteObject();
                objReturn = ((RemoteReceiveQueue)m_remoteObject).addRemoteMessageFilter(messageFilter, remoteSession);
            }
            else if (sessionHolder == null)
            {   // Session may be null.
                objReturn = ((RemoteReceiveQueue)m_remoteObject).addRemoteMessageFilter(messageFilter, null);
            }
            else
                Utility.getLogger().warning("Remote session not found");
            this.setReturnObject(out, objReturn);
        }
        else if (REMOVE_REMOTE_MESSAGE_FILTER.equals(strCommand))
        {
            BaseMessageFilter messageFilter = (BaseMessageFilter)this.getNextObjectParam(in, FILTER, properties);
            boolean bFreeFilter = this.getNextBooleanParam(in, FREE, properties);
            boolean bSuccess = ((RemoteReceiveQueue)m_remoteObject).removeRemoteMessageFilter(messageFilter, bFreeFilter);
            this.setReturnObject(out, new Boolean(bSuccess));
        }
        else if (UPDATE_REMOTE_FILTER_PROPERTIES.equals(strCommand))
        {
            BaseMessageFilter messageFilter = (BaseMessageFilter)this.getNextObjectParam(in, FILTER, properties);
            Object[][] propIn = (Object[][])this.getNextObjectParam(in, PROPERTIES, properties);
            Map<String,Object> propFilter = this.getNextPropertiesParam(in, MAP, properties);
            ((RemoteReceiveQueue)m_remoteObject).updateRemoteFilterProperties(messageFilter, propIn, propFilter);
        }
        else
            super.doProcess(in, out, properties);
    }
151639
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    AudienceSegmentServiceInterface audienceSegmentService =
        adManagerServices.get(session, AudienceSegmentServiceInterface.class);

    // Create a statement to select audience segments.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("type = :type")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("type", AudienceSegmentType.FIRST_PARTY.toString());

    // Retrieve a small amount of audience segments at a time, paging through
    // until all audience segments have been retrieved.
    int totalResultSetSize = 0;
    do {
      AudienceSegmentPage page =
          audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement());

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

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

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

    // Create a number custom field that can be used for an external ID in the
    // API.
    CustomField numberCustomField = new CustomField();
    numberCustomField.setName("External ID #" + new Random().nextInt(Integer.MAX_VALUE));
    numberCustomField.setEntityType(CustomFieldEntityType.LINE_ITEM);
    numberCustomField.setDataType(CustomFieldDataType.NUMBER);
    numberCustomField.setVisibility(CustomFieldVisibility.API_ONLY);

    // Create a drop-down custom field that can be used in the UI.
    CustomField dropDownCustomField = new CustomField();
    dropDownCustomField.setName(
        "Internal approval status #" + new Random().nextInt(Integer.MAX_VALUE));
    dropDownCustomField.setEntityType(CustomFieldEntityType.LINE_ITEM);
    dropDownCustomField.setDataType(CustomFieldDataType.DROP_DOWN);
    dropDownCustomField.setVisibility(CustomFieldVisibility.FULL);

    // Create the custom fields on the server.
    CustomField[] customFields =
        customFieldService.createCustomFields(
            new CustomField[] {numberCustomField, dropDownCustomField});

    for (CustomField createdCustomField : customFields) {
      System.out.printf(
          "A custom field with ID %d and name '%s' was created.%n",
          createdCustomField.getId(), createdCustomField.getName());
    }

    // Set the created drop-down custom field.
    dropDownCustomField = customFields[1];

    // Create approved custom field option.
    CustomFieldOption approvedCustomFieldOption = new CustomFieldOption();
    approvedCustomFieldOption.setDisplayName("APPROVED");
    approvedCustomFieldOption.setCustomFieldId(dropDownCustomField.getId());

    // Create unapproved custom field option.
    CustomFieldOption unapprovedCustomFieldOption = new CustomFieldOption();
    unapprovedCustomFieldOption.setDisplayName("UNAPPROVED");
    unapprovedCustomFieldOption.setCustomFieldId(dropDownCustomField.getId());

    // Create the custom field options on the server.
    CustomFieldOption[] customFieldOptions =
        customFieldService.createCustomFieldOptions(
            new CustomFieldOption[] {approvedCustomFieldOption, unapprovedCustomFieldOption});

    for (CustomFieldOption createdCustomFieldOption : customFieldOptions) {
      System.out.printf(
          "A custom field option with ID %d and display name '%s' was created.%n",
          createdCustomFieldOption.getId(), createdCustomFieldOption.getDisplayName());
    }
  }
74477
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the CustomTargetingService.
    CustomTargetingServiceInterface customTargetingService =
        adManagerServices.get(session, CustomTargetingServiceInterface.class);

    // Get all custom targeting keys.
    List<Long> customTargetingKeyIds = getAllCustomTargetingKeyIds(adManagerServices, 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);
  }
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);
  }
48051
public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
    // Get the CampaignService.
    ManagedCustomerServiceInterface managedCustomerService =
        adWordsServices.get(session, ManagedCustomerServiceInterface.class);

    // Create account.
    ManagedCustomer customer = new ManagedCustomer();
    customer.setName("Customer created with ManagedCustomerService on " + new DateTime());
    customer.setCurrencyCode("EUR");
    customer.setDateTimeZone("Europe/London");

    // Create operations.
    ManagedCustomerOperation operation = new ManagedCustomerOperation();
    operation.setOperand(customer);
    operation.setOperator(Operator.ADD);

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

    // Add account.
    ManagedCustomerReturnValue result = managedCustomerService.mutate(operations);

    // Display accounts.
    for (ManagedCustomer customerResult : result.getValue()) {
      System.out.printf("Account with customer ID %d was created.%n",
          customerResult.getCustomerId());
    }
  }
172829
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the ReconciliationReportService.
    ReconciliationReportServiceInterface reconciliationReportService =
        adManagerServices.get(session, ReconciliationReportServiceInterface.class);

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

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

    do {
      // Get reconciliation reports by statement.
      ReconciliationReportPage page =
          reconciliationReportService.getReconciliationReportsByStatement(
              statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (ReconciliationReport reconciliationReport : page.getResults()) {
          System.out.printf(
              "%d) Reconciliation report with ID %d for month %d/%d was found.%n",
              i++,
              reconciliationReport.getId(),
              reconciliationReport.getStartDate().getMonth(),
              reconciliationReport.getStartDate().getYear());
        }
      }

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

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
1273930
@Override
    public void setRemoteServices(RemoteServices remoteServices) {
        final String methodName = "setRemoteServices(remoteServices)";
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, methodName + " cacheName=" + cacheName + " ERROR because it should not be called");
        }
    }
211702
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    CompanyServiceInterface companyService =
        adManagerServices.get(session, CompanyServiceInterface.class);

    // Create a statement to select companies.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("type = :type")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("type", CompanyType.ADVERTISER.toString());

    // Retrieve a small amount of companies at a time, paging through
    // until all companies have been retrieved.
    int totalResultSetSize = 0;
    do {
      CompanyPage page = companyService.getCompaniesByStatement(statementBuilder.toStatement());

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

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

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
969119
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
      throws RemoteException {

    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    // Create the campaign.
    Campaign campaign = new Campaign();
    campaign.setName("Interplanetary Cruise App #" + System.currentTimeMillis());

    // 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);

    // Set the advertising channel and subchannel types for universal app campaigns.
    campaign.setAdvertisingChannelType(AdvertisingChannelType.MULTI_CHANNEL);
    campaign.setAdvertisingChannelSubType(AdvertisingChannelSubType.UNIVERSAL_APP_CAMPAIGN);

    // Set the campaign's bidding strategy. universal app campaigns
    // only support TARGET_CPA bidding strategy.
    BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
    biddingConfig.setBiddingStrategyType(BiddingStrategyType.TARGET_CPA);

    // Set the target CPA to $1 / app install.
    TargetCpaBiddingScheme biddingScheme = new TargetCpaBiddingScheme();
    biddingScheme.setTargetCpa(new Money());
    biddingScheme.getTargetCpa().setMicroAmount(1000000L);

    biddingConfig.setBiddingScheme(biddingScheme);
    campaign.setBiddingStrategyConfiguration(biddingConfig);

    // Set the campaign's budget.
    campaign.setBudget(new Budget());
    campaign.getBudget().setBudgetId(createBudget(adWordsServices, session));

    // 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"));

    // Set the campaign's assets and ad text ideas. These values will be used to
    // generate ads.
    UniversalAppCampaignSetting universalAppSetting = new UniversalAppCampaignSetting();
    universalAppSetting.setAppId("com.labpixies.colordrips");
    universalAppSetting.setAppVendor(MobileApplicationVendor.VENDOR_GOOGLE_MARKET);
    universalAppSetting.setDescription1("A cool puzzle game");
    universalAppSetting.setDescription2("Remove connected blocks");
    universalAppSetting.setDescription3("3 difficulty levels");
    universalAppSetting.setDescription4("4 colorful fun skins");

    // Optional: You can set up to 20 image assets for your campaign.
    // See UploadImage.java for an example on how to upload images.
    //
    // universalAppSetting.setImageMediaIds(new long[] { INSERT_IMAGE_MEDIA_ID_HERE });

    // Optimize this campaign for getting new users for your app.
    universalAppSetting.setUniversalAppBiddingStrategyGoalType(
        UniversalAppBiddingStrategyGoalType.OPTIMIZE_FOR_INSTALL_CONVERSION_VOLUME);

    // If you select the OPTIMIZE_FOR_IN_APP_CONVERSION_VOLUME goal type, then also specify
    // your in-app conversion types so AdWords can focus your campaign on people who are
    // most likely to complete the corresponding in-app actions.
    // Conversion type IDs can be retrieved using ConversionTrackerService.get.
    //
    // campaign.selectiveOptimization = new SelectiveOptimization();
    // campaign.selectiveOptimization.conversionTypeIds =
    //    new long[] { INSERT_CONVERSION_TYPE_ID_1_HERE, INSERT_CONVERSION_TYPE_ID_2_HERE };

    // Optional: Set the campaign settings for Advanced location options.
    GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
    geoSetting.setPositiveGeoTargetType(
        GeoTargetTypeSettingPositiveGeoTargetType.LOCATION_OF_PRESENCE);
    geoSetting.setNegativeGeoTargetType(GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE);

    campaign.setSettings(new Setting[] {universalAppSetting, geoSetting});

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

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

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

    // Display the results.
    for (Campaign newCampaign : result.getValue()) {
      System.out.printf(
          "Universal app campaign with name '%s' and ID %d was added.%n",
          newCampaign.getName(), newCampaign.getId());

      // Optional: Set the campaign's location and language targeting. No other targeting
      // criteria can be used for universal app campaigns.
      setCampaignTargetingCriteria(newCampaign, adWordsServices, session);
    }
  }
297110
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the PlacementService.
    PlacementServiceInterface placementService =
        adManagerServices.get(session, PlacementServiceInterface.class);

    // Get all ad units.
    List<AdUnit> adUnits = getAllAdUnits(adManagerServices, session);

    // Partition ad units by their size.
    Set<String> mediumSquareAdUnitIds = Sets.newHashSet();
    Set<String> skyscraperAdUnitIds = Sets.newHashSet();
    Set<String> bannerAdUnitIds = Sets.newHashSet();

    for (AdUnit adUnit : adUnits) {
      if (adUnit.getParentId() != null && adUnit.getAdUnitSizes() != null) {
        for (AdUnitSize adUnitSize : adUnit.getAdUnitSizes()) {
          Size size = adUnitSize.getSize();
          if (size.getWidth() == 300 && size.getHeight() == 250) {
            mediumSquareAdUnitIds.add(adUnit.getId());
          } else if (size.getWidth() == 120 && size.getHeight() == 600) {
            skyscraperAdUnitIds.add(adUnit.getId());
          } else if (size.getWidth() == 468 && size.getHeight() == 60) {
            bannerAdUnitIds.add(adUnit.getId());
          }
        }
      }
    }

    List<Placement> placementsToCreate = new ArrayList<>();

    // Only create placements with one or more ad unit.
    if (!mediumSquareAdUnitIds.isEmpty()) {
      // Create medium square placement.
      Placement mediumSquareAdUnitPlacement = new Placement();
      mediumSquareAdUnitPlacement.setName(
          "Medium Square AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
      mediumSquareAdUnitPlacement.setDescription(
          "Contains ad units that can hold creatives of size 300x250");
      mediumSquareAdUnitPlacement.setTargetedAdUnitIds(
          mediumSquareAdUnitIds.toArray(new String[] {}));

      placementsToCreate.add(mediumSquareAdUnitPlacement);
    }

    if (!skyscraperAdUnitIds.isEmpty()) {
      // Create skyscraper placement.
      Placement skyscraperAdUnitPlacement = new Placement();
      skyscraperAdUnitPlacement.setName(
          "Skyscraper AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
      skyscraperAdUnitPlacement.setDescription(
          "Contains ad units that can hold creatives of size 120x600");
      skyscraperAdUnitPlacement.setTargetedAdUnitIds(skyscraperAdUnitIds.toArray(new String[] {}));
      placementsToCreate.add(skyscraperAdUnitPlacement);
    }

    if (!bannerAdUnitIds.isEmpty()) {
      // Create banner placement.
      Placement bannerAdUnitPlacement = new Placement();
      bannerAdUnitPlacement.setName(
          "Banner AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
      bannerAdUnitPlacement.setDescription(
          "Contains ad units that can hold creatives of size 468x60");
      bannerAdUnitPlacement.setTargetedAdUnitIds(bannerAdUnitIds.toArray(new String[] {}));
      placementsToCreate.add(bannerAdUnitPlacement);
    }

    if (!placementsToCreate.isEmpty()) {
      // Create the placements on the server.
      Placement[] placements =
          placementService.createPlacements(placementsToCreate.toArray(new Placement[] {}));

      for (Placement createdPlacement : placements) {
        System.out.printf(
            "A placement with ID %d, name '%s', and containing ad units [%s] was created.%n",
            createdPlacement.getId(),
            createdPlacement.getName(),
            Joiner.on(", ").join(createdPlacement.getTargetedAdUnitIds()));
      }
    } else {
      System.out.println("No placements were created.");
    }
  }
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);
  }
300709
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the adjustment service and the network service.
    AdjustmentServiceInterface adjustmentService =
        adManagerServices.get(session, AdjustmentServiceInterface.class);
    NetworkServiceInterface networkService =
        adManagerServices.get(session, NetworkServiceInterface.class);

    // Get the root ad unit ID used to target the whole site.
    String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();

    // Create inventory targeting.
    InventoryTargeting inventoryTargeting = new InventoryTargeting();

    // Create ad unit targeting for the root ad unit (i.e. the whole network).
    AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
    adUnitTargeting.setAdUnitId(rootAdUnitId);
    adUnitTargeting.setIncludeDescendants(true);

    inventoryTargeting.setTargetedAdUnits(new AdUnitTargeting[] {adUnitTargeting});

    // Create a new adjustment for United States traffic.
    // When using GeoTargeting, only Locations of type COUNTRY are supported.
    GeoTargeting geoTargeting = new GeoTargeting();
    Location countryLocation = new Location();
    countryLocation.setId(2840L);
    geoTargeting.setTargetedLocations(new Location[] {countryLocation});

    Targeting targeting = new Targeting();
    targeting.setInventoryTargeting(inventoryTargeting);
    targeting.setGeoTargeting(geoTargeting);

    // Adjust only 1920x1080 video traffic.
    AdUnitSize adUnitSize = new AdUnitSize();
    Size size = new Size();
    size.setWidth(1920);
    size.setHeight(1080);
    adUnitSize.setSize(size);
    adUnitSize.setEnvironmentType(EnvironmentType.VIDEO_PLAYER);

    TrafficForecastAdjustment adjustment = new TrafficForecastAdjustment();
    TrafficTimeSeriesFilterCriteria criteria = new TrafficTimeSeriesFilterCriteria();
    criteria.setTargeting(targeting);
    criteria.setAdUnitSizes(new AdUnitSize[] {adUnitSize});

    adjustment.setFilterCriteria(criteria);

    // Create a new historical adjustment targeting next year's January with 105% of
    // the traffic of this year's January.
    HistoricalAdjustment januaryAdjustment = new HistoricalAdjustment();

    Date referenceRangeStart = new Date(new org.joda.time.DateTime().getYear(), 1, 1);
    Date referenceRangeEnd = new Date(new org.joda.time.DateTime().getYear(), 1, 30);
    DateRange referenceDateRange = new DateRange();
    referenceDateRange.setStartDate(referenceRangeStart);
    referenceDateRange.setEndDate(referenceRangeEnd);
    januaryAdjustment.setReferenceDateRange(referenceDateRange);

    Date targetStartDate = new Date(new org.joda.time.DateTime().plusYears(1).getYear(), 1, 1);
    Date targetEndDate = new Date(new org.joda.time.DateTime().plusYears(1).getYear(), 1, 30);
    DateRange targetDateRange = new DateRange();
    targetDateRange.setStartDate(targetStartDate);
    targetDateRange.setEndDate(targetEndDate);
    januaryAdjustment.setTargetDateRange(targetDateRange);

    januaryAdjustment.setMilliPercentMultiplier(105000L);

    TrafficForecastAdjustmentSegment januarySegment = new TrafficForecastAdjustmentSegment();
    januarySegment.setBasisType(BasisType.HISTORICAL);
    januarySegment.setHistoricalAdjustment(januaryAdjustment);

    // Create a new absolute adjustment of 500,000 ad opportunities for Christmas
    // and 1M ad opportunities for Boxing Day.
    TimeSeries holidayTimeSeries = new TimeSeries();
    Date christmas = new Date(new org.joda.time.DateTime().plusYears(1).getYear(), 12, 25);
    Date boxingDay = new Date(new org.joda.time.DateTime().plusYears(1).getYear(), 12, 26);
    DateRange holidayRange = new DateRange();
    holidayRange.setStartDate(christmas);
    holidayRange.setEndDate(boxingDay);
    holidayTimeSeries.setTimeSeriesDateRange(holidayRange);
    holidayTimeSeries.setTimeSeriesValues(new long[] {500000L, 1000000L});
    holidayTimeSeries.setValuePeriodType(PeriodType.DAILY);
    TrafficForecastAdjustmentSegment holidaySegment = new TrafficForecastAdjustmentSegment();
    holidaySegment.setBasisType(BasisType.ABSOLUTE);
    holidaySegment.setAdjustmentTimeSeries(holidayTimeSeries);

    // Create a new absolute adjustment of 900,000 ad opportunities for the first week in September.
    TimeSeries septemberTimeSeries = new TimeSeries();
    Date septemberStart = new Date(new org.joda.time.DateTime().plusYears(1).getYear(), 9, 1);
    Date septemberEnd = new Date(new org.joda.time.DateTime().plusYears(1).getYear(), 9, 7);
    DateRange septemberRange = new DateRange();
    septemberRange.setStartDate(septemberStart);
    septemberRange.setEndDate(septemberEnd);
    septemberTimeSeries.setTimeSeriesDateRange(septemberRange);
    septemberTimeSeries.setTimeSeriesValues(new long[] {900000L});
    septemberTimeSeries.setValuePeriodType(PeriodType.CUSTOM);
    TrafficForecastAdjustmentSegment septemberSegment = new TrafficForecastAdjustmentSegment();
    septemberSegment.setBasisType(BasisType.ABSOLUTE);
    septemberSegment.setAdjustmentTimeSeries(septemberTimeSeries);

    // Add the segments to the adjustment
    adjustment.setForecastAdjustmentSegments(
        new TrafficForecastAdjustmentSegment[] {januarySegment, holidaySegment, septemberSegment});

    // Update the traffic adjustment on the server.
    TrafficForecastAdjustment[] adjustments =
        adjustmentService.updateTrafficAdjustments(new TrafficForecastAdjustment[] {adjustment});

    for (TrafficForecastAdjustment updatedAdjustment : adjustments) {
      System.out.printf(
          "Traffic forecast adjustment with ID %d and %d segments was created or updated.%n",
          updatedAdjustment.getId(), updatedAdjustment.getForecastAdjustmentSegments().length);
    }
  }
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);
  }
694523
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    WorkflowRequestServiceInterface workflowRequestService =
        adManagerServices.get(session, WorkflowRequestServiceInterface.class);

    // Create a statement to select workflow requests.
    StatementBuilder statementBuilder = new StatementBuilder()
        .where("type = :type")
        .orderBy("id ASC")
        .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
        .withBindVariableValue("type", WorkflowRequestType.WORKFLOW_APPROVAL_REQUEST.toString());

    // Retrieve a small amount of workflow requests at a time, paging through
    // until all workflow requests have been retrieved.
    int totalResultSetSize = 0;
    do {
      WorkflowRequestPage page =
          workflowRequestService.getWorkflowRequestsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each workflow request.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (WorkflowRequest workflowRequest : page.getResults()) {
          System.out.printf(
              "%d) Workflow request with ID %d, entity type '%s', and entity ID %d was found.%n",
              i++,
              workflowRequest.getId(),
              workflowRequest.getEntityType(),
              workflowRequest.getEntityId()
          );
        }
      }

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

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
287863
private static List<AdUnit> getAllAdUnits(
      AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException {
    List<AdUnit> adUnits = new ArrayList<>();

    // Get the InventoryService.
    InventoryServiceInterface inventoryService =
        adManagerServices.get(session, InventoryServiceInterface.class);

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

    // 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();
        Collections.addAll(adUnits, page.getResults());
      }

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

    return adUnits;
  }