use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class UpdateCampaign method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param campaignId the ID of the campaign to update.
* @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 campaignId) throws RemoteException {
// Get the CampaignService.
CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
// Create campaign with updated status.
Campaign campaign = new Campaign();
campaign.setId(campaignId);
campaign.setStatus(CampaignStatus.PAUSED);
// Create operations.
CampaignOperation operation = new CampaignOperation();
operation.setOperand(campaign);
operation.setOperator(Operator.SET);
CampaignOperation[] operations = new CampaignOperation[] { operation };
// Update campaign.
CampaignReturnValue result = campaignService.mutate(operations);
// Display campaigns.
for (Campaign campaignResult : result.getValue()) {
System.out.printf("Campaign with name '%s', ID %d, and budget delivery method '%s' " + "was updated.%n", campaignResult.getName(), campaignResult.getId(), campaignResult.getBudget().getDeliveryMethod());
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class ProductPartitionTreeImpl method createAdGroupTree.
/**
* Returns a new instance of this class by retrieving the product partitions of the
* specified ad group. All parameters are required.
*/
static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services, AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface criterionService = services.get(session, AdGroupCriterionServiceInterface.class);
SelectorBuilder selectorBuilder = new SelectorBuilder().fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()])).equals(AdGroupCriterionField.AdGroupId, adGroupId.toString()).equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION").in(AdGroupCriterionField.Status, UserStatus.ENABLED.getValue(), UserStatus.PAUSED.getValue()).limit(PAGE_SIZE);
AdGroupCriterionPage adGroupCriterionPage;
// A multimap from each product partition ID to its direct children.
ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
int offset = 0;
do {
// Get the next page of results.
adGroupCriterionPage = criterionService.get(selectorBuilder.build());
if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
}
offset += adGroupCriterionPage.getEntries().length;
selectorBuilder.increaseOffsetBy(PAGE_SIZE);
}
} while (offset < adGroupCriterionPage.getTotalNumEntries());
// Construct the ProductPartitionTree from the parentIdMap.
if (!parentIdMap.containsKey(null)) {
Preconditions.checkState(parentIdMap.isEmpty(), "No root criterion found in the tree but the tree is not empty");
return createEmptyAdGroupTree(adGroupId, getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
}
return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class UploadOfflineData method main.
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();
UploadOfflineDataParams params = new UploadOfflineDataParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.emailAddresses = Arrays.asList("INSERT_EMAIL_ADDRESS_1_HERE", "INSERT_EMAIL_ADDRESS_2_HERE");
params.conversionName = "INSERT_CONVERSION_NAME_HERE";
params.externalUploadId = Long.valueOf("INSERT_EXTERNAL_UPLOAD_ID_HERE");
// Change the enum below to STORE_SALES_UPLOAD_THIRD_PARTY if uploading third party data.
params.offlineDataUploadType = OfflineDataUploadType.STORE_SALES_UPLOAD_FIRST_PARTY.getValue();
// The three constants below are needed when uploading third party data.
// You can safely ignore them if you are uploading first party data.
// For times, use the format yyyyMMdd HHmmss tz. For more details on formats, see:
// https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats
// For time zones, see:
// https://developers.google.com/adwords/api/docs/appendix/codes-formats#timezone-ids
params.advertiserUploadTime = "INSERT_ADVERTISER_UPLOAD_TIME";
params.bridgeMapVersionId = "INSERT_BRIDGE_MAP_VERSION_ID";
params.partnerId = Integer.valueOf("INSERT_PARTNER_ID");
}
OfflineDataUploadType uploadTypeEnum = OfflineDataUploadType.fromString(params.offlineDataUploadType);
// Set partial failure to true since this example demonstrates how to handle partial
// failure errors.
session.setPartialFailure(true);
try {
runExample(adWordsServices, session, params.conversionName, params.externalUploadId, params.emailAddresses, uploadTypeEnum, params.advertiserUploadTime, params.bridgeMapVersionId, params.partnerId);
} catch (ApiException apiException) {
// ApiException is the base class for most exceptions thrown by an API request. Instances
// of this exception have a message and a collection of ApiErrors that indicate the
// type and underlying cause of the exception. Every exception object in the adwords.axis
// packages will return a meaningful value from toString
//
// ApiException extends RemoteException, so this catch block must appear before the
// catch block for RemoteException.
System.err.println("Request failed due to ApiException. Underlying ApiErrors:");
if (apiException.getErrors() != null) {
int i = 0;
for (ApiError apiError : apiException.getErrors()) {
System.err.printf(" Error %d: %s%n", i++, apiError);
}
}
} catch (RemoteException re) {
System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
} catch (UnsupportedEncodingException ue) {
System.err.printf("Example failed due to encoding exception: %s%n", ue);
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class UploadOfflineData method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param conversionName the name of the conversion tracker.
* @param externalUploadId the external upload ID.
* @param emailAddresses the list of email addresses. Must contain exactly two entries for this
* example.
* @param offlineDataUploadType the type of store sales upload metadata to upload.
* @param advertiserUploadTime the date and time of the advertiser upload.
* @param bridgeMapVersionId the bridge map version ID.
* @param partnerId the partner ID.
* @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 UnsupportedEncodingException if encoding the offline data values failed.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, String conversionName, long externalUploadId, List<String> emailAddresses, OfflineDataUploadType offlineDataUploadType, String advertiserUploadTime, String bridgeMapVersionId, Integer partnerId) throws RemoteException, UnsupportedEncodingException {
// This example requires exactly 2 email addresses.
if (emailAddresses.size() != 2) {
throw new IllegalArgumentException(String.format("%d email addresses specified. Please specify exactly 2 email addresses.", emailAddresses.size()));
}
// Get the OfflineDataUploadService.
OfflineDataUploadServiceInterface offlineDataUploadService = adWordsServices.get(session, OfflineDataUploadServiceInterface.class);
List<OfflineData> offlineDataList = new ArrayList<>();
// Create the first offline data for upload.
// This transaction occurred 7 days ago with amount of 200 USD.
DateTime transactionTime1 = DateTime.now().minusDays(7);
long transactionAmount1 = 200_000_000L;
List<UserIdentifier> userIdentifiers1 = Arrays.asList(createUserIdentifier(OfflineDataUploadUserIdentifierType.HASHED_EMAIL, emailAddresses.get(0)), createUserIdentifier(OfflineDataUploadUserIdentifierType.STATE, "New York"));
offlineDataList.add(createOfflineData(transactionTime1, transactionAmount1, "USD", conversionName, userIdentifiers1));
// Create the second offline data for upload.
// This transaction occurred 14 days ago with amount of 450 EUR.
DateTime transactionTime2 = DateTime.now().minusDays(14);
long transactionAmount2 = 450_000_000L;
List<UserIdentifier> userIdentifiers2 = Arrays.asList(createUserIdentifier(OfflineDataUploadUserIdentifierType.HASHED_EMAIL, emailAddresses.get(1)), createUserIdentifier(OfflineDataUploadUserIdentifierType.STATE, "California"));
offlineDataList.add(createOfflineData(transactionTime2, transactionAmount2, "EUR", conversionName, userIdentifiers2));
// Create offline data upload object.
OfflineDataUpload offlineDataUpload = new OfflineDataUpload();
offlineDataUpload.setExternalUploadId(externalUploadId);
offlineDataUpload.setOfflineDataList(offlineDataList.toArray(new OfflineData[offlineDataList.size()]));
offlineDataUpload.setUploadType(offlineDataUploadType);
// Set the type and metadata of this upload.
StoreSalesUploadCommonMetadata storeSalesUploadMetadata;
if (OfflineDataUploadType.STORE_SALES_UPLOAD_FIRST_PARTY.equals(offlineDataUploadType)) {
storeSalesUploadMetadata = new FirstPartyUploadMetadata();
} else {
ThirdPartyUploadMetadata thirdPartyUploadMetadata = new ThirdPartyUploadMetadata();
thirdPartyUploadMetadata.setAdvertiserUploadTime(advertiserUploadTime);
thirdPartyUploadMetadata.setValidTransactionRate(1.0);
thirdPartyUploadMetadata.setPartnerMatchRate(1.0);
thirdPartyUploadMetadata.setPartnerUploadRate(1.0);
thirdPartyUploadMetadata.setBridgeMapVersionId(bridgeMapVersionId);
thirdPartyUploadMetadata.setPartnerId(partnerId);
storeSalesUploadMetadata = thirdPartyUploadMetadata;
}
storeSalesUploadMetadata.setLoyaltyRate(1.0);
storeSalesUploadMetadata.setTransactionUploadRate(1.0);
UploadMetadata uploadMetadata = new UploadMetadata();
uploadMetadata.setStoreSalesUploadCommonMetadata(storeSalesUploadMetadata);
offlineDataUpload.setUploadMetadata(uploadMetadata);
// Create an offline data upload operation.
List<OfflineDataUploadOperation> operations = new ArrayList<>();
OfflineDataUploadOperation offlineDataUploadOperation = new OfflineDataUploadOperation();
offlineDataUploadOperation.setOperator(Operator.ADD);
offlineDataUploadOperation.setOperand(offlineDataUpload);
operations.add(offlineDataUploadOperation);
// Upload offline data on the server and print some information.
OfflineDataUploadReturnValue returnValue = offlineDataUploadService.mutate(operations.toArray(new OfflineDataUploadOperation[0]));
offlineDataUpload = returnValue.getValue(0);
System.out.printf("Uploaded offline data with external upload ID %d, and upload status %s.%n", offlineDataUpload.getExternalUploadId(), offlineDataUpload.getUploadStatus());
// Print any partial failure errors from the response.
if (returnValue.getPartialFailureErrors() != null) {
for (ApiError apiError : returnValue.getPartialFailureErrors()) {
// Get the index of the failed operation from the error's field path elements.
Integer operationIndex = getFieldPathElementIndex(apiError, "operations");
if (operationIndex != null) {
OfflineDataUpload failedOfflineDataUpload = operations.get(operationIndex).getOperand();
// Get the index of the entry in the offline data list from the error's field path
// elements.
Integer offlineDataListIndex = getFieldPathElementIndex(apiError, "offlineDataList");
System.out.printf("Offline data list entry %d in operation %d with external upload ID %d and type " + "'%s' has triggered a failure for the following reason: '%s'.%n", offlineDataListIndex, operationIndex, failedOfflineDataUpload.getExternalUploadId(), failedOfflineDataUpload.getUploadType(), apiError.getErrorString());
} else {
System.out.printf("A failure has occurred for the following reason: %s%n", apiError.getErrorString());
}
}
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class ParallelReportDownload method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param numberOfThreads number of threads to use for concurrent report requests.
* @param maxElapsedSecondsPerCustomer the maximum number of seconds to wait for each report
* request to complete.
* @throws ApiException if the API request to retrieve managed customers failed with one or more
* service errors.
* @throws RemoteException if the API request to retrieve managed customers failed due to other
* errors.
* @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 read from the response.
* @throws ValidationException if creation of an ImmutableAdWordsSession for a customer failed due
* to validation issues.
* @throws InterruptedException if the thread was interrupted while waiting for all report
* downloads to complete.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, ImmutableAdWordsSession session, int numberOfThreads, int maxElapsedSecondsPerCustomer) throws ReportDownloadResponseException, ReportException, IOException, ValidationException, InterruptedException {
// Retrieve all accounts under the manager account.
Map<Long, ManagedCustomer> managedCustomers = getAllManagedCustomers(adWordsServices, session);
System.out.printf("Downloading report for %d managed customers.%n", managedCustomers.size());
// Create selector for the report definition.
Selector selector = new Selector();
selector.getFields().addAll(Arrays.asList("CampaignId", "AdGroupId", "Impressions", "Clicks", "Cost"));
// Create report definition.
ReportDefinition reportDefinition = new ReportDefinition();
reportDefinition.setReportName("Custom ADGROUP_PERFORMANCE_REPORT");
reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.LAST_7_DAYS);
reportDefinition.setReportType(ReportDefinitionReportType.ADGROUP_PERFORMANCE_REPORT);
reportDefinition.setDownloadFormat(DownloadFormat.CSV);
reportDefinition.setSelector(selector);
// 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).includeZeroImpressions(false).build();
// Create a thread pool for submitting report requests.
ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads);
// Customize this builder if you want to change the backoff policy on retryable report
// failures.
ExponentialBackOff.Builder backOffBuilder = new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(maxElapsedSecondsPerCustomer * 1000);
File reportDirectory = Files.createTempDir();
// List to keep track of the progress of each customer's report download task.
List<ReportDownloadFutureTask> reportDownloadFutureTasks = new ArrayList<>();
for (ManagedCustomer managedCustomer : managedCustomers.values()) {
File outputFile = new File(reportDirectory, String.format("adgroup_%010d.csv", managedCustomer.getCustomerId()));
ImmutableAdWordsSession sessionForCustomer = session.newBuilder().withClientCustomerId(Long.toString(managedCustomer.getCustomerId())).withReportingConfiguration(reportingConfiguration).buildImmutable();
ReportDownloadFutureTask reportDownloadFutureTask = new ReportDownloadFutureTask(new ReportDownloadCallable(sessionForCustomer, adWordsServices, reportDefinition, outputFile, backOffBuilder.build()));
// Use execute instead of submit since there is no need to get a Future for a FutureTask.
// Instead, store this ReportDownloadFutureTask in the list so that it can be used later
// to check the result and determine the task context (client customer ID).
threadPool.execute(reportDownloadFutureTask);
reportDownloadFutureTasks.add(reportDownloadFutureTask);
}
// All callables have been submitted. Shut down the thread pool.
threadPool.shutdown();
// Wait for the thread pool to terminate.
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
System.out.println();
System.out.println("All downloads completed. Results:");
Map<String, File> successfulReports = Maps.newHashMap();
Map<String, Exception> failedReports = Maps.newHashMap();
for (ReportDownloadFutureTask reportDownloadFutureTask : reportDownloadFutureTasks) {
String clientCustomerId = reportDownloadFutureTask.getClientCustomerId();
try {
File reportFile = reportDownloadFutureTask.get();
successfulReports.put(clientCustomerId, reportFile);
} catch (CancellationException | InterruptedException | ExecutionException e) {
failedReports.put(clientCustomerId, e);
}
}
System.out.println("Successful reports:");
successfulReports.forEach((clientCustomerId, reportFile) -> System.out.printf("\tClient ID %s => '%s'%n", clientCustomerId, reportFile));
System.out.println("Failed reports:");
failedReports.forEach((clientCustomerId, exception) -> System.out.printf("\tClient ID %s => Exception: %s%n", clientCustomerId, exception));
System.out.println("End of results.");
}
Aggregations