use of com.google.api.ads.adwords.axis.v201809.mcm.Customer in project googleads-java-lib by googleads.
the class AddMultiAssetResponsiveDisplayAd method uploadImageAsset.
/**
* Creates and uploads an {@link ImageAsset} for the specified URL.
*
* @return the ID of the {@link ImageAsset}.
* @throws IOException if unable to read the image from the specified URL.
*/
private static long uploadImageAsset(AdWordsServicesInterface adWordsServices, AdWordsSession session, String url) throws IOException {
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
// Create the image asset.
ImageAsset image = new ImageAsset();
// Optional: Provide a unique friendly name to identify your asset. If you specify the assetName
// field, then both the asset name and the image being uploaded should be unique, and should not
// match another ACTIVE asset in this customer account.
// image.setAssetName("Image asset #" + System.currentTimeMillis());
image.setImageData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));
// Create the operation.
AssetOperation operation = new AssetOperation();
operation.setOperator(Operator.ADD);
operation.setOperand(image);
// Create the asset and return the ID.
return assetService.mutate(new AssetOperation[] { operation }).getValue(0).getAssetId();
}
use of com.google.api.ads.adwords.axis.v201809.mcm.Customer in project googleads-java-lib by googleads.
the class UploadImageAsset 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.
* @throws IOException if unable to get media data from the URL.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session) throws IOException {
// Get the AssetService.
AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);
// Create the image asset.
ImageAsset image = new ImageAsset();
// Optional: Provide a unique friendly name to identify your asset. If you specify the assetName
// field, then both the asset name and the image being uploaded should be unique, and should not
// match another ACTIVE asset in this customer account.
// image.setAssetName("Jupiter Trip #" + System.currentTimeMillis());
image.setImageData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/3b9Wfh"));
// Create the operation.
AssetOperation operation = new AssetOperation();
operation.setOperator(Operator.ADD);
operation.setOperand(image);
// Create the asset.
AssetReturnValue result = assetService.mutate(new AssetOperation[] { operation });
// Display the results.
if (result != null && result.getValue() != null && result.getValue().length > 0) {
Asset newAsset = result.getValue(0);
System.out.printf("Image asset with ID %d and name '%s' was created.%n", newAsset.getAssetId(), newAsset.getAssetName());
} else {
System.out.println("No image asset was created.");
}
}
use of com.google.api.ads.adwords.axis.v201809.mcm.Customer in project googleads-java-lib by googleads.
the class AddGoogleMyBusinessLocationExtensions method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param gmbEmailAddress the email address of the owner or manager of the GMB account.
* @param gmbAccessToken the OAuth2 access token for GMB.
* @param businessAccountIdentifier optional identifier of the Google My Business account. This is
* required when the {@code gmbEmailAddress} is a GMB manager.
* @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.
*/
private static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, String gmbEmailAddress, String gmbAccessToken, @Nullable String businessAccountIdentifier) throws RemoteException, InterruptedException {
FeedServiceInterface feedService = adWordsServices.get(session, FeedServiceInterface.class);
// Create a feed that will sync to the Google My Business account specified
// by gmbEmailAddress. Do not add FeedAttributes to this object,
// as AdWords will add them automatically because this will be a
// system generated feed.
Feed gmbFeed = new Feed();
gmbFeed.setName("Google My Business feed #" + System.currentTimeMillis());
PlacesLocationFeedData feedData = new PlacesLocationFeedData();
feedData.setEmailAddress(gmbEmailAddress);
feedData.setBusinessAccountIdentifier(businessAccountIdentifier);
// Optional: specify labels to filter Google My Business listings. If
// specified, only listings that have any of the labels set are
// synchronized into FeedItems.
feedData.setLabelFilters(new String[] { "Stores in New York City" });
OAuthInfo oAuthInfo = new OAuthInfo();
oAuthInfo.setHttpMethod("GET");
oAuthInfo.setHttpRequestUrl(GetRefreshToken.ADWORDS_API_SCOPE);
oAuthInfo.setHttpAuthorizationHeader(String.format("Bearer %s", gmbAccessToken));
feedData.setOAuthInfo(oAuthInfo);
gmbFeed.setSystemFeedGenerationData(feedData);
// Since this feed's feed items will be managed by AdWords,
// you must set its origin to ADWORDS.
gmbFeed.setOrigin(FeedOrigin.ADWORDS);
// Create an operation to add the feed.
FeedOperation feedOperation = new FeedOperation();
feedOperation.setOperand(gmbFeed);
feedOperation.setOperator(Operator.ADD);
// Add the feed. Since it is a system generated feed, AdWords will automatically:
// 1. Set up the FeedAttributes on the feed.
// 2. Set up a FeedMapping that associates the FeedAttributes of the feed
// with the placeholder fields of the LOCATION placeholder type.
FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation });
Feed addedFeed = addFeedResult.getValue(0);
System.out.printf("Added GMB feed with ID %d%n", addedFeed.getId());
// Add a CustomerFeed that associates the feed with this customer for
// the LOCATION placeholder type.
CustomerFeed customerFeed = new CustomerFeed();
customerFeed.setFeedId(addedFeed.getId());
customerFeed.setPlaceholderTypes(new int[] { PLACEHOLDER_LOCATION });
// Create a matching function that will always evaluate to true.
Function customerMatchingFunction = new Function();
ConstantOperand constOperand = new ConstantOperand();
constOperand.setType(ConstantOperandConstantType.BOOLEAN);
constOperand.setBooleanValue(true);
customerMatchingFunction.setLhsOperand(new FunctionArgumentOperand[] { constOperand });
customerMatchingFunction.setOperator(FunctionOperator.IDENTITY);
customerFeed.setMatchingFunction(customerMatchingFunction);
// Create an operation to add the customer feed.
CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
customerFeedOperation.setOperand(customerFeed);
customerFeedOperation.setOperator(Operator.ADD);
CustomerFeedServiceInterface customerFeedService = adWordsServices.get(session, CustomerFeedServiceInterface.class);
// After the completion of the Feed ADD operation above the added feed will not be available
// for usage in a CustomerFeed until the sync between the AdWords and GMB accounts
// completes. The loop below will retry adding the CustomerFeed up to ten times with an
// exponential back-off policy.
CustomerFeed addedCustomerFeed = null;
int numberOfAttempts = 0;
do {
numberOfAttempts++;
try {
CustomerFeedReturnValue customerFeedResult = customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation });
addedCustomerFeed = customerFeedResult.getValue(0);
System.out.printf("Attempt #%d to add the CustomerFeed was successful%n", numberOfAttempts);
} catch (Exception e) {
// Wait using exponential backoff policy
long sleepSeconds = (long) Math.scalb(5, numberOfAttempts);
System.out.printf("Attempt #%d to add the CustomerFeed was not successful. " + "Waiting %d seconds before trying again.%n", numberOfAttempts, sleepSeconds);
Thread.sleep(sleepSeconds * 1000);
}
} while (numberOfAttempts < MAX_CUSTOMER_FEED_ADD_ATTEMPTS && addedCustomerFeed == null);
if (addedCustomerFeed == null) {
throw new RuntimeException("Could not create the CustomerFeed after " + MAX_CUSTOMER_FEED_ADD_ATTEMPTS + " attempts. Please retry " + "the CustomerFeed ADD operation later.");
}
System.out.printf("Added CustomerFeed for feed ID %d and placeholder type %d%n", addedCustomerFeed.getFeedId(), addedCustomerFeed.getPlaceholderTypes()[0]);
// OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at the Campaign
// level. This will be similar to the CampaignFeed in the AddSiteLinks example, except
// you can also filter based on the business name and category of each FeedItem
// by using a FeedAttributeOperand in your matching function.
// OPTIONAL: Create an AdGroupFeed for even more fine grained control over
// which feed items are used at the AdGroup level.
}
use of com.google.api.ads.adwords.axis.v201809.mcm.Customer 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.");
}
use of com.google.api.ads.adwords.axis.v201809.mcm.Customer in project googleads-java-lib by googleads.
the class AddCrmBasedUserList 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.
* @throws UnsupportedEncodingException if encoding the hashed email failed.
*/
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException, UnsupportedEncodingException {
// Get the UserListService.
AdwordsUserListServiceInterface userListService = adWordsServices.get(session, AdwordsUserListServiceInterface.class);
// Create a user list.
CrmBasedUserList userList = new CrmBasedUserList();
userList.setName("Customer relationship management list #" + System.currentTimeMillis());
userList.setDescription("A list of customers that originated from email addresses");
// CRM-based user lists can use a membershipLifeSpan of 10000 to indicate unlimited; otherwise
// normal values apply.
userList.setMembershipLifeSpan(30L);
userList.setUploadKeyType(CustomerMatchUploadKeyType.CONTACT_INFO);
// Create operation.
UserListOperation operation = new UserListOperation();
operation.setOperand(userList);
operation.setOperator(Operator.ADD);
// Add user list.
UserListReturnValue result = userListService.mutate(new UserListOperation[] { operation });
// Display user list.
UserList userListAdded = result.getValue(0);
System.out.printf("User list with name '%s' and ID %d was added.%n", userListAdded.getName(), userListAdded.getId());
// Get user list ID.
Long userListId = userListAdded.getId();
// Create operation to add members to the user list based on email addresses.
MutateMembersOperation mutateMembersOperation = new MutateMembersOperation();
MutateMembersOperand operand = new MutateMembersOperand();
operand.setUserListId(userListId);
// Hash normalized email addresses based on SHA-256 hashing algorithm.
List<Member> members = new ArrayList<>(EMAILS.size());
for (String email : EMAILS) {
String normalizedEmail = toNormalizedString(email);
Member member = new Member();
member.setHashedEmail(toSHA256String(normalizedEmail));
members.add(member);
}
String firstName = "John";
String lastName = "Doe";
String countryCode = "US";
String zipCode = "10011";
AddressInfo addressInfo = new AddressInfo();
// First and last name must be normalized and hashed.
addressInfo.setHashedFirstName(toSHA256String(toNormalizedString(firstName)));
addressInfo.setHashedLastName(toSHA256String(toNormalizedString(lastName)));
// Country code and zip code are sent in plaintext.
addressInfo.setCountryCode(countryCode);
addressInfo.setZipCode(zipCode);
Member memberByAddress = new Member();
memberByAddress.setAddressInfo(addressInfo);
members.add(memberByAddress);
operand.setMembersList(members.toArray(new Member[members.size()]));
mutateMembersOperation.setOperand(operand);
mutateMembersOperation.setOperator(Operator.ADD);
// Add members to the user list based on email addresses.
MutateMembersReturnValue mutateMembersResult = userListService.mutateMembers(new MutateMembersOperation[] { mutateMembersOperation });
// Reminder: it may take several hours for the list to be populated with members.
for (UserList userListResult : mutateMembersResult.getUserLists()) {
System.out.printf("%d email addresses were uploaded to user list with name '%s' and ID %d " + "and are scheduled for review.%n", EMAILS.size(), userListResult.getName(), userListResult.getId());
}
}
Aggregations