com.google.api.ads.adwords.lib.client.AdWordsSession.ImmutableAdWordsSession Java Examples

The following examples show how to use com.google.api.ads.adwords.lib.client.AdWordsSession.ImmutableAdWordsSession. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultipleClientReportDownloaderTest.java    From aw-reporting with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  // does not matter which report definition type
  reportDefinition = new ReportDefinition();
  reportDefinition.setReportType(ReportDefinitionReportType.PLACEHOLDER_REPORT);
  
  multipleClientReportDownloader =
      new MultipleClientReportDownloader(20) {
        @Override
        protected CallableReportDownloader genCallableReportDownloader(
            ImmutableAdWordsSession session, ReportDefinition reportDefinition) {
          return new CallableReportDownloader(session, reportDefinition) {
            @Override
            public File call() {
              return null;
            }
          };
        }
      };
}
 
Example #2
Source File: AlertProcessor.java    From adwords-alerting with Apache License 2.0 6 votes vote down vote up
/**
 * Process one alert for the given account IDs under the manager account.
 *
 * @param clientCustomerIds the client customer IDs
 * @param protoSession the prototype adwords session used for downloading reports
 * @param alertConfig the JSON config of the alert
 * @param count the sequence number of current alert
 */
protected void processAlert(
    Set<Long> clientCustomerIds,
    ImmutableAdWordsSession protoSession,
    JsonObject alertConfig,
    int count)
    throws AlertConfigLoadException, AlertProcessingException {
  String alertName = alertConfig.get(ConfigTags.ALERT_NAME).getAsString();
  LOGGER.info("*** Generating alert #{} (name: \"{}\") for {} accounts ***",
      count, alertName, clientCustomerIds.size());

  JsonObject downloaderConfig = alertConfig.getAsJsonObject(ConfigTags.REPORT_DOWNLOADER);
  JsonArray rulesConfig = alertConfig.getAsJsonArray(ConfigTags.RULES); // optional
  String alertMessage = alertConfig.get(ConfigTags.ALERT_MESSAGE).getAsString();
  JsonArray actionsConfig = alertConfig.getAsJsonArray(ConfigTags.ACTIONS);

  // Generate AWQL report query and download report data for all accounts under manager account.
  List<ReportData> reports = downloadReports(protoSession, clientCustomerIds, downloaderConfig);
  printReports(reports, "*** Downloaded report data:");

  // Process the downloaded reports
  processReports(reports, rulesConfig, alertMessage, actionsConfig);
}
 
Example #3
Source File: StreamingRunnableProcessor.java    From aw-reporting with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for {@code Runnable} to download reports from AdWords API.
 *
 * @param topCustomerId the top customer account id.
 * @param session AdWords session used for downloading report stream.
 * @param reportDefinition {@code ReportDefinition} to define report parameters.
 * @param csvToBean the {@code CsvToBean}.
 * @param mappingStrategy the mapping strategy to convert CSV files into Java beans.
 * @param dateRangeAndType the date range and type.
 * @param entityPersister the bean to persist report to database.
 * @param reportRowsSetSize the size of the set parsed that will be persisted to the database.
 */
public StreamingRunnableProcessor(
    String topCustomerId,
    ImmutableAdWordsSession session,
    ReportDefinition reportDefinition,
    DateRangeAndType dateRangeAndType,
    ModifiedCsvToBean<R> csvToBean,
    ReportEntityMappingStrategy<R> mappingStrategy,
    EntityPersister entityPersister,
    int reportRowsSetSize) {
  this.topCustomerId = Preconditions.checkNotNull(topCustomerId, "topCustomerId cannot be null");
  
  this.session = Preconditions.checkNotNull(session, "session cannot be null.");
  this.reportDefinition =
      Preconditions.checkNotNull(reportDefinition, "reportDefinition cannot be null");
  this.dateRangeAndType =
      Preconditions.checkNotNull(dateRangeAndType, "dateRangeAndType cannot be null");
  
  this.csvToBean = Preconditions.checkNotNull(csvToBean, "csvToBean cannot be null");
  this.mappingStrategy =
      Preconditions.checkNotNull(mappingStrategy, "mappingStrategy cannot be null");
  this.entityPersister =
      Preconditions.checkNotNull(entityPersister, "entityPersister cannot be null");
  this.reportRowsSetSize = reportRowsSetSize;
  Preconditions.checkArgument(reportRowsSetSize > 0, "reportRowsSetSize must be > 0");
}
 
Example #4
Source File: AdWordsSessionTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Tests that copy builder copies all values correctly. */
@Test
public void testImmutable_copyBuilder() throws Exception {
  AdWordsSession adWordsSession = build(allSettingsBuilder);

  AdWordsSession copy = build(adWordsSession.newBuilder());

  assertNotSame(adWordsSession, copy);
  for (Method method : ImmutableAdWordsSession.class.getMethods()) {
    if (method.getName().startsWith("get") && method.getParameterTypes().length == 1) {
      Object originalAttributeValue = method.invoke(adWordsSession);
      Object copyAttributeValue = method.invoke(copy);
      assertEquals(
          "Copied session value does not match original for getter: " + method.getName(),
          originalAttributeValue,
          copyAttributeValue);
    }
  }

  // The copy should point to the same OAuth2 credential and reporting configuration as
  // the original.
  assertSame(adWordsSession.getOAuth2Credential(), copy.getOAuth2Credential());
  assertSame(adWordsSession.getReportingConfiguration(), copy.getReportingConfiguration());
}
 
Example #5
Source File: AwqlReportDownloader.java    From adwords-alerting with Apache License 2.0 6 votes vote down vote up
/**
 * Downloads the specified report for all specified CIDs.
 *
 * @param protoSession the prototype adwords session used for downloading reports
 * @param clientCustomerIds the client customer IDs to download the report for
 * @return Collection of File objects reports have been downloaded to
 */
@Override
public List<ReportData> downloadReports(
    ImmutableAdWordsSession protoSession, Set<Long> clientCustomerIds)
    throws AlertProcessingException {
  ImmutableAdWordsSession session = null;
  try {
    // No need to specify clientCustomerId for getting report definition.
    session = buildSessionForCid(protoSession, null);
  } catch (ValidationException e) {
    throw new AlertProcessingException(
        "Failed to create valid adwords session for report definition downloader.", e);
  }

  AwReportDefinitionDownloader reportDefinitionDownloader =
      new AwReportDefinitionDownloader(session);
  return downloadReports(protoSession, reportDefinitionDownloader, clientCustomerIds);
}
 
Example #6
Source File: InstalledOAuth2Authenticator.java    From adwords-alerting with Apache License 2.0 6 votes vote down vote up
/**
 * Get an immutable adwords session from the authentication info.
 */
@Override
public ImmutableAdWordsSession authenticate() throws OAuthException, ValidationException {
  // For easy processing, skip report header and summary (but keep column header).
  ReportingConfiguration reportingConfig =
      new ReportingConfiguration.Builder()
          .skipReportHeader(true)
          .skipColumnHeader(false)
          .skipReportSummary(true)
          .includeZeroImpressions(true)
          .build();
  
  return new AdWordsSession.Builder()
      .withOAuth2Credential(getOAuth2Credential())
      .withUserAgent(this.userAgent)
      .withClientCustomerId(this.managerAccountId)
      .withDeveloperToken(this.developerToken)
      .withReportingConfiguration(reportingConfig)
      .buildImmutable();
}
 
Example #7
Source File: AlertProcessorTest.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws OAuthException, ValidationException {
  alertProcessor = new AlertProcessor(10);

  MockitoAnnotations.initMocks(this);

  // Mocking the Authentication because in OAuth2 we are force to call buildOAuth2Credentials
  ImmutableAdWordsSession session = TestEntitiesGenerator.getTestAdWordsSession();
  Mockito.doReturn(session).when(authenticator).authenticate();

  alertProcessor.setAuthentication(authenticator);
}
 
Example #8
Source File: CallableReportDownloader.java    From aw-reporting with Apache License 2.0 5 votes vote down vote up
/**
 * @param session the adwords session used for downloading report
 * @param reportDefinition the report to download
 */
public CallableReportDownloader(
    ImmutableAdWordsSession session, ReportDefinition reportDefinition) {
  this.session = Preconditions.checkNotNull(session, "session cannot be null.");
  this.reportDefinition = Preconditions.checkNotNull(reportDefinition,
      "reportDefinition cannot be null.");
}
 
Example #9
Source File: ParallelReportDownload.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private ReportDownloadCallable(
    ImmutableAdWordsSession session,
    AdWordsServicesInterface adWordsServices,
    ReportDefinition reportDefinition,
    File reportOutputFile,
    ExponentialBackOff backOff) {
  this.session = session;
  this.adWordsServices = adWordsServices;
  this.reportDefinition = reportDefinition;
  this.reportOutputFile = reportOutputFile;
  this.backOff = backOff;
}
 
Example #10
Source File: AlertProcessorTest.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateAlerts() throws Exception {
  InputStreamReader alertsConfigReader =
      new InputStreamReader(TestEntitiesGenerator.getTestAlertsConfigStream());
  
  int numberOfAlerts = 0;
  try {
    JsonObject alertsConfig = new JsonParser().parse(alertsConfigReader).getAsJsonObject();
    numberOfAlerts = alertsConfig.getAsJsonArray(ConfigTags.ALERTS).size();
    Set<Long> cids = new HashSet<Long>();
    alertProcessor.generateAlerts(cids, alertsConfig);
  } finally {
    alertsConfigReader.close();
  }
  
  verify(alertProcessor, times(numberOfAlerts)).processAlert(
      Mockito.<Set<Long>>anyObject(),
      Mockito.<ImmutableAdWordsSession>anyObject(),
      Mockito.<JsonObject>anyObject(),
      Mockito.anyInt());
  
  verify(alertProcessor, times(numberOfAlerts)).downloadReports(
      Mockito.<ImmutableAdWordsSession>anyObject(),
      Mockito.<Set<Long>>anyObject(),
      Mockito.<JsonObject>anyObject());
  
  verify(alertProcessor, times(numberOfAlerts)).processReports(
      reportsCaptor.capture(),
      Mockito.<JsonArray>anyObject(),
      Mockito.anyString(),
      Mockito.<JsonArray>anyObject());
}
 
Example #11
Source File: AlertReportDownloaderProcessorTest.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
@Test
public void testDownloadReports() throws ValidationException, AlertProcessingException {
  ImmutableAdWordsSession session = TestEntitiesGenerator.getTestAdWordsSession();
  Set<Long> clientCustomerIds = new HashSet<Long>();
  alertReportDownloaderProcessor.downloadReports(session, clientCustomerIds);

  verify(alertReportDownloaderProcessor, times(1)).downloadReports(
      Mockito.<ImmutableAdWordsSession>anyObject(), Mockito.<Set<Long>>anyObject());
}
 
Example #12
Source File: AlertProcessor.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
/**
 * Download report files for the given account IDs under the manager account.
 *
 * @param protoSession the prototype adwords session used for downloading reports
 * @param clientCustomerIds the client customer IDs
 * @param downloaderConfig the JSON config for this downloader
 */
protected List<ReportData> downloadReports(
    ImmutableAdWordsSession protoSession,
    Set<Long> clientCustomerIds,
    JsonObject downloaderConfig)
    throws AlertConfigLoadException, AlertProcessingException {
  AlertReportDownloaderProcessor reportDownloadProcessor =
      new AlertReportDownloaderProcessor(downloaderConfig);
  return reportDownloadProcessor.downloadReports(protoSession, clientCustomerIds);
}
 
Example #13
Source File: AwqlReportDownloader.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a CallableAwqlReportDownloader for downloading report in a service thread.
 */
protected CallableAwqlReportDownloader genCallableAwqlReportDownloader(
    ImmutableAdWordsSession session, ReportDataLoader loader) {
  return new CallableAwqlReportDownloader(session, reportQuery, loader);
}
 
Example #14
Source File: TestEntitiesGenerator.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
public static ImmutableAdWordsSession getTestAdWordsSession() throws ValidationException {
  return getTestAdWordsSessionBuilder().buildImmutable();
}
 
Example #15
Source File: SqlDbReportDownloader.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
@Override
public List<ReportData> downloadReports(
    ImmutableAdWordsSession protoSession, Set<Long> clientCustomerIds) {
  Map<Long, ReportData> reportDataMap = new HashMap<Long, ReportData>();
  
  JdbcTemplate jdbcTemplate = getJdbcTemplate();
  String sqlQuery = getSqlQueryWithReportColumnNames();
  ReportDefinitionReportType reportType = getReportType();
  SqlRowSet rowSet = jdbcTemplate.queryForRowSet(sqlQuery);
  
  // Get the column index of customer id. 
  int customerIdColumnIndex = rowSet.findColumn(EXTERNAL_CUSTOMER_ID_REPORT_COLUMN_NAME);
  Preconditions.checkState(
      customerIdColumnIndex >= 0,
      "You must choose \"%s\" field to generate report data",
      EXTERNAL_CUSTOMER_ID_REPORT_COLUMN_NAME);
  
  List<String> columnNames = Arrays.asList(rowSet.getMetaData().getColumnNames());
  int columns = columnNames.size();
  
  // Read result into map.
  int rows = 0;
  while (rowSet.next()) {
    rows++;
    List<String> row = new ArrayList<String>(columns);
    for (int i = 0; i < columns; i++) {
      row.add(rowSet.getString(i));
    }

    String customerIdStr = row.get(customerIdColumnIndex);
    Long customerId = Long.parseLong(customerIdStr);
    ReportData reportData = reportDataMap.get(customerId);
    if (reportData == null) {
      reportData = new ReportData(customerId, reportType, columnNames);
      reportDataMap.put(customerId, reportData);
    }
    reportData.addRow(row);
  }
  
  LOGGER.info("Retrieved and parsed {} rows from database.", rows);
  return new ArrayList<ReportData>(reportDataMap.values());
}
 
Example #16
Source File: AdWordsSessionTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Tests that copy constructor on {@link ImmutableAdWordsSession} copies all values correctly. */
@Test
public void testImmutable_setters_fail() throws Exception {
  if (!isImmutable) {
    assertTrue("Skipping immutability test because !isImmutable", true);
    return;
  }

  ImmutableAdWordsSession immutableAdWordsSession = allSettingsBuilder.buildImmutable();

  // Find each setter method and confirm that the immutable session throws an exception when the
  // method is invoked.
  for (Method method : ImmutableAdWordsSession.class.getMethods()) {
    if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) {
      Class<?> parameterType = method.getParameterTypes()[0];
      String attributeName = method.getName().substring("set".length());
      String getterPrefix = "get";
      if (parameterType.equals(boolean.class) || parameterType.equals(Boolean.class)) {
        getterPrefix = "is";
      }

      String getMethodName =
          getterPrefix + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
      Method getMethod = ImmutableAdWordsSession.class.getMethod(getMethodName);

      // Get the attribute value from the original session to use in the setter method invocation
      // below.
      Object attributeValue = getMethod.invoke(immutableAdWordsSession);

      // Attempt to invoke the setter on the original session and verify that this
      // throws an UnsupportedOperationException.
      try {
        method.invoke(immutableAdWordsSession, attributeValue);
        fail(
            "Invocation of setter method "
                + method.getName()
                + " should have failed for an ImmutableAdWordsSession, but it succeeded");
      } catch (InvocationTargetException e) {
        assertEquals(
            "UnsupportedOperationException is expected on set",
            UnsupportedOperationException.class,
            e.getCause().getClass());
      }
    }
  }
}
 
Example #17
Source File: NoOpAlertReportDownloader.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
@Override
public List<ReportData> downloadReports(
    ImmutableAdWordsSession protoSession, Set<Long> clientCustomerIds) {
  return new ArrayList<ReportData>();
}
 
Example #18
Source File: MultipleClientReportDownloader.java    From aw-reporting with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a CallableReportDownloader for downloading report in a service thread.
 */
protected CallableReportDownloader genCallableReportDownloader(
    ImmutableAdWordsSession session, ReportDefinition reportDefinition) {
  return new CallableReportDownloader(session, reportDefinition);
}
 
Example #19
Source File: AlertReportDownloaderProcessor.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
/**
 * Use the AlertReportDownloader object to download reports.
 */
public List<ReportData> downloadReports(
    ImmutableAdWordsSession protoSession, Set<Long> clientCustomerIds)
    throws AlertProcessingException {
  return reportDownloader.downloadReports(protoSession, clientCustomerIds);
}
 
Example #20
Source File: AlertReportDownloader.java    From adwords-alerting with Apache License 2.0 2 votes vote down vote up
/**
 * Downloads reports and transforms them to ReportData.
 *
 * @param protoSession the prototype adwords session used for downloading reports
 * @param clientCustomerIds the list of client customer IDs for downloading report data
 * @return a collection of ReportData objects
 */
List<ReportData> downloadReports(
    ImmutableAdWordsSession protoSession, Set<Long> clientCustomerIds)
    throws AlertProcessingException;
 
Example #21
Source File: AwqlReportDownloader.java    From adwords-alerting with Apache License 2.0 2 votes vote down vote up
/**
 * Builds a new {@code ImmutableAdWordsSession} for the given cid.
 * 
 * @param protoSession the prototype of adwords session for building another session
 * @param cid the client customer id
 * @return an immutable adwords session for the specified cid
 */
private ImmutableAdWordsSession buildSessionForCid(
    ImmutableAdWordsSession protoSession, Long cid) throws ValidationException {
  String cidStr = cid == null ? null : String.valueOf(cid);
  return protoSession.newBuilder().withClientCustomerId(cidStr).buildImmutable();
}
 
Example #22
Source File: AdWordsSessionUtil.java    From aw-reporting with Apache License 2.0 2 votes vote down vote up
/**
 * Build a new {@code ImmutableAdWordsSession} for the given cid.
 * @param sessionBuilder the adwords session builder
 * @param cid the client customer id (in long format)
 * @return an immutable adwords session for the specified cid
 */
public static ImmutableAdWordsSession buildImmutableSessionForCid(
    AdWordsSession.Builder sessionBuilder, Long cid) throws ValidationException {
  String cidStr = cid == null ? null : String.valueOf(cid);
  return buildImmutableSessionForCid(sessionBuilder, cidStr);
}
 
Example #23
Source File: AdWordsSessionUtil.java    From aw-reporting with Apache License 2.0 2 votes vote down vote up
/**
 * Build a new {@code ImmutableAdWordsSession} for the given cid.
 * @param sessionBuilder the adwords session builder
 * @param cid the client customer id (in string format)
 * @return an immutable adwords session for the specified cid
 */
public static ImmutableAdWordsSession buildImmutableSessionForCid(
    AdWordsSession.Builder sessionBuilder, String cid) throws ValidationException {
  return sessionBuilder.withClientCustomerId(cid).buildImmutable();
}
 
Example #24
Source File: Authenticator.java    From adwords-alerting with Apache License 2.0 2 votes vote down vote up
/**
 * Authenticates the user against the API(s) depending on the OAuth scope and then returns an
 * {@link com.google.api.ads.adwords.lib.client.AdWordsSession.ImmutableAdWordsSession}.
 *
 * @return the immutable adwords session after the authentication
 * @throws OAuthException error on the OAuth process
 * @throws ValidationException error on the session building process
 */
ImmutableAdWordsSession authenticate() throws OAuthException, ValidationException;