下面列出了com.google.protobuf.UInt64Value#com.google.protobuf.BoolValue 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Delete message by message Id
*
* @param messageId - subj
* @return - future with message UUID which has been deleted
*/
public CompletableFuture<UUID> delete(@Nonnull UUID messageId) {
DeletedMessage deletedMessage = DeletedMessage.newBuilder()
.setIsLocal(BoolValue.newBuilder().setValue(false).build())
.build();
MessageContent messageContent = MessageContent.newBuilder()
.setDeletedMessage(deletedMessage)
.build();
RequestUpdateMessage request = RequestUpdateMessage.newBuilder()
.setMid(UUIDUtils.convertToApi(messageId))
.setLastEditedAt(Instant.now().toEpochMilli())
.setUpdatedMessage(messageContent)
.build();
return internalBot.withToken(
MessagingGrpc.newFutureStub(channel).withDeadlineAfter(2, TimeUnit.MINUTES),
stub -> stub.updateMessage(request))
.thenApply(res -> UUIDUtils.convert(res.getMid()));
}
@Test
@SuppressWarnings("all")
public void addOfflineUserDataJobOperationsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockOfflineUserDataJobService.addException(exception);
try {
String formattedResourceName =
OfflineUserDataJobServiceClient.formatOfflineUserDataJobName(
"[CUSTOMER]", "[OFFLINE_USER_DATA_JOB]");
BoolValue enablePartialFailure = BoolValue.newBuilder().build();
List<OfflineUserDataJobOperation> operations = new ArrayList<>();
client.addOfflineUserDataJobOperations(
formattedResourceName, enablePartialFailure, operations);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Test
public void populateRoutesInVirtualHost_routeWithCaseInsensitiveMatch() {
VirtualHost virtualHost =
VirtualHost.newBuilder()
.setName("virtualhost00.googleapis.com") // don't care
.addDomains(TARGET_AUTHORITY)
.addRoutes(
Route.newBuilder()
.setRoute(RouteAction.newBuilder().setCluster("cluster.googleapis.com"))
.setMatch(
RouteMatch.newBuilder()
.setPrefix("")
.setCaseSensitive(BoolValue.newBuilder().setValue(false))))
.build();
thrown.expect(XdsClientImpl.InvalidProtoDataException.class);
XdsClientImpl.populateRoutesInVirtualHost(virtualHost);
}
@Test
public void populateRoutesInVirtualHost_lastRouteIsNotDefaultRoute() {
VirtualHost virtualHost =
VirtualHost.newBuilder()
.setName("virtualhost00.googleapis.com") // don't care
.addDomains(TARGET_AUTHORITY)
.addRoutes(
Route.newBuilder()
.setRoute(RouteAction.newBuilder().setCluster("cluster.googleapis.com"))
.setMatch(
RouteMatch.newBuilder()
.setPrefix("/service/method")
.setCaseSensitive(BoolValue.newBuilder().setValue(true))))
.build();
thrown.expect(XdsClientImpl.InvalidProtoDataException.class);
XdsClientImpl.populateRoutesInVirtualHost(virtualHost);
}
@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());
}
@Override
public void probe(csi.v1.Csi.ProbeRequest request,
StreamObserver<csi.v1.Csi.ProbeResponse> responseObserver) {
ProbeResponse response = ProbeResponse.newBuilder()
.setReady(BoolValue.of(true))
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
@Test
@SuppressWarnings("all")
public void addOfflineUserDataJobOperationsTest() {
AddOfflineUserDataJobOperationsResponse expectedResponse =
AddOfflineUserDataJobOperationsResponse.newBuilder().build();
mockOfflineUserDataJobService.addResponse(expectedResponse);
String formattedResourceName =
OfflineUserDataJobServiceClient.formatOfflineUserDataJobName(
"[CUSTOMER]", "[OFFLINE_USER_DATA_JOB]");
BoolValue enablePartialFailure = BoolValue.newBuilder().build();
List<OfflineUserDataJobOperation> operations = new ArrayList<>();
AddOfflineUserDataJobOperationsResponse actualResponse =
client.addOfflineUserDataJobOperations(
formattedResourceName, enablePartialFailure, operations);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockOfflineUserDataJobService.getRequests();
Assert.assertEquals(1, actualRequests.size());
AddOfflineUserDataJobOperationsRequest actualRequest =
(AddOfflineUserDataJobOperationsRequest) actualRequests.get(0);
Assert.assertEquals(formattedResourceName, actualRequest.getResourceName());
Assert.assertEquals(enablePartialFailure, actualRequest.getEnablePartialFailure());
Assert.assertEquals(operations, actualRequest.getOperationsList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
/**
* Builds new campaign criterion operations for creating negative campaign criteria (as keywords).
*
* @param campaignOperations the campaign operations to be used to create campaign criteria.
* @return the campaign criterion operations.
*/
private List<CampaignCriterionOperation> buildCampaignCriterionOperations(
List<CampaignOperation> campaignOperations) {
List<CampaignCriterionOperation> operations = new ArrayList<>();
for (CampaignOperation campaignOperation : campaignOperations) {
// Creates a campaign criterion.
CampaignCriterion campaignCriterion =
CampaignCriterion.newBuilder()
.setKeyword(
KeywordInfo.newBuilder()
.setText(StringValue.of("venus"))
.setMatchType(KeywordMatchType.BROAD)
.build())
// Sets the campaign criterion as a negative criterion.
.setNegative(BoolValue.of(Boolean.TRUE))
.setCampaign(StringValue.of(campaignOperation.getCreate().getResourceName()))
.build();
// Creates a campaign criterion operation and adds it to the operations list.
CampaignCriterionOperation op =
CampaignCriterionOperation.newBuilder().setCreate(campaignCriterion).build();
operations.add(op);
}
return operations;
}
/**
* Create a Campaign with a portfolio bidding strategy.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param biddingStrategyResourceName the bidding strategy resource name to use
* @param campaignBudgetResourceName the shared budget resource name to use
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String createCampaignWithBiddingStrategy(
GoogleAdsClient googleAdsClient,
long customerId,
String biddingStrategyResourceName,
String campaignBudgetResourceName) {
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Creates the campaign.
NetworkSettings networkSettings =
NetworkSettings.newBuilder()
.setTargetGoogleSearch(BoolValue.of(true))
.setTargetSearchNetwork(BoolValue.of(true))
.setTargetContentNetwork(BoolValue.of(true))
.build();
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
.setStatus(CampaignStatus.PAUSED)
.setCampaignBudget(StringValue.of(campaignBudgetResourceName))
.setBiddingStrategy(StringValue.of(biddingStrategyResourceName))
.setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
.setNetworkSettings(networkSettings)
.build();
// Constructs an operation that will create a campaign.
CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();
// Sends the operation in a mutate request.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
Long.toString(customerId), Lists.newArrayList(operation));
MutateCampaignResult mutateCampaignResult = response.getResults(0);
// Prints the resource name of the created object.
System.out.printf(
"Created campaign with resource name: '%s'.%n", mutateCampaignResult.getResourceName());
return mutateCampaignResult.getResourceName();
}
}
/**
* Creates a negative keyword as a campaign targeting criterion.
*
* @param keywordText the keyword text to exclude.
* @param campaignResourceName the campaign where the keyword will be excluded.
* @return a campaign criterion object with the negative keyword targeting.
*/
private static CampaignCriterion buildNegativeKeywordCriterion(
String keywordText, String campaignResourceName) {
return CampaignCriterion.newBuilder()
.setCampaign(StringValue.of(campaignResourceName))
.setNegative(BoolValue.of(true))
.setKeyword(
KeywordInfo.newBuilder()
.setMatchType(KeywordMatchType.BROAD)
.setText(StringValue.of(keywordText))
.build())
.build();
}
/**
* 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());
}
}
}
private void runExample(GoogleAdsClient googleAdsClient, Long managerId) {
// Formats the current date/time to use as a timestamp in the new customer description.
String dateTime = ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
// Initializes a Customer object to be created.
Customer customer =
Customer.newBuilder()
.setDescriptiveName(
StringValue.of("Account created with CustomerService on '" + dateTime + "'"))
.setCurrencyCode(StringValue.of("USD"))
.setTimeZone(StringValue.of("America/New_York"))
// Optional: Sets additional attributes of the customer.
.setTrackingUrlTemplate(StringValue.of("{lpurl}?device={device}"))
.setFinalUrlSuffix(
StringValue.of("keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}"))
.setHasPartnersBadge(BoolValue.of(false))
.build();
// Sends the request to create the customer.
try (CustomerServiceClient client =
googleAdsClient.getLatestVersion().createCustomerServiceClient()) {
CreateCustomerClientResponse response =
client.createCustomerClient(managerId.toString(), customer);
System.out.printf(
"Created a customer with resource name '%s' under the manager account with"
+ " customer ID '%d'.%n",
response.getResourceName(), managerId);
}
}
private static AlarmConfiguration toAlarmConfiguration(com.netflix.titus.api.appscale.model.AlarmConfiguration alarmConfiguration) {
AlarmConfiguration.Builder alarmConfigBuilder = AlarmConfiguration.newBuilder();
alarmConfiguration.getActionsEnabled().ifPresent(
actionsEnabled ->
alarmConfigBuilder.setActionsEnabled(BoolValue.newBuilder()
.setValue(actionsEnabled)
.build())
);
AlarmConfiguration.ComparisonOperator comparisonOperator =
toComparisonOperator(alarmConfiguration.getComparisonOperator());
AlarmConfiguration.Statistic statistic =
toStatistic(alarmConfiguration.getStatistic());
return AlarmConfiguration.newBuilder()
.setComparisonOperator(comparisonOperator)
.setEvaluationPeriods(Int32Value.newBuilder()
.setValue(alarmConfiguration.getEvaluationPeriods())
.build())
.setPeriodSec(Int32Value.newBuilder()
.setValue(alarmConfiguration.getPeriodSec())
.build())
.setThreshold(DoubleValue.newBuilder()
.setValue(alarmConfiguration.getThreshold())
.build())
.setMetricNamespace(alarmConfiguration.getMetricNamespace())
.setMetricName(alarmConfiguration.getMetricName())
.setStatistic(statistic)
.build();
}
private static TargetTrackingPolicyDescriptor toTargetTrackingPolicyDescriptor(TargetTrackingPolicy targetTrackingPolicy) {
TargetTrackingPolicyDescriptor.Builder targetTrackingPolicyDescBuilder = TargetTrackingPolicyDescriptor.newBuilder();
targetTrackingPolicyDescBuilder.setTargetValue(DoubleValue.newBuilder()
.setValue(targetTrackingPolicy.getTargetValue())
.build());
targetTrackingPolicy.getScaleOutCooldownSec().ifPresent(
scaleOutCoolDownSec -> targetTrackingPolicyDescBuilder.setScaleOutCooldownSec(
Int32Value.newBuilder().setValue(scaleOutCoolDownSec).build())
);
targetTrackingPolicy.getScaleInCooldownSec().ifPresent(
scaleInCoolDownSec -> targetTrackingPolicyDescBuilder.setScaleInCooldownSec(
Int32Value.newBuilder().setValue(scaleInCoolDownSec).build())
);
targetTrackingPolicy.getDisableScaleIn().ifPresent(
disableScaleIn -> targetTrackingPolicyDescBuilder.setDisableScaleIn(
BoolValue.newBuilder().setValue(disableScaleIn).build())
);
targetTrackingPolicy.getPredefinedMetricSpecification().ifPresent(
predefinedMetricSpecification ->
targetTrackingPolicyDescBuilder.setPredefinedMetricSpecification(
toPredefinedMetricSpecification(targetTrackingPolicy.getPredefinedMetricSpecification().get()))
);
targetTrackingPolicy.getCustomizedMetricSpecification().ifPresent(
customizedMetricSpecification ->
targetTrackingPolicyDescBuilder.setCustomizedMetricSpecification(
toCustomizedMetricSpecification(targetTrackingPolicy.getCustomizedMetricSpecification().get()))
);
return targetTrackingPolicyDescBuilder.build();
}
public static ScalingPolicy generateTargetPolicy() {
CustomizedMetricSpecification customizedMetricSpec = CustomizedMetricSpecification.newBuilder()
.addDimensions(MetricDimension.newBuilder()
.setName("testName")
.setValue("testValue")
.build())
.setMetricName("testMetric")
.setNamespace("NFLX/EPIC")
.setStatistic(AlarmConfiguration.Statistic.Sum)
.setMetricName("peanuts")
.build();
TargetTrackingPolicyDescriptor targetTrackingPolicyDescriptor = TargetTrackingPolicyDescriptor.newBuilder()
.setTargetValue(DoubleValue.newBuilder()
.setValue(ThreadLocalRandom.current().nextDouble())
.build())
.setScaleInCooldownSec(Int32Value.newBuilder()
.setValue(ThreadLocalRandom.current().nextInt())
.build())
.setScaleOutCooldownSec(Int32Value.newBuilder()
.setValue(ThreadLocalRandom.current().nextInt())
.build())
.setDisableScaleIn(BoolValue.newBuilder()
.setValue(false)
.build())
.setCustomizedMetricSpecification(customizedMetricSpec)
.build();
return ScalingPolicy.newBuilder().setTargetPolicyDescriptor(targetTrackingPolicyDescriptor).build();
}
/**
* Creates additional types (Value, Struct and ListValue) to be added to the Service config.
* TODO (guptasu): Fix this hack. Find a better way to add the predefined types.
* TODO (guptasu): Add them only when required and not in all cases.
*/
static Iterable<Type> createAdditionalServiceTypes() {
Map<String, DescriptorProto> additionalMessages = Maps.newHashMap();
additionalMessages.put(Struct.getDescriptor().getFullName(),
Struct.getDescriptor().toProto());
additionalMessages.put(Value.getDescriptor().getFullName(),
Value.getDescriptor().toProto());
additionalMessages.put(ListValue.getDescriptor().getFullName(),
ListValue.getDescriptor().toProto());
additionalMessages.put(Empty.getDescriptor().getFullName(),
Empty.getDescriptor().toProto());
additionalMessages.put(Int32Value.getDescriptor().getFullName(),
Int32Value.getDescriptor().toProto());
additionalMessages.put(DoubleValue.getDescriptor().getFullName(),
DoubleValue.getDescriptor().toProto());
additionalMessages.put(BoolValue.getDescriptor().getFullName(),
BoolValue.getDescriptor().toProto());
additionalMessages.put(StringValue.getDescriptor().getFullName(),
StringValue.getDescriptor().toProto());
for (Descriptor descriptor : Struct.getDescriptor().getNestedTypes()) {
additionalMessages.put(descriptor.getFullName(), descriptor.toProto());
}
// TODO (guptasu): Remove this hard coding. Without this, creation of Model from Service throws.
// Needs investigation.
String fileName = "struct.proto";
List<Type> additionalTypes = Lists.newArrayList();
for (String typeName : additionalMessages.keySet()) {
additionalTypes.add(TypesBuilderFromDescriptor.createType(typeName,
additionalMessages.get(typeName), fileName));
}
return additionalTypes;
}
private static void enablePolicies(String projectId, String filter, boolean enable)
throws IOException {
try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
ListAlertPoliciesPagedResponse response =
client.listAlertPolicies(
ListAlertPoliciesRequest.newBuilder()
.setName(ProjectName.of(projectId).toString())
.setFilter(filter)
.build());
for (AlertPolicy policy : response.iterateAll()) {
if (policy.getEnabled().getValue() == enable) {
System.out.println(
String.format(
"Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
continue;
}
AlertPolicy updatedPolicy =
AlertPolicy.newBuilder()
.setName(policy.getName())
.setEnabled(BoolValue.newBuilder().setValue(enable))
.build();
AlertPolicy result =
client.updateAlertPolicy(
FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
System.out.println(
String.format(
"%s %s",
result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled"));
}
}
}
/** Helper method to build DownstreamTlsContext for multiple test classes. */
static DownstreamTlsContext buildDownstreamTlsContext(
CommonTlsContext commonTlsContext, boolean requireClientCert) {
DownstreamTlsContext downstreamTlsContext =
DownstreamTlsContext.newBuilder()
.setCommonTlsContext(commonTlsContext)
.setRequireClientCertificate(BoolValue.of(requireClientCert))
.build();
return downstreamTlsContext;
}
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();
}
public AccountUpdateTransaction setReceiverSignatureRequired(boolean receiverSignatureRequired) {
builder.setReceiverSigRequiredWrapper(BoolValue.of(receiverSignatureRequired));
return this;
}
/**
* Creates a campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param budget the budget for the campaign.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private Campaign createCampaign(
GoogleAdsClient googleAdsClient, long customerId, CampaignBudget budget) {
String budgetResourceName = ResourceNames.campaignBudget(customerId, budget.getId().getValue());
// Configures the campaign network options
NetworkSettings networkSettings =
NetworkSettings.newBuilder()
.setTargetGoogleSearch(BoolValue.of(true))
.setTargetSearchNetwork(BoolValue.of(true))
.setTargetContentNetwork(BoolValue.of(false))
.setTargetPartnerSearchNetwork(BoolValue.of(false))
.build();
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
.setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
// 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)
// Sets the bidding strategy and budget.
.setManualCpc(ManualCpc.newBuilder().build())
.setCampaignBudget(StringValue.of(budgetResourceName))
// Adds the networkSettings configured above.
.setNetworkSettings(networkSettings)
// Optional: sets the start & end dates.
.setStartDate(StringValue.of(new DateTime().plusDays(1).toString("yyyyMMdd")))
.setEndDate(StringValue.of(new DateTime().plusDays(30).toString("yyyyMMdd")))
.build();
// Creates the operation.
CampaignOperation op = CampaignOperation.newBuilder().setCreate(campaign).build();
// Gets the Campaign service.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Adds the campaign.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(Long.toString(customerId), ImmutableList.of(op));
String campaignResourceName = response.getResults(0).getResourceName();
// Retrieves the campaign.
Campaign newCampaign = getCampaign(googleAdsClient, customerId, campaignResourceName);
// Displays the results.
System.out.printf(
"Campaign with ID %s and name '%s' was created.%n",
newCampaign.getId().getValue(), newCampaign.getName().getValue());
return newCampaign;
}
}
/**
* Creates a campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param budget the budget for the campaign.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private Campaign createCampaign(
GoogleAdsClient googleAdsClient, long customerId, CampaignBudget budget) {
String budgetResourceName = ResourceNames.campaignBudget(customerId, budget.getId().getValue());
// Configures the campaign network options
NetworkSettings networkSettings =
NetworkSettings.newBuilder()
.setTargetGoogleSearch(BoolValue.of(true))
.setTargetSearchNetwork(BoolValue.of(true))
.setTargetContentNetwork(BoolValue.of(false))
.setTargetPartnerSearchNetwork(BoolValue.of(false))
.build();
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
.setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
// 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)
// Sets the bidding strategy and budget.
.setManualCpc(ManualCpc.newBuilder().build())
.setCampaignBudget(StringValue.of(budgetResourceName))
// Adds the networkSettings configured above.
.setNetworkSettings(networkSettings)
// Optional: sets the start & end dates.
.setStartDate(StringValue.of(new DateTime().plusDays(1).toString("yyyyMMdd")))
.setEndDate(StringValue.of(new DateTime().plusDays(30).toString("yyyyMMdd")))
.build();
// Creates the operation.
CampaignOperation op = CampaignOperation.newBuilder().setCreate(campaign).build();
// Gets the Campaign service.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Adds the campaign.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(Long.toString(customerId), ImmutableList.of(op));
String campaignResourceName = response.getResults(0).getResourceName();
// Retrieves the campaign.
Campaign newCampaign = getCampaign(googleAdsClient, customerId, campaignResourceName);
// Displays the results.
System.out.printf(
"Campaign with ID %s and name '%s' was created.%n",
newCampaign.getId().getValue(), newCampaign.getName().getValue());
return newCampaign;
}
}
/**
* Creates a campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param budget the budget for the campaign.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private Campaign createCampaign(
GoogleAdsClient googleAdsClient, long customerId, CampaignBudget budget) {
String budgetResourceName = ResourceNames.campaignBudget(customerId, budget.getId().getValue());
// Configures the campaign network options
NetworkSettings networkSettings =
NetworkSettings.newBuilder()
.setTargetGoogleSearch(BoolValue.of(true))
.setTargetSearchNetwork(BoolValue.of(true))
.setTargetContentNetwork(BoolValue.of(false))
.setTargetPartnerSearchNetwork(BoolValue.of(false))
.build();
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
.setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
// 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)
// Sets the bidding strategy and budget.
.setManualCpc(ManualCpc.newBuilder().build())
.setCampaignBudget(StringValue.of(budgetResourceName))
// Adds the networkSettings configured above.
.setNetworkSettings(networkSettings)
// Optional: sets the start & end dates.
.setStartDate(StringValue.of(new DateTime().plusDays(1).toString("yyyyMMdd")))
.setEndDate(StringValue.of(new DateTime().plusDays(30).toString("yyyyMMdd")))
.build();
// Creates the operation.
CampaignOperation op = CampaignOperation.newBuilder().setCreate(campaign).build();
// Gets the Campaign service.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Adds the campaign.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(Long.toString(customerId), ImmutableList.of(op));
String campaignResourceName = response.getResults(0).getResourceName();
// Retrieves the campaign.
Campaign newCampaign = getCampaign(googleAdsClient, customerId, campaignResourceName);
// Displays the results.
System.out.printf(
"Campaign with ID %s and name '%s' was created.%n",
newCampaign.getId().getValue(), newCampaign.getName().getValue());
return newCampaign;
}
}
/**
* Creates a campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param budget the budget for the campaign.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private Campaign createCampaign(
GoogleAdsClient googleAdsClient, long customerId, CampaignBudget budget) {
String budgetResourceName = ResourceNames.campaignBudget(customerId, budget.getId().getValue());
// Configures the campaign network options
NetworkSettings networkSettings =
NetworkSettings.newBuilder()
.setTargetGoogleSearch(BoolValue.of(true))
.setTargetSearchNetwork(BoolValue.of(true))
.setTargetContentNetwork(BoolValue.of(false))
.setTargetPartnerSearchNetwork(BoolValue.of(false))
.build();
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
.setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
// 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)
// Sets the bidding strategy and budget.
.setManualCpc(ManualCpc.newBuilder().build())
.setCampaignBudget(StringValue.of(budgetResourceName))
// Adds the networkSettings configured above.
.setNetworkSettings(networkSettings)
// Optional: sets the start & end dates.
.setStartDate(StringValue.of(new DateTime().plusDays(1).toString("yyyyMMdd")))
.setEndDate(StringValue.of(new DateTime().plusDays(30).toString("yyyyMMdd")))
.build();
// Creates the operation.
CampaignOperation op = CampaignOperation.newBuilder().setCreate(campaign).build();
// Gets the Campaign service.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Adds the campaign.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(Long.toString(customerId), ImmutableList.of(op));
String campaignResourceName = response.getResults(0).getResourceName();
// Retrieves the campaign.
Campaign newCampaign = getCampaign(googleAdsClient, customerId, campaignResourceName);
// Displays the results.
System.out.printf(
"Campaign with ID %s and name '%s' was created.%n",
newCampaign.getId().getValue(), newCampaign.getName().getValue());
return newCampaign;
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID in which to create criterion.
* @param adGroupId the ad group ID in which to create criterion.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
List<AdGroupCriterionOperation> operations = new ArrayList<>();
// Creates a gender demographic criterion.
AdGroupCriterion genderAdGroupCriterionOperation =
AdGroupCriterion.newBuilder()
.setAdGroup(StringValue.of(adGroupResourceName))
.setGender(GenderInfo.newBuilder().setType(GenderType.MALE).build())
.build();
// Creates an age range negative demographic criterion.
AdGroupCriterion ageRangeNegativeAdGroupCriterionOperation =
AdGroupCriterion.newBuilder()
.setAdGroup(StringValue.of(adGroupResourceName))
.setNegative(BoolValue.of(true))
.setAgeRange(AgeRangeInfo.newBuilder().setType(AgeRangeType.AGE_RANGE_18_24).build())
.build();
// Creates and adds the operations.
operations.add(
AdGroupCriterionOperation.newBuilder().setCreate(genderAdGroupCriterionOperation).build());
operations.add(
AdGroupCriterionOperation.newBuilder()
.setCreate(ageRangeNegativeAdGroupCriterionOperation)
.build());
// Creates the service client.
try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
// Issues the mutate request.
MutateAdGroupCriteriaResponse response =
adGroupCriterionServiceClient.mutateAdGroupCriteria(
Long.toString(customerId), operations);
// Prints the results.
System.out.printf("Added %d ad group criteria:%n", response.getResultsCount());
for (MutateAdGroupCriterionResult result : response.getResultsList()) {
System.out.println(result.getResourceName());
}
}
}
/**
* 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.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
// Creates an empty TargetingSetting object.
TargetingSetting.Builder targetingSettingBuilder = TargetingSetting.newBuilder();
// Creates the Google Ads service client.
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
// Creates a search request that retrieves the targeting settings from a given ad group.
String searchQuery =
"SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions "
+ "FROM ad_group "
+ "WHERE ad_group.id = "
+ adGroupId;
// Creates a request that will retrieve all ad groups using pages of the specified page size.
SearchGoogleAdsRequest request =
SearchGoogleAdsRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setPageSize(PAGE_SIZE)
.setQuery(searchQuery)
.build();
// Issues the search request.
SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
// Iterates over all rows in all pages and prints the requested field values for the ad group
// in each row.
// Creates a flag that specifies whether or not we should update the targeting setting. We
// should only do this if we find an AUDIENCE target restriction with bid_only set to false.
boolean shouldUpdateTargetingSetting = false;
for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
AdGroup adGroup = googleAdsRow.getAdGroup();
// Prints the results.
System.out.printf(
"Ad group with ID %d and name '%s' was found with the following targeting"
+ " restrictions.%n",
adGroup.getId().getValue(), adGroup.getName().getValue());
List<TargetRestriction> targetRestrictions =
adGroup.getTargetingSetting().getTargetRestrictionsList();
// Loops through and prints each of the target restrictions.
// Reconstructs the TargetingSetting object with the updated audience target restriction
// because Google will overwrite the entire targeting_setting field of the ad group when
// the field mask includes targeting_setting in an update operation.
for (TargetRestriction targetRestriction : targetRestrictions) {
TargetingDimension targetingDimension = targetRestriction.getTargetingDimension();
boolean bidOnly = targetRestriction.getBidOnly().getValue();
System.out.printf(
"- Targeting restriction with targeting dimension '%s' and bid only set to '%b'.%n",
targetingDimension, bidOnly);
// Adds the target restriction to the TargetingSetting object as is if the targeting
// dimension has a value other than AUDIENCE because those should not change.
if (!targetingDimension.equals(TargetingDimension.AUDIENCE)) {
targetingSettingBuilder.addTargetRestrictions(targetRestriction);
} else if (!bidOnly) {
shouldUpdateTargetingSetting = true;
// Adds an AUDIENCE target restriction with bid_only set to true to the targeting
// setting object. This has the effect of setting the AUDIENCE target restriction to
// "Observation". For more details about the targeting setting, visit
// https://support.google.com/google-ads/answer/7365594.
targetingSettingBuilder.addTargetRestrictions(
TargetRestriction.newBuilder()
.setTargetingDimensionValue(TargetingDimension.AUDIENCE_VALUE)
.setBidOnly(BoolValue.of(true)));
}
}
}
// Only updates the TargetingSetting on the ad group if there is an AUDIENCE TargetRestriction
// with bid_only set to false.
if (shouldUpdateTargetingSetting) {
updateTargetingSetting(
googleAdsClient, customerId, adGroupId, targetingSettingBuilder.build());
} else {
System.out.println("No target restrictions to update.");
}
}
}
/**
* 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;
}
}
/**
* Creates the responsive display ad.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupResourceName the campaign resource name.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void createAd(
GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName)
throws IOException {
String marketingImageUrl = "https://goo.gl/3b9Wfh";
String marketingImageName = "Marketing Image";
String marketingImageResourceName =
uploadAsset(googleAdsClient, customerId, marketingImageUrl, marketingImageName);
String squareMarketingImageName = "Square Marketing Image";
String squareMarketingImageUrl = "https://goo.gl/mtt54n";
String squareMarketingImageResourceName =
uploadAsset(googleAdsClient, customerId, squareMarketingImageUrl, squareMarketingImageName);
// Creates the responsive display ad info object.
ResponsiveDisplayAdInfo responsiveDisplayAdInfo =
ResponsiveDisplayAdInfo.newBuilder()
.addMarketingImages(
AdImageAsset.newBuilder()
.setAsset(StringValue.of(marketingImageResourceName))
.build())
.addSquareMarketingImages(
AdImageAsset.newBuilder()
.setAsset(StringValue.of(squareMarketingImageResourceName))
.build())
.addHeadlines(AdTextAsset.newBuilder().setText(StringValue.of("Travel")).build())
.setLongHeadline(
AdTextAsset.newBuilder().setText(StringValue.of("Travel the World")).build())
.addDescriptions(
AdTextAsset.newBuilder().setText(StringValue.of("Take to the air!")).build())
.setBusinessName(StringValue.of("Interplanetary Cruises"))
// Optional: Call to action text.
// Valid texts: https://support.google.com/adwords/answer/7005917
.setCallToActionText(StringValue.of("Apply Now"))
// Optional: Sets the ad colors.
.setMainColor(StringValue.of("#0000ff"))
.setAccentColor(StringValue.of("#ffff00"))
// Optional: Sets to false to strictly render the ad using the colors.
.setAllowFlexibleColor(BoolValue.of(false))
// Optional: Sets the format setting that the ad will be served in.
.setFormatSetting(DisplayAdFormatSetting.NON_NATIVE)
// Optional: Creates a logo image and sets it to the ad.
/*
.addLogoImages(
AdImageAsset.newBuilder()
.setAsset(StringValue.of("INSERT_LOGO_IMAGE_RESOURCE_NAME_HERE"))
.build())
*/
// Optional: Creates a square logo image and sets it to the ad.
/*
.addSquareLogoImages(
AdImageAsset.newBuilder()
.setAsset(StringValue.of("INSERT_SQUARE_LOGO_IMAGE_RESOURCE_NAME_HERE"))
.build())
*/
.build();
// Creates the ad.
Ad ad =
Ad.newBuilder()
.setResponsiveDisplayAd(responsiveDisplayAdInfo)
.addFinalUrls(StringValue.of("http://www.example.com/"))
.build();
// Creates the ad group ad.
AdGroupAd adGroupAd =
AdGroupAd.newBuilder().setAdGroup(StringValue.of(adGroupResourceName)).setAd(ad).build();
// Creates the ad group ad operation.
AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();
// Creates the ad group ad service client.
try (AdGroupAdServiceClient adGroupAdServiceClient =
googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
// Adds the ad group ad.
MutateAdGroupAdsResponse response =
adGroupAdServiceClient.mutateAdGroupAds(
Long.toString(customerId), ImmutableList.of(operation));
System.out.printf(
"Created ad group ad with resource name '%s'.%n",
response.getResults(0).getResourceName());
}
}
/**
* Creates and executes an asynchronous job to add users to the Customer Match user list.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param userListResourceName the resource name of the Customer Match user list to add members
* to.
*/
private void addUsersToCustomerMatchUserList(
GoogleAdsClient googleAdsClient, long customerId, String userListResourceName)
throws InterruptedException, ExecutionException, TimeoutException,
UnsupportedEncodingException {
try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
// Creates a new offline user data job.
OfflineUserDataJob offlineUserDataJob =
OfflineUserDataJob.newBuilder()
.setType(OfflineUserDataJobType.CUSTOMER_MATCH_USER_LIST)
.setCustomerMatchUserListMetadata(
CustomerMatchUserListMetadata.newBuilder()
.setUserList(StringValue.of(userListResourceName)))
.build();
// Issues a request to create the offline user data job.
CreateOfflineUserDataJobResponse createOfflineUserDataJobResponse =
offlineUserDataJobServiceClient.createOfflineUserDataJob(
Long.toString(customerId), offlineUserDataJob);
String offlineUserDataJobResourceName = createOfflineUserDataJobResponse.getResourceName();
System.out.printf(
"Created an offline user data job with resource name: %s.%n",
offlineUserDataJobResourceName);
// Issues a request to add the operations to the offline user data job.
List<OfflineUserDataJobOperation> userDataJobOperations = buildOfflineUserDataJobOperations();
AddOfflineUserDataJobOperationsResponse response =
offlineUserDataJobServiceClient.addOfflineUserDataJobOperations(
offlineUserDataJobResourceName,
// Enables partial failure.
BoolValue.of(true),
userDataJobOperations);
// Prints the status message if any partial failure error is returned.
// NOTE: The details of each partial failure error are not printed here, you can refer to
// the example HandlePartialFailure.java to learn more.
if (response.hasPartialFailureError()) {
System.out.printf(
"Encountered %d partial failure errors while adding %d operations to the offline user "
+ "data job: '%s'. Only the successfully added operations will be executed when "
+ "the job runs.%n",
response.getPartialFailureError().getDetailsCount(),
userDataJobOperations.size(),
response.getPartialFailureError().getMessage());
} else {
System.out.printf(
"Successfully added %d operations to the offline user data job.%n",
userDataJobOperations.size());
}
// Issues an asynchronous request to run the offline user data job for executing all added
// operations.
OperationFuture<Empty, Empty> runFuture =
offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(
offlineUserDataJobResourceName);
System.out.println("Asynchronous request to execute the added operations started.");
System.out.println("Waiting until operation completes.");
// The polling future implements a default back-off policy for retrying.
runFuture.getPollingFuture().get(MAX_TOTAL_POLL_INTERVAL_SECONDS, TimeUnit.SECONDS);
System.out.printf(
"Offline user data job with resource name '%s' has finished.%n",
offlineUserDataJobResourceName);
}
}
/**
* Creates a new hotel campaign in the specified client account.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param budgetResourceName the resource name of the budget for the campaign.
* @param hotelCenterAccountId the Hotel Center account ID.
* @param cpcBidCeilingMicroAmount the maximum bid limit that can be set when creating a campaign
* using the Percent CPC bidding strategy.
* @return resource name of the newly created campaign.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String addHotelCampaign(
GoogleAdsClient googleAdsClient,
long customerId,
String budgetResourceName,
long hotelCenterAccountId,
long cpcBidCeilingMicroAmount) {
// Configures the hotel settings.
HotelSettingInfo hotelSettingInfo =
HotelSettingInfo.newBuilder().setHotelCenterId(Int64Value.of(hotelCenterAccountId)).build();
// Configures the campaign network options. Only Google Search is allowed for
// hotel campaigns.
NetworkSettings networkSettings =
NetworkSettings.newBuilder().setTargetGoogleSearch(BoolValue.of(true)).build();
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
// Configures settings related to hotel campaigns including advertising channel type
// and hotel setting info.
.setAdvertisingChannelType(AdvertisingChannelType.HOTEL)
.setHotelSetting(hotelSettingInfo)
// Recommendation: Sets 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)
// Sets the bidding strategy to Percent CPC. Only Manual CPC and Percent CPC can be used
// for hotel campaigns.
.setPercentCpc(
PercentCpc.newBuilder()
.setCpcBidCeilingMicros(Int64Value.of(cpcBidCeilingMicroAmount))
.build())
// Sets the budget.
.setCampaignBudget(StringValue.of(budgetResourceName))
// Adds the networkSettings configured above.
.setNetworkSettings(networkSettings)
.build();
// Creates a campaign operation.
CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();
// Issues a mutate request to add the campaign.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
Long.toString(customerId), Collections.singletonList(operation));
MutateCampaignResult result = response.getResults(0);
System.out.printf(
"Added a hotel campaign with resource name: '%s'%n", result.getResourceName());
return result.getResourceName();
}
}