Search in sources :

Example 16 with Selector

use of com.google.api.ads.adwords.axis.v201809.cm.Selector in project googleads-java-lib by googleads.

the class SelectorBuilderTest method testPagingAndLimits.

/**
 * Tests the offset, limit and paging logic of the builder.
 */
@Test
public void testPagingAndLimits() {
    SelectorBuilder builder = new SelectorBuilder();
    builder = builder.offset(10);
    Selector selector = builder.build();
    assertNotNull(selector.getPaging());
    assertNotNull(selector.getPaging().getStartIndex());
    assertNull(selector.getPaging().getNumberResults());
    assertEquals(10, selector.getPaging().getStartIndex().intValue());
    selector = builder.offset(10).limit(20).build();
    assertNotNull(selector.getPaging());
    assertNotNull(selector.getPaging().getStartIndex());
    assertNotNull(selector.getPaging().getNumberResults());
    assertEquals(10, selector.getPaging().getStartIndex().intValue());
    assertEquals(20, selector.getPaging().getNumberResults().intValue());
    selector = builder.offset(10).limit(20).increaseOffsetBy(5).build();
    assertNotNull(selector.getPaging());
    assertNotNull(selector.getPaging().getStartIndex());
    assertNotNull(selector.getPaging().getNumberResults());
    assertEquals(15, selector.getPaging().getStartIndex().intValue());
    assertEquals(20, selector.getPaging().getNumberResults().intValue());
    selector = builder.offset(10).limit(20).increaseOffsetBy(5).removeLimitAndOffset().build();
    assertNull(selector.getPaging());
    selector = builder.offset(10).limit(20).increaseOffsetBy(5).removeLimitAndOffset().offset(55).limit(4).build();
    assertNotNull(selector.getPaging());
    assertNotNull(selector.getPaging().getStartIndex());
    assertNotNull(selector.getPaging().getNumberResults());
    assertEquals(55, selector.getPaging().getStartIndex().intValue());
    assertEquals(4, selector.getPaging().getNumberResults().intValue());
    checkUtilitiesState(false);
}
Also used : Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector) Test(org.junit.Test)

Example 17 with Selector

use of com.google.api.ads.adwords.axis.v201809.cm.Selector in project googleads-java-lib by googleads.

the class SelectorBuilderTest method testOrderByBuild.

/**
 * Tests the order by criteria
 */
@Test
public void testOrderByBuild() {
    SelectorBuilder builder = new SelectorBuilder();
    builder = builder.orderAscBy(CampaignField.AdvertisingChannelType);
    Selector selector = builder.build();
    assertNotNull(selector.getOrdering());
    assertEquals(1, selector.getOrdering().length);
    OrderBy orderBy = selector.getOrdering()[0];
    assertEquals("AdvertisingChannelType", orderBy.getField());
    assertEquals(SortOrder.ASCENDING, orderBy.getSortOrder());
    builder.orderAscBy(CampaignField.Amount).orderDescBy(CampaignField.AdvertisingChannelType);
    selector = builder.build();
    assertNotNull(selector.getOrdering());
    assertEquals(3, selector.getOrdering().length);
    orderBy = selector.getOrdering()[0];
    assertEquals("AdvertisingChannelType", orderBy.getField());
    assertEquals(SortOrder.ASCENDING, orderBy.getSortOrder());
    orderBy = selector.getOrdering()[1];
    assertEquals("Amount", orderBy.getField());
    assertEquals(SortOrder.ASCENDING, orderBy.getSortOrder());
    orderBy = selector.getOrdering()[2];
    assertEquals("AdvertisingChannelType", orderBy.getField());
    assertEquals(SortOrder.DESCENDING, orderBy.getSortOrder());
    // Removing the OrderBy for AdvertisingChannelType
    selector = builder.removeOrderBy("AdvertisingChannelType").build();
    assertNotNull(selector.getOrdering());
    assertEquals(1, selector.getOrdering().length);
    orderBy = selector.getOrdering()[0];
    assertEquals("Amount", orderBy.getField());
    assertEquals(SortOrder.ASCENDING, orderBy.getSortOrder());
    checkUtilitiesState(true);
}
Also used : OrderBy(com.google.api.ads.adwords.axis.v201809.cm.OrderBy) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector) Test(org.junit.Test)

Example 18 with Selector

use of com.google.api.ads.adwords.axis.v201809.cm.Selector in project googleads-java-lib by googleads.

the class ParallelReportDownload method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param numberOfThreads number of threads to use for concurrent report requests.
 * @param maxElapsedSecondsPerCustomer the maximum number of seconds to wait for each report
 *     request to complete.
 * @throws ApiException if the API request to retrieve managed customers failed with one or more
 *     service errors.
 * @throws RemoteException if the API request to retrieve managed customers failed due to other
 *     errors.
 * @throws DetailedReportDownloadResponseException if the report request failed with a detailed
 *     error from the reporting service.
 * @throws ReportDownloadResponseException if the report request failed with a general error from
 *     the reporting service.
 * @throws ReportException if the report request failed due to a transport layer error.
 * @throws IOException if the report's contents could not be read from the response.
 * @throws ValidationException if creation of an ImmutableAdWordsSession for a customer failed due
 *     to validation issues.
 * @throws InterruptedException if the thread was interrupted while waiting for all report
 *     downloads to complete.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, ImmutableAdWordsSession session, int numberOfThreads, int maxElapsedSecondsPerCustomer) throws ReportDownloadResponseException, ReportException, IOException, ValidationException, InterruptedException {
    // Retrieve all accounts under the manager account.
    Map<Long, ManagedCustomer> managedCustomers = getAllManagedCustomers(adWordsServices, session);
    System.out.printf("Downloading report for %d managed customers.%n", managedCustomers.size());
    // Create selector for the report definition.
    Selector selector = new Selector();
    selector.getFields().addAll(Arrays.asList("CampaignId", "AdGroupId", "Impressions", "Clicks", "Cost"));
    // Create report definition.
    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setReportName("Custom ADGROUP_PERFORMANCE_REPORT");
    reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.LAST_7_DAYS);
    reportDefinition.setReportType(ReportDefinitionReportType.ADGROUP_PERFORMANCE_REPORT);
    reportDefinition.setDownloadFormat(DownloadFormat.CSV);
    reportDefinition.setSelector(selector);
    // Optional: Set the reporting configuration of the session to suppress header, column name, or
    // summary rows in the report output. You can also configure this via your ads.properties
    // configuration file. See AdWordsSession.Builder.from(Configuration) for details.
    // In addition, you can set whether you want to explicitly include or exclude zero impression
    // rows.
    ReportingConfiguration reportingConfiguration = new ReportingConfiguration.Builder().skipReportHeader(false).skipColumnHeader(false).skipReportSummary(false).includeZeroImpressions(false).build();
    // Create a thread pool for submitting report requests.
    ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads);
    // Customize this builder if you want to change the backoff policy on retryable report
    // failures.
    ExponentialBackOff.Builder backOffBuilder = new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(maxElapsedSecondsPerCustomer * 1000);
    File reportDirectory = Files.createTempDir();
    // List to keep track of the progress of each customer's report download task.
    List<ReportDownloadFutureTask> reportDownloadFutureTasks = new ArrayList<>();
    for (ManagedCustomer managedCustomer : managedCustomers.values()) {
        File outputFile = new File(reportDirectory, String.format("adgroup_%010d.csv", managedCustomer.getCustomerId()));
        ImmutableAdWordsSession sessionForCustomer = session.newBuilder().withClientCustomerId(Long.toString(managedCustomer.getCustomerId())).withReportingConfiguration(reportingConfiguration).buildImmutable();
        ReportDownloadFutureTask reportDownloadFutureTask = new ReportDownloadFutureTask(new ReportDownloadCallable(sessionForCustomer, adWordsServices, reportDefinition, outputFile, backOffBuilder.build()));
        // Use execute instead of submit since there is no need to get a Future for a FutureTask.
        // Instead, store this ReportDownloadFutureTask in the list so that it can be used later
        // to check the result and determine the task context (client customer ID).
        threadPool.execute(reportDownloadFutureTask);
        reportDownloadFutureTasks.add(reportDownloadFutureTask);
    }
    // All callables have been submitted. Shut down the thread pool.
    threadPool.shutdown();
    // Wait for the thread pool to terminate.
    threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    System.out.println();
    System.out.println("All downloads completed. Results:");
    Map<String, File> successfulReports = Maps.newHashMap();
    Map<String, Exception> failedReports = Maps.newHashMap();
    for (ReportDownloadFutureTask reportDownloadFutureTask : reportDownloadFutureTasks) {
        String clientCustomerId = reportDownloadFutureTask.getClientCustomerId();
        try {
            File reportFile = reportDownloadFutureTask.get();
            successfulReports.put(clientCustomerId, reportFile);
        } catch (CancellationException | InterruptedException | ExecutionException e) {
            failedReports.put(clientCustomerId, e);
        }
    }
    System.out.println("Successful reports:");
    successfulReports.forEach((clientCustomerId, reportFile) -> System.out.printf("\tClient ID %s => '%s'%n", clientCustomerId, reportFile));
    System.out.println("Failed reports:");
    failedReports.forEach((clientCustomerId, exception) -> System.out.printf("\tClient ID %s => Exception: %s%n", clientCustomerId, exception));
    System.out.println("End of results.");
}
Also used : ImmutableAdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession.ImmutableAdWordsSession) ManagedCustomer(com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomer) ArrayList(java.util.ArrayList) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) DetailedReportDownloadResponseException(com.google.api.ads.adwords.lib.utils.DetailedReportDownloadResponseException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) CancellationException(java.util.concurrent.CancellationException) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) IOException(java.io.IOException) ReportDownloadResponseException(com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException) RemoteException(java.rmi.RemoteException) ExecutionException(java.util.concurrent.ExecutionException) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) ReportException(com.google.api.ads.adwords.lib.utils.ReportException) CancellationException(java.util.concurrent.CancellationException) ExecutorService(java.util.concurrent.ExecutorService) ExecutionException(java.util.concurrent.ExecutionException) File(java.io.File) ReportDefinition(com.google.api.ads.adwords.lib.jaxb.v201809.ReportDefinition) ReportingConfiguration(com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration) Selector(com.google.api.ads.adwords.lib.jaxb.v201809.Selector)

Example 19 with Selector

use of com.google.api.ads.adwords.axis.v201809.cm.Selector in project googleads-java-lib by googleads.

the class GetCampaignCriterionBidModifierSimulations method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param campaignId the ID of the campaign.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId) throws RemoteException {
    // Get the DataService.
    DataServiceInterface dataService = adWordsServices.get(session, DataServiceInterface.class);
    // Create selector.
    Selector selector = new SelectorBuilder().fields(DataField.BidModifier, DataField.CampaignId, DataField.CriterionId, DataField.StartDate, DataField.EndDate, DataField.LocalClicks, DataField.LocalCost, DataField.LocalImpressions, DataField.TotalLocalClicks, DataField.TotalLocalCost, DataField.TotalLocalImpressions, DataField.RequiredBudget).equals(DataField.CampaignId, campaignId.toString()).limit(PAGE_SIZE).build();
    // Display bid landscapes.
    int landscapePointsInPreviousPage = 0;
    int startIndex = 0;
    do {
        // Offset the start index by the number of landscape points in the last retrieved page,
        // NOT the number of entries (bid landscapes) in the page.
        startIndex += landscapePointsInPreviousPage;
        selector.getPaging().setStartIndex(startIndex);
        // Reset the count of landscape points in preparation for processing the next page.
        landscapePointsInPreviousPage = 0;
        // Request the next page of bid landscapes.
        CriterionBidLandscapePage page = dataService.getCampaignCriterionBidLandscape(selector);
        if (page.getEntries() != null) {
            for (CriterionBidLandscape criterionBidLandscape : page.getEntries()) {
                System.out.printf("Found campaign-level criterion bid modifier landscape for" + " criterion with ID %d, start date '%s', end date '%s', and" + " landscape points:%n", criterionBidLandscape.getCriterionId(), criterionBidLandscape.getStartDate(), criterionBidLandscape.getEndDate());
                for (BidLandscapeLandscapePoint bidLandscapePoint : criterionBidLandscape.getLandscapePoints()) {
                    landscapePointsInPreviousPage++;
                    System.out.printf("  {bid modifier: %.2f => clicks: %d, cost: %d, impressions: %d, " + "total clicks: %d, total cost: %d, total impressions: %d, and " + "required budget: %d%n", bidLandscapePoint.getBidModifier(), bidLandscapePoint.getClicks(), bidLandscapePoint.getCost().getMicroAmount(), bidLandscapePoint.getImpressions(), bidLandscapePoint.getTotalLocalClicks(), bidLandscapePoint.getTotalLocalCost().getMicroAmount(), bidLandscapePoint.getTotalLocalImpressions(), bidLandscapePoint.getRequiredBudget().getMicroAmount());
                }
            }
        }
    } while (landscapePointsInPreviousPage >= PAGE_SIZE);
}
Also used : SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) CriterionBidLandscapePage(com.google.api.ads.adwords.axis.v201809.cm.CriterionBidLandscapePage) CriterionBidLandscape(com.google.api.ads.adwords.axis.v201809.cm.CriterionBidLandscape) DataServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.DataServiceInterface) BidLandscapeLandscapePoint(com.google.api.ads.adwords.axis.v201809.cm.BidLandscapeLandscapePoint) BidLandscapeLandscapePoint(com.google.api.ads.adwords.axis.v201809.cm.BidLandscapeLandscapePoint) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Example 20 with Selector

use of com.google.api.ads.adwords.axis.v201809.cm.Selector in project googleads-java-lib by googleads.

the class GetProductCategoryTaxonomy method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
    // Get the constant data service.
    ConstantDataServiceInterface constantDataService = adWordsServices.get(session, ConstantDataServiceInterface.class);
    Selector selector = new SelectorBuilder().equals(ConstantDataField.Country, "US").build();
    ProductBiddingCategoryData[] results = constantDataService.getProductBiddingCategoryData(selector);
    // List of top level category nodes.
    List<CategoryNode> rootCategories = new ArrayList<>();
    // Map of category ID to category node for all categories found in the results.
    Map<Long, CategoryNode> biddingCategories = Maps.newHashMap();
    for (ProductBiddingCategoryData productBiddingCategoryData : results) {
        Long id = productBiddingCategoryData.getDimensionValue().getValue();
        String name = productBiddingCategoryData.getDisplayValue(0).getValue();
        CategoryNode node = biddingCategories.get(id);
        if (node == null) {
            node = new CategoryNode(id, name);
            biddingCategories.put(id, node);
        } else if (node.name == null) {
            // Ensure that the name attribute for the node is set. Name will be null for nodes added
            // to biddingCategories as a result of being a parentNode below.
            node.name = name;
        }
        if (productBiddingCategoryData.getParentDimensionValue() != null && productBiddingCategoryData.getParentDimensionValue().getValue() != null) {
            Long parentId = productBiddingCategoryData.getParentDimensionValue().getValue();
            CategoryNode parentNode = biddingCategories.get(parentId);
            if (parentNode == null) {
                parentNode = new CategoryNode(parentId);
                biddingCategories.put(parentId, parentNode);
            }
            parentNode.children.add(node);
        } else {
            rootCategories.add(node);
        }
    }
    displayCategories(rootCategories, "");
}
Also used : SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) ArrayList(java.util.ArrayList) ConstantDataServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.ConstantDataServiceInterface) ProductBiddingCategoryData(com.google.api.ads.adwords.axis.v201809.cm.ProductBiddingCategoryData) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Aggregations

Selector (com.google.api.ads.adwords.axis.v201809.cm.Selector)36 Test (org.junit.Test)27 SelectorBuilder (com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder)22 Selector (com.google.api.ads.adwords.jaxws.v201809.cm.Selector)14 ArrayList (java.util.ArrayList)9 SimpleDateFormat (java.text.SimpleDateFormat)7 DateFormat (java.text.DateFormat)6 DateTime (org.joda.time.DateTime)6 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)5 CampaignPage (com.google.api.ads.adwords.axis.v201809.cm.CampaignPage)5 CampaignServiceInterface (com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface)5 OrderBy (com.google.api.ads.adwords.jaxws.v201809.cm.OrderBy)4 Predicate (com.google.api.ads.adwords.jaxws.v201809.cm.Predicate)4 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)4 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)4 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)4 RemoteException (java.rmi.RemoteException)4 AdWordsServices (com.google.api.ads.adwords.axis.factory.AdWordsServices)3 AdGroupAd (com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd)3 AdGroupAdPage (com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdPage)3