Java源码示例:com.google.api.ads.adwords.lib.utils.ReportException

示例1
/**
 * Downloads report from API (with retry logic) and transforms the result into a
 * {@link ReportData} object.
 */
@Override
public ReportData call() throws AlertProcessingException {
  ReportDownloaderInterface reportDownloader =
      AdWordsServicesUtil.getUtility(session, ReportDownloaderInterface.class);

  ReportDownloadResponse reportDownloadResponse = null;
  try {
    reportDownloadResponse =
        reportDownloader.downloadReport(reportQuery.generateAWQL(), DownloadFormat.GZIPPED_CSV);
  } catch (ReportException | ReportDownloadResponseException e) {
    String msg = "Failed to download report account " + session.getClientCustomerId() + ".";
    LOGGER.error(msg, e);
    throw new AlertProcessingException(msg, e);
  }
  
  InputStream inputStream = reportDownloadResponse.getInputStream();
  return handleReportStreamResult(inputStream);
}
 
示例2
/**
 * Logs the specified request and response information.
 *
 * <p>Note that in order to avoid any temptation to consume the contents of the response, this
 * does <em>not</em> take an {@link com.google.api.client.http.HttpResponse} object, but instead
 * accepts the status code and message from the response.
 */
public void logRequest(
    @Nullable HttpRequest request, int statusCode, @Nullable String statusMessage) {
  boolean isSuccess = HttpStatusCodes.isSuccess(statusCode);
  if (!loggerDelegate.isSummaryLoggable(isSuccess)
      && !loggerDelegate.isDetailsLoggable(isSuccess)) {
    return;
  }

  // Populate the RequestInfo builder from the request.
  RequestInfo requestInfo = buildRequestInfo(request);

  // Populate the ResponseInfo builder from the response.
  ResponseInfo responseInfo = buildResponseInfo(request, statusCode, statusMessage);

  RemoteCallReturn.Builder remoteCallReturnBuilder =
      new RemoteCallReturn.Builder().withRequestInfo(requestInfo).withResponseInfo(responseInfo);
  if (!isSuccess) {
    remoteCallReturnBuilder.withException(
        new ReportException(String.format("%s: %s", statusCode, statusMessage)));
  }
  RemoteCallReturn remoteCallReturn = remoteCallReturnBuilder.build();
  loggerDelegate.logRequestSummary(remoteCallReturn);
  loggerDelegate.logRequestDetails(remoteCallReturn);
}
 
示例3
/**
 * Downloads the file from the API into an InputStream.
 *
 * @return the InputStream from the online report, null if httpStatus is not {@code HTTP_OK}.
 */
private InputStream getReportInputStream() {
  ReportDownloaderInterface reportDownloader =
      AdWordsServicesUtil.getUtility(session, ReportDownloaderInterface.class);
  
  InputStream result = null;
  try {
    ReportDownloadResponse reportDownloadResponse =
        reportDownloader.downloadReport(reportDefinition);
    result = reportDownloadResponse.getInputStream();
  } catch (ReportException | ReportDownloadResponseException e) {
    logger.error(
        "Failed to download report stream for {} with account {}.",
        reportDefinition.getReportType(),
        session.getClientCustomerId(),
        e);
  }

  return result;
}
 
示例4
/**
 * Gets the report download response from the API and retries on failure.
 */
@VisibleForTesting
ReportDownloadResponse getReportDownloadResponse() throws ReportProcessingException {
  ReportDownloaderInterface reportDownloader =
      AdWordsServicesUtil.getUtility(session, ReportDownloaderInterface.class);
  
  ReportDownloadResponse result = null;
  try {
    result = reportDownloader.downloadReport(reportDefinition);
  } catch (ReportException | ReportDownloadResponseException e) {
    String msg =
        "Failed to download report file for "
            + reportDefinition.getReportType()
            + " with account "
            + session.getClientCustomerId()
            + ".";
    logger.error(msg, e);
    throw new ReportProcessingException(msg, e);
  }

  return result;
}
 
示例5
@Override
public ReportDownloadResponse downloadReport(ReportDefinition reportDefinition)
    throws ReportException, ReportDownloadResponseException {
  return adHocReportDownloadHelper.downloadReport(
      new XmlReportDefinitionRequest(reportDefinition),
      new DetailedReportDownloadResponseException.Builder());
}
 
示例6
@Override
public ReportDownloadResponse downloadReport(String reportQuery, DownloadFormat format)
    throws ReportException, ReportDownloadResponseException {
  return adHocReportDownloadHelper.downloadReport(
      new AwqlReportRequest(reportQuery, format),
      new DetailedReportDownloadResponseException.Builder());
}
 
示例7
/**
 * Invokes {@link ReportDownloader#downloadReport(ReportDefinition)} or
 * {@link ReportDownloader#downloadReport(String, DownloadFormat)}, depending on whether this
 * instance is configured to use AWQL.
 *
 * @param downloadFormat the DownloadFormat for the request
 * @param rawResponse the response to return from the mocked ad hoc helper
 */
private ReportDownloadResponse downloadReport(DownloadFormat downloadFormat,
    RawReportDownloadResponse rawResponse, String expectedErrorText) throws ReportException,
    ReportDownloadResponseException {
  if (rawResponse.getHttpStatus() == 200) {
    // Response indicates success, so return a ReportDownloadResponse.
    when(
            adHocDownloadHelper.downloadReport(
                Matchers.any(ReportRequest.class), Matchers.any(Builder.class)))
        .thenReturn(new ReportDownloadResponse(rawResponse));
  } else {
    // Response indicates failure, so throw an exception.
    when(
            adHocDownloadHelper.downloadReport(
                Matchers.any(ReportRequest.class), Matchers.any(Builder.class)))
        .thenThrow(new Builder().build(rawResponse.getHttpStatus(), expectedErrorText));
  }

  if (isUseAwql) {
    return reportDownloader.downloadReport(AWQL_REQUEST, downloadFormat);
  } else {
    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setSelector(new Selector());
    reportDefinition
        .getSelector()
        .getFields()
        .addAll(Arrays.asList("CampaignId", "CampaignName", "Impressions"));
    reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.LAST_7_DAYS);
    reportDefinition.setReportName("Custom report");
    reportDefinition.setReportType(ReportDefinitionReportType.CAMPAIGN_PERFORMANCE_REPORT);
    return reportDownloader.downloadReport(reportDefinition);
  }
}
 
示例8
public static void main(String[] args) {
  AdWordsSession session;
  try {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential =
        new OfflineCredentials.Builder()
            .forApi(Api.ADWORDS)
            .fromFile()
            .build()
            .generateCredential();

    // Construct an AdWordsSession.
    session =
        new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
  } catch (ConfigurationLoadException cle) {
    System.err.printf(
        "Failed to load configuration from the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, cle);
    return;
  } catch (ValidationException ve) {
    System.err.printf(
        "Invalid configuration in the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, ve);
    return;
  } catch (OAuthException oe) {
    System.err.printf(
        "Failed to create OAuth credentials. Check OAuth settings in the %s file. "
            + "Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, oe);
    return;
  }

  AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

  // Location to download report to.
  String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";

  try {
    runExample(adWordsServices, session, reportFile);
  } catch (DetailedReportDownloadResponseException dre) {
    // A DetailedReportDownloadResponseException will be thrown if the HTTP status code in the
    // response indicates an error occurred and the response body contains XML with further
    // information, such as the fieldPath and trigger.
    System.err.printf(
        "Report was not downloaded due to a %s with errorText '%s', trigger '%s' and "
            + "field path '%s'%n",
        dre.getClass().getSimpleName(),
        dre.getErrorText(),
        dre.getTrigger(),
        dre.getFieldPath());
  } catch (ReportDownloadResponseException rde) {
    // A ReportDownloadResponseException will be thrown if the HTTP status code in the response
    // indicates an error occurred, but the response did not contain further details.
    System.err.printf("Report was not downloaded due to: %s%n", rde);
  } catch (ReportException re) {
    // A ReportException will be thrown if the download failed due to a transport layer exception.
    System.err.printf("Report was not downloaded due to transport layer exception: %s%n", re);
  } catch (IOException ioe) {
    // An IOException in this example indicates that the report's contents could not be written
    // to the output file.
    System.err.printf(
        "Report was not written to file %s due to an IOException: %s%n", reportFile, ioe);
  }
}
 
示例9
/**
 * 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)
          // Set to false to exclude rows with zero impressions.
          .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);
}
 
示例10
public static void main(String[] args) {
  AdWordsSession session;
  try {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential =
        new OfflineCredentials.Builder()
            .forApi(Api.ADWORDS)
            .fromFile()
            .build()
            .generateCredential();

    // Construct an AdWordsSession.
    session =
        new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
  } catch (ConfigurationLoadException cle) {
    System.err.printf(
        "Failed to load configuration from the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, cle);
    return;
  } catch (ValidationException ve) {
    System.err.printf(
        "Invalid configuration in the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, ve);
    return;
  } catch (OAuthException oe) {
    System.err.printf(
        "Failed to create OAuth credentials. Check OAuth settings in the %s file. "
            + "Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, oe);
    return;
  }

  AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

  // Location to download report to.
  String reportFile = System.getProperty("user.home") + File.separatorChar + "report.csv";

  try {
    runExample(adWordsServices, session, reportFile);
  } catch (DetailedReportDownloadResponseException dre) {
    // A DetailedReportDownloadResponseException will be thrown if the HTTP status code in the
    // response indicates an error occurred and the response body contains XML with further
    // information, such as the fieldPath and trigger.
    System.err.printf(
        "Report was not downloaded due to a %s with errorText '%s', trigger '%s' and "
            + "field path '%s'%n",
        dre.getClass().getSimpleName(),
        dre.getErrorText(),
        dre.getTrigger(),
        dre.getFieldPath());
  } catch (ReportDownloadResponseException rde) {
    // A ReportDownloadResponseException will be thrown if the HTTP status code in the response
    // indicates an error occurred, but the response did not contain further details.
    System.err.printf("Report was not downloaded due to: %s%n", rde);
  } catch (ReportException re) {
    // A ReportException will be thrown if the download failed due to a transport layer exception.
    System.err.printf("Report was not downloaded due to transport layer exception: %s%n", re);
  } catch (IOException ioe) {
    // An IOException in this example indicates that the report's contents could not be written
    // to the output file.
    System.err.printf(
        "Report was not written to file %s due to an IOException: %s%n", reportFile, ioe);
  }
}
 
示例11
/**
 * 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 selector.
  Selector selector = new Selector();
  selector.getFields().addAll(Arrays.asList("CampaignId",
      "AdGroupId",
      "Id",
      "CriteriaType",
      "Criteria",
      "FinalUrls",
      "Impressions",
      "Clicks",
      "Cost"));

  // Create report definition.
  ReportDefinition reportDefinition = new ReportDefinition();
  reportDefinition.setReportName("Criteria performance report #" + System.currentTimeMillis());
  reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.YESTERDAY);
  reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);
  reportDefinition.setDownloadFormat(DownloadFormat.CSV);
  
  // 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)
          // Enable to allow rows with zero impressions to show.
          .includeZeroImpressions(false)
          .build();
  session.setReportingConfiguration(reportingConfiguration);
  
  reportDefinition.setSelector(selector);

  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(reportDefinition);
  response.saveToFile(reportFile);

  System.out.printf("Report successfully downloaded to: %s%n", reportFile);
}
 
示例12
public static void main(String[] args) {
  AdWordsSession session;
  try {
    // Generate a refreshable OAuth2 credential.
    Credential oAuth2Credential =
        new OfflineCredentials.Builder()
            .forApi(Api.ADWORDS)
            .fromFile()
            .build()
            .generateCredential();

    // Construct an AdWordsSession.
    session =
        new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
  } catch (ConfigurationLoadException cle) {
    System.err.printf(
        "Failed to load configuration from the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, cle);
    return;
  } catch (ValidationException ve) {
    System.err.printf(
        "Invalid configuration in the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, ve);
    return;
  } catch (OAuthException oe) {
    System.err.printf(
        "Failed to create OAuth credentials. Check OAuth settings in the %s file. "
            + "Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, oe);
    return;
  }

  AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

  try {
    runExample(adWordsServices, session);
  } catch (DetailedReportDownloadResponseException dre) {
    // A DetailedReportDownloadResponseException will be thrown if the HTTP status code in the
    // response indicates an error occurred and the response body contains XML with further
    // information, such as the fieldPath and trigger.
    System.err.printf(
        "Report was not downloaded due to a %s with errorText '%s', trigger '%s' and "
            + "field path '%s'%n",
        dre.getClass().getSimpleName(),
        dre.getErrorText(),
        dre.getTrigger(),
        dre.getFieldPath());
  } catch (ReportDownloadResponseException rde) {
    // A ReportDownloadResponseException will be thrown if the HTTP status code in the response
    // indicates an error occurred, but the response did not contain further details.
    System.err.printf("Report was not downloaded due to: %s%n", rde);
  } catch (ReportException re) {
    // A ReportException will be thrown if the download failed due to a transport layer exception.
    System.err.printf("Report was not downloaded due to transport layer exception: %s%n", re);
  } catch (IOException ioe) {
    // An IOException in this example indicates that the report's contents could not be read from
    // the response.
    System.err.printf(
        "Report was not read due to an IOException: %s%n", ioe);
  }
}
 
示例13
/**
 * 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 {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  // Create selector to retrieve the first 100 campaigns.
  Selector selector = new Selector();
  selector.setFields(new String[] {"Id", "Name"});
  Paging paging = new Paging();
  paging.setStartIndex(0);
  paging.setNumberResults(100);

  // Get the first page of campaigns.
  CampaignPage page = campaignService.get(selector);

  System.out.printf("Found %d total campaigns.%n", page.getTotalNumEntries());
  // Display campaigns.
  if (page.getEntries() != null) {
    for (Campaign campaign : page.getEntries()) {
      System.out.printf("Campaign with name '%s' and ID %d was found.%n", campaign.getName(),
           campaign.getId());
    }
  } else {
    System.out.println("No campaigns were found.");
  }

  // Create selector.
  com.google.api.ads.adwords.lib.jaxb.v201809.Selector reportSelector =
      new com.google.api.ads.adwords.lib.jaxb.v201809.Selector();
  reportSelector.getFields().addAll(Arrays.asList(
      "CampaignId",
      "AdGroupId",
      "Id",
      "CriteriaType",
      "Criteria",
      "Impressions",
      "Clicks",
      "Cost"));

  // Create report definition.
  ReportDefinition reportDefinition = new ReportDefinition();
  reportDefinition.setReportName("Criteria performance report #" + System.currentTimeMillis());
  reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.YESTERDAY);
  reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);
  reportDefinition.setDownloadFormat(DownloadFormat.CSV);
  
  reportDefinition.setSelector(reportSelector);

  ReportingConfiguration reportingConfig =
      new ReportingConfiguration.Builder()
          // Enable to allow rows with zero impressions to show.
          .includeZeroImpressions(false)
          .build();

  session.setReportingConfiguration(reportingConfig);

  ReportDownloadResponse response =
      new ReportDownloader(session).downloadReport(reportDefinition);
  FileOutputStream fos = new FileOutputStream(new File(reportFile));
  Streams.copy(response.getInputStream(), fos);
  fos.close();
  System.out.printf("Report successfully downloaded: %s%n", reportFile);
}
 
示例14
/**
 * Downloads a report and returns a ReportDownloadResponse with the results.
 *
 * @param reportDefinition to download a report for.
 * @return {@link ReportDownloadResponse} If the HTTP request completes successfully.
 * @throws ReportException If we don't receive a response from the server.
 * @throws ReportDownloadResponseException If the server indicates a problem with the request.
 */
public ReportDownloadResponse downloadReport(ReportDefinition reportDefinition)
    throws ReportException, ReportDownloadResponseException;
 
示例15
/**
 * Downloads a report query (AWQL) and returns a ReportDownloadResponse with the results.
 *
 * @param reportQuery to download a report for.
 * @param format Format to download the report as. CSV,
 * @return {@link ReportDownloadResponse} If the HTTP request completes successfully.
 * @throws ReportException If there is any issue making HTTP request with server.
 * @throws ReportDownloadResponseException If the server indicates a problem with the request.
 */
public ReportDownloadResponse downloadReport(String reportQuery, DownloadFormat format)
    throws ReportException, ReportDownloadResponseException;