//Copyright 2017 Google Inc. All Rights Reserved.
////Licensed under the Apache License, Version 2.0 (the "License");//you may not use this file except in compliance with the License.//You may obtain a copy of the License at//////Unless required by applicable law or agreed to in writing, software//distributed under the License is distributed on an "AS IS" BASIS,//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.//See the License for the specific language governing permissions and//limitations under the License.
import com.google.api.ads.adwords.axis.factory.AdWordsServices;import com.google.api.ads.adwords.lib.client.AdWordsSession;import com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration;import com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface;import com.google.api.ads.adwords.lib.jaxb.v201702.DownloadFormat;import com.google.api.ads.adwords.lib.utils.ReportDownloadResponse;import com.google.api.ads.adwords.lib.utils.ReportDownloadResponseException;import com.google.api.ads.adwords.lib.utils.v201702.ReportDownloaderInterface;import com.google.api.ads.common.lib.auth.OfflineCredentials;import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;import com.google.api.client.auth.oauth2.Credential;import java.io.File;
/*** This example downloads a criteria performance report with AWQL.** <p>Credentials and properties in {@code fromFile()} are pulled from the* "ads.properties" file. See README for more info.*/public class DownloadCriteriaReportWithAwql {
public static void main(String[] args) throws Exception { // Generate a refreshable OAuth2 credential. Credential oAuth2Credential = new OfflineCredentials.Builder() .forApi(Api.ADWORDS) .fromFile() .build() .generateCredential();
// Construct an AdWordsSession. AdWordsSession session = new AdWordsSession.Builder() .fromFile() .withOAuth2Credential(oAuth2Credential) .build();
AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
// Location to download report to. String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";
runExample(adWordsServices, session, reportFile);}
public static void runExample( AdWordsServicesInterface adWordsServices, AdWordsSession session, String reportFile) throws Exception { // Create query. String query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, " + "Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT " + "WHERE Status IN [ENABLED, PAUSED] " + "DURING YESTERDAY";
// 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) // Set to false to exclude rows with zero impressions. .includeZeroImpressions(true) .build(); session.setReportingConfiguration(reportingConfiguration); ReportDownloaderInterface reportDownloader = adWordsServices.getUtility(session, ReportDownloaderInterface.class);
try { // 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, DownloadFormat.CSV); response.saveToFile(reportFile); System.out.printf("Report successfully downloaded to: %s%n", reportFile); } catch (ReportDownloadResponseException e) { System.out.printf("Report was not downloaded due to: %s%n", e); }}}# Credentials to use for accessing the AdWords API
# OfflineCredentials authentication properties.# A refresh token can be acquired using the GetRefreshToken example.api.adwords.refreshToken=1/PEwUg5fUBaVUbncasQQdIaMXrtafucq93U_yOenXvOxsxBHdy4XpMWFkcrec2ZB3# If you do not have a client ID or secret, please create a project in the# Developers console. See the following link for more information:api.adwords.clientId=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxapi.adwords.clientSecret=xxxxxxxxxxxxxxxxxx# If you are using a service account, specify the path to the JSON# key file instead of using the above authentication properties.#api.adwords.jsonKeyFilePath=67147-4683fa608f31.json# If you are using a service account, specify the email address of# the user account to impersonate. Sees# for details.#api.adwords.serviceAccountUser=AdwordDataFetcher...@awesome-treat-187409.iam.gserviceaccount.com
#api.adwords.clientCustomerId=XXX-XXXX-XXX# Optional. Set a friendly application name identifier.#api.adwords.userAgent=api.adwords.developerToken=xxxxxxxxxxxxxxxxxxxxxx#api.adwords.isPartialFailure=false
# Optional. Configure reporting to skip header, column names, or summary rows# in responses, or return enum field values as enum values instead of display# values. All values default to false if omitted. api.adwords.reporting.skipHeader=false api.adwords.reporting.skipColumnHeader=false api.adwords.reporting.skipSummary=false api.adwords.reporting.useRawEnumValues=false
# Change the AdWords API endpoint. Optional.api.adwords.endpoint=https://adwords.google.com/
# [JVM] The following properties are JVM-level properties and# are read and set only ONCE, when the AdWordsServices# class is first loaded.
# Enable/disable compression. Default is disabled. See the following link for# more information:# api.adwords.useCompression=false
# Report download connect/read timeout. Defaults to 3 minutes if omitted.# A value of 0 indicates infinite timeout.# Can be overridden on each instance of ReportDownloader via# ReportDownloader.setReportDownloadTimeout(timeoutInMillis).# Specify a value >= 0 in milliseconds.api.adwords.reportDownloadTimeout=180000
# Enable/disable automatic OAuth2 token refreshing. Default is enabled.# api.adwords.refreshOAuth2Token=true
# Set the AdWords API request timeout in milliseconds. Defaults to 1200000.# api.adwords.soapRequestTimeout=1200000
# Optional. Set to false to not include utility usage information in the user agent in requests.# Defaults to true (usage included).# api.adwords.includeUtilitiesInUserAgent=true[06 Feb 2018 15:11:22,121-report_download:WARN:main] Request made: Service: reportdownload Method: POST clientCustomerId: 930-632-3400 URL: https://adwords.google.com//api/adwords/reportdownload/v201702 Request ID: null ResponseTime(ms): null OperationsCount: null IsFault: true FaultMessage: com.google.api.ads.adwords.lib.utils.ReportException: 500: Internal Server Error[06 Feb 2018 15:11:22,122-report_download:INFO:main] HTTP request:accept-encoding: [gzip]authorization: REDACTEDuser-agent: [http://www.jetsynthesys.com/ (AwApi-Java, AdWords-Axis/3.10.0, Common-Java/3.10.0, Axis/1.4, Java/1.8.0_151, maven, ReportDownloader)]developertoken: REDACTEDclientcustomerid: xxxxxxxskipreportheader: falseskipcolumnheader: falseskipreportsummary: falseincludezeroimpressions: true
Content:__rdquery: SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ENABLED, PAUSED] DURING YESTERDAY__fmt: CSV
[06 Feb 2018 15:11:22,122-report_download:INFO:main] HTTP response:500 Internal Server Errorcache-control: [private, max-age=0]content-encoding: [gzip]content-type: [text/xml]date: [Tue, 06 Feb 2018 09:41:22 GMT]expires: [Tue, 06 Feb 2018 09:41:22 GMT]transfer-encoding: [chunked]x-frame-options: [SAMEORIGIN]alt-svc: [hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"]server: [GSE]x-content-type-options: [nosniff]x-xss-protection: [1; mode=block]
Content:REDACTED REPORT DATAReport was not downloaded due to: HTTP Response Code: 500, Type: InternalApiError.UNEXPECTED_INTERNAL_API_ERROR