com.google.protobuf.BoolValue Java Examples

The following examples show how to use com.google.protobuf.BoolValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessagingApi.java    From java-bot-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 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()));
}
 
Example #2
Source File: OfflineUserDataJobServiceClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@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
  }
}
 
Example #3
Source File: WrappedPrimitiveTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: XdsClientImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: XdsClientImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: GrpcModelConverters.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #7
Source File: GrpcModelConverters.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #8
Source File: AutoScalingTestUtils.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #9
Source File: CreateCustomer.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example #10
Source File: TypesBuilderFromDescriptor.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
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"));
    }
  }
}
 
Example #12
Source File: AddConversionAction.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
  }
}
 
Example #13
Source File: CommonTlsContextTestsUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example #14
Source File: AddCampaignTargetingCriteria.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #15
Source File: UsePortfolioBiddingStrategy.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
  }
}
 
Example #16
Source File: AddCompleteCampaignsUsingMutateJob.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: OfflineUserDataJobServiceClientTest.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example #18
Source File: WrappedPrimitiveTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #19
Source File: IdentitiyService.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@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();

}
 
Example #20
Source File: EnvoyProtoDataTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void convertRouteMatch_pathMatching() {
  // path_specifier = prefix
  io.envoyproxy.envoy.api.v2.route.RouteMatch proto1 =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.newBuilder().setPrefix("/").build();
  StructOrError<RouteMatch> struct1 = Route.convertEnvoyProtoRouteMatch(proto1);
  assertThat(struct1.getErrorDetail()).isNull();
  assertThat(struct1.getStruct()).isEqualTo(
      new RouteMatch(
          new PathMatcher(null, "/", null), Collections.<HeaderMatcher>emptyList(), null));

  // path_specifier = path
  io.envoyproxy.envoy.api.v2.route.RouteMatch proto2 =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.newBuilder().setPath("/service/method").build();
  StructOrError<RouteMatch> struct2 = Route.convertEnvoyProtoRouteMatch(proto2);
  assertThat(struct2.getErrorDetail()).isNull();
  assertThat(struct2.getStruct()).isEqualTo(
      new RouteMatch(
          new PathMatcher("/service/method", null, null),
          Collections.<HeaderMatcher>emptyList(), null));

  // path_specifier = regex
  @SuppressWarnings("deprecation")
  io.envoyproxy.envoy.api.v2.route.RouteMatch proto3 =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.newBuilder().setRegex("*").build();
  StructOrError<RouteMatch> struct3 = Route.convertEnvoyProtoRouteMatch(proto3);
  assertThat(struct3.getErrorDetail()).isNotNull();
  assertThat(struct3.getStruct()).isNull();

  // path_specifier = safe_regex
  io.envoyproxy.envoy.api.v2.route.RouteMatch proto4 =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.newBuilder()
          .setSafeRegex(
              io.envoyproxy.envoy.type.matcher.RegexMatcher.newBuilder().setRegex(".")).build();
  StructOrError<RouteMatch> struct4 = Route.convertEnvoyProtoRouteMatch(proto4);
  assertThat(struct4.getErrorDetail()).isNull();
  assertThat(struct4.getStruct()).isEqualTo(
      new RouteMatch(
          new PathMatcher(null, null, Pattern.compile(".")),
          Collections.<HeaderMatcher>emptyList(), null));

  // case_sensitive = false
  io.envoyproxy.envoy.api.v2.route.RouteMatch proto5 =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.newBuilder()
          .setCaseSensitive(BoolValue.newBuilder().setValue(false))
          .build();
  StructOrError<RouteMatch> struct5 = Route.convertEnvoyProtoRouteMatch(proto5);
  assertThat(struct5.getErrorDetail()).isNotNull();
  assertThat(struct5.getStruct()).isNull();

  // query_parameters is set
  io.envoyproxy.envoy.api.v2.route.RouteMatch proto6 =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.newBuilder()
          .addQueryParameters(QueryParameterMatcher.getDefaultInstance())
          .build();
  StructOrError<RouteMatch> struct6 = Route.convertEnvoyProtoRouteMatch(proto6);
  assertThat(struct6).isNull();

  // path_specifier unset
  io.envoyproxy.envoy.api.v2.route.RouteMatch unsetProto =
      io.envoyproxy.envoy.api.v2.route.RouteMatch.getDefaultInstance();
  StructOrError<RouteMatch> unsetStruct = Route.convertEnvoyProtoRouteMatch(unsetProto);
  assertThat(unsetStruct.getErrorDetail()).isNotNull();
  assertThat(unsetStruct.getStruct()).isNull();
}
 
Example #21
Source File: ProtobufModule.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
@Override
public void setupModule(SetupContext context) {
  SimpleSerializers serializers = new SimpleSerializers();
  serializers.addSerializer(new MessageSerializer(config));
  serializers.addSerializer(new DurationSerializer());
  serializers.addSerializer(new FieldMaskSerializer());
  serializers.addSerializer(new ListValueSerializer());
  serializers.addSerializer(new NullValueSerializer());
  serializers.addSerializer(new StructSerializer());
  serializers.addSerializer(new TimestampSerializer());
  serializers.addSerializer(new ValueSerializer());
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(DoubleValue.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(FloatValue.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(Int64Value.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(UInt64Value.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(Int32Value.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(UInt32Value.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(BoolValue.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(StringValue.class));
  serializers.addSerializer(new WrappedPrimitiveSerializer<>(BytesValue.class));

  context.addSerializers(serializers);

  context.addDeserializers(new MessageDeserializerFactory(config));
  SimpleDeserializers deserializers = new SimpleDeserializers();
  deserializers.addDeserializer(Duration.class, new DurationDeserializer());
  deserializers.addDeserializer(FieldMask.class, new FieldMaskDeserializer());
  deserializers.addDeserializer(ListValue.class, new ListValueDeserializer().buildAtEnd());
  deserializers.addDeserializer(NullValue.class, new NullValueDeserializer());
  deserializers.addDeserializer(Struct.class, new StructDeserializer().buildAtEnd());
  deserializers.addDeserializer(Timestamp.class, new TimestampDeserializer());
  deserializers.addDeserializer(Value.class, new ValueDeserializer().buildAtEnd());
  deserializers.addDeserializer(DoubleValue.class, wrappedPrimitiveDeserializer(DoubleValue.class));
  deserializers.addDeserializer(FloatValue.class, wrappedPrimitiveDeserializer(FloatValue.class));
  deserializers.addDeserializer(Int64Value.class, wrappedPrimitiveDeserializer(Int64Value.class));
  deserializers.addDeserializer(UInt64Value.class, wrappedPrimitiveDeserializer(UInt64Value.class));
  deserializers.addDeserializer(Int32Value.class, wrappedPrimitiveDeserializer(Int32Value.class));
  deserializers.addDeserializer(UInt32Value.class, wrappedPrimitiveDeserializer(UInt32Value.class));
  deserializers.addDeserializer(BoolValue.class, wrappedPrimitiveDeserializer(BoolValue.class));
  deserializers.addDeserializer(StringValue.class, wrappedPrimitiveDeserializer(StringValue.class));
  deserializers.addDeserializer(BytesValue.class, wrappedPrimitiveDeserializer(BytesValue.class));
  context.addDeserializers(deserializers);
  context.setMixInAnnotations(MessageOrBuilder.class, MessageOrBuilderMixin.class);
}
 
Example #22
Source File: ProtoApiFromOpenApi.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
private static Option createBoolOption(String optionName, boolean value) {
  return Option.newBuilder()
      .setName(optionName)
      .setValue(Any.pack(BoolValue.newBuilder().setValue(value).build()))
      .build();
}
 
Example #23
Source File: AllMapValuesTest.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
private static HasAllMapValues hasAllMapValues() {
  Value value = Value.newBuilder().setStringValue("test").build();
  ByteString byteString = ByteString.copyFromUtf8("test");
  Any any = Any
          .newBuilder()
          .setTypeUrl("type.googleapis.com/google.protobuf.Value")
          .setValue(value.toByteString())
          .build();
  return HasAllMapValues
          .newBuilder()
          .putDoubleMap("double", 1.5d)
          .putFloatMap("float", 2.5f)
          .putInt32Map("int32", 1)
          .putInt64Map("int64", 2)
          .putUint32Map("uint32", 3)
          .putUint64Map("uint64", 4)
          .putSint32Map("sint32", 5)
          .putSint64Map("sint64", 6)
          .putFixed32Map("fixed32", 7)
          .putFixed64Map("fixed64", 8)
          .putSfixed32Map("sfixed32", 9)
          .putSfixed64Map("sfixed64", 10)
          .putBoolMap("bool", true)
          .putStringMap("string", "test")
          .putBytesMap("bytes", byteString)
          .putAnyMap("any", any)
          .putDurationMap("duration", Duration.newBuilder().setSeconds(30).build())
          .putFieldMaskMap("field_mask", FieldMask.newBuilder().addPaths("path_one").addPaths("path_two").build())
          .putListValueMap("list_value", ListValue.newBuilder().addValues(value).build())
          .putNullValueMap("null_value", NullValue.NULL_VALUE)
          .putStructMap("struct", Struct.newBuilder().putFields("field", value).build())
          .putTimestampMap("timestamp", Timestamp.newBuilder().setSeconds(946684800).build())
          .putValueMap("value", value)
          .putDoubleWrapperMap("double_wrapper", DoubleValue.newBuilder().setValue(3.5d).build())
          .putFloatWrapperMap("float_wrapper", FloatValue.newBuilder().setValue(4.5f).build())
          .putInt32WrapperMap("int32_wrapper", Int32Value.newBuilder().setValue(11).build())
          .putInt64WrapperMap("int64_wrapper", Int64Value.newBuilder().setValue(12).build())
          .putUint32WrapperMap("uint32_wrapper", UInt32Value.newBuilder().setValue(13).build())
          .putUint64WrapperMap("uint64_wrapper", UInt64Value.newBuilder().setValue(14).build())
          .putBoolWrapperMap("bool_wrapper", BoolValue.newBuilder().setValue(true).build())
          .putStringWrapperMap("string_wrapper", StringValue.newBuilder().setValue("test").build())
          .putBytesWrapperMap("bytes_wrapper", BytesValue.newBuilder().setValue(byteString).build())
          .putEnumMap("enum", EnumProto3.FIRST)
          .putProto2MessageMap("proto2", AllFields.newBuilder().setString("proto2").build())
          .putProto3MessageMap("proto3", AllFieldsProto3.newBuilder().setString("proto3").build())
          .build();
}
 
Example #24
Source File: TraceProtoUtils.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
/**
 * Converts {@link SpanData} to {@link Span} proto.
 *
 * @param spanData the {@code SpanData}.
 * @return proto representation of {@code Span}.
 */
static Span toSpanProto(SpanData spanData) {
  SpanContext spanContext = spanData.getContext();
  TraceId traceId = spanContext.getTraceId();
  SpanId spanId = spanContext.getSpanId();
  Span.Builder spanBuilder =
      Span.newBuilder()
          .setTraceId(toByteString(traceId.getBytes()))
          .setSpanId(toByteString(spanId.getBytes()))
          .setTracestate(toTracestateProto(spanContext.getTracestate()))
          .setName(toTruncatableStringProto(spanData.getName()))
          .setStartTime(toTimestampProto(spanData.getStartTimestamp()))
          .setAttributes(toAttributesProto(spanData.getAttributes()))
          .setTimeEvents(
              toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents()))
          .setLinks(toLinksProto(spanData.getLinks()));

  Kind kind = spanData.getKind();
  if (kind != null) {
    spanBuilder.setKind(toSpanKindProto(kind));
  }

  io.opencensus.trace.Status status = spanData.getStatus();
  if (status != null) {
    spanBuilder.setStatus(toStatusProto(status));
  }

  Timestamp end = spanData.getEndTimestamp();
  if (end != null) {
    spanBuilder.setEndTime(toTimestampProto(end));
  }

  Integer childSpanCount = spanData.getChildSpanCount();
  if (childSpanCount != null) {
    spanBuilder.setChildSpanCount(UInt32Value.newBuilder().setValue(childSpanCount).build());
  }

  Boolean hasRemoteParent = spanData.getHasRemoteParent();
  if (hasRemoteParent != null) {
    spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
  }

  SpanId parentSpanId = spanData.getParentSpanId();
  if (parentSpanId != null && parentSpanId.isValid()) {
    spanBuilder.setParentSpanId(toByteString(parentSpanId.getBytes()));
  }

  return spanBuilder.build();
}
 
Example #25
Source File: StackdriverV2ExporterHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
Span generateSpan(
    SpanData spanData,
    Map<String, AttributeValue> resourceLabels,
    Map<String, AttributeValue> fixedAttributes) {
  SpanContext context = spanData.getContext();
  final String spanIdHex = context.getSpanId().toLowerBase16();
  SpanName spanName =
      SpanName.newBuilder()
          .setProject(projectId)
          .setTrace(context.getTraceId().toLowerBase16())
          .setSpan(spanIdHex)
          .build();
  Span.Builder spanBuilder =
      Span.newBuilder()
          .setName(spanName.toString())
          .setSpanId(spanIdHex)
          .setDisplayName(
              toTruncatableStringProto(toDisplayName(spanData.getName(), spanData.getKind())))
          .setStartTime(toTimestampProto(spanData.getStartTimestamp()))
          .setAttributes(
              toAttributesProto(spanData.getAttributes(), resourceLabels, fixedAttributes))
          .setTimeEvents(
              toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents()));
  io.opencensus.trace.Status status = spanData.getStatus();
  if (status != null) {
    spanBuilder.setStatus(toStatusProto(status));
  }
  Timestamp end = spanData.getEndTimestamp();
  if (end != null) {
    spanBuilder.setEndTime(toTimestampProto(end));
  }
  spanBuilder.setLinks(toLinksProto(spanData.getLinks()));
  Integer childSpanCount = spanData.getChildSpanCount();
  if (childSpanCount != null) {
    spanBuilder.setChildSpanCount(Int32Value.newBuilder().setValue(childSpanCount).build());
  }
  if (spanData.getParentSpanId() != null && spanData.getParentSpanId().isValid()) {
    spanBuilder.setParentSpanId(spanData.getParentSpanId().toLowerBase16());
  }
  /*@Nullable*/ Boolean hasRemoteParent = spanData.getHasRemoteParent();
  if (hasRemoteParent != null) {
    spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
  }
  return spanBuilder.build();
}
 
Example #26
Source File: AutoScalingTestUtils.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a random scaling policy for use with tests.
 *
 * @return
 */
public static ScalingPolicy generateStepPolicy() {
    // TODO(Andrew L): Add target tracking support
    AlarmConfiguration alarmConfig = AlarmConfiguration.newBuilder()
            .setActionsEnabled(BoolValue.newBuilder()
                    .setValue(ThreadLocalRandom.current().nextBoolean())
                    .build())
            .setComparisonOperator(AlarmConfiguration.ComparisonOperator.GreaterThanThreshold)
            .setEvaluationPeriods(Int32Value.newBuilder()
                    .setValue(ThreadLocalRandom.current().nextInt())
                    .build())
            .setPeriodSec(Int32Value.newBuilder()
                    .setValue(ThreadLocalRandom.current().nextInt())
                    .build())
            .setThreshold(DoubleValue.newBuilder()
                    .setValue(ThreadLocalRandom.current().nextDouble())
                    .build())
            .setMetricNamespace("NFLX/EPIC")
            .setMetricName("Metric-" + ThreadLocalRandom.current().nextInt())
            .setStatistic(AlarmConfiguration.Statistic.Sum)
            .build();

    StepScalingPolicy stepScalingPolicy = StepScalingPolicy.newBuilder()
            .setAdjustmentType(StepScalingPolicy.AdjustmentType.ChangeInCapacity)
            .setCooldownSec(Int32Value.newBuilder()
                    .setValue(ThreadLocalRandom.current().nextInt())
                    .build())
            .setMinAdjustmentMagnitude(Int64Value.newBuilder()
                    .setValue(ThreadLocalRandom.current().nextLong())
                    .build())
            .setMetricAggregationType(StepScalingPolicy.MetricAggregationType.Maximum)
            .addStepAdjustments(StepAdjustments.newBuilder()
                    .setMetricIntervalLowerBound(DoubleValue.newBuilder()
                            .setValue(ThreadLocalRandom.current().nextDouble())
                            .build())
                    .setMetricIntervalUpperBound(DoubleValue.newBuilder()
                            .setValue(ThreadLocalRandom.current().nextDouble())
                            .build())
                    .setScalingAdjustment(Int32Value.newBuilder()
                            .setValue(ThreadLocalRandom.current().nextInt())
                            .build()))
            .build();

    StepScalingPolicyDescriptor stepScalingPolicyDescriptor = StepScalingPolicyDescriptor.newBuilder()
            .setAlarmConfig(alarmConfig)
            .setScalingPolicy(stepScalingPolicy)
            .build();
    return ScalingPolicy.newBuilder().setStepPolicyDescriptor(stepScalingPolicyDescriptor).build();
}
 
Example #27
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testExitCodeAndFallback()
    throws ExecutionException, InterruptedException, IOException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(2);
  EasyMock.replay(eventBus);
  String mockWorker = "mock_worker";
  RemoteExecutionMetadata remoteExecutionMetadata =
      RemoteExecutionMetadata.newBuilder()
          .setWorkerInfo(WorkerInfo.newBuilder().setHostname(mockWorker).build())
          .setExecutedActionInfo(
              ExecutedActionInfo.newBuilder()
                  .setIsFallbackEnabledForCompletedAction(
                      BoolValue.newBuilder().setValue(true).build())
                  .build())
          .build();

  StepFailedException exc =
      StepFailedException.createForFailingStepWithExitCode(
          new AbstractExecutionStep("remote_execution") {
            @Override
            public StepExecutionResult execute(ExecutionContext context) {
              throw new RuntimeException();
            }
          },
          executionContext,
          StepExecutionResult.builder().setExitCode(1).setStderr("").build(),
          remoteExecutionMetadata);

  // Just here to test if this is serializable by jackson, as we do Log.warn this.
  new ObjectMapper().writeValueAsString(exc);

  EasyMock.expect(strategyBuildResult.getBuildResult())
      .andReturn(Futures.immediateFailedFuture(exc))
      .times(2);
  BuildResult localResult = successBuildResult("//local/did:though");
  EasyMock.expect(buildStrategyContext.runWithDefaultBehavior())
      .andReturn(Futures.immediateFuture(Optional.of(localResult)))
      .once();
  EasyMock.expect(buildStrategyContext.getExecutorService()).andReturn(directExecutor).once();
  EasyMock.expect(strategyBuildResult.getRuleContext()).andReturn(ruleContext);

  EasyMock.replay(strategyBuildResult, buildStrategyContext);
  FallbackStrategyBuildResult fallbackStrategyBuildResult =
      new FallbackStrategyBuildResult(
          RULE_NAME, strategyBuildResult, buildStrategyContext, eventBus, true, false, false);
  Assert.assertEquals(
      localResult.getStatus(),
      fallbackStrategyBuildResult.getBuildResult().get().get().getStatus());
  EasyMock.verify(strategyBuildResult, buildStrategyContext);

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(1);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
  Assert.assertEquals(finishedEvent.getExitCode(), OptionalInt.of(1));
  Assert.assertEquals(
      finishedEvent.getRemoteExecutionMetadata().get().getWorkerInfo().getHostname(), mockWorker);
}
 
Example #28
Source File: AddMerchantCenterDynamicRemarketingCampaign.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
  }
}
 
Example #29
Source File: AccountUpdateTransaction.java    From hedera-sdk-java with Apache License 2.0 4 votes vote down vote up
public AccountUpdateTransaction setReceiverSignatureRequired(boolean receiverSignatureRequired) {
    builder.setReceiverSigRequiredWrapper(BoolValue.of(receiverSignatureRequired));
    return this;
}
 
Example #30
Source File: CreateCompleteCampaignBothApisPhase3.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
  }
}