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.
482759
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the CdnConfigurationService.
    CdnConfigurationServiceInterface cdnConfigurationService =
        adManagerServices.get(session, CdnConfigurationServiceInterface.class);

    // Make CDN configuration objects.
    // Only LIVE_STREAM_SOURCE_CONTENT is currently supported by the API.
    // Basic example with no security policies.
    CdnConfiguration cdnConfigurationWithoutSecurityPolicy = new CdnConfiguration();

    SecurityPolicySettings noSecurityPolicy = new SecurityPolicySettings();
    noSecurityPolicy.setSecurityPolicyType(SecurityPolicyType.NONE);
    MediaLocationSettings mediaLocationSettings = new MediaLocationSettings();
    mediaLocationSettings.setUrlPrefix("example.google.com");
    mediaLocationSettings.setSecurityPolicy(noSecurityPolicy);

    SourceContentConfiguration sourceContentConfigWithNoSecurityPolicy =
        new SourceContentConfiguration();
    sourceContentConfigWithNoSecurityPolicy.setIngestSettings(mediaLocationSettings);
    sourceContentConfigWithNoSecurityPolicy.setDefaultDeliverySettings(mediaLocationSettings);

    cdnConfigurationWithoutSecurityPolicy.setName("ApiConfig1");
    cdnConfigurationWithoutSecurityPolicy.setCdnConfigurationType(
        CdnConfigurationType.LIVE_STREAM_SOURCE_CONTENT);
    cdnConfigurationWithoutSecurityPolicy.setSourceContentConfiguration(
        sourceContentConfigWithNoSecurityPolicy);

    // Complex example with security policies.
    CdnConfiguration cdnConfigurationWithSecurityPolicy = new CdnConfiguration();

    SecurityPolicySettings ingestSecurityPolicySettings = new SecurityPolicySettings();
    ingestSecurityPolicySettings.setSecurityPolicyType(SecurityPolicyType.AKAMAI);
    ingestSecurityPolicySettings.setDisableServerSideUrlSigning(false);
    ingestSecurityPolicySettings.setTokenAuthenticationKey("abc123");

    MediaLocationSettings ingestSettings = new MediaLocationSettings();
    ingestSettings.setUrlPrefix("example.google.com");
    ingestSettings.setSecurityPolicy(ingestSecurityPolicySettings);

    SecurityPolicySettings deliverySecurityPolicySettings = new SecurityPolicySettings();
    deliverySecurityPolicySettings.setSecurityPolicyType(SecurityPolicyType.AKAMAI);
    deliverySecurityPolicySettings.setDisableServerSideUrlSigning(false);
    deliverySecurityPolicySettings.setOriginForwardingType(OriginForwardingType.CONVENTIONAL);
    deliverySecurityPolicySettings.setOriginPathPrefix("/path/to/my/origin");

    MediaLocationSettings deliverySettings = new MediaLocationSettings();
    deliverySettings.setUrlPrefix("example.google.com");
    deliverySettings.setSecurityPolicy(deliverySecurityPolicySettings);

    SourceContentConfiguration sourceContentConfigurationWithSecurityPolicy =
        new SourceContentConfiguration();
    sourceContentConfigurationWithSecurityPolicy.setIngestSettings(ingestSettings);
    sourceContentConfigurationWithSecurityPolicy.setDefaultDeliverySettings(deliverySettings);

    cdnConfigurationWithSecurityPolicy.setName("ApiConfig2");
    cdnConfigurationWithSecurityPolicy.setCdnConfigurationType(
        CdnConfigurationType.LIVE_STREAM_SOURCE_CONTENT);
    cdnConfigurationWithSecurityPolicy.setSourceContentConfiguration(
        sourceContentConfigurationWithSecurityPolicy);

    // Create the cdnConfigurations on the server.
    CdnConfiguration[] cdnConfigurations =
        cdnConfigurationService.createCdnConfigurations(
            new CdnConfiguration[] {
              cdnConfigurationWithoutSecurityPolicy, cdnConfigurationWithSecurityPolicy
            });

    for (CdnConfiguration createdCdnConfiguration : cdnConfigurations) {
      System.out.printf(
          "A CDN configuration with ID %d and name '%s' was created.%n",
          createdCdnConfiguration.getId(), createdCdnConfiguration.getName());
    }
  }
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);
  }
543496
private static AdGroup createAdGroup(
      AdWordsServicesInterface services, AdWordsSession session, Campaign campaign)
      throws RemoteException {
    AdGroupServiceInterface adGroupService = services.get(session, AdGroupServiceInterface.class);

    AdGroup group = new AdGroup();
    group.setName("Dynamic remarketing ad group");
    group.setCampaignId(campaign.getId());
    group.setStatus(AdGroupStatus.ENABLED);

    AdGroupOperation op = new AdGroupOperation();
    op.setOperand(group);
    op.setOperator(Operator.ADD);
    AdGroupReturnValue result = adGroupService.mutate(new AdGroupOperation[] {op});
    return result.getValue(0);
  }
226133
protected void remoteInit() throws JMSException
    {
        CreateConsumerQuery query = new CreateConsumerQuery();
        query.setConsumerId(id);
        query.setSessionId(session.getId());
        query.setDestination(destination);
        query.setMessageSelector(messageSelector);
        query.setNoLocal(noLocal);
        transportEndpoint.blockingRequest(query);        
    }
860042
private void setAuthenticationHeaders(Object soapClient, AdManagerSession adManagerSession)
      throws AuthenticationException {
    authorizationHeaderHandler.setAuthorization(soapClient, adManagerSession);
  }
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());
    }
  }
87298
static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services,
      AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface criterionService =
        services.get(session, AdGroupCriterionServiceInterface.class);

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

    AdGroupCriterionPage adGroupCriterionPage;

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

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

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

    return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
  }
576639
private static BiddingStrategyConfiguration getAdGroupBiddingStrategyConfiguration(
      AdWordsServicesInterface services, AdWordsSession session, Long adGroupId)
      throws ApiException, RemoteException {
    AdGroupServiceInterface adGroupService = services.get(session, AdGroupServiceInterface.class);

    Selector selector = new SelectorBuilder()
        .fields(
            AdGroupField.Id,
            AdGroupField.BiddingStrategyType,
            AdGroupField.BiddingStrategyId,
            AdGroupField.BiddingStrategyName)
        .equalsId(adGroupId).build();

    AdGroupPage adGroupPage = adGroupService.get(selector);

    if (adGroupPage.getEntries() == null || adGroupPage.getEntries().length == 0) {
      throw new IllegalArgumentException("No ad group found with ID " + adGroupId);
    }

    AdGroup adGroup = adGroupPage.getEntries(0);

    Preconditions.checkState(adGroup.getBiddingStrategyConfiguration() != null,
        "Unexpected state - ad group ID %s has a null BiddingStrategyConfiguration", adGroupId);
    return adGroup.getBiddingStrategyConfiguration();
  }
1359625
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    CdnConfigurationServiceInterface cdnConfigurationService =
        adManagerServices.get(session, CdnConfigurationServiceInterface.class);

    // Create a statement to select CDN configurations.
    int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
    StatementBuilder statementBuilder = new StatementBuilder().orderBy("id ASC").limit(pageSize);

    // Retrieve a small amount of CDN configurations at a time, paging through until all
    // CDN configurations have been retrieved.
    int totalResultSetSize = 0;
    do {
      CdnConfigurationPage page =
          cdnConfigurationService.getCdnConfigurationsByStatement(statementBuilder.toStatement());

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

      statementBuilder.increaseOffsetBy(pageSize);
    } while (statementBuilder.getOffset() < totalResultSetSize);

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

    // Create selector.
    Selector selector = new SelectorBuilder()
        .fields(
            AdGroupBidModifierField.CampaignId,
            AdGroupBidModifierField.AdGroupId,
            AdGroupBidModifierField.BidModifier,
            AdGroupBidModifierField.Id)
        .offset(0)
        .limit(PAGE_SIZE)
        .build();

    AdGroupBidModifierPage page = adGroupBidModifierService.get(selector);
    if (page.getEntries() != null) {
      for (AdGroupBidModifier bidModifierResult : page.getEntries()) {
        String bidModifierValue =
            bidModifierResult.getBidModifier() != null
                ? bidModifierResult.getBidModifier().toString()
                : "unset";
        System.out.printf("Campaign ID %d, AdGroup ID %d, Criterion ID %d, "
            + "has ad group level modifier: %s%n",
            bidModifierResult.getCampaignId(),
            bidModifierResult.getAdGroupId(),
            bidModifierResult.getCriterion().getId(),
            bidModifierValue);
      }
    } else {
      System.out.println("No ad group level bid modifiers were found.");
    }
  }
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);
  }
1343610
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    PackageServiceInterface packageService =
        adManagerServices.get(session, PackageServiceInterface.class);

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

    // Retrieve a small amount of packages at a time, paging through
    // until all packages have been retrieved.
    int totalResultSetSize = 0;
    do {
      PackagePage page =
          packageService.getPackagesByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each package.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (Package pkg : page.getResults()) {
          System.out.printf(
              "%d) Package with ID %d, name '%s', and 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);
  }
768922
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    // Get the AdjustmentService.
    AdjustmentServiceInterface adjustmentService =
        adManagerServices.get(session, AdjustmentServiceInterface.class);

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

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

    do {
      // Get forecast adjustments by statement.
      TrafficForecastAdjustmentPage page =
          adjustmentService.getTrafficAdjustmentsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (TrafficForecastAdjustment adjustment : page.getResults()) {
          System.out.printf(
              "%d) Forecast adjustment with ID %d containing %d adjustment segments was found.%n",
              i++,
              adjustment.getId(),
              adjustment.getForecastAdjustmentSegments() != null
                  ? adjustment.getForecastAdjustmentSegments().length
                  : 0);
        }
      }

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

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }
783140
private static void addCampaignsToGroup(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      CampaignGroup campaignGroup,
      List<Long> campaignIds)
      throws ApiException, RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    List<CampaignOperation> operations = new ArrayList<>();
    for (Long campaignId : campaignIds) {
      Campaign campaign = new Campaign();
      campaign.setId(campaignId);
      campaign.setCampaignGroupId(campaignGroup.getId());

      CampaignOperation operation = new CampaignOperation();
      operation.setOperand(campaign);
      operation.setOperator(Operator.SET);
      operations.add(operation);
    }

    CampaignReturnValue returnValue =
        campaignService.mutate(operations.toArray(new CampaignOperation[operations.size()]));
    System.out.printf(
        "The following campaign IDs were added to the campaign group with ID %d:%n",
        campaignGroup.getId());
    for (Campaign campaign : returnValue.getValue()) {
      System.out.printf("\t%d%n", campaign.getId());
    }
  }
1062528
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    LabelServiceInterface labelService =
        adManagerServices.get(session, LabelServiceInterface.class);

    // Create a statement to select labels.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("isActive = :isActive")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("isActive", true);

    // Retrieve a small amount of labels at a time, paging through
    // until all labels have been retrieved.
    int totalResultSetSize = 0;
    do {
      LabelPage page = labelService.getLabelsByStatement(statementBuilder.toStatement());

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

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

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

    // Create a statement to select creative templates.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("type = :type")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("type", CreativeTemplateType.SYSTEM_DEFINED.toString());

    // Retrieve a small amount of creative templates at a time, paging through
    // until all creative templates have been retrieved.
    int totalResultSetSize = 0;
    do {
      CreativeTemplatePage page =
          creativeTemplateService.getCreativeTemplatesByStatement(statementBuilder.toStatement());

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

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

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

    // Get the AdwordsUserListService.
    AdwordsUserListServiceInterface userListService =
        adWordsServices.get(session, AdwordsUserListServiceInterface.class);

    // First rule item group - users who visited the checkout page and had more than one item
    // in their shopping cart.
    StringKey pageTypeKey = new StringKey("ecomm_pagetype");

    StringRuleItem checkoutStringRuleItem = new StringRuleItem();
    checkoutStringRuleItem.setKey(pageTypeKey);
    checkoutStringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    checkoutStringRuleItem.setValue("checkout");

    RuleItem checkoutRuleItem = new RuleItem();
    checkoutRuleItem.setStringRuleItem(checkoutStringRuleItem);

    NumberKey cartSizeKey = new NumberKey("cartsize");

    NumberRuleItem cartSizeNumberRuleItem = new NumberRuleItem();
    cartSizeNumberRuleItem.setKey(cartSizeKey);
    cartSizeNumberRuleItem.setOp(NumberRuleItemNumberOperator.GREATER_THAN);
    cartSizeNumberRuleItem.setValue(1.0);

    RuleItem cartSizeRuleItem = new RuleItem();
    cartSizeRuleItem.setNumberRuleItem(cartSizeNumberRuleItem);

    // Combine the two rule items into a RuleItemGroup so AdWords will AND their rules
    // together.
    RuleItemGroup checkoutMultipleItemGroup = new RuleItemGroup();
    checkoutMultipleItemGroup.setItems(new RuleItem[] {checkoutRuleItem, cartSizeRuleItem});

    // Second rule item group - users who checked out within the next 3 months.
    DateKey checkoutDateKey = new DateKey("checkoutdate");

    DateRuleItem startDateDateRuleItem = new DateRuleItem();
    startDateDateRuleItem.setKey(checkoutDateKey);
    startDateDateRuleItem.setOp(DateRuleItemDateOperator.AFTER);
    startDateDateRuleItem.setValue(new DateTime().toString(DATE_FORMAT_STRING));

    RuleItem startDateRuleItem = new RuleItem();
    startDateRuleItem.setDateRuleItem(startDateDateRuleItem);

    DateRuleItem endDateDateRuleItem = new DateRuleItem();
    endDateDateRuleItem.setKey(checkoutDateKey);
    endDateDateRuleItem.setOp(DateRuleItemDateOperator.BEFORE);
    endDateDateRuleItem.setValue(new DateTime().plusMonths(3).toString(DATE_FORMAT_STRING));

    RuleItem endDateRuleItem = new RuleItem();
    endDateRuleItem.setDateRuleItem(endDateDateRuleItem);

    // Combine the date rule items into a RuleItemGroup.
    RuleItemGroup checkedOutNextThreeMonthsItemGroup = new RuleItemGroup();
    checkedOutNextThreeMonthsItemGroup.setItems(
        new RuleItem[] {startDateRuleItem, endDateRuleItem});

    // Combine the rule item groups into a Rule so AdWords knows how to apply the rules.
    Rule rule = new Rule();
    rule.setGroups(
        new RuleItemGroup[] {checkoutMultipleItemGroup, checkedOutNextThreeMonthsItemGroup});
    // ExpressionRuleUserLists can use either CNF or DNF for matching. CNF means 'at least one item
    // in each rule item group must match', and DNF means 'at least one entire rule item group must
    // match'. DateSpecificRuleUserList only supports DNF. You can also omit the rule type
    // altogether to default to DNF.
    rule.setRuleType(UserListRuleTypeEnumsEnum.DNF);

    // Third and fourth rule item groups.
    // Visitors of a page who visited another page.
    StringKey urlStringKey = new StringKey("url__");

    StringRuleItem site1StringRuleItem = new StringRuleItem();
    site1StringRuleItem.setKey(urlStringKey);
    site1StringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    site1StringRuleItem.setValue("example.com/example1");
    RuleItem site1RuleItem = new RuleItem();
    site1RuleItem.setStringRuleItem(site1StringRuleItem);

    StringRuleItem site2StringRuleItem = new StringRuleItem();
    site2StringRuleItem.setKey(urlStringKey);
    site2StringRuleItem.setOp(StringRuleItemStringOperator.EQUALS);
    site2StringRuleItem.setValue("example.com/example2");
    RuleItem site2RuleItem = new RuleItem();
    site2RuleItem.setStringRuleItem(site2StringRuleItem);

    // Create two RuleItemGroups to show that a visitor browsed two sites.
    RuleItemGroup site1RuleItemGroup = new RuleItemGroup();
    site1RuleItemGroup.setItems(new RuleItem[]{site1RuleItem});
    RuleItemGroup site2RuleItemGroup = new RuleItemGroup();
    site2RuleItemGroup.setItems(new RuleItem[]{site2RuleItem});

    // Create two rules to show that a visitor browsed two sites.
    Rule userVisitedSite1Rule = new Rule();
    userVisitedSite1Rule.setGroups(new RuleItemGroup[]{site1RuleItemGroup});

    Rule userVisitedSite2Rule = new Rule();
    userVisitedSite2Rule.setGroups(new RuleItemGroup[]{site2RuleItemGroup});

    // Create the user list with no restrictions on site visit date.
    ExpressionRuleUserList expressionUserList = new ExpressionRuleUserList();
    String creationTimeString = new DateTime().toString("yyyyMMdd_HHmmss");
    expressionUserList.setName(
        "Expression based user list created at " + creationTimeString);
    expressionUserList.setDescription(
        "Users who checked out in three month window OR visited the checkout page "
        + "with more than one item in their cart");
    expressionUserList.setRule(rule);

    // Optional: Set the prepopulationStatus to REQUESTED to include past users in the user list.
    expressionUserList.setPrepopulationStatus(RuleBasedUserListPrepopulationStatus.REQUESTED);

    // Create the user list restricted to users who visit your site within the next six months.
    DateTime startDate = new DateTime();
    DateTime endDate = startDate.plusMonths(6);

    DateSpecificRuleUserList dateUserList = new DateSpecificRuleUserList();
    dateUserList.setName(
        "Date rule user list created at " + creationTimeString);
    dateUserList.setDescription(String.format("Users who visited the site between %s and %s and "
        + "checked out in three month window OR visited the checkout page "
        + "with more than one item in their cart", startDate.toString(DATE_FORMAT_STRING),
        endDate.toString(DATE_FORMAT_STRING)));
    dateUserList.setRule(rule);

    // Set the start and end dates of the user list.
    dateUserList.setStartDate(startDate.toString(DATE_FORMAT_STRING));
    dateUserList.setEndDate(endDate.toString(DATE_FORMAT_STRING));

    // Create the user list where "Visitors of a page who did visit another page".
    // To create a user list where "Visitors of a page who did not visit another
    // page", change the ruleOperator from AND to AND_NOT.
    CombinedRuleUserList combinedRuleUserList = new CombinedRuleUserList();
    combinedRuleUserList.setName("Combined rule user list created at " + creationTimeString);
    combinedRuleUserList.setDescription("Users who visited two sites.");
    combinedRuleUserList.setLeftOperand(userVisitedSite1Rule);
    combinedRuleUserList.setRightOperand(userVisitedSite2Rule);
    combinedRuleUserList.setRuleOperator(CombinedRuleUserListRuleOperator.AND);

    // Create operations to add the user lists.
    List<UserListOperation> operations =
        Stream.of(expressionUserList, dateUserList, combinedRuleUserList)
            .map(
                userList -> {
                  UserListOperation operation = new UserListOperation();
                  operation.setOperand(userList);
                  operation.setOperator(Operator.ADD);
                  return operation;
                })
            .collect(Collectors.toList());

    // Submit the operations.
    UserListReturnValue result =
        userListService.mutate(operations.toArray(new UserListOperation[operations.size()]));

    // Display the results.
    for (UserList userListResult : result.getValue()) {
      System.out.printf("User list added with ID %d, name '%s', status '%s', list type '%s',"
          + " accountUserListStatus '%s', description '%s'.%n",
          userListResult.getId(),
          userListResult.getName(),
          userListResult.getStatus().getValue(),
          userListResult.getListType() == null ? null : userListResult.getListType().getValue(),
          userListResult.getAccountUserListStatus().getValue(),
          userListResult.getDescription());
    }
  }