AdGroupAdReturnValue result = adGroupAdValidationService.mutate(operations);
} catch (ApiException e) {
Set<Integer> indicesToRemove = new HashSet<Integer>();
for (ApiError error : e.getErrors()) {
if (error instanceof PolicyViolationError) {
PolicyViolationError policyVioloationError = (PolicyViolationError) error;
Matcher matcher = operationIndexPattern.matcher(error.getFieldPath());
if (matcher.matches()) {
int operationIndex = Integer.parseInt(matcher.group(1));
AdGroupAdOperation operation = operations[operationIndex];
System.out.printf("Ad with headline \"%s\" violated %s policy \"%s\".\n",
((TextAd) operation.getOperand().getAd()).getHeadline(), policyVioloationError
.getIsExemptable() ? "exemptable" : "non-exemptable", policyVioloationError
.getExternalPolicyName());
if (policyVioloationError.getIsExemptable()) {
// Add exemption request to the operation.
System.out.printf(
"Adding exemption request for policy name \"%s\" on text \"%s\".\n",
policyVioloationError.getKey().getPolicyName(), policyVioloationError.getKey()
.getViolatingText());
List<ExemptionRequest> exemptionRequests =
new ArrayList<ExemptionRequest>(Arrays
.asList(operation.getExemptionRequests() == null
? new ExemptionRequest[] {} : operation.getExemptionRequests()));
exemptionRequests.add(new ExemptionRequest(policyVioloationError.getKey()));
operation
.setExemptionRequests(exemptionRequests.toArray(new ExemptionRequest[] {}));
} else {
// Remove non-exemptable operation.
System.out.println("Removing non-exemptable operation at index " + operationIndex