Java Code Examples for com.google.api.ads.adwords.axis.v201809.cm.Money#setMicroAmount()

The following examples show how to use com.google.api.ads.adwords.axis.v201809.cm.Money#setMicroAmount() . 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: KeywordOptimizerUtil.java    From keyword-optimizer with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the mean of the two {@link Money} values if neither is null, else returns null.
 *
 * @param value1 first value
 * @param value2 second value
 * @return the mean of the two {@link Money} values
 */
private static Money calculateMean(Money value1, Money value2) {
  if (value1 == null || value2 == null) {
    return null;
  }

  Double meanAmount = calculateMean(value1.getMicroAmount(), value2.getMicroAmount());
  if (meanAmount == null) {
    return null;
  }

  Money mean = new Money();
  mean.setMicroAmount(meanAmount.longValue());

  return mean;
}
 
Example 2
Source File: AddDynamicSearchAdsCampaign.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Creates the budget. */
private static Budget createBudget(
    AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException, ApiException {
  // Get the BudgetService.
  BudgetServiceInterface budgetService =
      adWordsServices.get(session, BudgetServiceInterface.class);

  // Create a budget, which can be shared by multiple campaigns.
  Budget sharedBudget = new Budget();
  sharedBudget.setName("Interplanetary Cruise #" + System.currentTimeMillis());
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(50000000L);
  sharedBudget.setAmount(budgetAmount);
  sharedBudget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(sharedBudget);
  budgetOperation.setOperator(Operator.ADD);

  // Add the budget
  Budget budget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
  return budget;
}
 
Example 3
Source File: AxisBatchJobUploadBodyProviderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Override
protected void addBudgetOperation(
    BatchJobMutateRequest request,
    long budgetId,
    String budgetName,
    long budgetAmountInMicros,
    String deliveryMethod) {
  Budget budget = new Budget();
  budget.setBudgetId(budgetId);
  budget.setName(budgetName);
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(budgetAmountInMicros);
  budget.setAmount(budgetAmount);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.fromString(deliveryMethod));

  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(budget);
  budgetOperation.setOperator(Operator.ADD);
  request.addOperation(budgetOperation);
}
 
Example 4
Source File: AddPrices.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link PriceTableRow} with the specified attributes.
 *
 * @param header the header for the row
 * @param description the description for the row
 * @param finalUrl the final URL for the row
 * @param finalMobileUrl the final mobile URL for the row, or null if this field should not be set
 * @param priceInMicros the price for the row, in micros
 * @param currencyCode the currency for the row
 * @param priceUnit the price unit for the row
 * @return a new {@link PriceTableRow}
 */
private static PriceTableRow createPriceTableRow(
    String header,
    String description,
    String finalUrl,
    String finalMobileUrl,
    long priceInMicros,
    String currencyCode,
    PriceExtensionPriceUnit priceUnit) {
  PriceTableRow priceTableRow = new PriceTableRow();
  priceTableRow.setHeader(header);
  priceTableRow.setDescription(description);

  UrlList finalUrls = new UrlList();
  finalUrls.setUrls(new String[] {finalUrl});
  priceTableRow.setFinalUrls(finalUrls);

  if (finalMobileUrl != null) {
    UrlList finalMobileUrls = new UrlList();
    finalMobileUrls.setUrls(new String[] {finalMobileUrl});
    priceTableRow.setFinalMobileUrls(finalMobileUrls);
  }

  MoneyWithCurrency price = new MoneyWithCurrency();
  Money priceMoney = new Money();
  price.setCurrencyCode(currencyCode);
  priceMoney.setMicroAmount(priceInMicros);
  price.setMoney(priceMoney);
  priceTableRow.setPrice(price);
  priceTableRow.setPriceUnit(priceUnit);

  return priceTableRow;
}
 
Example 5
Source File: UploadOfflineData.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Returns a new offline data object with the specified values. */
private static OfflineData createOfflineData(
    DateTime transactionTime,
    long transactionMicroAmount,
    String transactionCurrency,
    String conversionName,
    List<UserIdentifier> userIdentifiers) {
  StoreSalesTransaction storeSalesTransaction = new StoreSalesTransaction();

  // For times use the format yyyyMMdd HHmmss [tz].
  // For details, see
  // https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats
  storeSalesTransaction.setTransactionTime(transactionTime.toString("yyyyMMdd HHmmss ZZZ"));
  storeSalesTransaction.setConversionName(conversionName);
  storeSalesTransaction.setUserIdentifiers(
      userIdentifiers.toArray(new UserIdentifier[userIdentifiers.size()]));

  Money money = new Money();
  money.setMicroAmount(transactionMicroAmount);

  MoneyWithCurrency moneyWithCurrency = new MoneyWithCurrency();
  moneyWithCurrency.setMoney(money);
  moneyWithCurrency.setCurrencyCode(transactionCurrency);
  storeSalesTransaction.setTransactionAmount(moneyWithCurrency);

  OfflineData offlineData = new OfflineData();
  offlineData.setStoreSalesTransaction(storeSalesTransaction);
  return offlineData;
}
 
Example 6
Source File: AddUniversalAppCampaign.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the budget for the campaign.
 *
 * @return the new budget.
 */
private static Long createBudget(AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException, ApiException {
  // Get the BudgetService.
  BudgetServiceInterface budgetService =
      adWordsServices.get(session, BudgetServiceInterface.class);

  // Create the campaign budget.
  Budget budget = new Budget();
  budget.setName("Interplanetary Cruise App Budget #" + System.currentTimeMillis());
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(50000000L);
  budget.setAmount(budgetAmount);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  // Universal app campaigns don't support shared budgets.
  budget.setIsExplicitlyShared(false);
  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(budget);
  budgetOperation.setOperator(Operator.ADD);

  // Add the budget
  Budget addedBudget = budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0);
  System.out.printf(
      "Budget with name '%s' and ID %d was created.%n",
      addedBudget.getName(), addedBudget.getBudgetId());
  return addedBudget.getBudgetId();
}
 
Example 7
Source File: AddCompleteCampaignsUsingBatchJob.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private static BudgetOperation buildBudgetOperation(Iterator<Long> tempIdGenerator,
    String namePrefix) {
  Budget budget = new Budget();
  budget.setBudgetId(tempIdGenerator.next());
  budget.setName(String.format("Interplanetary Cruise %s", namePrefix));
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(50000000L);
  budget.setAmount(budgetAmount);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperand(budget);
  budgetOperation.setOperator(Operator.ADD);
  return budgetOperation;
}
 
Example 8
Source File: AdWordsAxisSoapIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Submits a BudgetService.mutate call to the test server and asserts that the response contains
 * expected values.
 */
private void testBudgetServiceMutateRequest(AdWordsSession session) throws RemoteException,
    ApiException, IOException, SAXException {
  BudgetServiceInterface companyService =
      new AdWordsServices().get(session, BudgetServiceInterface.class);

  Budget budget = new Budget();
  budget.setName("Test Budget Name");
  Money money = new Money();
  money.setMicroAmount(50000000L);
  budget.setAmount(money);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation operation = new BudgetOperation();
  operation.setOperand(budget);
  operation.setOperator(Operator.ADD);

  Budget responseBudget = companyService.mutate(new BudgetOperation[] {operation}).getValue(0);

  assertEquals("Budget ID does not match", 251877074L, responseBudget.getBudgetId().longValue());
  assertEquals("Budget name does not match", budget.getName(), responseBudget.getName());
  assertEquals("Budget amount does not match", budget.getAmount().getMicroAmount(),
      responseBudget.getAmount().getMicroAmount());
  assertEquals("Budget delivery method does not match", budget.getDeliveryMethod(),
      responseBudget.getDeliveryMethod());

  assertFalse("Did not request compression but request was compressed",
      testHttpServer.wasLastRequestBodyCompressed());
  XMLAssert.assertXMLEqual(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
}
 
Example 9
Source File: ProductPartitionNodeAdapter.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new AdGroupCriterion configured for a SET operation that will set the criterion's
 * bid, tracking template, and custom parameters.
 *
 * @param node the node whose criterion should be updated
 * @param adGroupId the ad group ID of the criterion
 * @param biddingConfig the bidding strategy configuration of the criterion
 */
static AdGroupCriterion createCriterionForSetBiddableUnit(
    ProductPartitionNode node, long adGroupId, BiddingStrategyConfiguration biddingConfig) {
  Preconditions.checkNotNull(node, "Null node");
  Preconditions.checkNotNull(biddingConfig, "Null bidding configuration");
  Preconditions.checkArgument(node.isBiddableUnit(), "Node is not a biddable unit");

  BiddableAdGroupCriterion biddableCriterion = new BiddableAdGroupCriterion();
  biddableCriterion.setAdGroupId(adGroupId);

  ProductPartition partition = new ProductPartition();
  partition.setId(node.getProductPartitionId());
  if (node.getParent() != null) {
    partition.setParentCriterionId(node.getParent().getProductPartitionId());
  }
  partition.setCaseValue(node.getDimension());
  partition.setPartitionType(ProductPartitionType.UNIT);

  biddableCriterion.setCriterion(partition);

  // Set the bidding attributes on the new ad group criterion.
  if (node.getBid() != null) {
    Money bidMoney = new Money();
    bidMoney.setMicroAmount(node.getBid());
    CpcBid cpcBid = new CpcBid();
    cpcBid.setBid(bidMoney);
    biddingConfig.setBids(new Bids[] {cpcBid});
  } else {
    biddingConfig.setBids(new Bids[0]);
  }
  biddableCriterion.setBiddingStrategyConfiguration(biddingConfig);

  // Set the upgraded URL attributes on the new ad group criterion.
  if (node.getTrackingUrlTemplate() != null) {
    biddableCriterion.setTrackingUrlTemplate(
        node.getTrackingUrlTemplate());
  }
  biddableCriterion.setUrlCustomParameters(createCustomParameters(node));
  return biddableCriterion;
}
 
Example 10
Source File: EvaluatorTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  plumbing = new Keyword();
  plumbing.setText("plumbing");
  plumbing.setMatchType(KeywordMatchType.EXACT);

  plumbingBroad = new Keyword();
  plumbingBroad.setText("plumbing");
  plumbingBroad.setMatchType(KeywordMatchType.BROAD);

  plumbingSpecialist = new Keyword();
  plumbingSpecialist.setText("plumbing specialist");
  plumbingSpecialist.setMatchType(KeywordMatchType.EXACT);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd
  
  CampaignConfiguration campaignSettings = CampaignConfiguration.builder()
      .withMaxCpc(maxCpc)
      .build();
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(new KeywordInfo(plumbing, IdeaEstimate.EMPTY_ESTIMATE, null, null));
  keywords.add(new KeywordInfo(plumbingBroad, IdeaEstimate.EMPTY_ESTIMATE, null, null));
  keywords.add(new KeywordInfo(plumbingSpecialist, IdeaEstimate.EMPTY_ESTIMATE, null, null));

  minStats = new StatsEstimate();
  minStats.setClicksPerDay(10F);
  minStats.setImpressionsPerDay(1000F);

  maxStats = new StatsEstimate();
  maxStats.setClicksPerDay(20F);
  maxStats.setImpressionsPerDay(2000F);

  clicksEvaluator =
      new EstimatorBasedEvaluator(new MockTrafficEstimator(), new ClicksScoreCalculator());

  impressionsEvaluator =
      new EstimatorBasedEvaluator(new MockTrafficEstimator(), new ImpressionsScoreCalculator());
}
 
Example 11
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Creates an ad group in the Shopping campaign. */
private static AdGroup createAdGroup(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, Campaign campaign)
    throws RemoteException {
  // Get the AdGroupService.
  AdGroupServiceInterface adGroupService =
      adWordsServices.get(session, AdGroupServiceInterface.class);

  // Create ad group.
  AdGroup adGroup = new AdGroup();
  adGroup.setCampaignId(campaign.getId());
  adGroup.setName("Ad Group #" + System.currentTimeMillis());

  // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
  adGroup.setAdGroupType(AdGroupType.SHOPPING_SHOWCASE_ADS);

  // Required: Set the ad group's bidding strategy configuration.
  // Note: Showcase ads require that the campaign has a ManualCpc BiddingStrategyConfiguration.
  BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();

  // Optional: Set the bids.
  Money bidAmount = new Money();
  bidAmount.setMicroAmount(100000L);
  CpcBid cpcBid = new CpcBid();
  cpcBid.setBid(bidAmount);
  biddingStrategyConfiguration.setBids(new Bids[] {cpcBid});

  adGroup.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

  // Create operation.
  AdGroupOperation adGroupOperation = new AdGroupOperation();
  adGroupOperation.setOperand(adGroup);
  adGroupOperation.setOperator(Operator.ADD);

  // Make the mutate request.
  AdGroupReturnValue adGroupAddResult =
      adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});

  return adGroupAddResult.getValue(0);
}
 
Example 12
Source File: KeywordCollectionTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  plumbing = new Keyword();
  plumbing.setText("plumbing");
  plumbing.setMatchType(KeywordMatchType.EXACT);

  plumbingBroad = new Keyword();
  plumbingBroad.setText("plumbing");
  plumbingBroad.setMatchType(KeywordMatchType.BROAD);

  plumbingSpecialist = new Keyword();
  plumbingSpecialist.setText("plumbing specialist");
  plumbingSpecialist.setMatchType(KeywordMatchType.EXACT);

  newYork = new Location();
  newYork.setId(1023191L);

  english = new Language();
  english.setId(1000L);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd

  campaignSettings =
      CampaignConfiguration.builder()
          .withMaxCpc(maxCpc)
          .withCriterion(english)
          .withCriterion(newYork)
          .build();
  keywords = new KeywordCollection(campaignSettings);
  
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(new KeywordInfo(plumbing, null, null, null));
  keywords.add(new KeywordInfo(plumbingBroad, null, null, null));
  keywords.add(new KeywordInfo(plumbingSpecialist, null, null, null));
}
 
Example 13
Source File: KeywordCollectionScoreTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  alpha = new Keyword();
  alpha.setText("alpha");
  alpha.setMatchType(KeywordMatchType.EXACT);
  alphaInfo = new KeywordInfo(alpha, null, null, 3d);

  beta = new Keyword();
  beta.setText("beta");
  beta.setMatchType(KeywordMatchType.EXACT);
  betaInfo = new KeywordInfo(beta, null, null, 1d);

  betaBroad = new Keyword();
  betaBroad.setText("beta");
  betaBroad.setMatchType(KeywordMatchType.BROAD);
  betaBroadInfo = new KeywordInfo(betaBroad, null, null, 2d);

  gamma = new Keyword();
  gamma.setText("gamma");
  gamma.setMatchType(KeywordMatchType.EXACT);
  gammaInfo = new KeywordInfo(gamma, null, null, 4d);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd

  CampaignConfiguration campaignSettings = CampaignConfiguration.builder()
      .withMaxCpc(maxCpc)
      .build();
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(gammaInfo);
  keywords.add(betaInfo);
  keywords.add(alphaInfo);
  keywords.add(betaBroadInfo);
}
 
Example 14
Source File: KeywordOptimizer.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Read the campaign settings (max. Cpc, additional criteria) from the command line.
 * @param cmdLine the parsed command line parameters
 * @return {@link CampaignConfiguration} including the specified settings
 */
private static CampaignConfiguration getCampaignConfiguration(CommandLine cmdLine) {
  CampaignConfigurationBuilder builder = CampaignConfiguration.builder();

  // Read the max. Cpc parameter.
  double cpc = Double.parseDouble(cmdLine.getOptionValue("cpc"));
  Money maxCpc = new Money();
  maxCpc.setMicroAmount((long) (cpc * 1000000d));
  builder.withMaxCpc(maxCpc);

  // Read the language parameter.
  if (cmdLine.hasOption("lang")) {
    for (String language : cmdLine.getOptionValues("lang")) {
      long languageId = Long.parseLong(language);

      log("Using language: " + languageId);
      builder.withLanguage(languageId);
    }
  }

  // Read the location parameter.
  if (cmdLine.hasOption("loc")) {
    for (String location : cmdLine.getOptionValues("loc")) {
      long loc = Long.parseLong(location);

      log("Using location: " + loc);
      builder.withLocation(loc);
    }
  }

  return builder.build();
}
 
Example 15
Source File: ProductPartitionNodeAdapter.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new AdGroupCriterion configured for an ADD operation.
 *
 * @param node the node whose criterion should be added
 * @param adGroupId the ad group ID of the criterion
 * @param biddingConfig the bidding strategy configuration of the criterion
 */
static AdGroupCriterion createCriterionForAdd(ProductPartitionNode node, long adGroupId,
    BiddingStrategyConfiguration biddingConfig) {
  Preconditions.checkNotNull(node, "Null node");
  Preconditions.checkNotNull(biddingConfig, "Null bidding configuration");

  AdGroupCriterion adGroupCriterion;
  if (node.isExcludedUnit()) {
    adGroupCriterion = new NegativeAdGroupCriterion();
  } else if (node.isBiddableUnit()){
    BiddableAdGroupCriterion biddableCriterion = new BiddableAdGroupCriterion();
    if (node.getBid() != null) {
      Money bidMoney = new Money();
      bidMoney.setMicroAmount(node.getBid());
      CpcBid cpcBid = new CpcBid();
      cpcBid.setBid(bidMoney);
      cpcBid.setCpcBidSource(BidSource.CRITERION);
      biddingConfig.setBids(new Bids[] {cpcBid});
      biddableCriterion.setBiddingStrategyConfiguration(
          biddingConfig);
    }
    if (node.getTrackingUrlTemplate() != null) {
      biddableCriterion.setTrackingUrlTemplate(
          node.getTrackingUrlTemplate());
    }
    biddableCriterion.setUrlCustomParameters(createCustomParameters(node));
    adGroupCriterion = biddableCriterion;
  } else {
    adGroupCriterion = new BiddableAdGroupCriterion();
  }
  adGroupCriterion.setAdGroupId(adGroupId);

  ProductPartition partition = new ProductPartition();
  partition.setId(node.getProductPartitionId());
  if (node.getParent() != null) {
    partition.setParentCriterionId(node.getParent().getProductPartitionId());
  }
  partition.setCaseValue(node.getDimension());
  partition.setPartitionType(
      node.isUnit() ? ProductPartitionType.UNIT : ProductPartitionType.SUBDIVISION);
  adGroupCriterion.setCriterion(partition);
  return adGroupCriterion;
}
 
Example 16
Source File: ProductPartitionTreeTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new AdGroupCriterion based on this descriptor.
 */
AdGroupCriterion createCriterion() {
  AdGroupCriterion adGroupCriterion;
  ProductPartition partition = new ProductPartition();
  partition.setId(partitionId);
  partition.setParentCriterionId(parentPartitionId);
  partition.setCaseValue(dimension);
  partition.setPartitionType(
      isUnit ? ProductPartitionType.UNIT : ProductPartitionType.SUBDIVISION);
  if (isExcluded) {
    NegativeAdGroupCriterion negative = new NegativeAdGroupCriterion();
    adGroupCriterion = negative;
  } else {
    BiddableAdGroupCriterion biddable = new BiddableAdGroupCriterion();
    biddable.setUserStatus(UserStatus.ENABLED);
    biddable.setTrackingUrlTemplate(trackingUrlTemplate);
    if (!customParams.isEmpty()) {
      CustomParameters customParameters = new CustomParameters();
      List<CustomParameter> customParameterList = new ArrayList<>();
      for (Entry<String, String> paramEntry : customParams.entrySet()) {
        CustomParameter customParameter = new CustomParameter();
        customParameter.setKey(paramEntry.getKey());
        customParameter.setValue(paramEntry.getValue());
        customParameterList.add(customParameter);
      }
      customParameters.setParameters(customParameterList.toArray(new CustomParameter[0]));
      biddable.setUrlCustomParameters(customParameters);
    }

    BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
    if (isUnit && bid != null) {
      CpcBid cpcBid = new CpcBid();
      Money bidMoney = new Money();
      bidMoney.setMicroAmount(bid);
      cpcBid.setBid(bidMoney);
      cpcBid.setCpcBidSource(BidSource.CRITERION);
      biddingConfig.setBids(new Bids[] {cpcBid});
    }
    biddable.setBiddingStrategyConfiguration(biddingConfig);

    adGroupCriterion = biddable;
  }
  adGroupCriterion.setCriterion(partition);
  return adGroupCriterion;
}
 
Example 17
Source File: AdWordsAxisSoapCompressionIntegrationTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Tests making an Axis AdWords API call with OAuth2 and compression enabled.
 */
@Test
public void testGoldenSoap_oauth2_compressionEnabled() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));

  GoogleCredential credential = new GoogleCredential.Builder().setTransport(
      new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdWordsSession session = new AdWordsSession.Builder().withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  BudgetServiceInterface companyService =
      new AdWordsServices().get(session, BudgetServiceInterface.class);
  
  Budget budget = new Budget();
  budget.setName("Test Budget Name");
  Money money = new Money();
  money.setMicroAmount(50000000L);
  budget.setAmount(money);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation operation = new BudgetOperation();
  operation.setOperand(budget);
  operation.setOperator(Operator.ADD);
  
  Budget responseBudget = companyService.mutate(new BudgetOperation[] {operation}).getValue(0);

  assertEquals("Budget ID does not match", 251877074L, responseBudget.getBudgetId().longValue());
  assertEquals("Budget name does not match", budget.getName(), responseBudget.getName());
  assertEquals("Budget amount does not match", budget.getAmount().getMicroAmount(),
      responseBudget.getAmount().getMicroAmount());
  assertEquals("Budget delivery method does not match", budget.getDeliveryMethod(),
      responseBudget.getDeliveryMethod());
  
  assertTrue("Compression was enabled but the last request body was not compressed",
      testHttpServer.wasLastRequestBodyCompressed());
  XMLAssert.assertXMLEqual(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
  assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
}
 
Example 18
Source File: AddCampaignGroupsAndPerformanceTargets.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/** Creates a performance target for the campaign group. */
private static void createPerformanceTarget(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, CampaignGroup campaignGroup)
    throws ApiException, RemoteException {
  // Get the CampaignGroupPerformanceTargetService.
  CampaignGroupPerformanceTargetServiceInterface campaignGroupPerformanceTargetService =
      adWordsServices.get(session, CampaignGroupPerformanceTargetServiceInterface.class);

  // Create the performance target.
  CampaignGroupPerformanceTarget campaignGroupPerformanceTarget =
      new CampaignGroupPerformanceTarget();
  campaignGroupPerformanceTarget.setCampaignGroupId(campaignGroup.getId());

  PerformanceTarget performanceTarget = new PerformanceTarget();
  // Keep the CPC for the campaigns < $3.
  performanceTarget.setEfficiencyTargetType(EfficiencyTargetType.CPC_LESS_THAN_OR_EQUAL_TO);
  performanceTarget.setEfficiencyTargetValue(3000000d);

  // Keep the maximum spend under $50.
  performanceTarget.setSpendTargetType(SpendTargetType.MAXIMUM);
  Money maxSpend = new Money();
  maxSpend.setMicroAmount(500000000L);
  performanceTarget.setSpendTarget(maxSpend);

  // Aim for at least 3000 clicks.
  performanceTarget.setVolumeTargetValue(3000L);
  performanceTarget.setVolumeGoalType(VolumeGoalType.MAXIMIZE_CLICKS);

  // Start the performance target today, and run it for the next 90 days.
  DateTime startDate = DateTime.now();
  DateTime endDate = DateTime.now().plusDays(90);

  performanceTarget.setStartDate(startDate.toString("yyyyMMdd"));
  performanceTarget.setEndDate(endDate.toString("yyyyMMdd"));

  campaignGroupPerformanceTarget.setPerformanceTarget(performanceTarget);

  // Create the operation.
  CampaignGroupPerformanceTargetOperation operation =
      new CampaignGroupPerformanceTargetOperation();
  operation.setOperand(campaignGroupPerformanceTarget);
  operation.setOperator(Operator.ADD);

  CampaignGroupPerformanceTarget newCampaignGroupPerformanceTarget =
      campaignGroupPerformanceTargetService
          .mutate(new CampaignGroupPerformanceTargetOperation[] {operation})
          .getValue(0);

  // Display the results.
  System.out.printf(
      "Campaign group performance target with ID %d was added for campaign group ID %d.%n",
      newCampaignGroupPerformanceTarget.getId(),
      newCampaignGroupPerformanceTarget.getCampaignGroupId());
}
 
Example 19
Source File: GraduateTrial.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param trialId the ID of the trial to graduate.
 * @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 trialId)
    throws RemoteException {
  // Get the TrialService and BudgetService.
  TrialServiceInterface trialService = adWordsServices.get(session, TrialServiceInterface.class);
  BudgetServiceInterface budgetService =
      adWordsServices.get(session, BudgetServiceInterface.class);

  // To graduate a trial, you must specify a different budget from the base campaign. The base
  // campaign (in order to have had a trial based on it) must have a non-shared budget, so it
  // cannot be shared with the new independent campaign created by graduation.
  Budget budget = new Budget();
  budget.setName("Budget #" + System.currentTimeMillis());
  Money budgetAmount = new Money();
  budgetAmount.setMicroAmount(50000000L);
  budget.setAmount(budgetAmount);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.setOperator(Operator.ADD);
  budgetOperation.setOperand(budget);

  // Add budget.
  long budgetId =
      budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0).getBudgetId();

  Trial trial = new Trial();
  trial.setId(trialId);
  trial.setBudgetId(budgetId);
  trial.setStatus(TrialStatus.GRADUATED);

  TrialOperation trialOperation = new TrialOperation();
  trialOperation.setOperator(Operator.SET);
  trialOperation.setOperand(trial);

  // Update the trial.
  trial = trialService.mutate(new TrialOperation[] {trialOperation}).getValue(0);

  // Graduation is a synchronous operation, so the campaign is already ready. If you promote
  // instead, make sure to see the polling scheme demonstrated in AddTrial.java to wait for the
  // asynchronous operation to finish.
  System.out.printf(
      "Trial ID %d graduated. Campaign ID %d was given a new budget ID %d and "
          + "is no longer dependent on this trial.%n",
      trial.getId(),
      trial.getTrialCampaignId(),
      budgetId);
}
 
Example 20
Source File: KeywordOptimizerUtil.java    From keyword-optimizer with Apache License 2.0 2 votes vote down vote up
/**
 * Convenience method for creating a money object.
 *
 * @param microAmount the amount in micros
 * @return the newly created {@link Money} object
 */
public static Money createMoney(long microAmount) {
  Money money = new Money();
  money.setMicroAmount(microAmount);
  return money;
}