use of com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation in project googleads-java-lib by googleads.
the class AddCompleteCampaignsUsingBatchJob method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @throws BatchJobException if uploading operations or downloading results failed.
* @throws ApiException if the API request failed with one or more service errors.
* @throws RemoteException if the API request failed due to other errors.
* @throws InterruptedException if the thread was interrupted while sleeping between retries.
* @throws TimeoutException if the job did not complete after job status was polled {@link
* #MAX_POLL_ATTEMPTS} times.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException, BatchJobException, InterruptedException, TimeoutException {
// Get the MutateJobService.
BatchJobServiceInterface batchJobService = adWordsServices.get(session, BatchJobServiceInterface.class);
// Create a BatchJob.
BatchJobOperation addOp = new BatchJobOperation();
addOp.setOperator(Operator.ADD);
addOp.setOperand(new BatchJob());
BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[] { addOp }).getValue(0);
// Get the upload URL from the new job.
String uploadUrl = batchJob.getUploadUrl().getUrl();
System.out.printf("Created BatchJob with ID %d, status '%s' and upload URL %s.%n", batchJob.getId(), batchJob.getStatus(), uploadUrl);
// Create a temporary ID generator that will produce a sequence of descending negative numbers.
Iterator<Long> tempIdGenerator = new AbstractSequentialIterator<Long>(-1L) {
@Override
protected Long computeNext(Long previous) {
return Long.MIN_VALUE == previous ? null : previous - 1;
}
};
// Use a random UUID name prefix to avoid name collisions.
String namePrefix = UUID.randomUUID().toString();
// Create the mutate request that will be sent to the upload URL.
List<Operation> operations = new ArrayList<>();
// Create and add an operation to create a new budget.
BudgetOperation budgetOperation = buildBudgetOperation(tempIdGenerator, namePrefix);
operations.add(budgetOperation);
// Create and add operations to create new campaigns.
List<CampaignOperation> campaignOperations = buildCampaignOperations(tempIdGenerator, namePrefix, budgetOperation);
operations.addAll(campaignOperations);
// Create and add operations to create new negative keyword criteria for each campaign.
operations.addAll(buildCampaignCriterionOperations(campaignOperations));
// Create and add operations to create new ad groups.
List<AdGroupOperation> adGroupOperations = new ArrayList<>(buildAdGroupOperations(tempIdGenerator, namePrefix, campaignOperations));
operations.addAll(adGroupOperations);
// Create and add operations to create new ad group criteria (keywords).
operations.addAll(buildAdGroupCriterionOperations(adGroupOperations));
// Create and add operations to create new ad group ads (text ads).
operations.addAll(buildAdGroupAdOperations(adGroupOperations));
// Use a BatchJobHelper to upload all operations.
BatchJobHelper batchJobHelper = adWordsServices.getUtility(session, BatchJobHelper.class);
batchJobHelper.uploadBatchJobOperations(operations, uploadUrl);
System.out.printf("Uploaded %d operations for batch job with ID %d.%n", operations.size(), batchJob.getId());
// Poll for completion of the batch job using an exponential back off.
int pollAttempts = 0;
boolean isPending;
Selector selector = new SelectorBuilder().fields(BatchJobField.Id, BatchJobField.Status, BatchJobField.DownloadUrl, BatchJobField.ProcessingErrors, BatchJobField.ProgressStats).equalsId(batchJob.getId()).build();
do {
long sleepSeconds = (long) Math.scalb(30, pollAttempts);
System.out.printf("Sleeping %d seconds...%n", sleepSeconds);
Thread.sleep(sleepSeconds * 1000);
batchJob = batchJobService.get(selector).getEntries(0);
System.out.printf("Batch job ID %d has status '%s'.%n", batchJob.getId(), batchJob.getStatus());
pollAttempts++;
isPending = PENDING_STATUSES.contains(batchJob.getStatus());
} while (isPending && pollAttempts < MAX_POLL_ATTEMPTS);
if (isPending) {
throw new TimeoutException("Job is still in pending state after polling " + MAX_POLL_ATTEMPTS + " times.");
}
if (batchJob.getProcessingErrors() != null) {
int i = 0;
for (BatchJobProcessingError processingError : batchJob.getProcessingErrors()) {
System.out.printf(" Processing error [%d]: errorType=%s, trigger=%s, errorString=%s, fieldPath=%s" + ", reason=%s%n", i++, processingError.getApiErrorType(), processingError.getTrigger(), processingError.getErrorString(), processingError.getFieldPath(), processingError.getReason());
}
} else {
System.out.println("No processing errors found.");
}
if (batchJob.getDownloadUrl() != null && batchJob.getDownloadUrl().getUrl() != null) {
BatchJobMutateResponse mutateResponse = batchJobHelper.downloadBatchJobMutateResponse(batchJob.getDownloadUrl().getUrl());
System.out.printf("Downloaded results from %s:%n", batchJob.getDownloadUrl().getUrl());
for (MutateResult mutateResult : mutateResponse.getMutateResults()) {
String outcome = mutateResult.getErrorList() == null ? "SUCCESS" : "FAILURE";
System.out.printf(" Operation [%d] - %s%n", mutateResult.getIndex(), outcome);
}
} else {
System.out.println("No results available for download.");
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation in project googleads-java-lib by googleads.
the class AddCompleteCampaignsUsingBatchJob method buildCampaignCriterionOperations.
private static List<CampaignCriterionOperation> buildCampaignCriterionOperations(List<CampaignOperation> campaignOperations) {
List<CampaignCriterionOperation> operations = new ArrayList<>();
for (CampaignOperation campaignOperation : campaignOperations) {
Keyword keyword = new Keyword();
keyword.setMatchType(KeywordMatchType.BROAD);
keyword.setText("venus");
NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
negativeCriterion.setCampaignId(campaignOperation.getOperand().getId());
negativeCriterion.setCriterion(keyword);
CampaignCriterionOperation operation = new CampaignCriterionOperation();
operation.setOperand(negativeCriterion);
operation.setOperator(Operator.ADD);
operations.add(operation);
}
return operations;
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation in project googleads-java-lib by googleads.
the class AddCompleteCampaignsUsingBatchJob method buildCampaignOperations.
private static List<CampaignOperation> buildCampaignOperations(Iterator<Long> tempIdGenerator, String namePrefix, BudgetOperation budgetOperation) {
long budgetId = budgetOperation.getOperand().getBudgetId();
List<CampaignOperation> operations = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++) {
Campaign campaign = new Campaign();
campaign.setName(String.format("Batch Campaign %s.%s", namePrefix, i));
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
campaign.setStatus(CampaignStatus.PAUSED);
campaign.setId(tempIdGenerator.next());
campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);
Budget budget = new Budget();
budget.setBudgetId(budgetId);
campaign.setBudget(budget);
BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
// You can optionally provide a bidding scheme in place of the type.
ManualCpcBiddingScheme cpcBiddingScheme = new ManualCpcBiddingScheme();
biddingStrategyConfiguration.setBiddingScheme(cpcBiddingScheme);
campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
CampaignOperation operation = new CampaignOperation();
operation.setOperand(campaign);
operation.setOperator(Operator.ADD);
operations.add(operation);
}
return operations;
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation in project googleads-java-lib by googleads.
the class AddDynamicSearchAdsCampaign method createCampaign.
/**
* Creates the campaign.
*/
private static Campaign createCampaign(AdWordsServicesInterface adWordsServices, AdWordsSession session, Budget budget) throws RemoteException, ApiException {
// Get the CampaignService.
CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
// Create campaign.
Campaign campaign = new Campaign();
campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis());
campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
campaign.setStatus(CampaignStatus.PAUSED);
BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
// Only the budgetId should be sent, all other fields will be ignored by CampaignService.
Budget campaignBudget = new Budget();
campaignBudget.setBudgetId(budget.getBudgetId());
campaign.setBudget(campaignBudget);
// Required: Set the campaign's Dynamic Search Ads settings.
DynamicSearchAdsSetting dynamicSearchAdsSetting = new DynamicSearchAdsSetting();
// Required: Set the domain name and language.
dynamicSearchAdsSetting.setDomainName("example.com");
dynamicSearchAdsSetting.setLanguageCode("en");
// Set the campaign settings.
campaign.setSettings(new Setting[] { dynamicSearchAdsSetting });
// Optional: Set the start date.
campaign.setStartDate(DateTime.now().plusDays(1).toString("yyyyMMdd"));
// Optional: Set the end date.
campaign.setEndDate(DateTime.now().plusYears(1).toString("yyyyMMdd"));
// Create the operation.
CampaignOperation operation = new CampaignOperation();
operation.setOperand(campaign);
operation.setOperator(Operator.ADD);
// Add the campaign.
Campaign newCampaign = campaignService.mutate(new CampaignOperation[] { operation }).getValue(0);
// Display the results.
System.out.printf("Campaign with name '%s' and ID %d was added.%n", newCampaign.getName(), newCampaign.getId());
return newCampaign;
}
use of com.google.api.ads.adwords.axis.v201809.cm.CampaignOperation in project googleads-java-lib by googleads.
the class AddCampaigns method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @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) throws RemoteException {
// 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(50_000_000L);
sharedBudget.setAmount(budgetAmount);
sharedBudget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);
BudgetOperation budgetOperation = new BudgetOperation();
budgetOperation.setOperand(sharedBudget);
budgetOperation.setOperator(Operator.ADD);
// Add the budget
Long budgetId = budgetService.mutate(new BudgetOperation[] { budgetOperation }).getValue(0).getBudgetId();
// Get the CampaignService.
CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
// Create campaign.
Campaign campaign = new Campaign();
campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis());
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
campaign.setStatus(CampaignStatus.PAUSED);
BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
// You can optionally provide a bidding scheme in place of the type.
ManualCpcBiddingScheme cpcBiddingScheme = new ManualCpcBiddingScheme();
biddingStrategyConfiguration.setBiddingScheme(cpcBiddingScheme);
campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
// You can optionally provide these field(s).
campaign.setStartDate(DateTime.now().plusDays(1).toString("yyyyMMdd"));
campaign.setEndDate(DateTime.now().plusDays(30).toString("yyyyMMdd"));
campaign.setFrequencyCap(new FrequencyCap(5L, TimeUnit.DAY, Level.ADGROUP));
// Only the budgetId should be sent, all other fields will be ignored by CampaignService.
Budget budget = new Budget();
budget.setBudgetId(budgetId);
campaign.setBudget(budget);
campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);
// Set the campaign network options to Search and Search Network.
NetworkSetting networkSetting = new NetworkSetting();
networkSetting.setTargetGoogleSearch(true);
networkSetting.setTargetSearchNetwork(true);
networkSetting.setTargetContentNetwork(false);
networkSetting.setTargetPartnerSearchNetwork(false);
campaign.setNetworkSetting(networkSetting);
// Set options that are not required.
GeoTargetTypeSetting geoTarget = new GeoTargetTypeSetting();
geoTarget.setPositiveGeoTargetType(GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE);
campaign.setSettings(new Setting[] { geoTarget });
// You can create multiple campaigns in a single request.
Campaign campaign2 = new Campaign();
campaign2.setName("Interplanetary Cruise banner #" + System.currentTimeMillis());
campaign2.setStatus(CampaignStatus.PAUSED);
BiddingStrategyConfiguration biddingStrategyConfiguration2 = new BiddingStrategyConfiguration();
biddingStrategyConfiguration2.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
campaign2.setBiddingStrategyConfiguration(biddingStrategyConfiguration2);
Budget budget2 = new Budget();
budget2.setBudgetId(budgetId);
campaign2.setBudget(budget2);
campaign2.setAdvertisingChannelType(AdvertisingChannelType.DISPLAY);
// Create operations.
CampaignOperation operation = new CampaignOperation();
operation.setOperand(campaign);
operation.setOperator(Operator.ADD);
CampaignOperation operation2 = new CampaignOperation();
operation2.setOperand(campaign2);
operation2.setOperator(Operator.ADD);
CampaignOperation[] operations = new CampaignOperation[] { operation, operation2 };
// Add campaigns.
CampaignReturnValue result = campaignService.mutate(operations);
// Display campaigns.
for (Campaign campaignResult : result.getValue()) {
System.out.printf("Campaign with name '%s' and ID %d was added.%n", campaignResult.getName(), campaignResult.getId());
}
}
Aggregations