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);
}
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);
}
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.");
}
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);
}
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, "");
}
Aggregations