/
AddRealEstateFeed.java
416 lines (383 loc) · 18.6 KB
/
AddRealEstateFeed.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.remarketing;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v16.enums.FeedAttributeTypeEnum.FeedAttributeType;
import com.google.ads.googleads.v16.enums.PlaceholderTypeEnum.PlaceholderType;
import com.google.ads.googleads.v16.enums.RealEstatePlaceholderFieldEnum.RealEstatePlaceholderField;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.resources.AttributeFieldMapping;
import com.google.ads.googleads.v16.resources.Feed;
import com.google.ads.googleads.v16.resources.FeedAttribute;
import com.google.ads.googleads.v16.resources.FeedItem;
import com.google.ads.googleads.v16.resources.FeedItemAttributeValue;
import com.google.ads.googleads.v16.resources.FeedMapping;
import com.google.ads.googleads.v16.services.FeedItemOperation;
import com.google.ads.googleads.v16.services.FeedItemServiceClient;
import com.google.ads.googleads.v16.services.FeedMappingOperation;
import com.google.ads.googleads.v16.services.FeedMappingServiceClient;
import com.google.ads.googleads.v16.services.FeedOperation;
import com.google.ads.googleads.v16.services.FeedServiceClient;
import com.google.ads.googleads.v16.services.GoogleAdsRow;
import com.google.ads.googleads.v16.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v16.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v16.services.MutateFeedItemResult;
import com.google.ads.googleads.v16.services.MutateFeedItemsResponse;
import com.google.ads.googleads.v16.services.MutateFeedMappingResult;
import com.google.ads.googleads.v16.services.MutateFeedMappingsResponse;
import com.google.ads.googleads.v16.services.MutateFeedsResponse;
import com.google.ads.googleads.v16.services.SearchGoogleAdsRequest;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Adds a real estate feed, creates the feed mapping, and adds items to the feed. */
public class AddRealEstateFeed {
private static final int PAGE_SIZE = 1_000;
private static class AddRealEstateFeedParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private long customerId;
}
public static void main(String[] args) {
AddRealEstateFeedParams params = new AddRealEstateFeedParams();
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.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddRealEstateFeed().runExample(googleAdsClient, params);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param params the AddRealEstateFeedParams for the example.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, AddRealEstateFeedParams params) {
// Creates a new feed, but you can fetch and re-use an existing feed by skipping the
// createFeed method and inserting the feed resource name of the existing feed into the
// getFeed method.
String feedResourceName = createFeed(googleAdsClient, params.customerId);
// Gets the page feed details.
Map<RealEstatePlaceholderField, FeedAttribute> feedAttributes =
getFeed(googleAdsClient, params.customerId, feedResourceName);
// Creates the feed mapping.
createFeedMapping(googleAdsClient, params.customerId, feedAttributes, feedResourceName);
// Creates feed items and adds them to the feed.
createFeedItems(googleAdsClient, params.customerId, feedAttributes, feedResourceName);
}
/**
* Creates a feed.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @return a String of the feed resource name.
*/
private String createFeed(GoogleAdsClient googleAdsClient, long customerId) {
// Creates a Listing ID attribute.
FeedAttribute listingIdAttribute =
FeedAttribute.newBuilder().setType(FeedAttributeType.STRING).setName("Listing ID").build();
// Creates a Listing Name attribute.
FeedAttribute listingNameAttribute =
FeedAttribute.newBuilder()
.setType(FeedAttributeType.STRING)
.setName("Listing Name")
.build();
// Creates a Final URLs attribute.
FeedAttribute finalUrlsAttribute =
FeedAttribute.newBuilder()
.setType(FeedAttributeType.URL_LIST)
.setName("Final URLs")
.build();
// Creates an Image URL attribute
FeedAttribute imageUrlAttribute =
FeedAttribute.newBuilder().setType(FeedAttributeType.URL).setName("Image URL").build();
// Creates a Contextual Keywords attribute
FeedAttribute contextualKeywordsAttribute =
FeedAttribute.newBuilder()
.setType(FeedAttributeType.STRING_LIST)
.setName("Contextual Keywords")
.build();
// Creates the feed.
Feed feed =
Feed.newBuilder()
.setName("Real Estate Feed #" + getPrintableDateTime())
.addAttributes(listingIdAttribute)
.addAttributes(listingNameAttribute)
.addAttributes(finalUrlsAttribute)
.addAttributes(imageUrlAttribute)
.addAttributes(contextualKeywordsAttribute)
.build();
// Creates the operation.
FeedOperation operation = FeedOperation.newBuilder().setCreate(feed).build();
// Creates the feed service client.
try (FeedServiceClient feedServiceClient =
googleAdsClient.getLatestVersion().createFeedServiceClient()) {
// Adds the feed.
MutateFeedsResponse response =
feedServiceClient.mutateFeeds(String.valueOf(customerId), ImmutableList.of(operation));
String feedResourceName = response.getResults(0).getResourceName();
// Displays the result.
System.out.printf("Feed with resource name '%s' was created.%n", feedResourceName);
return feedResourceName;
}
}
/**
* Retrieves details about a feed. The initial query retrieves the FeedAttributes, or columns, of
* the feed. Each FeedAttribute will also include the FeedAttributeId, which will be used in a
* subsequent step. The example then inserts a new key, value pair into a map for each
* FeedAttribute, which is the return value of the method. The keys are the placeholder types that
* the columns will be. The values are the FeedAttributes.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param feedResourceName the resource name of the feed.
* @return a Map containing the RealEstatePlaceholderField and FeedAttribute.
*/
// [START add_real_estate_feed]
private Map<RealEstatePlaceholderField, FeedAttribute> getFeed(
GoogleAdsClient googleAdsClient, long customerId, String feedResourceName) {
// Constructs the query.
String query =
"SELECT feed.attributes FROM feed WHERE feed.resource_name = '" + feedResourceName + "'";
// Constructs the request.
SearchGoogleAdsRequest request =
SearchGoogleAdsRequest.newBuilder()
.setCustomerId(String.valueOf(customerId))
.setPageSize(PAGE_SIZE)
.setQuery(query)
.build();
// Issues the search request.
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
// Gets the first result because we only need the single feed item we created previously.
GoogleAdsRow googleAdsRow = searchPagedResponse.getPage().getResponse().getResults(0);
// Gets the attributes list from the feed and creates a map with keys of each attribute and
// values of each corresponding ID.
List<FeedAttribute> feedAttributeList = googleAdsRow.getFeed().getAttributesList();
// Creates a map to return.
Map<RealEstatePlaceholderField, FeedAttribute> feedAttributes = new HashMap<>();
// Loops through each of the feed attributes and populates the map.
for (FeedAttribute feedAttribute : feedAttributeList) {
switch (feedAttribute.getName()) {
case "Listing ID":
feedAttributes.put(RealEstatePlaceholderField.LISTING_ID, feedAttribute);
break;
case "Listing Name":
feedAttributes.put(RealEstatePlaceholderField.LISTING_NAME, feedAttribute);
break;
case "Final URLs":
feedAttributes.put(RealEstatePlaceholderField.FINAL_URLS, feedAttribute);
break;
case "Image URL":
feedAttributes.put(RealEstatePlaceholderField.IMAGE_URL, feedAttribute);
break;
case "Contextual Keywords":
feedAttributes.put(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS, feedAttribute);
break;
// Optionally add other RealEstatePlaceholderFields.
default:
throw new Error("Invalid attribute name.");
}
}
return feedAttributes;
}
}
// [END add_real_estate_feed]
/**
* Creates a feed mapping for a given feed.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param feedAttributes the feed attributes.
* @param feedResourceName the feed resource name.
*/
private void createFeedMapping(
GoogleAdsClient googleAdsClient,
long customerId,
Map<RealEstatePlaceholderField, FeedAttribute> feedAttributes,
String feedResourceName) {
// Maps the FeedAttributeIds to the placeholder values. The FeedAttributeId is the ID of the
// FeedAttribute created in the createdFeed method. This can be thought of as the generic ID of
// the column of the new feed. The placeholder value specifies the type of column this is in
// the context of a real estate feed (e.g. a LISTING_ID or LISTING_NAME). The FeedMapping
// associates the feed column by ID to this type and controls how the feed attributes are
// presented in dynamic content.
// See
// https://developers.google.com/google-ads/api/reference/rpc/latest/RealEstatePlaceholderFieldEnum.RealEstatePlaceholderField
// for the full list of placeholder values.
AttributeFieldMapping listingIdMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.LISTING_ID).getId())
.setRealEstateField(RealEstatePlaceholderField.LISTING_ID)
.build();
AttributeFieldMapping listingNameMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.LISTING_NAME).getId())
.setRealEstateField(RealEstatePlaceholderField.LISTING_NAME)
.build();
AttributeFieldMapping finalUrlsMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.FINAL_URLS).getId())
.setRealEstateField(RealEstatePlaceholderField.FINAL_URLS)
.build();
AttributeFieldMapping imageUrlMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.IMAGE_URL).getId())
.setRealEstateField(RealEstatePlaceholderField.IMAGE_URL)
.build();
AttributeFieldMapping contextualKeywordsMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
feedAttributes.get(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS).getId())
.setRealEstateField(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS)
.build();
// Creates the feed mapping.
FeedMapping feedMapping =
FeedMapping.newBuilder()
.setPlaceholderType(PlaceholderType.DYNAMIC_REAL_ESTATE)
.setFeed(feedResourceName)
.addAttributeFieldMappings(listingIdMapping)
.addAttributeFieldMappings(listingNameMapping)
.addAttributeFieldMappings(finalUrlsMapping)
.addAttributeFieldMappings(imageUrlMapping)
.addAttributeFieldMappings(contextualKeywordsMapping)
.build();
// Creates the operation.
FeedMappingOperation operation =
FeedMappingOperation.newBuilder().setCreate(feedMapping).build();
// Adds the FeedMapping.
try (FeedMappingServiceClient feedMappingServiceClient =
googleAdsClient.getLatestVersion().createFeedMappingServiceClient()) {
MutateFeedMappingsResponse response =
feedMappingServiceClient.mutateFeedMappings(
Long.toString(customerId), ImmutableList.of(operation));
// Displays the results.
for (MutateFeedMappingResult result : response.getResultsList()) {
System.out.printf(
"Created feed mapping with resource name '%s'.%n", result.getResourceName());
}
}
}
/**
* Adds the new items to the feed.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param feedAttributes the feed attributes.
* @param feedResourceName the feed resource name.
*/
// [START add_real_estate_feed_1]
private void createFeedItems(
GoogleAdsClient googleAdsClient,
long customerId,
Map<RealEstatePlaceholderField, FeedAttribute> feedAttributes,
String feedResourceName) {
// Creates the listing ID feed attribute value.
FeedItemAttributeValue listingId =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.LISTING_ID).getId())
.setStringValue("ABC123DEF")
.build();
// Creates the listing name feed attribute value.
FeedItemAttributeValue listingName =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.LISTING_NAME).getId())
.setStringValue("Two bedroom with magnificent views")
.build();
// Creates the final URLs feed attribute value.
FeedItemAttributeValue finalUrls =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.FINAL_URLS).getId())
.addStringValues("http://www.example.com/listings/")
.build();
// Optionally insert additional attributes here, such as address, city, description, etc.
// Creates the image URL feed attribute value.
FeedItemAttributeValue imageUrl =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.IMAGE_URL).getId())
.setStringValue("http://www.example.com/listings/images?listing_id=ABC123DEF")
.build();
// Creates the contextual keywords feed attribute value.
FeedItemAttributeValue contextualKeywords =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
feedAttributes.get(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS).getId())
.addStringValues("beach community")
.addStringValues("ocean view")
.addStringValues("two bedroom")
.build();
// Creates the FeedItem, specifying the Feed ID and the attributes created above.
FeedItem feedItem =
FeedItem.newBuilder()
.setFeed(feedResourceName)
.addAttributeValues(listingId)
.addAttributeValues(listingName)
.addAttributeValues(finalUrls)
// Optionally include additional attributes.
.addAttributeValues(imageUrl)
.addAttributeValues(contextualKeywords)
.build();
// Creates an operation to add the FeedItem. You can include multiple feed items in a single
// operation.
FeedItemOperation operation = FeedItemOperation.newBuilder().setCreate(feedItem).build();
// Creates the feed item service client.
try (FeedItemServiceClient feedItemServiceClient =
googleAdsClient.getLatestVersion().createFeedItemServiceClient()) {
// Adds the feed items.
MutateFeedItemsResponse response =
feedItemServiceClient.mutateFeedItems(
Long.toString(customerId), ImmutableList.of(operation));
for (MutateFeedItemResult result : response.getResultsList()) {
System.out.printf("Created feed item with resource name '%s'.%n", result.getResourceName());
}
}
}
// [END add_real_estate_feed_1]
}