com.google.protobuf.DoubleValue Java Examples

The following examples show how to use com.google.protobuf.DoubleValue. 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: AddCampaignTargetingCriteria.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #2
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 #3
Source File: MetricsProtoUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static SummaryValue.Snapshot toSnapshotProto(
    io.opencensus.metrics.export.Summary.Snapshot snapshot) {
  SummaryValue.Snapshot.Builder builder = SummaryValue.Snapshot.newBuilder();
  if (snapshot.getSum() != null) {
    builder.setSum(DoubleValue.of(snapshot.getSum()));
  }
  if (snapshot.getCount() != null) {
    builder.setCount(Int64Value.of(snapshot.getCount()));
  }
  for (io.opencensus.metrics.export.Summary.Snapshot.ValueAtPercentile valueAtPercentile :
      snapshot.getValueAtPercentiles()) {
    builder.addPercentileValues(
        SummaryValue.Snapshot.ValueAtPercentile.newBuilder()
            .setValue(valueAtPercentile.getValue())
            .setPercentile(valueAtPercentile.getPercentile())
            .build());
  }
  return builder.build();
}
 
Example #4
Source File: GrpcModelConverters.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private static StepAdjustments toStepAdjustments(StepAdjustment stepAdjustment) {
    StepAdjustments.Builder stepAdjustmentsBuilder = StepAdjustments.newBuilder()
            .setScalingAdjustment(Int32Value.newBuilder()
                    .setValue(stepAdjustment.getScalingAdjustment())
                    .build());
    stepAdjustment.getMetricIntervalLowerBound().ifPresent(
            metricIntervalLowerBound ->
                    stepAdjustmentsBuilder.setMetricIntervalLowerBound(DoubleValue.newBuilder()
                            .setValue(metricIntervalLowerBound)
                            .build())
    );
    stepAdjustment.getMetricIntervalUpperBound().ifPresent(
            metricIntervalUpperBound ->
                    stepAdjustmentsBuilder.setMetricIntervalUpperBound(DoubleValue.newBuilder()
                            .setValue(metricIntervalUpperBound)
                            .build())
    );

    return stepAdjustmentsBuilder.build();
}
 
Example #5
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 #6
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 #7
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 #8
Source File: MetricsProtoUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static SummaryValue toSummaryProto(io.opencensus.metrics.export.Summary summary) {
  SummaryValue.Builder builder = SummaryValue.newBuilder();
  if (summary.getSum() != null) {
    builder.setSum(DoubleValue.of(summary.getSum()));
  }
  if (summary.getCount() != null) {
    builder.setCount(Int64Value.of(summary.getCount()));
  }
  builder.setSnapshot(toSnapshotProto(summary.getSnapshot()));
  return builder.build();
}
 
Example #9
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 #10
Source File: AutoScalingTestUtils.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static UpdatePolicyRequest generateUpdateStepScalingPolicyRequest(String policyRefId, double threshold) {
    ScalingPolicy scalingPolicy = generateStepPolicy();
    AlarmConfiguration alarmConfig = scalingPolicy.getStepPolicyDescriptor().getAlarmConfig().toBuilder().setThreshold(DoubleValue.newBuilder().setValue(threshold).build()).build();
    StepScalingPolicyDescriptor stepScalingPolicyDescriptor = scalingPolicy.getStepPolicyDescriptor().toBuilder().setAlarmConfig(alarmConfig).build();
    ScalingPolicy scalingPolicyToBeUpdated = scalingPolicy.toBuilder().setStepPolicyDescriptor(stepScalingPolicyDescriptor).build();
    UpdatePolicyRequest updatePolicyRequest = UpdatePolicyRequest.newBuilder().setPolicyId(ScalingPolicyID.newBuilder().setId(policyRefId).build())
            .setScalingPolicy(scalingPolicyToBeUpdated).build();
    return updatePolicyRequest;
}
 
Example #11
Source File: AutoScalingTestUtils.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static UpdatePolicyRequest generateUpdateTargetTrackingPolicyRequest(String policyRefId, double targetValue) {
    ScalingPolicy scalingPolicy = generateTargetPolicy();
    TargetTrackingPolicyDescriptor targetPolicyDescriptor = scalingPolicy.getTargetPolicyDescriptor();
    TargetTrackingPolicyDescriptor targetPolicyWithUpdatedValue = targetPolicyDescriptor.toBuilder().setTargetValue(DoubleValue.newBuilder().setValue(targetValue).build()).build();
    ScalingPolicy scalingPolicyTobeUpdated = scalingPolicy.toBuilder().setTargetPolicyDescriptor(targetPolicyWithUpdatedValue).build();
    UpdatePolicyRequest updatePolicyRequest = UpdatePolicyRequest.newBuilder().setPolicyId(ScalingPolicyID.newBuilder().setId(policyRefId).build())
            .setScalingPolicy(scalingPolicyTobeUpdated).build();
    return updatePolicyRequest;
}
 
Example #12
Source File: AddCampaignBidModifier.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.
 * @param campaignId the ID of the campaign where the bid modifier will be added.
 * @param bidModifier the value of the bid modifier to add.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, long campaignId, double bidModifier) {

  String campaignResourceName = ResourceNames.campaign(customerId, campaignId);

  // Constructs a campaign bid modifier.
  CampaignBidModifier campaignBidModifier =
      CampaignBidModifier.newBuilder()
          .setCampaign(StringValue.of(campaignResourceName))
          // Makes the bid modifier apply to call interactions.
          .setInteractionType(
              InteractionTypeInfo.newBuilder().setType(InteractionTypeEnum.InteractionType.CALLS))
          // Uses the specified bid modifier value.
          .setBidModifier(DoubleValue.of(bidModifier))
          .build();

  // Constructs an operation to create the campaign bid modifier.
  CampaignBidModifierOperation op =
      CampaignBidModifierOperation.newBuilder().setCreate(campaignBidModifier).build();

  // Sends the operation in a mutate request.
  try (CampaignBidModifierServiceClient agcServiceClient =
      googleAdsClient.getLatestVersion().createCampaignBidModifierServiceClient()) {
    MutateCampaignBidModifiersResponse response =
        agcServiceClient.mutateCampaignBidModifiers(
            Long.toString(customerId), ImmutableList.of(op));
    System.out.printf("Added %d campaign bid modifiers:%n", response.getResultsCount());
    for (MutateCampaignBidModifierResult result : response.getResultsList()) {
      System.out.printf("\t%s%n", result.getResourceName());
    }
  }
}
 
Example #13
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 #14
Source File: AddAdGroupBidModifier.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.
 * @param adGroupId the ID of the ad group.
 * @param bidModifier the bid modifier value to set
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, long adGroupId, double bidModifier) {

  // Creates an ad group bid modifier for mobile devices with the specified ad group ID and
  // bid modifier value.
  AdGroupBidModifier adGroupBidModifier =
      AdGroupBidModifier.newBuilder()
          .setAdGroup(
              StringValue.of(
                  AdGroupName.format(Long.toString(customerId), Long.toString(adGroupId))))
          .setBidModifier(DoubleValue.of(bidModifier))
          .setDevice(DeviceInfo.newBuilder().setType(Device.MOBILE))
          .build();

  // Creates an ad group bid modifier operation for creating an ad group bid modifier.
  AdGroupBidModifierOperation adGroupBidModifierOperation =
      AdGroupBidModifierOperation.newBuilder().setCreate(adGroupBidModifier).build();

  // Issues a mutate request to add the ad group bid modifier.
  try (AdGroupBidModifierServiceClient adGroupBidModifierServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupBidModifierServiceClient()) {
    MutateAdGroupBidModifiersResponse response =
        adGroupBidModifierServiceClient.mutateAdGroupBidModifiers(
            Long.toString(customerId), ImmutableList.of(adGroupBidModifierOperation));

    System.out.printf("Added %d ad group bid modifiers:%n", response.getResultsCount());
    for (MutateAdGroupBidModifierResult mutateAdGroupBidModifierResult :
        response.getResultsList()) {
      System.out.printf("\t%s%n", mutateAdGroupBidModifierResult.getResourceName());
    }
  }
}
 
Example #15
Source File: SetupRemarketing.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the bid modifier on an ad group criterion.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param adGroupCriterionResourceName the ad group criterion to update.
 * @param bidModifier the bid modifier.
 */
private void modifyAdGroupBids(
    GoogleAdsClient googleAdsClient,
    long customerId,
    String adGroupCriterionResourceName,
    double bidModifier) {
  // Creates the ad group criterion with a bid modifier. You may alternatively set the bid for
  // the ad group criterion directly.
  AdGroupCriterion adGroupCriterion =
      AdGroupCriterion.newBuilder()
          .setResourceName(adGroupCriterionResourceName)
          .setBidModifier(DoubleValue.of(bidModifier))
          .build();

  // Creates the update operation.
  AdGroupCriterionOperation operation =
      AdGroupCriterionOperation.newBuilder()
          .setUpdate(adGroupCriterion)
          .setUpdateMask(FieldMasks.allSetFieldsOf(adGroupCriterion))
          .build();

  // Creates the ad group criterion service.
  try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
    // Updates the ad group criterion.
    MutateAdGroupCriteriaResponse response =
        adGroupCriterionServiceClient.mutateAdGroupCriteria(
            Long.toString(customerId), ImmutableList.of(operation));
    // Prints the results.
    System.out.printf(
        "Successfully updated the bid for ad group criterion with resource name '%s'.%n",
        response.getResults(0).getResourceName());
  }
}
 
Example #16
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 #17
Source File: AggregatingAutoScalingServiceTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Test
public void createAndUpdatePolicyForJobIdFromTwoCells() {
    ScalingPolicyID policy1 = ScalingPolicyID.newBuilder().setId(POLICY_1).build();
    ScalingPolicyID policy2 = ScalingPolicyID.newBuilder().setId(POLICY_2).build();

    ScalingPolicyResult policyOneResult = ScalingPolicyResult.newBuilder().setId(policy1).setJobId(JOB_1).build();
    ScalingPolicyResult policyTwoResult = ScalingPolicyResult.newBuilder().setId(policy2).setJobId(JOB_2).build();

    CellWithPolicies cellOneService = new CellWithPolicies(Collections.singletonList(policyOneResult));
    CellWithPolicies cellTwoService = new CellWithPolicies(Collections.singletonList(policyTwoResult));

    CellWithJobIds cellOneJobsService = new CellWithJobIds(Collections.singletonList(JOB_1));
    CellWithJobIds cellTwoJobsService = new CellWithJobIds(Collections.singletonList(JOB_2));
    cellOne.getServiceRegistry().addService(cellOneService);
    cellOne.getServiceRegistry().addService(cellOneJobsService);
    cellTwo.getServiceRegistry().addService(cellTwoService);
    cellTwo.getServiceRegistry().addService(cellTwoJobsService);

    AssertableSubscriber<ScalingPolicyID> testSubscriber = service.setAutoScalingPolicy(PutPolicyRequest.newBuilder().setJobId(JOB_2).build(), JUNIT_REST_CALL_METADATA).test();
    testSubscriber.awaitValueCount(1, 1, TimeUnit.SECONDS);
    testSubscriber.assertNoErrors();

    List<ScalingPolicyID> onNextEvents = testSubscriber.getOnNextEvents();
    assertThat(onNextEvents).isNotNull();
    assertThat(onNextEvents.size()).isEqualTo(1);
    assertThat(onNextEvents.get(0).getId()).isNotEmpty();

    AssertableSubscriber<GetPolicyResult> testSubscriber2 = service.getJobScalingPolicies(JobId.newBuilder().setId(JOB_2).build(), JUNIT_REST_CALL_METADATA).test();
    testSubscriber2.awaitValueCount(1, 1, TimeUnit.SECONDS);

    List<GetPolicyResult> onNextEvents1 = testSubscriber2.getOnNextEvents();
    assertThat(onNextEvents1).isNotNull();
    assertThat(onNextEvents1.size()).isEqualTo(1);
    assertThat(onNextEvents1.get(0).getItemsCount()).isEqualTo(2);
    assertThat(onNextEvents1.get(0).getItems(0).getJobId()).isEqualTo(JOB_2);
    assertThat(onNextEvents1.get(0).getItems(1).getJobId()).isEqualTo(JOB_2);

    UpdatePolicyRequest updatePolicyRequest = UpdatePolicyRequest.newBuilder()
            .setPolicyId(ScalingPolicyID.newBuilder().setId(POLICY_2))
            .setScalingPolicy(ScalingPolicy.newBuilder()
                    .setTargetPolicyDescriptor(TargetTrackingPolicyDescriptor.newBuilder()
                            .setTargetValue(DoubleValue.newBuilder().setValue(100.0).build()).build()).build()).build();

    AssertableSubscriber<Void> testSubscriber3 = service.updateAutoScalingPolicy(updatePolicyRequest, JUNIT_REST_CALL_METADATA).test();
    testSubscriber3.assertNoErrors();

    AssertableSubscriber<GetPolicyResult> testSubscriber4 = service.getScalingPolicy(ScalingPolicyID.newBuilder().setId(POLICY_2).build(), JUNIT_REST_CALL_METADATA).test();
    testSubscriber2.awaitValueCount(1, 1, TimeUnit.SECONDS);

    List<GetPolicyResult> onNextEvents2 = testSubscriber4.getOnNextEvents();
    assertThat(onNextEvents2).isNotNull();
    assertThat(onNextEvents2.size()).isEqualTo(1);
    assertThat(onNextEvents2.get(0).getItemsCount()).isEqualTo(1);
    assertThat(onNextEvents2.get(0).getItems(0).getJobId()).isEqualTo(JOB_2);
    assertThat(onNextEvents2.get(0).getItems(0).getId().getId()).isEqualTo(POLICY_2);
    ScalingPolicy scalingPolicy = onNextEvents2.get(0).getItems(0).getScalingPolicy();
    double updatedValue = scalingPolicy.getTargetPolicyDescriptor().getTargetValue().getValue();
    assertThat(updatedValue).isEqualTo(100);
}
 
Example #18
Source File: UploadCallConversion.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param googleAdsClient the client.
 * @param customerId the customer ID.
 * @param conversionActionId the conversion action ID.
 * @param callerId the caller ID.
 * @param callStartDateTime the call start date time
 * @param conversionValue the value of the conversion in USD.
 */
private void runExample(
    GoogleAdsClient googleAdsClient,
    long customerId,
    String conversionActionId,
    String callerId,
    String callStartDateTime,
    double conversionValue) {
  // Create a call conversion by specifying currency as USD.
  CallConversion conversion =
      CallConversion.newBuilder()
          .setConversionAction(StringValue.of(conversionActionId))
          .setCallerId(StringValue.of(callerId))
          .setCallStartDateTime(StringValue.of(callStartDateTime))
          .setConversionValue(DoubleValue.of(conversionValue))
          .setCurrencyCode(StringValue.of("USD"))
          .build();

  // Uploads the call conversion to the API.
  try (ConversionUploadServiceClient conversionUploadServiceClient =
      googleAdsClient.getLatestVersion().createConversionUploadServiceClient()) {
    // Partial failure MUST be enabled for this request.
    UploadCallConversionsResponse response =
        conversionUploadServiceClient.uploadCallConversions(
            String.valueOf(customerId), ImmutableList.of(conversion), true, false);

    // Prints any partial failure errors returned.
    if (response.hasPartialFailureError()) {
      throw new RuntimeException(
          "Partial failure occurred " + response.getPartialFailureError().getMessage());
    }

    // Prints the result if valid.
    CallConversionResult result = response.getResults(0);
    System.out.printf(
        "Uploaded call conversion that occurred at '%' for caller ID '%' to the conversion"
            + " action with resource name '%'.%n",
        result.getCallStartDateTime().getValue(),
        result.getCallerId().getValue(),
        result.getConversionAction().getValue());
  }
}
 
Example #19
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 #20
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 #21
Source File: MetricsProtoUtilsTests.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void toMetricProto_Summary() {
  Metric metric = Metric.create(DESCRIPTOR_2, Collections.singletonList(TIME_SERIES_2));
  io.opencensus.proto.metrics.v1.Metric expected =
      io.opencensus.proto.metrics.v1.Metric.newBuilder()
          .setMetricDescriptor(
              io.opencensus.proto.metrics.v1.MetricDescriptor.newBuilder()
                  .setName(METRIC_NAME_2)
                  .setDescription(METRIC_DESCRIPTION)
                  .setUnit(UNIT)
                  .setType(io.opencensus.proto.metrics.v1.MetricDescriptor.Type.SUMMARY)
                  .addLabelKeys(
                      io.opencensus.proto.metrics.v1.LabelKey.newBuilder()
                          .setKey(KEY_1.getKey())
                          .setDescription(KEY_1.getDescription())
                          .build())
                  .addLabelKeys(
                      io.opencensus.proto.metrics.v1.LabelKey.newBuilder()
                          .setKey(KEY_2.getKey())
                          .setDescription(KEY_2.getDescription())
                          .build())
                  .build())
          .addTimeseries(
              io.opencensus.proto.metrics.v1.TimeSeries.newBuilder()
                  .setStartTimestamp(MetricsProtoUtils.toTimestampProto(TIMESTAMP_5))
                  .addLabelValues(
                      io.opencensus.proto.metrics.v1.LabelValue.newBuilder()
                          .setHasValue(true)
                          .setValue(VALUE_2.getValue())
                          .build())
                  .addLabelValues(
                      io.opencensus.proto.metrics.v1.LabelValue.newBuilder()
                          .setHasValue(false)
                          .build())
                  .addPoints(
                      io.opencensus.proto.metrics.v1.Point.newBuilder()
                          .setTimestamp(MetricsProtoUtils.toTimestampProto(TIMESTAMP_3))
                          .setSummaryValue(
                              SummaryValue.newBuilder()
                                  .setCount(Int64Value.of(5))
                                  .setSum(DoubleValue.of(45.0))
                                  .setSnapshot(
                                      SummaryValue.Snapshot.newBuilder()
                                          .setCount(Int64Value.of(3))
                                          .setSum(DoubleValue.of(25.0))
                                          .addPercentileValues(
                                              SummaryValue.Snapshot.ValueAtPercentile.newBuilder()
                                                  .setValue(11)
                                                  .setPercentile(0.4)
                                                  .build())
                                          .build())
                                  .build())
                          .build())
                  .build())
          .build();
  io.opencensus.proto.metrics.v1.Metric actual = MetricsProtoUtils.toMetricProto(metric, null);
  assertThat(actual).isEqualTo(expected);
}
 
Example #22
Source File: UploadConversionAdjustment.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param conversionActionId conversion action ID associated with this conversion.
 * @param gclid the GCLID for the conversion.
 * @param adjustmentType the type of adjustment, e.g. RETRACTION, RESTATEMENT.
 * @param conversionDateTime date and time of the conversion.
 * @param adjustmentDateTime date and time of the adjustment.
 * @param restatementValue the adjusted value for adjustment type RESTATEMENT.
 */
private void runExample(
    GoogleAdsClient googleAdsClient,
    long customerId,
    long conversionActionId,
    String gclid,
    String adjustmentType,
    String conversionDateTime,
    String adjustmentDateTime,
    @Nullable Float restatementValue) {
  // Gets the conversion adjustment enum value from the adjustmentType String.
  ConversionAdjustmentType conversionAdjustmentType =
      ConversionAdjustmentType.valueOf(adjustmentType);

  // Associates conversion adjustments with the existing conversion action.
  // The GCLID should have been uploaded before with a conversion.
  ConversionAdjustment conversionAdjustment =
      ConversionAdjustment.newBuilder()
          .setConversionAction(
              StringValue.of(ResourceNames.conversionAction(customerId, conversionActionId)))
          .setAdjustmentType(conversionAdjustmentType)
          .setGclidDateTimePair(
              GclidDateTimePair.newBuilder()
                  .setGclid(StringValue.of(gclid))
                  .setConversionDateTime(StringValue.of(conversionDateTime))
                  .build())
          .setAdjustmentDateTime(StringValue.of(adjustmentDateTime))
          .build();

  // Sets adjusted value for adjustment type RESTATEMENT.
  if (restatementValue != null
      && conversionAdjustmentType == ConversionAdjustmentType.RESTATEMENT) {
    conversionAdjustment =
        conversionAdjustment.toBuilder()
            .setRestatementValue(
                RestatementValue.newBuilder()
                    .setAdjustedValue(DoubleValue.of(restatementValue))
                    .build())
            .build();
  }

  // Creates the conversion upload service client.
  try (ConversionAdjustmentUploadServiceClient conversionUploadServiceClient =
      googleAdsClient.getLatestVersion().createConversionAdjustmentUploadServiceClient()) {
    // Uploads the click conversion. Partial failure should always be set to true.
    UploadConversionAdjustmentsResponse response =
        conversionUploadServiceClient.uploadConversionAdjustments(
            Long.toString(customerId),
            ImmutableList.of(conversionAdjustment),
            // Enables partial failure (must be true).
            true,
            // Disables validate only.
            false);

    // Prints any partial errors returned.
    if (response.hasPartialFailureError()) {
      System.out.printf(
          "Partial error encountered: '%s'.%n", response.getPartialFailureError().getMessage());
    } else {
      // Prints the result.
      ConversionAdjustmentResult result = response.getResults(0);
      System.out.printf(
          "Uploaded conversion adjustment of '%s' for Google Click ID '%s'.%n",
          result.getConversionAction().getValue(),
          result.getGclidDateTimePair().getGclid().getValue());
    }
  }
}
 
Example #23
Source File: MessageMarshallerTest.java    From curiostack with MIT License 4 votes vote down vote up
@Test
public void anyFields() throws Exception {
  TestAllTypes content = TestAllTypes.newBuilder().setOptionalInt32(1234).build();
  TestAny message = TestAny.newBuilder().setAnyValue(Any.pack(content)).build();
  assertMatchesUpstream(message, TestAllTypes.getDefaultInstance());

  TestAny messageWithDefaultAnyValue =
      TestAny.newBuilder().setAnyValue(Any.getDefaultInstance()).build();
  assertMatchesUpstream(messageWithDefaultAnyValue);

  // Well-known types have a special formatting when embedded in Any.
  //
  // 1. Any in Any.
  Any anyMessage = Any.pack(Any.pack(content));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 2. Wrappers in Any.
  anyMessage = Any.pack(Int32Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(UInt32Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(Int64Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(UInt64Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(FloatValue.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(DoubleValue.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(BoolValue.newBuilder().setValue(true).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(StringValue.newBuilder().setValue("Hello").build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage =
      Any.pack(BytesValue.newBuilder().setValue(ByteString.copyFrom(new byte[] {1, 2})).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 3. Timestamp in Any.
  anyMessage = Any.pack(Timestamps.parse("1969-12-31T23:59:59Z"));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 4. Duration in Any
  anyMessage = Any.pack(Durations.parse("12345.10s"));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 5. FieldMask in Any
  anyMessage = Any.pack(FieldMaskUtil.fromString("foo.bar,baz"));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 6. Struct in Any
  Struct.Builder structBuilder = Struct.newBuilder();
  structBuilder.putFields("number", Value.newBuilder().setNumberValue(1.125).build());
  anyMessage = Any.pack(structBuilder.build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 7. Value (number type) in Any
  Value.Builder valueBuilder = Value.newBuilder();
  valueBuilder.setNumberValue(1);
  anyMessage = Any.pack(valueBuilder.build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 8. Value (null type) in Any
  anyMessage = Any.pack(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
}
 
Example #24
Source File: AutoScalingResourceTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Test
public void createAndUpdatePolicyForJobIdFromTwoCells() {
    ScalingPolicyID policy1 = ScalingPolicyID.newBuilder().setId(POLICY_1).build();
    ScalingPolicyID policy2 = ScalingPolicyID.newBuilder().setId(POLICY_2).build();

    ScalingPolicyResult policyOneResult = ScalingPolicyResult.newBuilder().setId(policy1).setJobId(JOB_1).build();
    ScalingPolicyResult policyTwoResult = ScalingPolicyResult.newBuilder().setId(policy2).setJobId(JOB_2).build();

    CellWithPolicies cellOneService = new CellWithPolicies(Collections.singletonList(policyOneResult));
    CellWithPolicies cellTwoService = new CellWithPolicies(Collections.singletonList(policyTwoResult));

    CellWithJobIds cellOneJobsService = new CellWithJobIds(Collections.singletonList(JOB_1));
    CellWithJobIds cellTwoJobsService = new CellWithJobIds(Collections.singletonList(JOB_2));
    cellOne.getServiceRegistry().addService(cellOneService);
    cellOne.getServiceRegistry().addService(cellOneJobsService);
    cellTwo.getServiceRegistry().addService(cellTwoService);
    cellTwo.getServiceRegistry().addService(cellTwoJobsService);

    final AutoScalingResource autoScalingResource = new AutoScalingResource(service, callMetadataResolver);
    final ScalingPolicyID scalingPolicyID = autoScalingResource.setScalingPolicy(PutPolicyRequest.newBuilder().setJobId(JOB_2).build());

    assertThat(scalingPolicyID).isNotNull();
    assertThat(scalingPolicyID.getId()).isNotEmpty();

    final GetPolicyResult scalingPolicyForJob = autoScalingResource.getScalingPolicyForJob(JOB_2);
    assertThat(scalingPolicyForJob).isNotNull();
    assertThat(scalingPolicyForJob.getItemsCount()).isEqualTo(2);
    assertThat(scalingPolicyForJob.getItems(0).getJobId()).isEqualTo(JOB_2);
    assertThat(scalingPolicyForJob.getItems(1).getJobId()).isEqualTo(JOB_2);

    UpdatePolicyRequest updatePolicyRequest = UpdatePolicyRequest.newBuilder()
            .setPolicyId(ScalingPolicyID.newBuilder().setId(POLICY_2))
            .setScalingPolicy(ScalingPolicy.newBuilder()
                    .setTargetPolicyDescriptor(TargetTrackingPolicyDescriptor.newBuilder()
                            .setTargetValue(DoubleValue.newBuilder().setValue(100.0).build()).build()).build()).build();

    final Response updateScalingPolicyResponse = autoScalingResource.updateScalingPolicy(updatePolicyRequest);
    assertThat(updateScalingPolicyResponse.getStatus()).isEqualTo(200);

    final GetPolicyResult updatedScalingPolicy = autoScalingResource.getScalingPolicy(POLICY_2);
    assertThat(updatedScalingPolicy.getItemsCount()).isEqualTo(1);
    assertThat(updatedScalingPolicy.getItems(0).getJobId()).isEqualTo(JOB_2);
    assertThat(updatedScalingPolicy.getItems(0).getId().getId()).isEqualTo(POLICY_2);
    final DoubleValue targetValue = updatedScalingPolicy.getItems(0).getScalingPolicy().getTargetPolicyDescriptor().getTargetValue();
    assertThat(targetValue.getValue()).isEqualTo(100.0);
}
 
Example #25
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 #26
Source File: UploadOfflineConversion.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param conversionActionId conversion action ID associated with this conversion.
 * @param gclid the GCLID for the conversion.
 * @param conversionDateTime date and time of the conversion.
 * @param conversionValue the value of the conversion.
 */
private void runExample(
    GoogleAdsClient googleAdsClient,
    long customerId,
    long conversionActionId,
    String gclid,
    String conversionDateTime,
    Double conversionValue) {
  // Gets the conversion action resource name.
  String conversionActionResourceName =
      ResourceNames.conversionAction(customerId, conversionActionId);

  // Creates the click conversion.
  ClickConversion clickConversion =
      ClickConversion.newBuilder()
          .setConversionAction(StringValue.of(conversionActionResourceName))
          .setConversionDateTime(StringValue.of(conversionDateTime))
          .setConversionValue(DoubleValue.of(conversionValue))
          .setCurrencyCode(StringValue.of("USD"))
          .setGclid(StringValue.of(gclid))
          .build();

  // Creates the conversion upload service client.
  try (ConversionUploadServiceClient conversionUploadServiceClient =
      googleAdsClient.getLatestVersion().createConversionUploadServiceClient()) {
    // Uploads the click conversion. Partial failure should always be set to true.
    UploadClickConversionsResponse response =
        conversionUploadServiceClient.uploadClickConversions(
            Long.toString(customerId),
            ImmutableList.of(clickConversion),
            // Enables partial failure (must be true).
            true,
            // Disables validate only.
            false);

    // Prints any partial errors returned.
    if (response.hasPartialFailureError()) {
      System.out.printf(
          "Partial error encountered: '%s'.%n", response.getPartialFailureError().getMessage());
    }

    // Prints the result.
    ClickConversionResult result = response.getResults(0);
    // Only prints valid results.
    if (result.hasGclid()) {
      System.out.printf(
          "Uploaded conversion that occurred at '%s' from Google Click ID '%s' to '%s'.%n",
          result.getConversionDateTime().getValue(),
          result.getGclid().getValue(),
          result.getConversionAction().getValue());
    }
  }
}
 
Example #27
Source File: AddHotelAdGroupBidModifiers.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param adGroupId the ID of the ad group.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
  List<AdGroupBidModifierOperation> operations = new ArrayList<>();

  // Constructs the ad group resource name to use for each bid modifier.
  String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);

  // 1) Creates an ad group bid modifier based on the hotel check-in day.
  AdGroupBidModifier checkInDayAdGroupBidModifier =
      AdGroupBidModifier.newBuilder()
          // Sets the resource name to the ad group resource name joined with the criterion ID
          // whose value corresponds to the desired check-in day.
          .setAdGroup(StringValue.of(adGroupResourceName))
          .setHotelCheckInDay(HotelCheckInDayInfo.newBuilder().setDayOfWeek(DayOfWeek.MONDAY))
          // Sets the bid modifier value to 150%.
          .setBidModifier(DoubleValue.of(1.5d))
          .build();
  operations.add(
      AdGroupBidModifierOperation.newBuilder().setCreate(checkInDayAdGroupBidModifier).build());

  // 2) Creates an ad group bid modifier based on the hotel length of stay.
  AdGroupBidModifier lengthOfStayAdGroupBidModifier =
      AdGroupBidModifier.newBuilder()
          // Sets the ad group.
          .setAdGroup(StringValue.of(adGroupResourceName))
          // Creates the hotel length of stay info.
          .setHotelLengthOfStay(
              HotelLengthOfStayInfo.newBuilder()
                  .setMinNights(Int64Value.of(3L))
                  .setMaxNights(Int64Value.of(7L))
                  .build())
          // Sets the bid modifier value to 170%.
          .setBidModifier(DoubleValue.of(1.7d))
          .build();
  operations.add(
      AdGroupBidModifierOperation.newBuilder().setCreate(lengthOfStayAdGroupBidModifier).build());

  // Issues a mutate request to add the ad group bid modifiers.
  try (AdGroupBidModifierServiceClient adGroupBidModifierServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupBidModifierServiceClient()) {
    MutateAdGroupBidModifiersResponse response =
        adGroupBidModifierServiceClient.mutateAdGroupBidModifiers(
            Long.toString(customerId), operations);

    // Prints the resource names of the added ad group bid modifiers.
    System.out.printf("Added %d hotel ad group bid modifiers:%n", response.getResultsCount());
    for (MutateAdGroupBidModifierResult mutateAdGroupBidModifierResult :
        response.getResultsList()) {
      System.out.printf("  %s%n", mutateAdGroupBidModifierResult.getResourceName());
    }
  }
}
 
Example #28
Source File: AddShoppingSmartAd.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new shopping campaign for Smart Shopping ads 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 merchantCenterAccountId the Merchant Center account ID.
 * @return resource name of the newly created campaign.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private String addSmartShoppingCampaign(
    GoogleAdsClient googleAdsClient,
    long customerId,
    String budgetResourceName,
    long merchantCenterAccountId) {

  // Configures the shopping settings for Smart Shopping campaigns.
  ShoppingSetting shoppingSetting =
      ShoppingSetting.newBuilder()
          // Sets the sales country of products to include in the campaign.
          // Only products from Merchant Center targeting this country will appear in the
          // campaign.
          .setSalesCountry(StringValue.of("US"))
          .setMerchantId(Int64Value.of(merchantCenterAccountId))
          .build();

  // Creates the campaign.
  Campaign campaign =
      Campaign.newBuilder()
          .setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
          // Configures settings related to shopping campaigns including advertising channel type,
          // advertising sub-type and shopping setting.
          .setAdvertisingChannelType(AdvertisingChannelType.SHOPPING)
          .setAdvertisingChannelSubType(AdvertisingChannelSubType.SHOPPING_SMART_ADS)
          .setShoppingSetting(shoppingSetting)
          // 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)
          // Bidding strategy must be set directly on the campaign.
          // Setting a portfolio bidding strategy by resourceName is not supported.
          // Maximize conversion value is the only strategy supported for Smart Shopping
          // campaigns.
          // An optional ROAS (Return on Advertising Spend) can be set for
          // MaximizeConversionValue.
          // The ROAS value must be specified as a ratio in the API. It is calculated by dividing
          // "total value" by "total spend".
          // For more information on maximize conversion value, see the support article:
          // http://support.google.com/google-ads/answer/7684216)
          .setMaximizeConversionValue(
              MaximizeConversionValue.newBuilder().setTargetRoas(DoubleValue.of(3.5)).build())
          // Sets the budget.
          .setCampaignBudget(StringValue.of(budgetResourceName))
          .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()) {
    MutateCampaignResult result =
        campaignServiceClient
            .mutateCampaigns(Long.toString(customerId), Collections.singletonList(operation))
            .getResults(0);
    System.out.printf(
        "Added a Smart Shopping campaign with resource name: '%s'%n", result.getResourceName());
    return result.getResourceName();
  }
}
 
Example #29
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 4 votes vote down vote up
DoubleValueMarshaller() {
  super(DoubleValue.getDefaultInstance());
}
 
Example #30
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 4 votes vote down vote up
@Override
protected final void doMerge(JsonParser parser, int unused, Message.Builder messageBuilder)
    throws IOException {
  DoubleValue.Builder builder = (DoubleValue.Builder) messageBuilder;
  builder.setValue(ParseSupport.parseDouble(parser));
}