下面列出了com.google.protobuf.UInt64Value#com.google.protobuf.Int64Value 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Removes a feed item attribute value.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param feedAttributes a Map containing the FlightPlaceholderField and FeedAttribute.
* @param feedItemResourceName the resource name of the feedItem to be updated.
* @param flightPlaceholderField the placeholder type for the attribute to be removed.
*/
private FeedItem removeAttributeValueFromFeedItem(
GoogleAdsClient googleAdsClient,
long customerId,
Map<FlightPlaceholderField, FeedAttribute> feedAttributes,
String feedItemResourceName,
FlightPlaceholderField flightPlaceholderField) {
// Gets the ID of the FeedAttribute for the placeholder field and converts to an integer.
long attributeId = feedAttributes.get(flightPlaceholderField).getId().getValue();
// Retrieves the feed item and its associated attributes based on its resource name.
FeedItem feedItem = getFeedItem(googleAdsClient, customerId, feedItemResourceName);
// Creates the FeedItemAttributeValue that will be updated.
FeedItemAttributeValue feedItemAttributeValue =
FeedItemAttributeValue.newBuilder().setFeedAttributeId(Int64Value.of(attributeId)).build();
// Gets the index of the attribute value that will be removed.
int attributeIndex = getAttributeIndex(feedItem, feedItemAttributeValue);
// Returns the feed item with the removed FeedItemAttributeValue. Any FeedItemAttributeValues
// that are not included in the updated FeedItem will be removed from the FeedItem, which is
// why you must create the FeedItem from the existing FeedItem and set the field(s) that will
// be removed.
return feedItem.toBuilder().removeAttributeValues(attributeIndex).build();
}
/**
* Creates a new price offer with the specified parameters.
*
* @param header the headline for the price extension.
* @param description a detailed description line that may show on the price extension.
* @param priceInMicros the price to display, measured in micros (e.g. 1_000_000 micros = 1 USD).
* @param currencyCode the currency code representing the unit of currency.
* @param unit optionally set a unit describing the quantity obtained for the price.
* @param finalUrl the final URL to which a click on the price extension drives traffic.
* @param finalMobileUrl the final URL to which mobile clicks on the price extension drives
* traffic.
* @return a newly created price offer object.
*/
private PriceOffer createPriceOffer(
String header,
String description,
int priceInMicros,
String currencyCode,
PriceExtensionPriceUnit unit,
String finalUrl,
String finalMobileUrl) {
PriceOffer.Builder priceBuilder =
PriceOffer.newBuilder()
.setHeader(StringValue.of(header))
.setDescription(StringValue.of(description))
.addFinalUrls(StringValue.of(finalUrl))
.setPrice(
Money.newBuilder()
.setAmountMicros(Int64Value.of(priceInMicros))
.setCurrencyCode(StringValue.of(currencyCode)))
.setUnit(unit);
// Optional: Sets the final mobile URLs.
if (finalMobileUrl != null) {
priceBuilder.addFinalMobileUrls(StringValue.of(finalMobileUrl));
}
return priceBuilder.build();
}
@Test
public void anyInMaps() throws Exception {
TestAny.Builder testAny = TestAny.newBuilder();
testAny.putAnyMap("int32_wrapper", Any.pack(Int32Value.newBuilder().setValue(123).build()));
testAny.putAnyMap("int64_wrapper", Any.pack(Int64Value.newBuilder().setValue(456).build()));
testAny.putAnyMap("timestamp", Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")));
testAny.putAnyMap("duration", Any.pack(Durations.parse("12345.1s")));
testAny.putAnyMap("field_mask", Any.pack(FieldMaskUtil.fromString("foo.bar,baz")));
Value numberValue = Value.newBuilder().setNumberValue(1.125).build();
Struct.Builder struct = Struct.newBuilder();
struct.putFields("number", numberValue);
testAny.putAnyMap("struct", Any.pack(struct.build()));
Value nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();
testAny.putAnyMap(
"list_value",
Any.pack(ListValue.newBuilder().addValues(numberValue).addValues(nullValue).build()));
testAny.putAnyMap("number_value", Any.pack(numberValue));
testAny.putAnyMap("any_value_number", Any.pack(Any.pack(numberValue)));
testAny.putAnyMap("any_value_default", Any.pack(Any.getDefaultInstance()));
testAny.putAnyMap("default", Any.getDefaultInstance());
assertMatchesUpstream(testAny.build(), TestAllTypes.getDefaultInstance());
}
private static SummaryValue.Snapshot toSnapshotProto(
io.opencensus.metrics.export.Summary.Snapshot snapshot) {
SummaryValue.Snapshot.Builder builder = SummaryValue.Snapshot.newBuilder();
if (snapshot.getSum() != null) {
builder.setSum(DoubleValue.of(snapshot.getSum()));
}
if (snapshot.getCount() != null) {
builder.setCount(Int64Value.of(snapshot.getCount()));
}
for (io.opencensus.metrics.export.Summary.Snapshot.ValueAtPercentile valueAtPercentile :
snapshot.getValueAtPercentiles()) {
builder.addPercentileValues(
SummaryValue.Snapshot.ValueAtPercentile.newBuilder()
.setValue(valueAtPercentile.getValue())
.setPercentile(valueAtPercentile.getPercentile())
.build());
}
return builder.build();
}
@Test
public void writeUsesContentGenerationIfProvided() throws Exception {
AsyncWriteChannelOptions options = AsyncWriteChannelOptions.builder().build();
ObjectWriteConditions writeConditions =
new ObjectWriteConditions(Optional.of(1L), Optional.absent());
GoogleCloudStorageGrpcWriteChannel writeChannel =
newWriteChannel(options, writeConditions, Optional.absent());
ByteString data = ByteString.copyFromUtf8("test data");
writeChannel.initialize();
writeChannel.write(data.asReadOnlyByteBuffer());
writeChannel.close();
StartResumableWriteRequest.Builder expectedRequestBuilder = START_REQUEST.toBuilder();
expectedRequestBuilder
.getInsertObjectSpecBuilder()
.setIfGenerationMatch(Int64Value.newBuilder().setValue(1L));
verify(fakeService, times(1)).startResumableWrite(eq(expectedRequestBuilder.build()), any());
}
@Test
public void writeUsesMetaGenerationIfProvided() throws Exception {
AsyncWriteChannelOptions options = AsyncWriteChannelOptions.builder().build();
ObjectWriteConditions writeConditions =
new ObjectWriteConditions(Optional.absent(), Optional.of(1L));
GoogleCloudStorageGrpcWriteChannel writeChannel =
newWriteChannel(options, writeConditions, Optional.absent());
ByteString data = ByteString.copyFromUtf8("test data");
writeChannel.initialize();
writeChannel.write(data.asReadOnlyByteBuffer());
writeChannel.close();
StartResumableWriteRequest.Builder expectedRequestBuilder = START_REQUEST.toBuilder();
expectedRequestBuilder
.getInsertObjectSpecBuilder()
.setIfMetagenerationMatch(Int64Value.newBuilder().setValue(1L));
verify(fakeService, times(1)).startResumableWrite(eq(expectedRequestBuilder.build()), any());
}
@Test
public void itSetsFieldsWhenZeroInJson() throws IOException {
String json = camelCase().writeValueAsString(defaultPopulatedJsonNode(camelCase()));
HasWrappedPrimitives message = camelCase().readValue(json, HasWrappedPrimitives.class);
assertThat(message.hasDoubleWrapper()).isTrue();
assertThat(message.getDoubleWrapper()).isEqualTo(DoubleValue.getDefaultInstance());
assertThat(message.hasFloatWrapper()).isTrue();
assertThat(message.getFloatWrapper()).isEqualTo(FloatValue.getDefaultInstance());
assertThat(message.hasInt64Wrapper()).isTrue();
assertThat(message.getInt64Wrapper()).isEqualTo(Int64Value.getDefaultInstance());
assertThat(message.hasUint64Wrapper()).isTrue();
assertThat(message.getUint64Wrapper()).isEqualTo(UInt64Value.getDefaultInstance());
assertThat(message.hasInt32Wrapper()).isTrue();
assertThat(message.getInt32Wrapper()).isEqualTo(Int32Value.getDefaultInstance());
assertThat(message.hasUint32Wrapper()).isTrue();
assertThat(message.getUint32Wrapper()).isEqualTo(UInt32Value.getDefaultInstance());
assertThat(message.hasBoolWrapper()).isTrue();
assertThat(message.getBoolWrapper()).isEqualTo(BoolValue.getDefaultInstance());
assertThat(message.hasStringWrapper()).isTrue();
assertThat(message.getStringWrapper()).isEqualTo(StringValue.getDefaultInstance());
assertThat(message.hasBytesWrapper()).isTrue();
assertThat(message.getBytesWrapper()).isEqualTo(BytesValue.getDefaultInstance());
}
public ProtoDomain get() {
rootNamespace = root.path("namespace").asText();
protoMessageOf(root);
Map<String, FileDescriptorProto.Builder> fileMap = new HashMap<>();
messageMap.forEach(
(fullName, message) -> {
String packageName =
fullName.substring(0, fullName.length() - message.getName().length() - 1);
FileDescriptorProto.Builder fdp = fileMap.get(packageName);
if (fdp == null) {
fdp =
DescriptorProtos.FileDescriptorProto.newBuilder()
.setName(packageNameToFileName(packageName))
.setPackage(packageName)
.setSyntax("proto3");
fileMap.put(packageName, fdp);
}
fdp.addMessageType(message);
});
DescriptorProtos.FileDescriptorSet.Builder fds =
DescriptorProtos.FileDescriptorSet.newBuilder();
fileMap.forEach(
(name, fdp) -> {
Set<String> imports = importMap.get(fdp.getPackage());
if (imports != null) {
imports.forEach(im -> fdp.addDependency(im));
}
fds.addFile(fdp);
});
fds.addFile(Int64Value.getDescriptor().getFile().toProto());
return ProtoDomain.buildFrom(fds.build());
}
static SocketData extractSocketData(SocketStats socketStats) {
SocketData.Builder builder = SocketData.newBuilder();
if (socketStats.data != null) {
TransportStats s = socketStats.data;
builder
.setStreamsStarted(s.streamsStarted)
.setStreamsSucceeded(s.streamsSucceeded)
.setStreamsFailed(s.streamsFailed)
.setMessagesSent(s.messagesSent)
.setMessagesReceived(s.messagesReceived)
.setKeepAlivesSent(s.keepAlivesSent)
.setLastLocalStreamCreatedTimestamp(
Timestamps.fromNanos(s.lastLocalStreamCreatedTimeNanos))
.setLastRemoteStreamCreatedTimestamp(
Timestamps.fromNanos(s.lastRemoteStreamCreatedTimeNanos))
.setLastMessageSentTimestamp(
Timestamps.fromNanos(s.lastMessageSentTimeNanos))
.setLastMessageReceivedTimestamp(
Timestamps.fromNanos(s.lastMessageReceivedTimeNanos))
.setLocalFlowControlWindow(
Int64Value.of(s.localFlowControlWindow))
.setRemoteFlowControlWindow(
Int64Value.of(s.remoteFlowControlWindow));
}
builder.addAllOption(toSocketOptionsList(socketStats.socketOptions));
return builder.build();
}
/**
* Creates an experiment by issuing an asynchronous operation and immediately blocking to get the
* result.
*
* @param googleAdsClient the API client to use.
* @param customerId the customer ID to operate on.
* @param baseCampaignId the original campaign ID.
* @param draftId the draft campaign ID.
* @return a newly created experiment.
*/
private CreateCampaignExperimentMetadata createExperiment(
GoogleAdsClient googleAdsClient, long customerId, long baseCampaignId, long draftId) {
// Defines the experiment to be created.
CampaignExperiment experiment =
CampaignExperiment.newBuilder()
.setCampaignDraft(
StringValue.of(ResourceNames.campaignDraft(customerId, baseCampaignId, draftId)))
.setName(StringValue.of("Campaign experiment #" + System.currentTimeMillis()))
.setTrafficSplitPercent(Int64Value.of(50))
.setTrafficSplitType(CampaignExperimentTrafficSplitType.RANDOM_QUERY)
.build();
// Creates an API service client.
try (CampaignExperimentServiceClient campaignExperimentServiceClient =
googleAdsClient.getLatestVersion().createCampaignExperimentServiceClient()) {
// Issues the create request.
OperationFuture<Empty, CreateCampaignExperimentMetadata> campaignExperimentAsync =
campaignExperimentServiceClient.createCampaignExperimentAsync(
String.valueOf(customerId), experiment);
// Block on the long running (i.e. async) operation result.
try {
return campaignExperimentAsync.getMetadata().get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Create operation failed", e);
}
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
// Creates a ConversionAction.
ConversionAction conversionAction =
ConversionAction.newBuilder()
.setName(
StringValue.of("Earth to Mars Cruises Conversion #" + System.currentTimeMillis()))
.setCategory(ConversionActionCategory.DEFAULT)
.setType(ConversionActionType.WEBPAGE)
.setStatus(ConversionActionStatus.ENABLED)
.setViewThroughLookbackWindowDays(Int64Value.of(15L))
.setValueSettings(
ValueSettings.newBuilder()
.setDefaultValue(DoubleValue.of(23.41))
.setAlwaysUseDefaultValue(BoolValue.of(true))
.build())
.build();
// Creates the operation.
ConversionActionOperation operation =
ConversionActionOperation.newBuilder().setCreate(conversionAction).build();
try (ConversionActionServiceClient conversionActionServiceClient =
googleAdsClient.getLatestVersion().createConversionActionServiceClient()) {
MutateConversionActionsResponse response =
conversionActionServiceClient.mutateConversionActions(
Long.toString(customerId), Collections.singletonList(operation));
System.out.printf("Added %d conversion actions:%n", response.getResultsCount());
for (MutateConversionActionResult result : response.getResultsList()) {
System.out.printf(
"New conversion action added with resource name: '%s'%n", result.getResourceName());
}
}
}
/**
* Creates a Customer Match user list.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @return the resource name of the newly created user list.
*/
private String createCustomerMatchUserList(GoogleAdsClient googleAdsClient, long customerId) {
// Creates the new user list.
UserList userList =
UserList.newBuilder()
.setName(StringValue.of("Customer Match list #" + System.currentTimeMillis()))
.setDescription(
StringValue.of("A list of customers that originated from email addresses"))
// Customer Match user lists can use a membership life span of 10,000 to indicate
// unlimited; otherwise normal values apply.
// Sets the membership life span to 30 days.
.setMembershipLifeSpan(Int64Value.of(30))
// Sets the upload key type to indicate the type of identifier that will be used to
// add users to the list. This field is immutable and required for an ADD operation.
.setCrmBasedUserList(
CrmBasedUserListInfo.newBuilder()
.setUploadKeyType(CustomerMatchUploadKeyType.CONTACT_INFO))
.build();
// Creates the operation.
UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();
// Creates the service client.
try (UserListServiceClient userListServiceClient =
googleAdsClient.getLatestVersion().createUserListServiceClient()) {
// Adds the user list.
MutateUserListsResponse response =
userListServiceClient.mutateUserLists(
Long.toString(customerId), ImmutableList.of(operation));
// Prints the response.
System.out.printf(
"Created Customer Match user list with resource name: %s.%n",
response.getResults(0).getResourceName());
return response.getResults(0).getResourceName();
}
}
/**
* Creates a new criterion containing a biddable unit listing group node.
*
* @param customerId the client customer ID.
* @param adGroupId the ID of the ad group.
* @param parentAdGroupCriterionResourceName the resource name of the parent of this criterion.
* @param listingDimensionInfo the ListingDimensionInfo to be set for this listing group.
* @param cpcBidMicros the CPC bid for items in this listing group. This value should be specified
* in micros.
* @return the ad group criterion object that contains the biddable unit listing group node.
*/
private AdGroupCriterion createListingGroupUnitBiddable(
long customerId,
long adGroupId,
String parentAdGroupCriterionResourceName,
ListingDimensionInfo listingDimensionInfo,
long cpcBidMicros) {
String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
// Note: There are two approaches for creating new unit nodes:
// (1) Set the ad group resource name on the criterion (no temporary ID required).
// (2) Use a temporary ID to construct the criterion resource name and set it using
// setResourceName.
// In both cases you must set the parentAdGroupCriterionResourceName on the listing
// group for non-root nodes.
// This example demonstrates method (1).
AdGroupCriterion adGroupCriterion =
AdGroupCriterion.newBuilder()
// The ad group the listing group will be attached to.
.setAdGroup(StringValue.of(adGroupResourceName))
.setStatus(AdGroupCriterionStatus.ENABLED)
.setListingGroup(
ListingGroupInfo.newBuilder()
// Sets the type as a UNIT, which will allow the group to be biddable.
.setType(ListingGroupType.UNIT)
// Sets the ad group criterion resource name for the parent listing group.
// This can include a temporary ID if the parent criterion is not yet created.
// Use StringValue to convert from a String to a compatible argument type.
.setParentAdGroupCriterion(StringValue.of(parentAdGroupCriterionResourceName))
// Case values contain the listing dimension used for the node.
.setCaseValue(listingDimensionInfo)
.build())
// Sets the bid for this listing group unit.
// This will be used as the CPC bid for items that are included in this listing group
.setCpcBidMicros(Int64Value.of(cpcBidMicros))
.build();
return adGroupCriterion;
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ID of the ad group to update.
* @param bidMicroAmount the bid amount in micros to use for the ad group bid.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient, long customerId, long adGroupId, long bidMicroAmount) {
try (AdGroupServiceClient adGroupServiceClient =
googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
// Creates an ad group object with the proper resource name and any other changes.
AdGroup adGroup =
AdGroup.newBuilder()
.setResourceName(ResourceNames.adGroup(customerId, adGroupId))
.setCpcBidMicros(Int64Value.of(bidMicroAmount))
.setStatus(AdGroupStatus.PAUSED)
.build();
// Constructs an operation that will update the ad group, using the FieldMasks utility to
// derive the update mask. This mask tells the Google Ads API which attributes of the
// ad group you want to change.
AdGroupOperation operation =
AdGroupOperation.newBuilder()
.setUpdate(adGroup)
.setUpdateMask(FieldMasks.allSetFieldsOf(adGroup))
.build();
// Sends the operation in a mutate request.
MutateAdGroupsResponse response =
adGroupServiceClient.mutateAdGroups(
Long.toString(customerId), ImmutableList.of(operation));
// Prints the resource name of each updated object.
for (MutateAdGroupResult mutateAdGroupResult : response.getResultsList()) {
System.out.printf(
"Updated ad group with resourceName: '%s'.%n", mutateAdGroupResult.getResourceName());
}
}
}
private static StepScalingPolicy toStepScalingPolicy(StepScalingPolicyConfiguration stepScalingPolicyConfiguration) {
StepScalingPolicy.Builder stepScalingPolicyBuilder = StepScalingPolicy.newBuilder();
stepScalingPolicyConfiguration.getCoolDownSec().ifPresent(
coolDown ->
stepScalingPolicyBuilder.setCooldownSec(Int32Value.newBuilder().setValue(coolDown).build())
);
stepScalingPolicyConfiguration.getMetricAggregationType().ifPresent(
metricAggregationType ->
stepScalingPolicyBuilder.setMetricAggregationType(toMetricAggregationType(metricAggregationType))
);
stepScalingPolicyConfiguration.getAdjustmentType().ifPresent(
stepAdjustmentType ->
stepScalingPolicyBuilder.setAdjustmentType(toAdjustmentType(stepAdjustmentType))
);
stepScalingPolicyConfiguration.getMinAdjustmentMagnitude().ifPresent(
minAdjustmentMagnitude ->
stepScalingPolicyBuilder.setMinAdjustmentMagnitude(
Int64Value.newBuilder()
.setValue(minAdjustmentMagnitude)
.build())
);
stepScalingPolicyBuilder.addAllStepAdjustments(toStepAdjustmentsList(stepScalingPolicyConfiguration.getSteps()));
return stepScalingPolicyBuilder
.build();
}
private static SummaryValue toSummaryProto(io.opencensus.metrics.export.Summary summary) {
SummaryValue.Builder builder = SummaryValue.newBuilder();
if (summary.getSum() != null) {
builder.setSum(DoubleValue.of(summary.getSum()));
}
if (summary.getCount() != null) {
builder.setCount(Int64Value.of(summary.getCount()));
}
builder.setSnapshot(toSnapshotProto(summary.getSnapshot()));
return builder.build();
}
static SocketData extractSocketData(SocketStats socketStats) {
SocketData.Builder builder = SocketData.newBuilder();
if (socketStats.data != null) {
TransportStats s = socketStats.data;
builder
.setStreamsStarted(s.streamsStarted)
.setStreamsSucceeded(s.streamsSucceeded)
.setStreamsFailed(s.streamsFailed)
.setMessagesSent(s.messagesSent)
.setMessagesReceived(s.messagesReceived)
.setKeepAlivesSent(s.keepAlivesSent)
.setLastLocalStreamCreatedTimestamp(
Timestamps.fromNanos(s.lastLocalStreamCreatedTimeNanos))
.setLastRemoteStreamCreatedTimestamp(
Timestamps.fromNanos(s.lastRemoteStreamCreatedTimeNanos))
.setLastMessageSentTimestamp(
Timestamps.fromNanos(s.lastMessageSentTimeNanos))
.setLastMessageReceivedTimestamp(
Timestamps.fromNanos(s.lastMessageReceivedTimeNanos))
.setLocalFlowControlWindow(
Int64Value.of(s.localFlowControlWindow))
.setRemoteFlowControlWindow(
Int64Value.of(s.remoteFlowControlWindow));
}
builder.addAllOption(toSocketOptionsList(socketStats.socketOptions));
return builder.build();
}
private static HasWrappedPrimitives defaultPopulatedMessage() {
return HasWrappedPrimitives
.newBuilder()
.setDoubleWrapper(DoubleValue.getDefaultInstance())
.setFloatWrapper(FloatValue.getDefaultInstance())
.setInt64Wrapper(Int64Value.getDefaultInstance())
.setUint64Wrapper(UInt64Value.getDefaultInstance())
.setInt32Wrapper(Int32Value.getDefaultInstance())
.setUint32Wrapper(UInt32Value.getDefaultInstance())
.setBoolWrapper(BoolValue.getDefaultInstance())
.setStringWrapper(StringValue.getDefaultInstance())
.setBytesWrapper(BytesValue.getDefaultInstance())
.build();
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ad group ID.
* @param criterionId criterion ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient, long customerId, long adGroupId, long criterionId) {
String adGroupCriterionResourceName =
ResourceNames.adGroupCriterion(customerId, adGroupId, criterionId);
// Creates ad parameters.
// There can be a maximum of two AdParameters per ad group criterion.
// (One with parameter_index = 1 and one with parameter_index = 2.)
AdParameter adParameter1 =
AdParameter.newBuilder()
.setAdGroupCriterion(StringValue.of(adGroupCriterionResourceName))
// The unique index of this ad parameter. Must be either 1 or 2.
.setParameterIndex(Int64Value.of(1))
// String containing a numeric value to insert into the ad text.
// The following restrictions apply: (a) can use comma or period as a separator,
// with an optional period or comma (respectively) for fractional values,
// (b) can be prepended or appended with a currency code, (c) can use plus or minus,
// (d) can use '/' between two numbers.
.setInsertionText(StringValue.of("100"))
.build();
AdParameter adParameter2 =
AdParameter.newBuilder()
.setAdGroupCriterion(StringValue.of(adGroupCriterionResourceName))
.setParameterIndex(Int64Value.of(2))
.setInsertionText(StringValue.of("$40"))
.build();
List<AdParameterOperation> operations = new ArrayList<>();
operations.add(AdParameterOperation.newBuilder().setCreate(adParameter1).build());
operations.add(AdParameterOperation.newBuilder().setCreate(adParameter2).build());
try (AdParameterServiceClient adParameterServiceClient =
googleAdsClient.getLatestVersion().createAdParameterServiceClient()) {
MutateAdParametersResponse response =
adParameterServiceClient.mutateAdParameters(Long.toString(customerId), operations);
System.out.printf("Set %d ad params:%n", response.getResultsCount());
for (MutateAdParameterResult result : response.getResultsList()) {
System.out.println(result.getResourceName());
}
}
}
/**
* Creates a feed mapping for a given feed.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID.
* @param feedDetails a map of the names and IDs of feed attributes.
* @param feedResourceName the resource name of the feed.
*/
private static void createFeedMapping(
GoogleAdsClient googleAdsClient,
long customerId,
Map<String, Long> feedDetails,
String feedResourceName) {
// Maps the feed attribute IDs to the field ID constants.
AttributeFieldMapping urlFieldMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(Int64Value.of(feedDetails.get("Page URL")))
.setDsaPageFeedField(DsaPageFeedCriterionField.PAGE_URL)
.build();
AttributeFieldMapping labelFieldMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(Int64Value.of(feedDetails.get("Label")))
.setDsaPageFeedField(DsaPageFeedCriterionField.LABEL)
.build();
// Creates the feed mapping.
FeedMapping feedMapping =
FeedMapping.newBuilder()
.setCriterionType(FeedMappingCriterionType.DSA_PAGE_FEED)
.setFeed(StringValue.of(feedResourceName))
.addAllAttributeFieldMappings(ImmutableList.of(urlFieldMapping, labelFieldMapping))
.build();
// Creates the operation.
FeedMappingOperation operation =
FeedMappingOperation.newBuilder().setCreate(feedMapping).build();
// Creates the service client.
try (FeedMappingServiceClient feedMappingServiceClient =
googleAdsClient.getLatestVersion().createFeedMappingServiceClient()) {
// Adds the feed mapping.
MutateFeedMappingsResponse response =
feedMappingServiceClient.mutateFeedMappings(
Long.toString(customerId), ImmutableList.of(operation));
// Displays the results.
System.out.printf(
"Created feed maping with resource name '%s'.%n",
response.getResults(0).getResourceName());
}
}
/**
* Creates feed items for a given feed.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID.
* @param feedDetails a map of the names and IDs of feed attributes.
* @param feedResourceName the resource name of the feed.
* @param dsaPageUrlLabel the label for the DSA page URLs.
*/
private static void createFeedItems(
GoogleAdsClient googleAdsClient,
long customerId,
Map<String, Long> feedDetails,
String feedResourceName,
String dsaPageUrlLabel) {
List<String> urls =
ImmutableList.of(
"http://www.example.com/discounts/rental-cars",
"http://www.example.com/discounts/hotel-deals",
"http://www.example.com/discounts/flight-deals");
// Creates a value for the label attribute.
FeedItemAttributeValue labelAttributeValue =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(Int64Value.of(feedDetails.get("Label")))
.addAllStringValues(
ImmutableList.of(StringValue.newBuilder().setValue(dsaPageUrlLabel).build()))
.build();
// Creates one operation per URL.
List<FeedItemOperation> feedItemOperations = new ArrayList<>();
for (String url : urls) {
// Creates a url attribute.
FeedItemAttributeValue urlAttributeValue =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(Int64Value.of(feedDetails.get("Page URL")))
.addAllStringValues(ImmutableList.of(StringValue.newBuilder().setValue(url).build()))
.build();
// Creates a feed item.
FeedItem feedItem =
FeedItem.newBuilder()
.setFeed(StringValue.of(feedResourceName))
.addAllAttributeValues(ImmutableList.of(urlAttributeValue, labelAttributeValue))
.build();
// Creates an operation and adds it to the list of operations.
FeedItemOperation feedItemOperation =
FeedItemOperation.newBuilder().setCreate(feedItem).build();
feedItemOperations.add(feedItemOperation);
}
// Creates the service client.
try (FeedItemServiceClient feedItemServiceClient =
googleAdsClient.getLatestVersion().createFeedItemServiceClient()) {
// Adds the feed items.
MutateFeedItemsResponse response =
feedItemServiceClient.mutateFeedItems(Long.toString(customerId), feedItemOperations);
// Displays the results.
for (MutateFeedItemResult result : response.getResultsList()) {
System.out.printf("Created feed item with resource name '%s'.%n", result.getResourceName());
}
}
}
/**
* Creates an App campaign under the given customer ID.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID.
* @param budgetResourceName the resource name of the budget to associate with the campaign.
* @return the resource name of the newly created App campaign.
*/
private String createCampaign(
GoogleAdsClient googleAdsClient, long customerId, String budgetResourceName) {
// Creates a campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise App #" + System.currentTimeMillis()))
.setCampaignBudget(StringValue.of(budgetResourceName))
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
.setStatus(CampaignStatus.PAUSED)
// All App campaigns have an advertising_channel_type of
// MULTI_CHANNEL to reflect the fact that ads from these campaigns are
// eligible to appear on multiple channels.
.setAdvertisingChannelType(AdvertisingChannelType.MULTI_CHANNEL)
.setAdvertisingChannelSubType(AdvertisingChannelSubType.APP_CAMPAIGN)
// Sets the target CPA to $1 / app install.
//
// campaign_bidding_strategy is a 'oneof' message so setting target_cpa
// is mutually exclusive with other bidding strategies such as
// manual_cpc, commission, maximize_conversions, etc.
// See https://developers.google.com/google-ads/api/reference/rpc
// under current version / resources / Campaign.
.setTargetCpa(TargetCpa.newBuilder().setTargetCpaMicros(Int64Value.of(1000000)).build())
// Sets the App campaign settings.
.setAppCampaignSetting(
AppCampaignSetting.newBuilder()
.setAppId(StringValue.of("com.google.android.apps.adwords"))
.setAppStore(AppCampaignAppStore.GOOGLE_APP_STORE)
// Optional: Optimize this campaign for getting new users for your app.
.setBiddingStrategyGoalType(
AppCampaignBiddingStrategyGoalType.OPTIMIZE_INSTALLS_TARGET_INSTALL_COST)
.build())
// Optional fields.
.setStartDate(StringValue.of(new DateTime().plusDays(1).toString("yyyyMMdd")))
.setEndDate(StringValue.of(new DateTime().plusDays(365).toString("yyyyMMdd")))
// If you select the
// OPTIMIZE_IN_APP_CONVERSIONS_TARGET_INSTALL_COST goal type, then also
// specify your in-app conversion types so the Google Ads API can focus
// your campaign on people who are most likely to complete the
// corresponding in-app actions.
// .setSelectiveOptimization(SelectiveOptimization.newBuilder()
// .addConversionActions(StringValue.of("INSERT_CONVERSION_TYPE_ID_HERE"))
// .build())
.build();
// Creates a campaign operation.
CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();
// Create a campaign service client.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Adds the campaign.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
Long.toString(customerId), ImmutableList.of(operation));
// Prints and returns the campaign resource name.
String campaignResourceName = response.getResults(0).getResourceName();
System.out.printf("Created App campaign with resource name '%s'.%n", campaignResourceName);
return campaignResourceName;
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param conversionActionIds the IDs of the conversion actions for the basic user list.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient, long customerId, List<Long> conversionActionIds) {
List<UserListActionInfo> userListActionInfoList = new ArrayList<>();
for (long conversionActionId : conversionActionIds) {
// Creates the UserListActionInfo object for a given conversion action. This specifies the
// conversion action that, when triggered, will cause a user to be added to a UserList.
UserListActionInfo userListActionInfo =
UserListActionInfo.newBuilder()
.setConversionAction(
StringValue.of(ResourceNames.conversionAction(customerId, conversionActionId)))
.build();
userListActionInfoList.add(userListActionInfo);
}
// Creates a basic user list info object with all of the conversion actions.
BasicUserListInfo basicUserListInfo =
BasicUserListInfo.newBuilder().addAllActions(userListActionInfoList).build();
// Creates the basic user list.
UserList basicUserList =
UserList.newBuilder()
.setName(StringValue.of("Example BasicUserList #" + System.currentTimeMillis()))
.setDescription(
StringValue.of(
"A list of people who have triggered one or more conversion actions"))
.setMembershipLifeSpan(Int64Value.of(365))
.setBasicUserList(basicUserListInfo)
.setMembershipStatus(UserListMembershipStatus.OPEN)
.build();
// Creates the operation.
UserListOperation operation = UserListOperation.newBuilder().setCreate(basicUserList).build();
// Creates the service client.
try (UserListServiceClient userListServiceClient =
googleAdsClient.getLatestVersion().createUserListServiceClient()) {
// Adds the basic user list.
MutateUserListsResponse response =
userListServiceClient.mutateUserLists(
Long.toString(customerId), ImmutableList.of(operation));
// Prints the results.
System.out.printf(
"Created basic user list with resource name '%s'.%n",
response.getResults(0).getResourceName());
}
}
/**
* Creates a user list targeting users that have visited a given url.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @return the user list resource name.
*/
private String createUserList(GoogleAdsClient googleAdsClient, long customerId) {
// Creates a rule targeting any user that visited a url containing 'example.com'.
UserListRuleItemInfo rule =
UserListRuleItemInfo.newBuilder()
// Uses a built-in parameter to create a domain URL rule.
.setName(StringValue.of("url__"))
.setStringRuleItem(
UserListStringRuleItemInfo.newBuilder()
.setOperator(UserListStringRuleItemOperator.CONTAINS)
.setValue(StringValue.of("example.com"))
.build())
.build();
// Specifies that the user list targets visitors of a page based on the provided rule.
ExpressionRuleUserListInfo expressionRuleUserListInfo =
ExpressionRuleUserListInfo.newBuilder()
.setRule(
UserListRuleInfo.newBuilder()
.addRuleItemGroups(
UserListRuleItemGroupInfo.newBuilder().addRuleItems(rule).build())
.build())
.build();
// Defines a representation of a user list that is generated by a rule.
RuleBasedUserListInfo ruleBasedUserListInfo =
RuleBasedUserListInfo.newBuilder()
// Optional: To include past users in the user list, set the prepopulation_status to
// REQUESTED.
.setPrepopulationStatus(UserListPrepopulationStatus.REQUESTED)
.setExpressionRuleUserList(expressionRuleUserListInfo)
.build();
// Creates the user list.
UserList userList =
UserList.newBuilder()
.setName(StringValue.of("All visitors to example.com" + System.currentTimeMillis()))
.setDescription(StringValue.of("Any visitor to any page of example.com"))
.setMembershipStatus(UserListMembershipStatus.OPEN)
.setMembershipLifeSpan(Int64Value.of(365))
.setRuleBasedUserList(ruleBasedUserListInfo)
.build();
// Creates the operation.
UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();
// Creates the user list service client.
try (UserListServiceClient userListServiceClient =
googleAdsClient.getLatestVersion().createUserListServiceClient()) {
// Adds the user list.
MutateUserListsResponse response =
userListServiceClient.mutateUserLists(
Long.toString(customerId), ImmutableList.of(operation));
String userListResourceName = response.getResults(0).getResourceName();
// Prints the result.
System.out.printf("Created user list with resource name '%s'.%n", userListResourceName);
return userListResourceName;
}
}
/**
* 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/google.ads.googleads.v3.enums#google.ads.googleads.v3.enums.RealEstatePlaceholderFieldEnum.RealEstatePlaceholderField
// for the full list of placeholder values.
AttributeFieldMapping listingIdMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.LISTING_ID).getId().getValue()))
.setRealEstateField(RealEstatePlaceholderField.LISTING_ID)
.build();
AttributeFieldMapping listingNameMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.LISTING_NAME).getId().getValue()))
.setRealEstateField(RealEstatePlaceholderField.LISTING_NAME)
.build();
AttributeFieldMapping finalUrlsMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.FINAL_URLS).getId().getValue()))
.setRealEstateField(RealEstatePlaceholderField.FINAL_URLS)
.build();
AttributeFieldMapping imageUrlMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.IMAGE_URL).getId().getValue()))
.setRealEstateField(RealEstatePlaceholderField.IMAGE_URL)
.build();
AttributeFieldMapping contextualKeywordsMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes
.get(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS)
.getId()
.getValue()))
.setRealEstateField(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS)
.build();
// Creates the feed mapping.
FeedMapping feedMapping =
FeedMapping.newBuilder()
.setPlaceholderType(PlaceholderType.DYNAMIC_REAL_ESTATE)
.setFeed(StringValue.of(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.
*/
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(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.LISTING_ID).getId().getValue()))
.setStringValue(StringValue.of("ABC123DEF"))
.build();
// Creates the listing name feed attribute value.
FeedItemAttributeValue listingName =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.LISTING_NAME).getId().getValue()))
.setStringValue(StringValue.of("Two bedroom with magnificent views"))
.build();
// Creates the final URLs feed attribute value.
FeedItemAttributeValue finalUrls =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.FINAL_URLS).getId().getValue()))
.addStringValues(StringValue.of("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(
Int64Value.of(
feedAttributes.get(RealEstatePlaceholderField.IMAGE_URL).getId().getValue()))
.setStringValue(
StringValue.of("http://www.example.com/listings/images?listing_id=ABC123DEF"))
.build();
// Creates the contextual keywords feed attribute value.
FeedItemAttributeValue contextualKeywords =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes
.get(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS)
.getId()
.getValue()))
.addStringValues(StringValue.of("beach community"))
.addStringValues(StringValue.of("ocean view"))
.addStringValues(StringValue.of("two bedroom"))
.build();
// Creates the FeedItem, specifying the Feed ID and the attributes created above.
FeedItem feedItem =
FeedItem.newBuilder()
.setFeed(StringValue.of(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());
}
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
String urlString = "url__";
// Creates a rule targeting any user that visited a url that contains 'example.com/section1'.
UserListRuleItemInfo rule1 =
UserListRuleItemInfo.newBuilder()
// Uses a built-in parameter to create a domain URL rule.
.setName(StringValue.of(urlString))
.setStringRuleItem(
UserListStringRuleItemInfo.newBuilder()
.setOperator(UserListStringRuleItemOperator.CONTAINS)
.setValue(StringValue.of("example.com/section1"))
.build())
.build();
// Creates a rule targeting any user that visited a url that contains 'example.com/section2'.
UserListRuleItemInfo rule2 =
UserListRuleItemInfo.newBuilder()
// Uses a built-in parameter to create a domain URL rule.
.setName(StringValue.of(urlString))
.setStringRuleItem(
UserListStringRuleItemInfo.newBuilder()
.setOperator(UserListStringRuleItemOperator.CONTAINS)
.setValue(StringValue.of("example.com/section2"))
.build())
.build();
// Creates an ExpressionRuleUserListInfo object, or a boolean rule that defines this user list.
// The default rule_type for a UserListRuleInfo object is OR of ANDs (disjunctive normal form).
// That is, rule items will be ANDed together within rule item groups and the groups themselves
// will be ORed together.
ExpressionRuleUserListInfo expressionRuleUserListInfo =
ExpressionRuleUserListInfo.newBuilder()
.setRule(
UserListRuleInfo.newBuilder()
.addRuleItemGroups(
// Combine the two rule items into a UserListRuleItemGroupInfo object so
// Google Ads will AND their rules together. To instead OR the rules
// together, each rule should be placed in its own rule item group.
UserListRuleItemGroupInfo.newBuilder()
.addAllRuleItems(ImmutableList.of(rule1, rule2))
.build())
.build())
.build();
// Defines a representation of a user list that is generated by a rule.
RuleBasedUserListInfo ruleBasedUserListInfo =
RuleBasedUserListInfo.newBuilder()
// Optional: To include past users in the user list, set the prepopulation_status to
// REQUESTED.
.setPrepopulationStatus(UserListPrepopulationStatus.REQUESTED)
.setExpressionRuleUserList(expressionRuleUserListInfo)
.build();
// Creates a user list.
UserList userList =
UserList.newBuilder()
.setName(
StringValue.of(
"All visitors to example.com/section1 AND example.com/section2 #"
+ System.currentTimeMillis()))
.setDescription(
StringValue.of("Visitors of both example.com/section1 AND example.com/section2"))
.setMembershipStatus(UserListMembershipStatus.OPEN)
.setMembershipLifeSpan(Int64Value.of(365))
.setRuleBasedUserList(ruleBasedUserListInfo)
.build();
// Creates the operation.
UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();
// Creates the user list service client.
try (UserListServiceClient userListServiceClient =
googleAdsClient.getLatestVersion().createUserListServiceClient()) {
// Adds the user list.
MutateUserListsResponse response =
userListServiceClient.mutateUserLists(
Long.toString(customerId), ImmutableList.of(operation));
String userListResourceName = response.getResults(0).getResourceName();
// Prints the result.
System.out.printf("Created user list with resource name '%s'.%n", userListResourceName);
}
}
/**
* 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<FlightPlaceholderField, FeedAttribute> feedAttributes,
String feedResourceName) {
// Maps the FeedAttributeIds to the fieldId constants.
AttributeFieldMapping flightDescriptionMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes
.get(FlightPlaceholderField.FLIGHT_DESCRIPTION)
.getId()
.getValue()))
.setFlightField(FlightPlaceholderField.FLIGHT_DESCRIPTION)
.build();
AttributeFieldMapping destinationIdMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(FlightPlaceholderField.DESTINATION_ID).getId().getValue()))
.setFlightField(FlightPlaceholderField.DESTINATION_ID)
.build();
AttributeFieldMapping flightPriceMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(FlightPlaceholderField.FLIGHT_PRICE).getId().getValue()))
.setFlightField(FlightPlaceholderField.FLIGHT_PRICE)
.build();
AttributeFieldMapping flightSalePriceMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes
.get(FlightPlaceholderField.FLIGHT_SALE_PRICE)
.getId()
.getValue()))
.setFlightField(FlightPlaceholderField.FLIGHT_SALE_PRICE)
.build();
AttributeFieldMapping finalUrlsMapping =
AttributeFieldMapping.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(FlightPlaceholderField.FINAL_URLS).getId().getValue()))
.setFlightField(FlightPlaceholderField.FINAL_URLS)
.build();
// Creates the feed mapping.
FeedMapping feedMapping =
FeedMapping.newBuilder()
.setPlaceholderType(PlaceholderType.DYNAMIC_FLIGHT)
.setFeed(StringValue.of(feedResourceName))
.addAttributeFieldMappings(flightDescriptionMapping)
.addAttributeFieldMappings(destinationIdMapping)
.addAttributeFieldMappings(flightPriceMapping)
.addAttributeFieldMappings(flightSalePriceMapping)
.addAttributeFieldMappings(finalUrlsMapping)
.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 a new item 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.
*/
private void createFeedItem(
GoogleAdsClient googleAdsClient,
long customerId,
Map<FlightPlaceholderField, FeedAttribute> feedAttributes,
String feedResourceName) {
// Creates the flight description feed attribute value.
FeedItemAttributeValue flightDescription =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes
.get(FlightPlaceholderField.FLIGHT_DESCRIPTION)
.getId()
.getValue()))
.setStringValue(StringValue.of("Earth to Mars"))
.build();
// Creates the destination ID feed attribute value.
FeedItemAttributeValue destinationId =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(FlightPlaceholderField.DESTINATION_ID).getId().getValue()))
.setStringValue(StringValue.of("Mars"))
.build();
// Creates the flight price feed attribute value.
FeedItemAttributeValue flightPrice =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(FlightPlaceholderField.FLIGHT_PRICE).getId().getValue()))
.setStringValue(StringValue.of("499.99 USD"))
.build();
// Creates the flight sale price feed attribute value.
FeedItemAttributeValue flightSalePrice =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes
.get(FlightPlaceholderField.FLIGHT_SALE_PRICE)
.getId()
.getValue()))
.setStringValue(StringValue.of("299.99 USD"))
.build();
// Creates the final URLs feed attribute value.
FeedItemAttributeValue finalUrls =
FeedItemAttributeValue.newBuilder()
.setFeedAttributeId(
Int64Value.of(
feedAttributes.get(FlightPlaceholderField.FINAL_URLS).getId().getValue()))
.addStringValues(StringValue.of("http://www.example.com/flights/"))
.build();
// Creates the FeedItem, specifying the Feed ID and the attributes created above.
FeedItem feedItem =
FeedItem.newBuilder()
.setFeed(StringValue.of(feedResourceName))
.addAttributeValues(flightDescription)
.addAttributeValues(destinationId)
.addAttributeValues(flightPrice)
.addAttributeValues(flightSalePrice)
.addAttributeValues(finalUrls)
.build();
// Creates an operation to add the FeedItem.
FeedItemOperation operation = FeedItemOperation.newBuilder().setCreate(feedItem).build();
// Creates the feed item service client.
try (FeedItemServiceClient feedItemServiceClient =
googleAdsClient.getLatestVersion().createFeedItemServiceClient()) {
// Adds the feed item.
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());
}
}
}
/**
* Creates a campaign linked to a Merchant Center product feed.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param merchantCenterAccountId the Merchant Center account ID.
* @param campaignBudgetId the campaign budget ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String createCampaign(
GoogleAdsClient googleAdsClient,
long customerId,
long merchantCenterAccountId,
long campaignBudgetId) {
String budgetResourceName = ResourceNames.campaignBudget(customerId, campaignBudgetId);
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Shopping campaign #" + System.currentTimeMillis()))
// Dynamic remarketing campaigns are only available on the Google Display Network.
.setAdvertisingChannelType(AdvertisingChannelType.DISPLAY)
.setStatus(CampaignStatus.PAUSED)
.setCampaignBudget(StringValue.of(budgetResourceName))
.setManualCpc(ManualCpc.newBuilder().build())
// The settings for the shopping campaign.
// This connects the campaign to the merchant center account.
.setShoppingSetting(
ShoppingSetting.newBuilder()
.setCampaignPriority(Int32Value.of(0))
.setMerchantId(Int64Value.of(merchantCenterAccountId))
// Display Network campaigns do not support partition by country. The only
// supported value is "ZZ". This signals that products from all countries are
// available in the campaign. The actual products which serve are based on
// the products tagged in the user list entry.
.setSalesCountry(StringValue.of("ZZ"))
.setEnableLocal(BoolValue.of(true))
.build())
.build();
// Creates the campaign operation.
CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();
// Creates the campaign service client.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Adds the campaign.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
Long.toString(customerId), ImmutableList.of(operation));
String campaignResourceName = response.getResults(0).getResourceName();
System.out.printf("Created campaign with resource name '%s'.%n", campaignResourceName);
return campaignResourceName;
}
}