use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class HandlePartialFailures method runExample.
/**
* Runs the example.
*
* @param adWordsServices the services factory.
* @param session the session.
* @param adGroupId the ID of the ad group.
* @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 adGroupId) throws RemoteException {
// Enable partial failure.
session.setPartialFailure(true);
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
List<AdGroupCriterionOperation> operations = new ArrayList<>();
// Create keywords.
String[] keywords = new String[] { "mars cruise", "inv@lid cruise", "venus cruise", "b(a)d keyword cruise" };
for (String keywordText : keywords) {
// Create keyword
Keyword keyword = new Keyword();
keyword.setText(keywordText);
keyword.setMatchType(KeywordMatchType.BROAD);
// Create biddable ad group criterion.
BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
keywordBiddableAdGroupCriterion.setAdGroupId(adGroupId);
keywordBiddableAdGroupCriterion.setCriterion(keyword);
// Create operation.
AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
keywordAdGroupCriterionOperation.setOperator(Operator.ADD);
operations.add(keywordAdGroupCriterionOperation);
}
// Add ad group criteria.
AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[] {}));
// Display results.
Arrays.stream(result.getValue()).filter(adGroupCriterionResult -> adGroupCriterionResult.getCriterion() != null).forEach(adGroupCriterionResult -> System.out.printf("Ad group criterion with ad group ID %d, and criterion ID %d, " + "and keyword '%s' was added.%n", adGroupCriterionResult.getAdGroupId(), adGroupCriterionResult.getCriterion().getId(), ((Keyword) adGroupCriterionResult.getCriterion()).getText()));
for (ApiError apiError : result.getPartialFailureErrors()) {
// Get the index of the failed operation from the error's field path elements.
FieldPathElement[] fieldPathElements = apiError.getFieldPathElements();
FieldPathElement firstFieldPathElement = null;
if (fieldPathElements != null && fieldPathElements.length > 0) {
firstFieldPathElement = fieldPathElements[0];
}
if (firstFieldPathElement != null && "operations".equals(firstFieldPathElement.getField()) && firstFieldPathElement.getIndex() != null) {
int operationIndex = firstFieldPathElement.getIndex();
AdGroupCriterion adGroupCriterion = operations.get(operationIndex).getOperand();
System.out.printf("Ad group criterion with ad group ID %d and keyword '%s' " + "triggered a failure for the following reason: %s.%n", adGroupCriterion.getAdGroupId(), ((Keyword) adGroupCriterion.getCriterion()).getText(), 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 HandlePartialFailures 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();
HandlePartialFailuresParams params = new HandlePartialFailuresParams();
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.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
}
try {
runExample(adWordsServices, session, params.adGroupId);
} 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);
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class SetAdParameters 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();
SetAdParametersParams params = new SetAdParametersParams();
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.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
params.keywordId = Long.parseLong("INSERT_KEYWORD_ID_HERE");
}
try {
runExample(adWordsServices, session, params.adGroupId, params.keywordId);
} 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);
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException in project googleads-java-lib by googleads.
the class ValidateTextAd 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();
ValidateTextAdParams params = new ValidateTextAdParams();
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.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
}
try {
runExample(adWordsServices, session, params.adGroupId);
} 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);
}
}
use of com.google.api.ads.adwords.axis.v201809.cm.ApiException 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.
}
Aggregations