use of com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration in project googleads-java-lib by googleads.
the class AdWordsSessionTest method testReadPropertiesFromConfiguration.
/**
* Tests that the builder correctly reads properties from a configuration.
*/
@Test
public void testReadPropertiesFromConfiguration() throws ValidationException {
PropertiesConfiguration config = new PropertiesConfiguration();
config.setProperty("api.adwords.clientCustomerId", "1234567890");
config.setProperty("api.adwords.userAgent", "FooBar");
config.setProperty("api.adwords.developerToken", "devTokendevTokendevTok");
config.setProperty("api.adwords.isPartialFailure", "false");
AdWordsSession session = build(new AdWordsSession.Builder().from(config).withOAuth2Credential(credential));
assertEquals("1234567890", session.getClientCustomerId());
assertEquals("FooBar", session.getUserAgent());
assertEquals("devTokendevTokendevTok", session.getDeveloperToken());
assertFalse(session.isPartialFailure());
ReportingConfiguration reportingConfig = session.getReportingConfiguration();
assertNotNull("reporting configuration is null", reportingConfig);
// Verify that the ReportingConfiguration's attributes are set to the expected default value
// (null).
assertNull("include zero impressions is not null when no reporting options in config", reportingConfig.isIncludeZeroImpressions());
assertNull("skip column header is not null, but no reporting options in config", reportingConfig.isSkipColumnHeader());
assertNull("skip report header is not null, but no reporting options in config", reportingConfig.isSkipReportHeader());
assertNull("skip report summary is not null, but no reporting options in config", reportingConfig.isSkipReportSummary());
assertNull("use raw enum values is not null, but no reporting options in config", reportingConfig.isUseRawEnumValues());
assertNull("download timeout is not null, but no reporting options in config", reportingConfig.getReportDownloadTimeout());
}
use of com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration in project googleads-java-lib by googleads.
the class AdWordsSessionTest method testBuilder_withReportingConfiguration.
@Test
public void testBuilder_withReportingConfiguration() throws Exception {
ReportingConfiguration reportingConfiguration = new ReportingConfiguration.Builder().skipReportHeader(true).skipReportSummary(true).build();
AdWordsSession adWordsSession = build(new AdWordsSession.Builder().withUserAgent("FooBar").withEndpoint("https://www.google.com").withOAuth2Credential(credential).withDeveloperToken("developerToken").withReportingConfiguration(reportingConfiguration));
ReportingConfiguration sessionReportingConfig = adWordsSession.getReportingConfiguration();
assertNotNull("reporting configuration should not be null when passed to the builder", sessionReportingConfig);
}
use of com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration 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.lib.client.reporting.ReportingConfiguration in project googleads-java-lib by googleads.
the class DownloadCriteriaReportWithAwql method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param reportFile the output file for the report contents.
* @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 written to {@code reportFile}.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, String reportFile) throws ReportDownloadResponseException, ReportException, IOException {
// Create query.
ReportQuery query = new ReportQuery.Builder().fields("CampaignId", "AdGroupId", "Id", "Criteria", "CriteriaType", "Impressions", "Clicks", "Cost").from(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT).where("Status").in("ENABLED", "PAUSED").during(ReportDefinitionDateRangeType.LAST_7_DAYS).build();
// 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(true).build();
session.setReportingConfiguration(reportingConfiguration);
ReportDownloaderInterface reportDownloader = adWordsServices.getUtility(session, ReportDownloaderInterface.class);
// Set the property api.adwords.reportDownloadTimeout or call
// ReportDownloader.setReportDownloadTimeout to set a timeout (in milliseconds)
// for CONNECT and READ in report downloads.
ReportDownloadResponse response = reportDownloader.downloadReport(query.toString(), DownloadFormat.CSV);
response.saveToFile(reportFile);
System.out.printf("Report successfully downloaded to: %s%n", reportFile);
}
use of com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration in project googleads-java-lib by googleads.
the class StreamCriteriaReportResults method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @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.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session) throws ReportDownloadResponseException, ReportException, IOException {
// Create the query.
ReportQuery query = new ReportQuery.Builder().fields("Id", "AdNetworkType1", "Impressions").from(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT).where("Status").in("ENABLED", "PAUSED").during(ReportDefinitionDateRangeType.LAST_7_DAYS).build();
// 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(true).skipColumnHeader(true).skipReportSummary(true).includeZeroImpressions(false).build();
session.setReportingConfiguration(reportingConfiguration);
ReportDownloaderInterface reportDownloader = adWordsServices.getUtility(session, ReportDownloaderInterface.class);
BufferedReader reader = null;
try {
// Set the property api.adwords.reportDownloadTimeout or call
// ReportDownloader.setReportDownloadTimeout to set a timeout (in milliseconds)
// for CONNECT and READ in report downloads.
final ReportDownloadResponse response = reportDownloader.downloadReport(query.toString(), DownloadFormat.CSV);
// Read the response as a BufferedReader.
reader = new BufferedReader(new InputStreamReader(response.getInputStream(), UTF_8));
// Map to store total impressions by ad network type 1.
Map<String, Long> impressionsByAdNetworkType1 = Maps.newTreeMap();
// Stream the results one line at a time and perform any line-specific processing.
String line;
Splitter splitter = Splitter.on(',');
while ((line = reader.readLine()) != null) {
System.out.println(line);
// Split the line into a list of field values.
List<String> values = splitter.splitToList(line);
// Update the total impressions for the ad network type 1 value.
String adNetworkType1 = values.get(1);
Long impressions = Longs.tryParse(values.get(2));
if (impressions != null) {
Long impressionsTotal = impressionsByAdNetworkType1.get(adNetworkType1);
impressionsTotal = impressionsTotal == null ? 0L : impressionsTotal;
impressionsByAdNetworkType1.put(adNetworkType1, impressionsTotal + impressions);
}
}
// Print the impressions totals by ad network type 1.
System.out.println();
System.out.printf("Total impressions by ad network type 1:%n%s%n", Joiner.on(SystemUtils.LINE_SEPARATOR).join(impressionsByAdNetworkType1.entrySet()));
} finally {
if (reader != null) {
reader.close();
}
}
}
Aggregations