Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
9005 manish.sha 1
// Copyright 2012 Google Inc. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
 
15
package adwords.axis.v201302.errorhandling;
16
 
17
import com.google.api.ads.adwords.axis.factory.AdWordsServices;
18
import com.google.api.ads.adwords.axis.v201302.cm.AdGroupAd;
19
import com.google.api.ads.adwords.axis.v201302.cm.AdGroupAdOperation;
20
import com.google.api.ads.adwords.axis.v201302.cm.AdGroupAdReturnValue;
21
import com.google.api.ads.adwords.axis.v201302.cm.AdGroupAdServiceInterface;
22
import com.google.api.ads.adwords.axis.v201302.cm.ApiError;
23
import com.google.api.ads.adwords.axis.v201302.cm.ApiException;
24
import com.google.api.ads.adwords.axis.v201302.cm.ExemptionRequest;
25
import com.google.api.ads.adwords.axis.v201302.cm.Operator;
26
import com.google.api.ads.adwords.axis.v201302.cm.PolicyViolationError;
27
import com.google.api.ads.adwords.axis.v201302.cm.TextAd;
28
import com.google.api.ads.adwords.lib.client.AdWordsSession;
29
import com.google.api.ads.common.lib.auth.OfflineCredentials;
30
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
31
import com.google.api.client.auth.oauth2.Credential;
32
 
33
import java.util.ArrayList;
34
import java.util.Arrays;
35
import java.util.HashSet;
36
import java.util.List;
37
import java.util.Set;
38
import java.util.regex.Matcher;
39
import java.util.regex.Pattern;
40
 
41
/**
42
 * This example demonstrates how to handle policy violation errors.
43
 *
44
 * Credentials and properties in {@code fromFile()} are pulled from the
45
 * "ads.properties" file. See README for more info.
46
 *
47
 * Tags: AdGroupAdService.mutate
48
 *
49
 * Category: adx-exclude
50
 *
51
 * @author Adam Rogal
52
 */
53
public class HandlePolicyViolationError {
54
 
55
  private static Pattern operationIndexPattern = Pattern.compile("^.*operations\\[(\\d+)\\].*$");
56
 
57
  public static void main(String[] args) throws Exception {
58
    // Generate a refreshable OAuth2 credential similar to a ClientLogin token
59
    // and can be used in place of a service account.
60
    Credential oAuth2Credential = new OfflineCredentials.Builder()
61
        .forApi(Api.ADWORDS)
62
        .fromFile()
63
        .build()
64
        .generateCredential();
65
 
66
    // Construct an AdWordsSession.
67
    AdWordsSession session = new AdWordsSession.Builder()
68
        .fromFile()
69
        .withOAuth2Credential(oAuth2Credential)
70
        .build();
71
 
72
    long adGroupId = Long.parseLong("INSERT_ADGROUP_ID_HERE");
73
    AdWordsServices adWordsServices = new AdWordsServices();
74
 
75
    runExample(adWordsServices, session, adGroupId);
76
  }
77
 
78
  public static void runExample(
79
      AdWordsServices adWordsServices, AdWordsSession session, Long adGroupId) throws Exception {
80
    // Enable validateOnly mode.
81
    session.setValidateOnly(true);
82
 
83
    // Get the AdGroupAdService.
84
    AdGroupAdServiceInterface adGroupAdService =
85
        adWordsServices.get(session, AdGroupAdServiceInterface.class);
86
 
87
    // Create text ad that violates an exemptable policy. This ad will only
88
    // trigger an error in the production environment.
89
    TextAd exemptableTextAd = new TextAd();
90
    exemptableTextAd.setHeadline("Mars " + System.currentTimeMillis() + "!!!");
91
    exemptableTextAd.setDescription1("Visit the Red Planet in style.");
92
    exemptableTextAd.setDescription2("Low-gravity fun for everyone!");
93
    exemptableTextAd.setDisplayUrl("www.example.com");
94
    exemptableTextAd.setUrl("http://www.example.com/");
95
 
96
    // Create ad group ad.
97
    AdGroupAd exemptableAdGroupAd = new AdGroupAd();
98
    exemptableAdGroupAd.setAdGroupId(adGroupId);
99
    exemptableAdGroupAd.setAd(exemptableTextAd);
100
 
101
    // Create operations.
102
    AdGroupAdOperation exemptableOperation = new AdGroupAdOperation();
103
    exemptableOperation.setOperand(exemptableAdGroupAd);
104
    exemptableOperation.setOperator(Operator.ADD);
105
 
106
    // Create text ad that violates an non-exemptable policy.
107
    TextAd nonExemptableTextAd = new TextAd();
108
    nonExemptableTextAd.setHeadline("Mars Cruise with too long of a headline.");
109
    nonExemptableTextAd.setDescription1("Visit the Red Planet in style.");
110
    nonExemptableTextAd.setDescription2("Low-gravity fun for everyone.");
111
    nonExemptableTextAd.setDisplayUrl("www.example.com");
112
    nonExemptableTextAd.setUrl("http://www.example.com/");
113
 
114
    // Create ad group ad.
115
    AdGroupAd nonExemptableAdGroupAd = new AdGroupAd();
116
    nonExemptableAdGroupAd.setAdGroupId(adGroupId);
117
    nonExemptableAdGroupAd.setAd(nonExemptableTextAd);
118
 
119
    // Create operations.
120
    AdGroupAdOperation nonExemptableOperation = new AdGroupAdOperation();
121
    nonExemptableOperation.setOperand(nonExemptableAdGroupAd);
122
    nonExemptableOperation.setOperator(Operator.ADD);
123
 
124
    AdGroupAdOperation[] operations =
125
        new AdGroupAdOperation[] {exemptableOperation, nonExemptableOperation};
126
 
127
    try {
128
      // Validate the ads.
129
      AdGroupAdReturnValue result = adGroupAdService.mutate(operations);
130
    } catch (ApiException e) {
131
      Set<Integer> indicesToRemove = new HashSet<Integer>();
132
      for (ApiError error : e.getErrors()) {
133
        if (error instanceof PolicyViolationError) {
134
          PolicyViolationError policyViolationError = (PolicyViolationError) error;
135
          Matcher matcher = operationIndexPattern.matcher(error.getFieldPath());
136
          if (matcher.matches()) {
137
            int operationIndex = Integer.parseInt(matcher.group(1));
138
            AdGroupAdOperation operation = operations[operationIndex];
139
            System.out.printf("Ad with headline \"%s\" violated %s policy \"%s\".\n",
140
                ((TextAd) operation.getOperand().getAd()).getHeadline(), policyViolationError
141
                    .getIsExemptable() ? "exemptable" : "non-exemptable", policyViolationError
142
                    .getExternalPolicyName());
143
            if (policyViolationError.getIsExemptable()) {
144
              // Add exemption request to the operation.
145
              System.out.printf(
146
                  "Adding exemption request for policy name \"%s\" on text \"%s\".\n",
147
                  policyViolationError.getKey().getPolicyName(), policyViolationError.getKey()
148
                      .getViolatingText());
149
              List<ExemptionRequest> exemptionRequests =
150
                  new ArrayList<ExemptionRequest>(Arrays
151
                      .asList(operation.getExemptionRequests() == null
152
                          ? new ExemptionRequest[] {} : operation.getExemptionRequests()));
153
              exemptionRequests.add(new ExemptionRequest(policyViolationError.getKey()));
154
              operation
155
                  .setExemptionRequests(exemptionRequests.toArray(new ExemptionRequest[] {}));
156
            } else {
157
              // Remove non-exemptable operation.
158
              System.out.println("Removing non-exemptable operation at index " + operationIndex
159
                  + ".");
160
              indicesToRemove.add(operationIndex);
161
            }
162
          }
163
        } else {
164
          // Non-policy error returned.
165
          Matcher matcher = operationIndexPattern.matcher(error.getFieldPath());
166
          if (matcher.matches()) {
167
            int operationIndex = Integer.parseInt(matcher.group(1));
168
            AdGroupAdOperation operation = operations[operationIndex];
169
            System.out.printf("Ad with headline \"%s\" created non-policy error \"%s\".\n",
170
                ((TextAd) operation.getOperand().getAd()).getHeadline(), error.getErrorString());
171
            System.out.println("Removing non-exemptable operation at index " + operationIndex
172
                + ".");
173
            indicesToRemove.add(operationIndex);
174
          }
175
        }
176
      }
177
 
178
      // Remove operations that cannot be exempted.
179
      List<AdGroupAdOperation> remainingOperations = new ArrayList<AdGroupAdOperation>();
180
      for (int i = 0; i < operations.length; i++) {
181
        if (!indicesToRemove.contains(i)) {
182
          remainingOperations.add(operations[i]);
183
        }
184
      }
185
      operations = remainingOperations.toArray(new AdGroupAdOperation[]{});
186
    }
187
 
188
    if (operations.length > 0) {
189
      // Disable validateOnly so we can submit the AdGroupAds with exemptions.
190
      session.setValidateOnly(false);
191
 
192
      // Add ads with exemptions.
193
      AdGroupAdReturnValue result = adGroupAdService.mutate(operations);
194
 
195
      // Display ads.
196
      if (result != null && result.getValue() != null) {
197
        for (AdGroupAd adGroupAdResult : result.getValue()) {
198
          System.out.printf("Ad with id \"%s\" and headline \"%s\" was added.\n", adGroupAdResult
199
              .getAd().getId(), ((TextAd) adGroupAdResult.getAd()).getHeadline());
200
        }
201
      }
202
    } else {
203
      System.out.println("No ads were added.");
204
    }
205
  }
206
}