com.google.protobuf.Int64Value Java Examples

The following examples show how to use com.google.protobuf.Int64Value. 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: 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 #2
Source File: GoogleCloudStorageGrpcWriteChannelTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void writeUsesMetaGenerationIfProvided() throws Exception {
  AsyncWriteChannelOptions options = AsyncWriteChannelOptions.builder().build();
  ObjectWriteConditions writeConditions =
      new ObjectWriteConditions(Optional.absent(), Optional.of(1L));
  GoogleCloudStorageGrpcWriteChannel writeChannel =
      newWriteChannel(options, writeConditions, Optional.absent());

  ByteString data = ByteString.copyFromUtf8("test data");
  writeChannel.initialize();
  writeChannel.write(data.asReadOnlyByteBuffer());
  writeChannel.close();

  StartResumableWriteRequest.Builder expectedRequestBuilder = START_REQUEST.toBuilder();
  expectedRequestBuilder
      .getInsertObjectSpecBuilder()
      .setIfMetagenerationMatch(Int64Value.newBuilder().setValue(1L));
  verify(fakeService, times(1)).startResumableWrite(eq(expectedRequestBuilder.build()), any());
}
 
Example #3
Source File: GoogleCloudStorageGrpcWriteChannelTest.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void writeUsesContentGenerationIfProvided() throws Exception {
  AsyncWriteChannelOptions options = AsyncWriteChannelOptions.builder().build();
  ObjectWriteConditions writeConditions =
      new ObjectWriteConditions(Optional.of(1L), Optional.absent());
  GoogleCloudStorageGrpcWriteChannel writeChannel =
      newWriteChannel(options, writeConditions, Optional.absent());

  ByteString data = ByteString.copyFromUtf8("test data");
  writeChannel.initialize();
  writeChannel.write(data.asReadOnlyByteBuffer());
  writeChannel.close();

  StartResumableWriteRequest.Builder expectedRequestBuilder = START_REQUEST.toBuilder();
  expectedRequestBuilder
      .getInsertObjectSpecBuilder()
      .setIfGenerationMatch(Int64Value.newBuilder().setValue(1L));
  verify(fakeService, times(1)).startResumableWrite(eq(expectedRequestBuilder.build()), any());
}
 
Example #4
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 #5
Source File: RemoveFlightsFeedItemStringAttributeValue.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Removes a feed item attribute value.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @param feedAttributes a Map containing the FlightPlaceholderField and FeedAttribute.
 * @param feedItemResourceName the resource name of the feedItem to be updated.
 * @param flightPlaceholderField the placeholder type for the attribute to be removed.
 */
private FeedItem removeAttributeValueFromFeedItem(
    GoogleAdsClient googleAdsClient,
    long customerId,
    Map<FlightPlaceholderField, FeedAttribute> feedAttributes,
    String feedItemResourceName,
    FlightPlaceholderField flightPlaceholderField) {
  // Gets the ID of the FeedAttribute for the placeholder field and converts to an integer.
  long attributeId = feedAttributes.get(flightPlaceholderField).getId().getValue();

  // Retrieves the feed item and its associated attributes based on its resource name.
  FeedItem feedItem = getFeedItem(googleAdsClient, customerId, feedItemResourceName);
  // Creates the FeedItemAttributeValue that will be updated.
  FeedItemAttributeValue feedItemAttributeValue =
      FeedItemAttributeValue.newBuilder().setFeedAttributeId(Int64Value.of(attributeId)).build();
  // Gets the index of the attribute value that will be removed.
  int attributeIndex = getAttributeIndex(feedItem, feedItemAttributeValue);

  // Returns the feed item with the removed FeedItemAttributeValue. Any FeedItemAttributeValues
  // that are not included in the updated FeedItem will be removed from the FeedItem, which is
  // why you must create the FeedItem from the existing FeedItem and set the field(s) that will
  // be removed.
  return feedItem.toBuilder().removeAttributeValues(attributeIndex).build();
}
 
Example #6
Source File: MessageMarshallerTest.java    From curiostack with MIT License 6 votes vote down vote up
@Test
public void anyInMaps() throws Exception {
  TestAny.Builder testAny = TestAny.newBuilder();
  testAny.putAnyMap("int32_wrapper", Any.pack(Int32Value.newBuilder().setValue(123).build()));
  testAny.putAnyMap("int64_wrapper", Any.pack(Int64Value.newBuilder().setValue(456).build()));
  testAny.putAnyMap("timestamp", Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")));
  testAny.putAnyMap("duration", Any.pack(Durations.parse("12345.1s")));
  testAny.putAnyMap("field_mask", Any.pack(FieldMaskUtil.fromString("foo.bar,baz")));
  Value numberValue = Value.newBuilder().setNumberValue(1.125).build();
  Struct.Builder struct = Struct.newBuilder();
  struct.putFields("number", numberValue);
  testAny.putAnyMap("struct", Any.pack(struct.build()));
  Value nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();
  testAny.putAnyMap(
      "list_value",
      Any.pack(ListValue.newBuilder().addValues(numberValue).addValues(nullValue).build()));
  testAny.putAnyMap("number_value", Any.pack(numberValue));
  testAny.putAnyMap("any_value_number", Any.pack(Any.pack(numberValue)));
  testAny.putAnyMap("any_value_default", Any.pack(Any.getDefaultInstance()));
  testAny.putAnyMap("default", Any.getDefaultInstance());

  assertMatchesUpstream(testAny.build(), TestAllTypes.getDefaultInstance());
}
 
Example #7
Source File: AddPrices.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new price offer with the specified parameters.
 *
 * @param header the headline for the price extension.
 * @param description a detailed description line that may show on the price extension.
 * @param priceInMicros the price to display, measured in micros (e.g. 1_000_000 micros = 1 USD).
 * @param currencyCode the currency code representing the unit of currency.
 * @param unit optionally set a unit describing the quantity obtained for the price.
 * @param finalUrl the final URL to which a click on the price extension drives traffic.
 * @param finalMobileUrl the final URL to which mobile clicks on the price extension drives
 *     traffic.
 * @return a newly created price offer object.
 */
private PriceOffer createPriceOffer(
    String header,
    String description,
    int priceInMicros,
    String currencyCode,
    PriceExtensionPriceUnit unit,
    String finalUrl,
    String finalMobileUrl) {
  PriceOffer.Builder priceBuilder =
      PriceOffer.newBuilder()
          .setHeader(StringValue.of(header))
          .setDescription(StringValue.of(description))
          .addFinalUrls(StringValue.of(finalUrl))
          .setPrice(
              Money.newBuilder()
                  .setAmountMicros(Int64Value.of(priceInMicros))
                  .setCurrencyCode(StringValue.of(currencyCode)))
          .setUnit(unit);

  // Optional: Sets the final mobile URLs.
  if (finalMobileUrl != null) {
    priceBuilder.addFinalMobileUrls(StringValue.of(finalMobileUrl));
  }
  return priceBuilder.build();
}
 
Example #8
Source File: AddShoppingProductListingGroupTree.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new criterion containing a biddable unit listing group node.
 *
 * @param customerId the client customer ID.
 * @param adGroupId the ID of the ad group.
 * @param parentAdGroupCriterionResourceName the resource name of the parent of this criterion.
 * @param listingDimensionInfo the ListingDimensionInfo to be set for this listing group.
 * @param cpcBidMicros the CPC bid for items in this listing group. This value should be specified
 *     in micros.
 * @return the ad group criterion object that contains the biddable unit listing group node.
 */
private AdGroupCriterion createListingGroupUnitBiddable(
    long customerId,
    long adGroupId,
    String parentAdGroupCriterionResourceName,
    ListingDimensionInfo listingDimensionInfo,
    long cpcBidMicros) {

  String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
  // Note: There are two approaches for creating new unit nodes:
  // (1) Set the ad group resource name on the criterion (no temporary ID required).
  // (2) Use a temporary ID to construct the criterion resource name and set it using
  // setResourceName.
  // In both cases you must set the parentAdGroupCriterionResourceName on the listing
  // group for non-root nodes.
  // This example demonstrates method (1).
  AdGroupCriterion adGroupCriterion =
      AdGroupCriterion.newBuilder()
          // The ad group the listing group will be attached to.
          .setAdGroup(StringValue.of(adGroupResourceName))
          .setStatus(AdGroupCriterionStatus.ENABLED)
          .setListingGroup(
              ListingGroupInfo.newBuilder()
                  // Sets the type as a UNIT, which will allow the group to be biddable.
                  .setType(ListingGroupType.UNIT)
                  // Sets the ad group criterion resource name for the parent listing group.
                  // This can include a temporary ID if the parent criterion is not yet created.
                  // Use StringValue to convert from a String to a compatible argument type.
                  .setParentAdGroupCriterion(StringValue.of(parentAdGroupCriterionResourceName))
                  // Case values contain the listing dimension used for the node.
                  .setCaseValue(listingDimensionInfo)
                  .build())
          // Sets the bid for this listing group unit.
          // This will be used as the CPC bid for items that are included in this listing group
          .setCpcBidMicros(Int64Value.of(cpcBidMicros))
          .build();

  return adGroupCriterion;
}
 
Example #9
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 #10
Source File: ChannelzProtoUtil.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
static SocketData extractSocketData(SocketStats socketStats) {
  SocketData.Builder builder = SocketData.newBuilder();
  if (socketStats.data != null) {
    TransportStats s = socketStats.data;
    builder
        .setStreamsStarted(s.streamsStarted)
        .setStreamsSucceeded(s.streamsSucceeded)
        .setStreamsFailed(s.streamsFailed)
        .setMessagesSent(s.messagesSent)
        .setMessagesReceived(s.messagesReceived)
        .setKeepAlivesSent(s.keepAlivesSent)
        .setLastLocalStreamCreatedTimestamp(
            Timestamps.fromNanos(s.lastLocalStreamCreatedTimeNanos))
        .setLastRemoteStreamCreatedTimestamp(
            Timestamps.fromNanos(s.lastRemoteStreamCreatedTimeNanos))
        .setLastMessageSentTimestamp(
            Timestamps.fromNanos(s.lastMessageSentTimeNanos))
        .setLastMessageReceivedTimestamp(
            Timestamps.fromNanos(s.lastMessageReceivedTimeNanos))
        .setLocalFlowControlWindow(
            Int64Value.of(s.localFlowControlWindow))
        .setRemoteFlowControlWindow(
            Int64Value.of(s.remoteFlowControlWindow));
  }
  builder.addAllOption(toSocketOptionsList(socketStats.socketOptions));
  return builder.build();
}
 
Example #11
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 #12
Source File: GrpcModelConverters.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static StepScalingPolicy toStepScalingPolicy(StepScalingPolicyConfiguration stepScalingPolicyConfiguration) {
    StepScalingPolicy.Builder stepScalingPolicyBuilder = StepScalingPolicy.newBuilder();

    stepScalingPolicyConfiguration.getCoolDownSec().ifPresent(
            coolDown ->
                    stepScalingPolicyBuilder.setCooldownSec(Int32Value.newBuilder().setValue(coolDown).build())
    );
    stepScalingPolicyConfiguration.getMetricAggregationType().ifPresent(
            metricAggregationType ->
                    stepScalingPolicyBuilder.setMetricAggregationType(toMetricAggregationType(metricAggregationType))
    );
    stepScalingPolicyConfiguration.getAdjustmentType().ifPresent(
            stepAdjustmentType ->
                    stepScalingPolicyBuilder.setAdjustmentType(toAdjustmentType(stepAdjustmentType))
    );
    stepScalingPolicyConfiguration.getMinAdjustmentMagnitude().ifPresent(
            minAdjustmentMagnitude ->
                    stepScalingPolicyBuilder.setMinAdjustmentMagnitude(
                            Int64Value.newBuilder()
                                    .setValue(minAdjustmentMagnitude)
                                    .build())
    );
    stepScalingPolicyBuilder.addAllStepAdjustments(toStepAdjustmentsList(stepScalingPolicyConfiguration.getSteps()));

    return stepScalingPolicyBuilder
            .build();
}
 
Example #13
Source File: UpdateAdGroup.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 to update.
 * @param bidMicroAmount the bid amount in micros to use for the ad group bid.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, long adGroupId, long bidMicroAmount) {
  try (AdGroupServiceClient adGroupServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
    // Creates an ad group object with the proper resource name and any other changes.
    AdGroup adGroup =
        AdGroup.newBuilder()
            .setResourceName(ResourceNames.adGroup(customerId, adGroupId))
            .setCpcBidMicros(Int64Value.of(bidMicroAmount))
            .setStatus(AdGroupStatus.PAUSED)
            .build();
    // Constructs an operation that will update the ad group, using the FieldMasks utility to
    // derive the update mask. This mask tells the Google Ads API which attributes of the
    // ad group you want to change.
    AdGroupOperation operation =
        AdGroupOperation.newBuilder()
            .setUpdate(adGroup)
            .setUpdateMask(FieldMasks.allSetFieldsOf(adGroup))
            .build();
    // Sends the operation in a mutate request.
    MutateAdGroupsResponse response =
        adGroupServiceClient.mutateAdGroups(
            Long.toString(customerId), ImmutableList.of(operation));
    // Prints the resource name of each updated object.
    for (MutateAdGroupResult mutateAdGroupResult : response.getResultsList()) {
      System.out.printf(
          "Updated ad group with resourceName: '%s'.%n", mutateAdGroupResult.getResourceName());
    }
  }
}
 
Example #14
Source File: AvroToProtoSchema.java    From metastore with Apache License 2.0 5 votes vote down vote up
public ProtoDomain get() {
  rootNamespace = root.path("namespace").asText();

  protoMessageOf(root);

  Map<String, FileDescriptorProto.Builder> fileMap = new HashMap<>();

  messageMap.forEach(
      (fullName, message) -> {
        String packageName =
            fullName.substring(0, fullName.length() - message.getName().length() - 1);
        FileDescriptorProto.Builder fdp = fileMap.get(packageName);
        if (fdp == null) {
          fdp =
              DescriptorProtos.FileDescriptorProto.newBuilder()
                  .setName(packageNameToFileName(packageName))
                  .setPackage(packageName)
                  .setSyntax("proto3");
          fileMap.put(packageName, fdp);
        }
        fdp.addMessageType(message);
      });

  DescriptorProtos.FileDescriptorSet.Builder fds =
      DescriptorProtos.FileDescriptorSet.newBuilder();
  fileMap.forEach(
      (name, fdp) -> {
        Set<String> imports = importMap.get(fdp.getPackage());
        if (imports != null) {
          imports.forEach(im -> fdp.addDependency(im));
        }

        fds.addFile(fdp);
      });
  fds.addFile(Int64Value.getDescriptor().getFile().toProto());

  return ProtoDomain.buildFrom(fds.build());
}
 
Example #15
Source File: AddCustomerMatchUserList.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Customer Match user list.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the client customer ID.
 * @return the resource name of the newly created user list.
 */
private String createCustomerMatchUserList(GoogleAdsClient googleAdsClient, long customerId) {
  // Creates the new user list.
  UserList userList =
      UserList.newBuilder()
          .setName(StringValue.of("Customer Match list #" + System.currentTimeMillis()))
          .setDescription(
              StringValue.of("A list of customers that originated from email addresses"))
          // Customer Match user lists can use a membership life span of 10,000 to indicate
          // unlimited; otherwise normal values apply.
          // Sets the membership life span to 30 days.
          .setMembershipLifeSpan(Int64Value.of(30))
          // Sets the upload key type to indicate the type of identifier that will be used to
          // add users to the list. This field is immutable and required for an ADD operation.
          .setCrmBasedUserList(
              CrmBasedUserListInfo.newBuilder()
                  .setUploadKeyType(CustomerMatchUploadKeyType.CONTACT_INFO))
          .build();

  // Creates the operation.
  UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();

  // Creates the service client.
  try (UserListServiceClient userListServiceClient =
      googleAdsClient.getLatestVersion().createUserListServiceClient()) {
    // Adds the user list.
    MutateUserListsResponse response =
        userListServiceClient.mutateUserLists(
            Long.toString(customerId), ImmutableList.of(operation));
    // Prints the response.
    System.out.printf(
        "Created Customer Match user list with resource name: %s.%n",
        response.getResults(0).getResourceName());
    return response.getResults(0).getResourceName();
  }
}
 
Example #16
Source File: ChannelzProtoUtil.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
static SocketData extractSocketData(SocketStats socketStats) {
  SocketData.Builder builder = SocketData.newBuilder();
  if (socketStats.data != null) {
    TransportStats s = socketStats.data;
    builder
        .setStreamsStarted(s.streamsStarted)
        .setStreamsSucceeded(s.streamsSucceeded)
        .setStreamsFailed(s.streamsFailed)
        .setMessagesSent(s.messagesSent)
        .setMessagesReceived(s.messagesReceived)
        .setKeepAlivesSent(s.keepAlivesSent)
        .setLastLocalStreamCreatedTimestamp(
            Timestamps.fromNanos(s.lastLocalStreamCreatedTimeNanos))
        .setLastRemoteStreamCreatedTimestamp(
            Timestamps.fromNanos(s.lastRemoteStreamCreatedTimeNanos))
        .setLastMessageSentTimestamp(
            Timestamps.fromNanos(s.lastMessageSentTimeNanos))
        .setLastMessageReceivedTimestamp(
            Timestamps.fromNanos(s.lastMessageReceivedTimeNanos))
        .setLocalFlowControlWindow(
            Int64Value.of(s.localFlowControlWindow))
        .setRemoteFlowControlWindow(
            Int64Value.of(s.remoteFlowControlWindow));
  }
  builder.addAllOption(toSocketOptionsList(socketStats.socketOptions));
  return builder.build();
}
 
Example #17
Source File: CreateCampaignExperiment.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an experiment by issuing an asynchronous operation and immediately blocking to get the
 * result.
 *
 * @param googleAdsClient the API client to use.
 * @param customerId the customer ID to operate on.
 * @param baseCampaignId the original campaign ID.
 * @param draftId the draft campaign ID.
 * @return a newly created experiment.
 */
private CreateCampaignExperimentMetadata createExperiment(
    GoogleAdsClient googleAdsClient, long customerId, long baseCampaignId, long draftId) {
  // Defines the experiment to be created.
  CampaignExperiment experiment =
      CampaignExperiment.newBuilder()
          .setCampaignDraft(
              StringValue.of(ResourceNames.campaignDraft(customerId, baseCampaignId, draftId)))
          .setName(StringValue.of("Campaign experiment #" + System.currentTimeMillis()))
          .setTrafficSplitPercent(Int64Value.of(50))
          .setTrafficSplitType(CampaignExperimentTrafficSplitType.RANDOM_QUERY)
          .build();

  // Creates an API service client.
  try (CampaignExperimentServiceClient campaignExperimentServiceClient =
      googleAdsClient.getLatestVersion().createCampaignExperimentServiceClient()) {
    // Issues the create request.
    OperationFuture<Empty, CreateCampaignExperimentMetadata> campaignExperimentAsync =
        campaignExperimentServiceClient.createCampaignExperimentAsync(
            String.valueOf(customerId), experiment);

    // Block on the long running (i.e. async) operation result.
    try {
      return campaignExperimentAsync.getMetadata().get();
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException("Create operation failed", e);
    }
  }
}
 
Example #18
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 #19
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 #20
Source File: SetAdParameters.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 ad group ID.
 * @param criterionId criterion ID.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, long adGroupId, long criterionId) {
  String adGroupCriterionResourceName =
      ResourceNames.adGroupCriterion(customerId, adGroupId, criterionId);

  // Creates ad parameters.
  // There can be a maximum of two AdParameters per ad group criterion.
  // (One with parameter_index = 1 and one with parameter_index = 2.)
  AdParameter adParameter1 =
      AdParameter.newBuilder()
          .setAdGroupCriterion(StringValue.of(adGroupCriterionResourceName))
          // The unique index of this ad parameter. Must be either 1 or 2.
          .setParameterIndex(Int64Value.of(1))
          // String containing a numeric value to insert into the ad text.
          // The following restrictions apply: (a) can use comma or period as a separator,
          // with an optional period or comma (respectively) for fractional values,
          // (b) can be prepended or appended with a currency code, (c) can use plus or minus,
          // (d) can use '/' between two numbers.
          .setInsertionText(StringValue.of("100"))
          .build();

  AdParameter adParameter2 =
      AdParameter.newBuilder()
          .setAdGroupCriterion(StringValue.of(adGroupCriterionResourceName))
          .setParameterIndex(Int64Value.of(2))
          .setInsertionText(StringValue.of("$40"))
          .build();

  List<AdParameterOperation> operations = new ArrayList<>();
  operations.add(AdParameterOperation.newBuilder().setCreate(adParameter1).build());
  operations.add(AdParameterOperation.newBuilder().setCreate(adParameter2).build());

  try (AdParameterServiceClient adParameterServiceClient =
      googleAdsClient.getLatestVersion().createAdParameterServiceClient()) {
    MutateAdParametersResponse response =
        adParameterServiceClient.mutateAdParameters(Long.toString(customerId), operations);
    System.out.printf("Set %d ad params:%n", response.getResultsCount());
    for (MutateAdParameterResult result : response.getResultsList()) {
      System.out.println(result.getResourceName());
    }
  }
}
 
Example #21
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 #22
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 #23
Source File: AddDynamicPageFeed.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a feed mapping for a given feed.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the customer ID.
 * @param feedDetails a map of the names and IDs of feed attributes.
 * @param feedResourceName the resource name of the feed.
 */
private static void createFeedMapping(
    GoogleAdsClient googleAdsClient,
    long customerId,
    Map<String, Long> feedDetails,
    String feedResourceName) {
  // Maps the feed attribute IDs to the field ID constants.
  AttributeFieldMapping urlFieldMapping =
      AttributeFieldMapping.newBuilder()
          .setFeedAttributeId(Int64Value.of(feedDetails.get("Page URL")))
          .setDsaPageFeedField(DsaPageFeedCriterionField.PAGE_URL)
          .build();

  AttributeFieldMapping labelFieldMapping =
      AttributeFieldMapping.newBuilder()
          .setFeedAttributeId(Int64Value.of(feedDetails.get("Label")))
          .setDsaPageFeedField(DsaPageFeedCriterionField.LABEL)
          .build();

  // Creates the feed mapping.
  FeedMapping feedMapping =
      FeedMapping.newBuilder()
          .setCriterionType(FeedMappingCriterionType.DSA_PAGE_FEED)
          .setFeed(StringValue.of(feedResourceName))
          .addAllAttributeFieldMappings(ImmutableList.of(urlFieldMapping, labelFieldMapping))
          .build();

  // Creates the operation.
  FeedMappingOperation operation =
      FeedMappingOperation.newBuilder().setCreate(feedMapping).build();

  // Creates the service client.
  try (FeedMappingServiceClient feedMappingServiceClient =
      googleAdsClient.getLatestVersion().createFeedMappingServiceClient()) {
    // Adds the feed mapping.
    MutateFeedMappingsResponse response =
        feedMappingServiceClient.mutateFeedMappings(
            Long.toString(customerId), ImmutableList.of(operation));
    // Displays the results.
    System.out.printf(
        "Created feed maping with resource name '%s'.%n",
        response.getResults(0).getResourceName());
  }
}
 
Example #24
Source File: AddDynamicPageFeed.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates feed items for a given feed.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the customer ID.
 * @param feedDetails a map of the names and IDs of feed attributes.
 * @param feedResourceName the resource name of the feed.
 * @param dsaPageUrlLabel the label for the DSA page URLs.
 */
private static void createFeedItems(
    GoogleAdsClient googleAdsClient,
    long customerId,
    Map<String, Long> feedDetails,
    String feedResourceName,
    String dsaPageUrlLabel) {
  List<String> urls =
      ImmutableList.of(
          "http://www.example.com/discounts/rental-cars",
          "http://www.example.com/discounts/hotel-deals",
          "http://www.example.com/discounts/flight-deals");

  // Creates a value for the label attribute.
  FeedItemAttributeValue labelAttributeValue =
      FeedItemAttributeValue.newBuilder()
          .setFeedAttributeId(Int64Value.of(feedDetails.get("Label")))
          .addAllStringValues(
              ImmutableList.of(StringValue.newBuilder().setValue(dsaPageUrlLabel).build()))
          .build();

  // Creates one operation per URL.
  List<FeedItemOperation> feedItemOperations = new ArrayList<>();
  for (String url : urls) {
    // Creates a url attribute.
    FeedItemAttributeValue urlAttributeValue =
        FeedItemAttributeValue.newBuilder()
            .setFeedAttributeId(Int64Value.of(feedDetails.get("Page URL")))
            .addAllStringValues(ImmutableList.of(StringValue.newBuilder().setValue(url).build()))
            .build();

    // Creates a feed item.
    FeedItem feedItem =
        FeedItem.newBuilder()
            .setFeed(StringValue.of(feedResourceName))
            .addAllAttributeValues(ImmutableList.of(urlAttributeValue, labelAttributeValue))
            .build();

    // Creates an operation and adds it to the list of operations.
    FeedItemOperation feedItemOperation =
        FeedItemOperation.newBuilder().setCreate(feedItem).build();
    feedItemOperations.add(feedItemOperation);
  }

  // Creates the service client.
  try (FeedItemServiceClient feedItemServiceClient =
      googleAdsClient.getLatestVersion().createFeedItemServiceClient()) {
    // Adds the feed items.
    MutateFeedItemsResponse response =
        feedItemServiceClient.mutateFeedItems(Long.toString(customerId), feedItemOperations);

    // Displays the results.
    for (MutateFeedItemResult result : response.getResultsList()) {
      System.out.printf("Created feed item with resource name '%s'.%n", result.getResourceName());
    }
  }
}
 
Example #25
Source File: GoogleCloudStorageGrpcWriteChannel.java    From hadoop-connectors with Apache License 2.0 4 votes vote down vote up
/** Send a StartResumableWriteRequest and return the uploadId of the resumable write. */
private String startResumableUpload() throws IOException {
  InsertObjectSpec.Builder insertObjectSpecBuilder =
      InsertObjectSpec.newBuilder()
          .setResource(
              Object.newBuilder()
                  .setBucket(resourceId.getBucketName())
                  .setName(resourceId.getObjectName())
                  .setContentType(contentType)
                  .putAllMetadata(metadata)
                  .build());
  if (writeConditions.hasContentGenerationMatch()) {
    insertObjectSpecBuilder.setIfGenerationMatch(
        Int64Value.newBuilder().setValue(writeConditions.getContentGenerationMatch()));
  }
  if (writeConditions.hasMetaGenerationMatch()) {
    insertObjectSpecBuilder.setIfMetagenerationMatch(
        Int64Value.newBuilder().setValue(writeConditions.getMetaGenerationMatch()));
  }
  if (requesterPaysProject.isPresent()) {
    insertObjectSpecBuilder.setUserProject(requesterPaysProject.get());
  }
  StartResumableWriteRequest request =
      StartResumableWriteRequest.newBuilder()
          .setInsertObjectSpec(insertObjectSpecBuilder)
          .build();

  SimpleResponseObserver<StartResumableWriteResponse> responseObserver =
      new SimpleResponseObserver<>();
  runWithRetries(
      () -> {
        stub.withDeadlineAfter(START_RESUMABLE_WRITE_TIMEOUT.toMillis(), MILLISECONDS)
            .startResumableWrite(request, responseObserver);
        try {
          responseObserver.done.await();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
          throw new RuntimeException(
              String.format("Failed to start resumable upload for '%s'", getResourceString()),
              e);
        }
      },
      responseObserver);

  return responseObserver.getResponse().getUploadId();
}
 
Example #26
Source File: ProtoDomainTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void testNamespaceEqual() {
  ProtoDomain domainFromInt32 = ProtoDomain.buildFrom(Int32Value.getDescriptor());
  ProtoDomain domainFromInt64 = ProtoDomain.buildFrom(Int64Value.getDescriptor());
  Assert.assertTrue(domainFromInt64.equals(domainFromInt32));
}
 
Example #27
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 #28
Source File: AddAppCampaign.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an App campaign under the given customer ID.
 *
 * @param googleAdsClient the Google Ads API client.
 * @param customerId the customer ID.
 * @param budgetResourceName the resource name of the budget to associate with the campaign.
 * @return the resource name of the newly created App campaign.
 */
private String createCampaign(
    GoogleAdsClient googleAdsClient, long customerId, String budgetResourceName) {
  // Creates a campaign.
  Campaign campaign =
      Campaign.newBuilder()
          .setName(StringValue.of("Interplanetary Cruise App #" + System.currentTimeMillis()))
          .setCampaignBudget(StringValue.of(budgetResourceName))
          // Recommendation: Set the campaign to PAUSED when creating it to prevent
          // the ads from immediately serving. Set to ENABLED once you've added
          // targeting and the ads are ready to serve.
          .setStatus(CampaignStatus.PAUSED)
          // All App campaigns have an advertising_channel_type of
          // MULTI_CHANNEL to reflect the fact that ads from these campaigns are
          // eligible to appear on multiple channels.
          .setAdvertisingChannelType(AdvertisingChannelType.MULTI_CHANNEL)
          .setAdvertisingChannelSubType(AdvertisingChannelSubType.APP_CAMPAIGN)
          // Sets the target CPA to $1 / app install.
          //
          // campaign_bidding_strategy is a 'oneof' message so setting target_cpa
          // is mutually exclusive with other bidding strategies such as
          // manual_cpc, commission, maximize_conversions, etc.
          // See https://developers.google.com/google-ads/api/reference/rpc
          // under current version / resources / Campaign.
          .setTargetCpa(TargetCpa.newBuilder().setTargetCpaMicros(Int64Value.of(1000000)).build())
          // Sets the App campaign settings.
          .setAppCampaignSetting(
              AppCampaignSetting.newBuilder()
                  .setAppId(StringValue.of("com.google.android.apps.adwords"))
                  .setAppStore(AppCampaignAppStore.GOOGLE_APP_STORE)
                  // Optional: Optimize this campaign for getting new users for your app.
                  .setBiddingStrategyGoalType(
                      AppCampaignBiddingStrategyGoalType.OPTIMIZE_INSTALLS_TARGET_INSTALL_COST)
                  .build())
          // Optional fields.
          .setStartDate(StringValue.of(new DateTime().plusDays(1).toString("yyyyMMdd")))
          .setEndDate(StringValue.of(new DateTime().plusDays(365).toString("yyyyMMdd")))
          // If you select the
          // OPTIMIZE_IN_APP_CONVERSIONS_TARGET_INSTALL_COST goal type, then also
          // specify your in-app conversion types so the Google Ads API can focus
          // your campaign on people who are most likely to complete the
          // corresponding in-app actions.
          // .setSelectiveOptimization(SelectiveOptimization.newBuilder()
          //     .addConversionActions(StringValue.of("INSERT_CONVERSION_TYPE_ID_HERE"))
          //     .build())
          .build();

  // Creates a campaign operation.
  CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();

  // Create a campaign service client.
  try (CampaignServiceClient campaignServiceClient =
      googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
    // Adds the campaign.
    MutateCampaignsResponse response =
        campaignServiceClient.mutateCampaigns(
            Long.toString(customerId), ImmutableList.of(operation));
    // Prints and returns the campaign resource name.
    String campaignResourceName = response.getResults(0).getResourceName();
    System.out.printf("Created App campaign with resource name '%s'.%n", campaignResourceName);
    return campaignResourceName;
  }
}
 
Example #29
Source File: AddConversionBasedUserList.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 conversionActionIds the IDs of the conversion actions for the basic user list.
 * @throws GoogleAdsException if an API request failed with one or more service errors.
 */
private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, List<Long> conversionActionIds) {
  List<UserListActionInfo> userListActionInfoList = new ArrayList<>();
  for (long conversionActionId : conversionActionIds) {
    // Creates the UserListActionInfo object for a given conversion action. This specifies the
    // conversion action that, when triggered, will cause a user to be added to a UserList.
    UserListActionInfo userListActionInfo =
        UserListActionInfo.newBuilder()
            .setConversionAction(
                StringValue.of(ResourceNames.conversionAction(customerId, conversionActionId)))
            .build();
    userListActionInfoList.add(userListActionInfo);
  }

  // Creates a basic user list info object with all of the conversion actions.
  BasicUserListInfo basicUserListInfo =
      BasicUserListInfo.newBuilder().addAllActions(userListActionInfoList).build();

  // Creates the basic user list.
  UserList basicUserList =
      UserList.newBuilder()
          .setName(StringValue.of("Example BasicUserList #" + System.currentTimeMillis()))
          .setDescription(
              StringValue.of(
                  "A list of people who have triggered one or more conversion actions"))
          .setMembershipLifeSpan(Int64Value.of(365))
          .setBasicUserList(basicUserListInfo)
          .setMembershipStatus(UserListMembershipStatus.OPEN)
          .build();

  // Creates the operation.
  UserListOperation operation = UserListOperation.newBuilder().setCreate(basicUserList).build();

  // Creates the service client.
  try (UserListServiceClient userListServiceClient =
      googleAdsClient.getLatestVersion().createUserListServiceClient()) {
    // Adds the basic user list.
    MutateUserListsResponse response =
        userListServiceClient.mutateUserLists(
            Long.toString(customerId), ImmutableList.of(operation));
    // Prints the results.
    System.out.printf(
        "Created basic user list with resource name '%s'.%n",
        response.getResults(0).getResourceName());
  }
}
 
Example #30
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();
}