下面列出了com.google.protobuf.UInt64Value#com.google.protobuf.UInt32Value 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public JobScenarioBuilder updateJobCapacityDesired(int desired, int unchangedMin, int unchangedMax) {
logger.info("[{}] Changing job {} capacity desired to {}...", discoverActiveTest(), jobId, desired);
Stopwatch stopWatch = Stopwatch.createStarted();
TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
client.updateJobCapacityWithOptionalAttributes(
JobCapacityUpdateWithOptionalAttributes.newBuilder().setJobId(jobId)
.setJobCapacityWithOptionalAttributes(JobCapacityWithOptionalAttributes.newBuilder().setDesired(UInt32Value.newBuilder().setValue(desired).build()).build()).build(),
responseObserver);
rethrow(() -> responseObserver.awaitDone(TIMEOUT_MS, TimeUnit.MILLISECONDS));
expectJobUpdateEvent(job -> {
ServiceJobExt ext = (ServiceJobExt) job.getJobDescriptor().getExtensions();
Capacity capacity = ext.getCapacity();
return capacity.getDesired() == desired && capacity.getMin() == unchangedMin && capacity.getMax() == unchangedMax;
}, "Job capacity update did not complete in time");
logger.info("[{}] Job {} scaled to new desired size in {}ms", discoverActiveTest(), jobId, stopWatch.elapsed(TimeUnit.MILLISECONDS));
return this;
}
public JobScenarioBuilder updateJobCapacityDesiredInvalid(int targetDesired, int currentDesired) {
logger.info("[{}] Changing job {} capacity desired to {}...", discoverActiveTest(), jobId, targetDesired);
TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
client.updateJobCapacityWithOptionalAttributes(
JobCapacityUpdateWithOptionalAttributes.newBuilder().setJobId(jobId)
.setJobCapacityWithOptionalAttributes(JobCapacityWithOptionalAttributes.newBuilder().setDesired(UInt32Value.newBuilder().setValue(targetDesired).build()).build()).build(),
responseObserver);
await().timeout(TIMEOUT_MS, TimeUnit.MILLISECONDS).until(responseObserver::hasError);
Throwable error = responseObserver.getError();
assertThat(error).isNotNull();
assertThat(error).isInstanceOf(StatusRuntimeException.class);
StatusRuntimeException statusRuntimeException = (StatusRuntimeException) error;
assertThat(statusRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT).isTrue();
// Make sure desired count is unchanged
Job job = getJob();
JobDescriptor.JobDescriptorExt ext = job.getJobDescriptor().getExtensions();
int currentCapacity = ext instanceof BatchJobExt ? ((BatchJobExt) ext).getSize() : ((ServiceJobExt) ext).getCapacity().getDesired();
assertThat(currentCapacity).isEqualTo(currentDesired);
return this;
}
public JobScenarioBuilder updateJobCapacityMaxInvalid(int targetMax) {
logger.info("[{}] Changing job {} capacity max to {}...", discoverActiveTest(), jobId, targetMax);
TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
client.updateJobCapacityWithOptionalAttributes(
JobCapacityUpdateWithOptionalAttributes.newBuilder().setJobId(jobId)
.setJobCapacityWithOptionalAttributes(JobCapacityWithOptionalAttributes.newBuilder().setMax(UInt32Value.newBuilder().setValue(targetMax).build()).build()).build(),
responseObserver);
await().timeout(TIMEOUT_MS, TimeUnit.MILLISECONDS).until(responseObserver::hasError);
Throwable error = responseObserver.getError();
assertThat(error).isNotNull();
assertThat(error).isInstanceOf(StatusRuntimeException.class);
StatusRuntimeException statusRuntimeException = (StatusRuntimeException) error;
assertThat(statusRuntimeException.getStatus().getCode() == Status.Code.INVALID_ARGUMENT).isTrue();
return this;
}
public JobScenarioBuilder updateJobCapacityMin(int min, int unchangedMax, int unchangedDesired) {
logger.info("[{}] Changing job {} capacity min to {}...", discoverActiveTest(), jobId, min);
Stopwatch stopWatch = Stopwatch.createStarted();
TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
client.updateJobCapacityWithOptionalAttributes(
JobCapacityUpdateWithOptionalAttributes.newBuilder().setJobId(jobId)
.setJobCapacityWithOptionalAttributes(JobCapacityWithOptionalAttributes.newBuilder().setMin(UInt32Value.newBuilder().setValue(min).build()).build()).build(),
responseObserver);
rethrow(() -> responseObserver.awaitDone(TIMEOUT_MS, TimeUnit.MILLISECONDS));
expectJobUpdateEvent(job -> {
ServiceJobExt ext = (ServiceJobExt) job.getJobDescriptor().getExtensions();
Capacity capacity = ext.getCapacity();
return capacity.getMin() == min && capacity.getMax() == unchangedMax && capacity.getDesired() == unchangedDesired;
}, "Job capacity update did not complete in time");
logger.info("[{}] Job {} scaled to new min size in {}ms", discoverActiveTest(), jobId, stopWatch.elapsed(TimeUnit.MILLISECONDS));
return this;
}
public JobScenarioBuilder updateJobCapacityMax(int max, int unchangedMin, int unchangedDesired) {
logger.info("[{}] Changing job {} capacity max to {}...", discoverActiveTest(), jobId, max);
Stopwatch stopWatch = Stopwatch.createStarted();
TestStreamObserver<Empty> responseObserver = new TestStreamObserver<>();
client.updateJobCapacityWithOptionalAttributes(
JobCapacityUpdateWithOptionalAttributes.newBuilder().setJobId(jobId)
.setJobCapacityWithOptionalAttributes(JobCapacityWithOptionalAttributes.newBuilder().setMax(UInt32Value.newBuilder().setValue(max).build()).build()).build(),
responseObserver);
rethrow(() -> responseObserver.awaitDone(TIMEOUT_MS, TimeUnit.MILLISECONDS));
expectJobUpdateEvent(job -> {
ServiceJobExt ext = (ServiceJobExt) job.getJobDescriptor().getExtensions();
Capacity capacity = ext.getCapacity();
return capacity.getMax() == max && capacity.getMin() == unchangedMin && capacity.getDesired() == unchangedDesired;
}, "Job capacity update did not complete in time");
logger.info("[{}] Job {} scaled to new max size in {}ms", discoverActiveTest(), jobId, stopWatch.elapsed(TimeUnit.MILLISECONDS));
return this;
}
@Test
public void testSetCapacityWithOptionalAttributes() throws Exception {
JobCapacityWithOptionalAttributes restRequest = JobCapacityWithOptionalAttributes.newBuilder()
.setMin(UInt32Value.newBuilder().setValue(1).build())
.setDesired(UInt32Value.newBuilder().setValue(2).build())
.setMax(UInt32Value.newBuilder().setValue(3).build())
.build();
JobCapacityUpdateWithOptionalAttributes forwardedRequest = JobCapacityUpdateWithOptionalAttributes.newBuilder()
.setJobId(JOB_ID_1)
.setJobCapacityWithOptionalAttributes(restRequest)
.build();
when(jobServiceGatewayMock.updateJobCapacityWithOptionalAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA)).thenReturn(Completable.complete());
SpringMockMvcUtil.doPut(mockMvc, String.format("/api/v3/jobs/%s/capacityAttributes", JOB_ID_1), restRequest);
verify(jobServiceGatewayMock, times(1)).updateJobCapacityWithOptionalAttributes(forwardedRequest, JUNIT_REST_CALL_METADATA);
}
@Override
public Observable<ScalableTargetResourceInfo> setScalableTargetResourceInfo(String jobId,
ScalableTargetResourceInfo scalableTargetResourceInfo,
CallMetadata callMetadata) {
logger.info("(BEFORE setting job instances) for jobId {} :: {}", jobId, scalableTargetResourceInfo);
JobCapacityWithOptionalAttributes jobCapacityWithOptionalAttributes = JobCapacityWithOptionalAttributes.newBuilder()
.setDesired(UInt32Value.newBuilder().setValue(scalableTargetResourceInfo.getDesiredCapacity()).build()).build();
JobCapacityUpdateWithOptionalAttributes jobCapacityRequest = JobCapacityUpdateWithOptionalAttributes.newBuilder()
.setJobId(jobId)
.setJobCapacityWithOptionalAttributes(jobCapacityWithOptionalAttributes).build();
return jobServiceGateway.updateJobCapacityWithOptionalAttributes(jobCapacityRequest, callMetadata)
.andThen(getScalableTargetResourceInfo(jobId, callMetadata).map(scalableTargetResourceInfoReturned -> {
scalableTargetResourceInfoReturned.setScalingStatus(ScalingStatus.Pending.name());
logger.info("(set job instances) Returning value Instances for jobId {} :: {}", jobId, scalableTargetResourceInfo);
return scalableTargetResourceInfoReturned;
}));
}
@Test
public void writeSendsSingleInsertObjectRequest() throws Exception {
GoogleCloudStorageGrpcWriteChannel writeChannel = newWriteChannel();
ByteString data = ByteString.copyFromUtf8("test data");
writeChannel.initialize();
writeChannel.write(data.asReadOnlyByteBuffer());
writeChannel.close();
InsertObjectRequest expectedInsertRequest =
InsertObjectRequest.newBuilder()
.setUploadId(UPLOAD_ID)
.setChecksummedData(
ChecksummedData.newBuilder()
.setContent(data)
.setCrc32C(UInt32Value.newBuilder().setValue(uInt32Value(863614154))))
.setObjectChecksums(
ObjectChecksums.newBuilder()
.setCrc32C(UInt32Value.newBuilder().setValue(uInt32Value(863614154))))
.setFinishWrite(true)
.build();
verify(fakeService, times(1)).startResumableWrite(eq(START_REQUEST), any());
verify(fakeService.insertRequestObserver, times(1)).onNext(expectedInsertRequest);
verify(fakeService.insertRequestObserver, atLeast(1)).onCompleted();
}
@Test
public void multipleSequentialsReadsSucceedWithValidObjectChecksum() throws Exception {
fakeService.setObject(
DEFAULT_OBJECT.toBuilder()
.setCrc32C(UInt32Value.newBuilder().setValue(DEFAULT_OBJECT_CRC32C))
.build());
GoogleCloudStorageReadOptions options =
GoogleCloudStorageReadOptions.builder().setGrpcChecksumsEnabled(true).build();
GoogleCloudStorageGrpcReadChannel readChannel = newReadChannel(options);
ByteBuffer firstBuffer = ByteBuffer.allocate(100);
ByteBuffer secondBuffer = ByteBuffer.allocate(OBJECT_SIZE - 100);
readChannel.read(firstBuffer);
readChannel.read(secondBuffer);
assertArrayEquals(fakeService.data.substring(0, 100).toByteArray(), firstBuffer.array());
assertArrayEquals(fakeService.data.substring(100).toByteArray(), secondBuffer.array());
}
@Test
public void multipleReadsIgnoreObjectChecksumForLatestGenerationReads() throws Exception {
fakeService.setObject(
DEFAULT_OBJECT.toBuilder().setCrc32C(UInt32Value.newBuilder().setValue(0)).build());
GoogleCloudStorageReadOptions options =
GoogleCloudStorageReadOptions.builder().setGrpcChecksumsEnabled(true).build();
GoogleCloudStorageGrpcReadChannel readChannel = newReadChannel(options);
ByteBuffer firstBuffer = ByteBuffer.allocate(100);
ByteBuffer secondBuffer = ByteBuffer.allocate(OBJECT_SIZE - 100);
readChannel.read(firstBuffer);
readChannel.read(secondBuffer);
assertArrayEquals(fakeService.data.substring(0, 100).toByteArray(), firstBuffer.array());
assertArrayEquals(fakeService.data.substring(100).toByteArray(), secondBuffer.array());
}
static io.envoyproxy.envoy.api.v2.endpoint.LocalityLbEndpoints buildLocalityLbEndpoints(
String region, String zone, String subZone,
List<io.envoyproxy.envoy.api.v2.endpoint.LbEndpoint> lbEndpoints,
int loadBalancingWeight, int priority) {
return
io.envoyproxy.envoy.api.v2.endpoint.LocalityLbEndpoints.newBuilder()
.setLocality(
io.envoyproxy.envoy.api.v2.core.Locality.newBuilder()
.setRegion(region)
.setZone(zone)
.setSubZone(subZone))
.addAllLbEndpoints(lbEndpoints)
.setLoadBalancingWeight(UInt32Value.of(loadBalancingWeight))
.setPriority(priority)
.build();
}
private static FilterChain createInFilter() {
FilterChain filterChain =
FilterChain.newBuilder()
.setFilterChainMatch(
FilterChainMatch.newBuilder()
.setDestinationPort(UInt32Value.of(8000))
.addPrefixRanges(CidrRange.newBuilder()
.setAddressPrefix("10.20.0.15")
.setPrefixLen(UInt32Value.of(32))
.build())
.addApplicationProtocols("managed-mtls")
.build())
.setTransportSocket(TransportSocket.newBuilder().setName("tls")
.setTypedConfig(Any.pack(CommonTlsContextTestsUtil.buildTestDownstreamTlsContext()))
.build())
.addFilters(Filter.newBuilder()
.setName("envoy.http_connection_manager")
.setTypedConfig(Any.newBuilder()
.setTypeUrl(
"type.googleapis.com/envoy.config.filter.network.http_connection_manager"
+ ".v2.HttpConnectionManager"))
.build())
.build();
return filterChain;
}
@SuppressWarnings("deprecation")
private static FilterChain createDeprecatedInFilter() {
FilterChain filterChain =
FilterChain.newBuilder()
.setFilterChainMatch(
FilterChainMatch.newBuilder()
.setDestinationPort(UInt32Value.of(8000))
.addPrefixRanges(CidrRange.newBuilder()
.setAddressPrefix("10.20.0.15")
.setPrefixLen(UInt32Value.of(32)).build())
.addApplicationProtocols("managed-mtls")
.build())
.setTlsContext(CommonTlsContextTestsUtil.buildTestDownstreamTlsContext())
.addFilters(Filter.newBuilder()
.setName("envoy.http_connection_manager")
.setTypedConfig(Any.newBuilder()
.setTypeUrl(
"type.googleapis.com/envoy.config.filter.network.http_connection_manager"
+ ".v2.HttpConnectionManager"))
.build())
.build();
return filterChain;
}
@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());
}
/**
* Sets the service config based on a sequence of sources of heterogeneous types. Sources of the
* same type will be merged together, and those applicable to the framework will be attached to
* it.
*/
public void setConfigSources(Iterable<ConfigSource> configs) {
// Merge configs of same type.
Map<Descriptor, ConfigSource.Builder> mergedConfigs = Maps.newHashMap();
for (ConfigSource config : configs) {
Descriptor descriptor = config.getConfig().getDescriptorForType();
ConfigSource.Builder builder = mergedConfigs.get(descriptor);
if (builder == null) {
mergedConfigs.put(descriptor, config.toBuilder());
} else if (experiments.isExperimentEnabled(PROTO3_CONFIG_MERGING_EXPERIMENT)) {
builder.mergeFromWithProto3Semantics(config);
} else {
builder.mergeFrom(config);
}
}
// Pick the configs we know and care about (currently, Service and Legacy).
ConfigSource.Builder serviceConfig = mergedConfigs.get(Service.getDescriptor());
if (serviceConfig != null) {
setServiceConfig(serviceConfig.build());
} else {
// Set empty config.
setServiceConfig(
ConfigSource.newBuilder(
Service.newBuilder()
.setConfigVersion(
UInt32Value.newBuilder().setValue(Model.getDefaultConfigVersion()))
.build())
.build());
}
}
/** Sets special configuration needed for 3rd party Endpoints APIs. */
private void applyThirdPartyApiSettings(Service.Builder serviceBuilder) {
serviceBuilder.getControlBuilder().setEnvironment(ControlConfigUtil.PROD_SERVICE_CONTROL);
// Set the config version to 3.
serviceBuilder.setConfigVersion(
UInt32Value.newBuilder().setValue(TOOLS_CONFIG_VERSION).build());
}
@Test
public void singleReadSucceedsWithValidObjectChecksum() throws Exception {
fakeService.setObject(
DEFAULT_OBJECT.toBuilder()
.setCrc32C(UInt32Value.newBuilder().setValue(DEFAULT_OBJECT_CRC32C))
.build());
GoogleCloudStorageReadOptions options =
GoogleCloudStorageReadOptions.builder().setGrpcChecksumsEnabled(true).build();
GoogleCloudStorageGrpcReadChannel readChannel = newReadChannel(options);
ByteBuffer buffer = ByteBuffer.allocate(OBJECT_SIZE);
readChannel.read(buffer);
assertArrayEquals(fakeService.data.toByteArray(), buffer.array());
}
@Test
public void partialReadSucceedsWithInvalidObjectChecksum() throws Exception {
fakeService.setObject(
DEFAULT_OBJECT.toBuilder().setCrc32C(UInt32Value.newBuilder().setValue(0)).build());
GoogleCloudStorageReadOptions options =
GoogleCloudStorageReadOptions.builder().setGrpcChecksumsEnabled(true).build();
GoogleCloudStorageGrpcReadChannel readChannel = newReadChannel(options);
ByteBuffer buffer = ByteBuffer.allocate(OBJECT_SIZE - 10);
readChannel.read(buffer);
assertArrayEquals(
fakeService.data.substring(0, OBJECT_SIZE - 10).toByteArray(), buffer.array());
}
@Override
public void getObjectMedia(
GetObjectMediaRequest request, StreamObserver<GetObjectMediaResponse> responseObserver) {
if (getMediaException != null) {
responseObserver.onError(getMediaException);
} else {
int readStart = (int) request.getReadOffset();
int readEnd =
request.getReadLimit() > 0
? (int) Math.min(object.getSize(), readStart + request.getReadLimit())
: (int) object.getSize();
for (int position = readStart; position < readEnd; position += CHUNK_SIZE) {
ByteString messageData =
data.substring(position, Math.min((int) object.getSize(), position + CHUNK_SIZE));
int crc32c = Hashing.crc32c().hashBytes(messageData.toByteArray()).asInt();
if (alterMessageChecksum) {
crc32c += 1;
}
GetObjectMediaResponse response =
GetObjectMediaResponse.newBuilder()
.setChecksummedData(
ChecksummedData.newBuilder()
.setContent(messageData)
.setCrc32C(UInt32Value.newBuilder().setValue(crc32c)))
.build();
responseObserver.onNext(response);
}
responseObserver.onCompleted();
}
}
static FilterChainMatch buildFilterChainMatch(int destPort, CidrRange...prefixRanges) {
return
FilterChainMatch.newBuilder()
.setDestinationPort(UInt32Value.of(destPort))
.addAllPrefixRanges(Arrays.asList(prefixRanges))
.build();
}
@Test
public void convertClusterWeight() {
io.envoyproxy.envoy.api.v2.route.WeightedCluster.ClusterWeight proto =
io.envoyproxy.envoy.api.v2.route.WeightedCluster.ClusterWeight.newBuilder()
.setName("cluster-foo")
.setWeight(UInt32Value.newBuilder().setValue(30)).build();
ClusterWeight struct = ClusterWeight.fromEnvoyProtoClusterWeight(proto);
assertThat(struct.getName()).isEqualTo("cluster-foo");
assertThat(struct.getWeight()).isEqualTo(30);
}
/**
* Builds a RouteAction for a weighted cluster route. The given map is keyed by cluster name and
* valued by the weight of the cluster.
*/
private static RouteAction buildWeightedClusterRoute(Map<String, Integer> clusterWeights) {
WeightedCluster.Builder builder = WeightedCluster.newBuilder();
for (Map.Entry<String, Integer> entry : clusterWeights.entrySet()) {
builder.addClusters(
ClusterWeight.newBuilder()
.setName(entry.getKey())
.setWeight(UInt32Value.of(entry.getValue())));
}
return RouteAction.newBuilder()
.setWeightedClusters(builder)
.build();
}
static io.envoyproxy.envoy.api.v2.endpoint.LbEndpoint buildLbEndpoint(String address,
int port, HealthStatus healthStatus, int loadbalancingWeight) {
return
io.envoyproxy.envoy.api.v2.endpoint.LbEndpoint.newBuilder()
.setEndpoint(
io.envoyproxy.envoy.api.v2.endpoint.Endpoint.newBuilder().setAddress(
Address.newBuilder().setSocketAddress(
SocketAddress.newBuilder().setAddress(address).setPortValue(port))))
.setHealthStatus(healthStatus)
.setLoadBalancingWeight(UInt32Value.of(loadbalancingWeight))
.build();
}
private static FilterChain createOutFilter() {
FilterChain filterChain =
FilterChain.newBuilder()
.setFilterChainMatch(
FilterChainMatch.newBuilder()
.setDestinationPort(UInt32Value.of(8000))
.build())
.addFilters(Filter.newBuilder()
.setName("envoy.http_connection_manager")
.build())
.build();
return filterChain;
}
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();
}
UInt32ValueMarshaller() {
super(UInt32Value.getDefaultInstance());
}
@Override
protected final void doMerge(JsonParser parser, int unused, Message.Builder messageBuilder)
throws IOException {
UInt32Value.Builder builder = (UInt32Value.Builder) messageBuilder;
builder.setValue(ParseSupport.parseUInt32(parser));
}
@Override
protected final void doWrite(UInt32Value message, JsonGenerator gen) throws IOException {
SerializeSupport.printUnsignedInt32(message.getValue(), gen);
}
@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());
}
/**
* Converts {@link SpanData} to {@link Span} proto.
*
* @param spanData the {@code SpanData}.
* @return proto representation of {@code Span}.
*/
static Span toSpanProto(SpanData spanData) {
SpanContext spanContext = spanData.getContext();
TraceId traceId = spanContext.getTraceId();
SpanId spanId = spanContext.getSpanId();
Span.Builder spanBuilder =
Span.newBuilder()
.setTraceId(toByteString(traceId.getBytes()))
.setSpanId(toByteString(spanId.getBytes()))
.setTracestate(toTracestateProto(spanContext.getTracestate()))
.setName(toTruncatableStringProto(spanData.getName()))
.setStartTime(toTimestampProto(spanData.getStartTimestamp()))
.setAttributes(toAttributesProto(spanData.getAttributes()))
.setTimeEvents(
toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents()))
.setLinks(toLinksProto(spanData.getLinks()));
Kind kind = spanData.getKind();
if (kind != null) {
spanBuilder.setKind(toSpanKindProto(kind));
}
io.opencensus.trace.Status status = spanData.getStatus();
if (status != null) {
spanBuilder.setStatus(toStatusProto(status));
}
Timestamp end = spanData.getEndTimestamp();
if (end != null) {
spanBuilder.setEndTime(toTimestampProto(end));
}
Integer childSpanCount = spanData.getChildSpanCount();
if (childSpanCount != null) {
spanBuilder.setChildSpanCount(UInt32Value.newBuilder().setValue(childSpanCount).build());
}
Boolean hasRemoteParent = spanData.getHasRemoteParent();
if (hasRemoteParent != null) {
spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
}
SpanId parentSpanId = spanData.getParentSpanId();
if (parentSpanId != null && parentSpanId.isValid()) {
spanBuilder.setParentSpanId(toByteString(parentSpanId.getBytes()));
}
return spanBuilder.build();
}