下面列出了com.google.protobuf.UInt64Value#com.google.protobuf.StringValue 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@ParameterizedTest
@ArgumentsSource(BlockingClientProvider.class)
void error_withMessage(UnitTestServiceBlockingStub blockingClient) throws Exception {
final StatusRuntimeException t = (StatusRuntimeException) catchThrowable(
() -> blockingClient.errorWithMessage(REQUEST_MESSAGE));
assertThat(t.getStatus().getCode()).isEqualTo(Code.ABORTED);
assertThat(t.getStatus().getDescription()).isEqualTo("aborted call");
assertThat(t.getTrailers().getAll(STRING_VALUE_KEY))
.containsExactly(StringValue.newBuilder().setValue("custom metadata").build());
assertThat(t.getTrailers().getAll(INT_32_VALUE_KEY))
.containsExactly(Int32Value.newBuilder().setValue(10).build(),
Int32Value.newBuilder().setValue(20).build());
assertThat(t.getTrailers().get(CUSTOM_VALUE_KEY)).isEqualTo("custom value");
checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
assertThat(rpcReq.method()).isEqualTo("armeria.grpc.testing.UnitTestService/ErrorWithMessage");
assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
assertThat(grpcStatus).isNotNull();
assertThat(grpcStatus.getCode()).isEqualTo(Code.ABORTED);
assertThat(grpcStatus.getDescription()).isEqualTo("aborted call");
});
}
private InteractiveMediaWidget buildSelectMenu(InteractiveSelect select) {
InteractiveMediaSelect.Builder apiSelect = InteractiveMediaSelect.newBuilder();
for (InteractiveSelectOption selectOption : select.getOptions()) {
InteractiveMediaSelectOption.Builder apiSelectOption = InteractiveMediaSelectOption.newBuilder();
apiSelectOption.setValue(selectOption.getValue()).setLabel(selectOption.getLabel());
apiSelect.addOptions(apiSelectOption);
}
if (select.getLabel() != null && !select.getLabel().isEmpty()) {
apiSelect.setLabel(StringValue.of(select.getLabel()));
}
if (select.getDefaultValue() != null && !select.getDefaultValue().isEmpty()) {
apiSelect.setDefaultValue(StringValue.of(select.getDefaultValue()));
}
return InteractiveMediaWidget.newBuilder().setInteractiveMediaSelect(apiSelect).build();
}
private InteractiveMediaConfirm.Builder buildConfirm(InteractiveAction action) {
InteractiveMediaConfirm.Builder confirm = InteractiveMediaConfirm.newBuilder();
if (action.getConfirm().getText() != null) {
confirm.setText(StringValue.of(action.getConfirm().getText()));
}
if (action.getConfirm().getTitle() != null) {
confirm.setTitle(StringValue.of(action.getConfirm().getTitle()));
}
if (action.getConfirm().getOk() != null) {
confirm.setOk(StringValue.of(action.getConfirm().getOk()));
}
if (action.getConfirm().getDismiss() != null) {
confirm.setDismiss(StringValue.of(action.getConfirm().getDismiss()));
}
return confirm;
}
/**
* 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
@SuppressWarnings("all")
public void suggestGeoTargetConstantsTest() {
SuggestGeoTargetConstantsResponse expectedResponse =
SuggestGeoTargetConstantsResponse.newBuilder().build();
mockGeoTargetConstantService.addResponse(expectedResponse);
StringValue locale = StringValue.newBuilder().build();
StringValue countryCode = StringValue.newBuilder().build();
SuggestGeoTargetConstantsResponse actualResponse =
client.suggestGeoTargetConstants(locale, countryCode);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockGeoTargetConstantService.getRequests();
Assert.assertEquals(1, actualRequests.size());
SuggestGeoTargetConstantsRequest actualRequest =
(SuggestGeoTargetConstantsRequest) actualRequests.get(0);
Assert.assertEquals(locale, actualRequest.getLocale());
Assert.assertEquals(countryCode, actualRequest.getCountryCode());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
private PLongIntIntByteByteStringValue newLongIntIntByteByteStringValue(LongIntIntByteByteStringValue v) {
final PLongIntIntByteByteStringValue.Builder builder = PLongIntIntByteByteStringValue.newBuilder();
builder.setLongValue(v.getLongValue());
builder.setIntValue1(v.getIntValue1());
if (v.getIntValue2() != -1) {
builder.setIntValue2(v.getIntValue2());
}
if (v.getByteValue1() != -1) {
builder.setByteValue1(v.getByteValue1());
}
if (v.getByteValue2() != -1) {
builder.setByteValue2(v.getByteValue2());
}
if (v.getStringValue() != null) {
StringValue stringValue = newStringValue(v.getStringValue());
builder.setStringValue(stringValue);
}
return builder.build();
}
@Test
@SuppressWarnings("all")
public void suggestGeoTargetConstantsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockGeoTargetConstantService.addException(exception);
try {
StringValue locale = StringValue.newBuilder().build();
StringValue countryCode = StringValue.newBuilder().build();
client.suggestGeoTargetConstants(locale, countryCode);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception
}
}
@Override
public void errorWithMessage(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
final Metadata metadata = new Metadata();
metadata.put(STRING_VALUE_KEY, StringValue.newBuilder().setValue("custom metadata").build());
metadata.put(CUSTOM_VALUE_KEY, "custom value");
final ServiceRequestContext ctx = ServiceRequestContext.current();
// gRPC wire format allow comma-separated binary headers.
ctx.mutateAdditionalResponseTrailers(
mutator -> mutator.add(
INT_32_VALUE_KEY.name(),
Base64.getEncoder().encodeToString(
Int32Value.newBuilder().setValue(10).build().toByteArray()) +
',' +
Base64.getEncoder().encodeToString(
Int32Value.newBuilder().setValue(20).build().toByteArray())));
responseObserver.onError(Status.ABORTED.withDescription("aborted call").asException(metadata));
}
@Test
@SuppressWarnings("all")
public void suggestGeoTargetConstantsTest() {
SuggestGeoTargetConstantsResponse expectedResponse =
SuggestGeoTargetConstantsResponse.newBuilder().build();
mockGeoTargetConstantService.addResponse(expectedResponse);
StringValue locale = StringValue.newBuilder().build();
StringValue countryCode = StringValue.newBuilder().build();
SuggestGeoTargetConstantsResponse actualResponse =
client.suggestGeoTargetConstants(locale, countryCode);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockGeoTargetConstantService.getRequests();
Assert.assertEquals(1, actualRequests.size());
SuggestGeoTargetConstantsRequest actualRequest =
(SuggestGeoTargetConstantsRequest) actualRequests.get(0);
Assert.assertEquals(locale, actualRequest.getLocale());
Assert.assertEquals(countryCode, actualRequest.getCountryCode());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
/**
* Creates a keyword plan.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
*/
private static String createKeywordPlan(GoogleAdsClient googleAdsClient, Long customerId) {
KeywordPlan plan =
KeywordPlan.newBuilder()
.setName(
StringValue.of("Keyword plan for traffic estimate #" + System.currentTimeMillis()))
.setForecastPeriod(
KeywordPlanForecastPeriod.newBuilder()
.setDateInterval(KeywordPlanForecastInterval.NEXT_QUARTER)
.build())
.build();
KeywordPlanOperation op = KeywordPlanOperation.newBuilder().setCreate(plan).build();
try (KeywordPlanServiceClient client =
googleAdsClient.getLatestVersion().createKeywordPlanServiceClient()) {
// Adds the keyword plan.
MutateKeywordPlansResponse response =
client.mutateKeywordPlans(String.valueOf(customerId), Arrays.asList(op));
// Displays the results.
String resourceName = response.getResults(0).getResourceName();
System.out.printf("Created keyword plan: %s%n", resourceName);
return resourceName;
}
}
/**
* Creates a campaign criterion from an address and proximity radius.
*
* @param campaignResourceName the campaign resource name to target.
* @return a campaign criterion object with the specified address and targeting radius.
*/
private static CampaignCriterion buildProximityLocation(String campaignResourceName) {
Builder builder =
CampaignCriterion.newBuilder().setCampaign(StringValue.of(campaignResourceName));
ProximityInfo.Builder proximityBuilder = builder.getProximityBuilder();
proximityBuilder.setRadius(DoubleValue.of(10.0)).setRadiusUnits(ProximityRadiusUnits.MILES);
AddressInfo.Builder addressBuilder = proximityBuilder.getAddressBuilder();
addressBuilder
.setStreetAddress(StringValue.of("38 avenue de l'Opéra"))
.setCityName(StringValue.of("Paris"))
.setPostalCode(StringValue.of("75002"))
.setCountryCode(StringValue.of("FR"));
return builder.build();
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ad group ID.
* @param keywordText the keyword text to add.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient, long customerId, long adGroupId, String keywordText) {
// Configures the keywordText text and match type settings.
KeywordInfo keywordInfo =
KeywordInfo.newBuilder()
.setText(StringValue.of(keywordText))
.setMatchType(KeywordMatchType.EXACT)
.build();
String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
// Constructs an ad group criterion using the keywordText configuration above.
AdGroupCriterion criterion =
AdGroupCriterion.newBuilder()
.setAdGroup(StringValue.of(adGroupResourceName))
.setStatus(AdGroupCriterionStatus.ENABLED)
.setKeyword(keywordInfo)
.build();
AdGroupCriterionOperation op =
AdGroupCriterionOperation.newBuilder().setCreate(criterion).build();
try (AdGroupCriterionServiceClient agcServiceClient =
googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
MutateAdGroupCriteriaResponse response =
agcServiceClient.mutateAdGroupCriteria(Long.toString(customerId), ImmutableList.of(op));
System.out.printf("Added %d ad group criteria:%n", response.getResultsCount());
for (MutateAdGroupCriterionResult result : response.getResultsList()) {
System.out.println(result.getResourceName());
}
}
}
/**
* Attempts to create 3 ad groups with partial failure enabled. One of the ad groups will succeed,
* while the other will fail.
*/
private MutateAdGroupsResponse createAdGroups(
GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
// This AdGroup should be created successfully - assuming the campaign in the params exists.
AdGroup group1 =
AdGroup.newBuilder()
.setCampaign(StringValue.of(ResourceNames.campaign(customerId, campaignId)))
.setName(StringValue.of("Valid AdGroup: " + System.currentTimeMillis()))
.build();
// This AdGroup will always fail - campaign ID 0 in resource names is never valid.
AdGroup group2 =
AdGroup.newBuilder()
.setCampaign(StringValue.of(ResourceNames.campaign(customerId, 0L)))
.setName(StringValue.of("Broken AdGroup: " + System.currentTimeMillis()))
.build();
// This AdGroup will always fail - duplicate ad group names are not allowed.
AdGroup group3 =
AdGroup.newBuilder()
.setCampaign(StringValue.of(ResourceNames.campaign(customerId, campaignId)))
.setName(group1.getName())
.build();
AdGroupOperation op1 = AdGroupOperation.newBuilder().setCreate(group1).build();
AdGroupOperation op2 = AdGroupOperation.newBuilder().setCreate(group2).build();
AdGroupOperation op3 = AdGroupOperation.newBuilder().setCreate(group3).build();
try (AdGroupServiceClient service =
googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
// Issues the mutate request, setting partialFailure=true.
return service.mutateAdGroups(
String.valueOf(customerId),
Arrays.asList(op1, op2, op3),
// Sets partial failure to true.
true,
// Sets validate only to false.
false);
}
}
/**
* Creates a new hotel ad group ad in the specified ad group.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupResourceName the resource name of the ad group that the new ad group ad will
* belong to.
* @return resource name of the newly created ad group ad.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String addHotelAdGroupAd(
GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) {
// Creates a new hotel ad.
Ad ad = Ad.newBuilder().setHotelAd(HotelAdInfo.newBuilder().build()).build();
// Creates a new ad group ad and sets the hotel ad to it.
AdGroupAd adGroupAd =
AdGroupAd.newBuilder()
// Sets the ad to the ad created above.
.setAd(ad)
// Set the ad group ad to enabled. Setting this to paused will cause an error
// for hotel campaigns. For hotels pausing should happen at either the ad group or
// campaign level.
.setStatus(AdGroupAdStatus.ENABLED)
// Sets the ad group.
.setAdGroup(StringValue.of(adGroupResourceName))
.build();
// Creates an ad group ad operation.
AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();
// Issues a mutate request to add an ad group ad.
try (AdGroupAdServiceClient adGroupAdServiceClient =
googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
MutateAdGroupAdResult mutateAdGroupAdResult =
adGroupAdServiceClient
.mutateAdGroupAds(Long.toString(customerId), Collections.singletonList(operation))
.getResults(0);
System.out.printf(
"Added a hotel ad group ad with resource name: '%s'%n",
mutateAdGroupAdResult.getResourceName());
return mutateAdGroupAdResult.getResourceName();
}
}
private InteractiveMediaWidget buildButton(InteractiveButton button) {
InteractiveMediaButton.Builder btn = InteractiveMediaButton.newBuilder()
.setValue(button.getValue());
if (button.getLabel() != null && !button.getLabel().isEmpty()) {
btn.setLabel(StringValue.of(button.getLabel()));
}
return InteractiveMediaWidget.newBuilder().setInteractiveMediaButton(btn).build();
}
/** Adds the extension feed item to the Campaign. */
private void addExtensionToCampaign(
GoogleAdsClient googleAdsClient,
long customerId,
long campaignId,
String extensionFeedItemResourceName) {
String campaignResourceName = ResourceNames.campaign(customerId, campaignId);
// Creates the campaign extension setting, sets it to HOTEL_CALLOUT, and attaches the feed item.
CampaignExtensionSetting campaignExtensionSetting =
CampaignExtensionSetting.newBuilder()
.setExtensionType(ExtensionType.HOTEL_CALLOUT)
.setCampaign(StringValue.of(campaignResourceName))
.addExtensionFeedItems(StringValue.of(extensionFeedItemResourceName))
.build();
// Creates the campaign extension setting operation.
CampaignExtensionSettingOperation op =
CampaignExtensionSettingOperation.newBuilder().setCreate(campaignExtensionSetting).build();
// Issues the create request to add the callout.
try (CampaignExtensionSettingServiceClient campaignExtensionServiceClient =
googleAdsClient.getLatestVersion().createCampaignExtensionSettingServiceClient()) {
MutateCampaignExtensionSettingsResponse response =
campaignExtensionServiceClient.mutateCampaignExtensionSettings(
Long.toString(customerId), ImmutableList.of(op));
String campaignExtensionResourceName = response.getResults(0).getResourceName();
System.out.printf(
"Added a campaign extension with resource name: '%s'.%n", campaignExtensionResourceName);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignId the campaign ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) {
String campaignResourceName = ResourceNames.campaign(customerId, campaignId);
List<StringValue> extensionFeedItems =
createExtensionFeedItems(googleAdsClient, customerId, campaignResourceName);
// Creates a CampaignExtensionSetting.
CampaignExtensionSetting campaignExtensionSetting =
CampaignExtensionSetting.newBuilder()
.setCampaign(StringValue.of(campaignResourceName))
.setExtensionType(ExtensionType.SITELINK)
.addAllExtensionFeedItems(extensionFeedItems)
.build();
// Creates the operation.
CampaignExtensionSettingOperation operation =
CampaignExtensionSettingOperation.newBuilder().setCreate(campaignExtensionSetting).build();
// Creates the CampaignExtensionSettingServiceClient.
try (CampaignExtensionSettingServiceClient campaignExtensionSettingServiceClient =
googleAdsClient.getLatestVersion().createCampaignExtensionSettingServiceClient()) {
// Adds the CampaignExtensionSettingServiceClient.
MutateCampaignExtensionSettingsResponse response =
campaignExtensionSettingServiceClient.mutateCampaignExtensionSettings(
Long.toString(customerId), ImmutableList.of(operation));
for (MutateCampaignExtensionSettingResult result : response.getResultsList()) {
System.out.printf(
"Created CampaignExtensionSetting with resource name '%s'.%n",
result.getResourceName());
}
}
}
private CompletableFuture<Void> setOnlineStatus(boolean status, DeviceType deviceType, String deviceCategory, Duration timeout) {
RequestSetOnline request = RequestSetOnline.newBuilder()
.setIsOnline(status)
.setDeviceType(deviceType.toGrpcType())
.setDeviceCategory(StringValue.newBuilder().setValue(deviceCategory).build())
.setTimeout(timeout.toMillis())
.build();
return internalBot.withToken(
TypingAndOnlineGrpc.newFutureStub(channel),
stub -> stub.setOnline(request)).thenApply(t -> null);
}
@Test
void exchangeHeadersUnaryCall_grpcMetadata() throws Exception {
final Metadata metadata = new Metadata();
metadata.put(TestServiceImpl.EXTRA_HEADER_KEY, "dog");
TestServiceBlockingStub stub = MetadataUtils.attachHeaders(blockingStub, metadata);
final AtomicReference<Metadata> headers = new AtomicReference<>();
final AtomicReference<Metadata> trailers = new AtomicReference<>();
stub = MetadataUtils.captureMetadata(stub, headers, trailers);
assertThat(stub.emptyCall(EMPTY)).isNotNull();
final HttpHeaders clientHeaders = CLIENT_HEADERS_CAPTURE.get();
assertThat(clientHeaders.get(HttpHeaderNames.TE))
.isEqualTo(HttpHeaderValues.TRAILERS.toString());
// Assert that our side channel object is echoed back in both headers and trailers
assertThat(clientHeaders.get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");
assertThat(SERVER_TRAILERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");
assertThat(headers.get()).isNull();
assertThat(trailers.get().get(TestServiceImpl.EXTRA_HEADER_KEY)).isEqualTo("dog");
assertThat(trailers.get().getAll(TestServiceImpl.STRING_VALUE_KEY)).containsExactly(
StringValue.newBuilder().setValue("hello").build(),
StringValue.newBuilder().setValue("world").build());
checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
assertThat(rpcReq.params()).containsExactly(EMPTY);
assertThat(rpcRes.get()).isEqualTo(EMPTY);
});
}
/** Adds the extension feed item to the ad group. */
private void addExtensionToAdGroup(
GoogleAdsClient googleAdsClient,
long customerId,
long adGroupId,
String extensionFeedItemResourceName) {
String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
// Creates the ad group extension setting, sets it to HOTEL_CALLOUT, and attaches the feed item.
AdGroupExtensionSetting adGroupExtensionSetting =
AdGroupExtensionSetting.newBuilder()
.setExtensionType(ExtensionType.HOTEL_CALLOUT)
.setAdGroup(StringValue.of(adGroupResourceName))
.addExtensionFeedItems(StringValue.of(extensionFeedItemResourceName))
.build();
// Creates the ad group extension setting operation.
AdGroupExtensionSettingOperation op =
AdGroupExtensionSettingOperation.newBuilder().setCreate(adGroupExtensionSetting).build();
// Issues the create request to add the callout.
try (AdGroupExtensionSettingServiceClient adGroupExtensionServiceClient =
googleAdsClient.getLatestVersion().createAdGroupExtensionSettingServiceClient()) {
MutateAdGroupExtensionSettingsResponse response =
adGroupExtensionServiceClient.mutateAdGroupExtensionSettings(
Long.toString(customerId), ImmutableList.of(op));
String adGroupExtensionResourceName = response.getResults(0).getResourceName();
System.out.printf(
"Added an ad group extension with resource name: '%s'.%n", adGroupExtensionResourceName);
}
}
/**
* 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) throws IOException {
byte[] imageData = ByteStreams.toByteArray(new URL("https://goo.gl/3b9Wfh").openStream());
MediaImage image =
MediaImage.newBuilder().setData(BytesValue.of(ByteString.copyFrom(imageData))).build();
MediaFile file =
MediaFile.newBuilder()
.setName(StringValue.of("Ad Image"))
.setType(MediaType.IMAGE)
.setSourceUrl(StringValue.of("https://goo.gl/3b9Wfh"))
.setImage(image)
.build();
MediaFileOperation op = MediaFileOperation.newBuilder().setCreate(file).build();
try (MediaFileServiceClient mediaFileServiceClient =
googleAdsClient.getLatestVersion().createMediaFileServiceClient()) {
MutateMediaFilesResponse response =
mediaFileServiceClient.mutateMediaFiles(Long.toString(customerId), Arrays.asList(op));
System.out.printf("Added %d images:%n", response.getResultsCount());
for (MutateMediaFileResult result : response.getResultsList()) {
System.out.println(result.getResourceName());
}
}
}
/**
* 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;
}
@Test
void exchangeHeadersUnaryCall_armeriaHeaders() throws Exception {
TestServiceBlockingStub stub =
Clients.newDerivedClient(
blockingStub,
ClientOption.HTTP_HEADERS.newValue(
HttpHeaders.of(TestServiceImpl.EXTRA_HEADER_NAME, "dog")));
final AtomicReference<Metadata> headers = new AtomicReference<>();
final AtomicReference<Metadata> trailers = new AtomicReference<>();
stub = MetadataUtils.captureMetadata(stub, headers, trailers);
assertThat(stub.emptyCall(EMPTY)).isNotNull();
// Assert that our side channel object is echoed back in both headers and trailers
assertThat(CLIENT_HEADERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");
assertThat(SERVER_TRAILERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");
assertThat(headers.get()).isNull();
assertThat(trailers.get().get(TestServiceImpl.EXTRA_HEADER_KEY)).isEqualTo("dog");
assertThat(trailers.get().getAll(TestServiceImpl.STRING_VALUE_KEY)).containsExactly(
StringValue.newBuilder().setValue("hello").build(),
StringValue.newBuilder().setValue("world").build());
checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
assertThat(rpcReq.params()).containsExactly(EMPTY);
assertThat(rpcRes.get()).isEqualTo(EMPTY);
});
}
private PStringStringValue newStringStringValue(StringStringValue v) {
PStringStringValue.Builder builder = PStringStringValue.newBuilder();
if (v.getStringValue1() != null) {
StringValue stringValue1 = newStringValue(v.getStringValue1());
builder.setStringValue1(stringValue1);
}
if (v.getStringValue2() != null) {
StringValue stringValue2 = newStringValue(v.getStringValue2());
builder.setStringValue2(stringValue2);
}
return builder.build();
}
@Override
public void errorAdditionalMetadata(SimpleRequest request,
StreamObserver<SimpleResponse> responseObserver) {
ServiceRequestContext.current().mutateAdditionalResponseTrailers(
mutator -> mutator.add(
ERROR_METADATA_HEADER,
Base64.getEncoder().encodeToString(StringValue.newBuilder()
.setValue("an error occurred")
.build()
.toByteArray())));
responseObserver.onError(new IllegalStateException("This error should have metadata"));
}
/**
* 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());
}
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param feedItemId the ID of the feed item to update.
* @param sitelinkText the new sitelink text to update to.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient, long customerId, long feedItemId, String sitelinkText) {
try (ExtensionFeedItemServiceClient extensionFeedItemServiceClient =
googleAdsClient.getLatestVersion().createExtensionFeedItemServiceClient()) {
// Creates an extension feed item using the specified feed item ID and sitelink text.
ExtensionFeedItem extensionFeedItem =
ExtensionFeedItem.newBuilder()
.setResourceName(ResourceNames.extensionFeedItem(customerId, feedItemId))
.setSitelinkFeedItem(
SitelinkFeedItem.newBuilder().setLinkText(StringValue.of(sitelinkText)).build())
.build();
// Constructs an operation that will update the extension feed item, using the FieldMasks
// utility to derive the update mask. This mask tells the Google Ads API which attributes of
// the extension feed item you want to change.
ExtensionFeedItemOperation operation =
ExtensionFeedItemOperation.newBuilder()
.setUpdate(extensionFeedItem)
.setUpdateMask(FieldMasks.allSetFieldsOf(extensionFeedItem))
.build();
// Sends the operation in a mutate request.
MutateExtensionFeedItemsResponse response =
extensionFeedItemServiceClient.mutateExtensionFeedItems(
Long.toString(customerId), ImmutableList.of(operation));
// Prints the resource name of each updated object.
for (MutateExtensionFeedItemResult mutateExtensionFeedItemResult :
response.getResultsList()) {
System.out.printf(
"Updated extension feed item with the resource name: '%s'.%n",
mutateExtensionFeedItemResult.getResourceName());
}
}
}
@Test
@SuppressWarnings("all")
public void generateKeywordIdeasTest() {
GenerateKeywordIdeaResponse expectedResponse = GenerateKeywordIdeaResponse.newBuilder().build();
mockKeywordPlanIdeaService.addResponse(expectedResponse);
String customerId = "customerId-1772061412";
StringValue language = StringValue.newBuilder().build();
List<StringValue> geoTargetConstants = new ArrayList<>();
KeywordPlanNetworkEnum.KeywordPlanNetwork keywordPlanNetwork =
KeywordPlanNetworkEnum.KeywordPlanNetwork.UNSPECIFIED;
GenerateKeywordIdeaResponse actualResponse =
client.generateKeywordIdeas(customerId, language, geoTargetConstants, keywordPlanNetwork);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockKeywordPlanIdeaService.getRequests();
Assert.assertEquals(1, actualRequests.size());
GenerateKeywordIdeasRequest actualRequest = (GenerateKeywordIdeasRequest) actualRequests.get(0);
Assert.assertEquals(customerId, actualRequest.getCustomerId());
Assert.assertEquals(language, actualRequest.getLanguage());
Assert.assertEquals(geoTargetConstants, actualRequest.getGeoTargetConstantsList());
Assert.assertEquals(keywordPlanNetwork, actualRequest.getKeywordPlanNetwork());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
/** Creates a new extension feed item for the callout. */
private String addExtensionFeedItem(
GoogleAdsClient googleAdsClient, long customerId, String calloutText, String languageCode) {
// Creates the callout with text and language of choice.
HotelCalloutFeedItem hotelCallout =
HotelCalloutFeedItem.newBuilder()
.setText(StringValue.of(calloutText))
.setLanguageCode(StringValue.of(languageCode))
.build();
// Attaches the callout to a feed item.
ExtensionFeedItem feedItem =
ExtensionFeedItem.newBuilder().setHotelCalloutFeedItem(hotelCallout).build();
// Creates the feed item operation.
ExtensionFeedItemOperation feedItemOperation =
ExtensionFeedItemOperation.newBuilder().setCreate(feedItem).build();
// Issues the create request to create the feed item.
try (ExtensionFeedItemServiceClient extensionFeedItemServiceClient =
googleAdsClient.getLatestVersion().createExtensionFeedItemServiceClient()) {
MutateExtensionFeedItemsResponse response =
extensionFeedItemServiceClient.mutateExtensionFeedItems(
Long.toString(customerId), ImmutableList.of(feedItemOperation));
String extensionFeedItemResourceName = response.getResults(0).getResourceName();
System.out.printf(
"Added a extension feed item with resource name: '%s'.%n", extensionFeedItemResourceName);
return extensionFeedItemResourceName;
}
}
/**
* Runs the example.
*
* @param googleAdsClient the client to use for connecting to the API.
* @param customerId the customer ID to update.
* @param adId the ad ID to update.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adId) {
// Creates an AdOperation to update an ad.
AdOperation.Builder adOperation = AdOperation.newBuilder();
// Creates an Ad in the update field of the operation.
Ad.Builder adBuilder =
adOperation
.getUpdateBuilder()
.setResourceName(ResourceNames.ad(customerId, adId))
.addFinalUrls(StringValue.of("http://www.example.com/"))
.addFinalMobileUrls(StringValue.of("http://www.example.com/mobile"));
// Sets the expanded text ad properties to update on the ad.
adBuilder
.getExpandedTextAdBuilder()
.setHeadlinePart1(StringValue.of("Cruise to Pluto #" + System.currentTimeMillis()))
.setHeadlinePart2(StringValue.of("Tickets on sale now"))
.setDescription(StringValue.of("Best space cruise ever."));
// Sets the update mask (the fields which will be modified) to be all the fields we set above.
adOperation.setUpdateMask(FieldMasks.allSetFieldsOf(adBuilder.build()));
// Creates a service client to connect to the API.
try (AdServiceClient adServiceClient =
googleAdsClient.getLatestVersion().createAdServiceClient()) {
// Issues the mutate request.
MutateAdsResponse response =
adServiceClient.mutateAds(
String.valueOf(customerId), ImmutableList.of(adOperation.build()));
// Displays the result.
for (MutateAdResult result : response.getResultsList()) {
System.out.printf("Ad with resource name '%s' was updated.%n", result.getResourceName());
}
}
}