下面列出了怎么用com.google.protobuf.Struct的API类实例代码及写法,或者点击链接到github查看源代码。
private Mono<SpannerResult> runStreamingSql(Struct params) {
Flux<PartialResultSet> resultSetFlux =
this.client.executeStreamingSql(
this.ctx, this.sql, params, this.statementBindings.getTypes());
if (this.statementType == StatementType.SELECT) {
PartialResultRowExtractor partialResultRowExtractor = new PartialResultRowExtractor();
return resultSetFlux
.flatMapIterable(partialResultRowExtractor, this.config.getPartialResultSetFetchSize())
.transform(result -> Mono.just(new SpannerResult(result, Mono.just(0))))
.next();
} else {
return resultSetFlux.last()
.map(partialResultSet -> {
long rowsUpdated =
Math.max(
partialResultSet.getStats().getRowCountExact(),
partialResultSet.getStats().getRowCountLowerBound());
return Math.toIntExact(rowsUpdated);
})
.map(rowCount -> new SpannerResult(Flux.empty(), Mono.just(rowCount)));
}
}
@Test
public void addBasicBinding() {
StatementBindings statementBindings = new StatementBindings();
statementBindings.createBind("name", "John");
statementBindings.createBind("age", 50);
statementBindings.createBind("array", new String[]{"a", "b"});
statementBindings.completeBinding();
assertThat(statementBindings.getTypes())
.containsExactly(
entry("array", Type.newBuilder().setCode(TypeCode.ARRAY)
.setArrayElementType(Type.newBuilder().setCode(TypeCode.STRING).build()).build()),
entry("name", Type.newBuilder().setCode(TypeCode.STRING).build()),
entry("age", Type.newBuilder().setCode(TypeCode.INT64).build())
);
assertThat(statementBindings.getBindings())
.containsExactly(
Struct.newBuilder()
.putFields("name", Value.newBuilder().setStringValue("John").build())
.putFields("age", Value.newBuilder().setStringValue("50").build())
.putFields("array", Value.newBuilder().setListValue(
ListValue.newBuilder().addValues(Value.newBuilder().setStringValue("a").build())
.addValues(Value.newBuilder().setStringValue("b").build()).build()).build())
.build());
}
/** Convert a Struct to an ImmutableMap. */
public static ImmutableMap<String, Object> toMap(Struct struct) {
return struct
.getFieldsMap()
.entrySet()
.stream()
.collect(
ImmutableMap.toImmutableMap(
entry -> entry.getKey(),
entry -> {
Value value = entry.getValue();
switch (value.getKindCase()) {
case STRUCT_VALUE:
return toMap(value.getStructValue());
case LIST_VALUE:
return toList(value.getListValue());
default:
return getScalarValue(value);
}
}));
}
@Override
public void doMerge(JsonParser parser, int currentDepth, Message.Builder messageBuilder)
throws IOException {
Value.Builder builder = (Value.Builder) messageBuilder;
JsonToken token = parser.currentToken();
if (token.isBoolean()) {
builder.setBoolValue(ParseSupport.parseBool(parser));
} else if (token.isNumeric()) {
builder.setNumberValue(ParseSupport.parseDouble(parser));
} else if (token == JsonToken.VALUE_NULL) {
builder.setNullValue(NullValue.NULL_VALUE);
} else if (token.isScalarValue()) {
builder.setStringValue(ParseSupport.parseString(parser));
} else if (token == JsonToken.START_OBJECT) {
Struct.Builder structBuilder = builder.getStructValueBuilder();
StructMarshaller.INSTANCE.mergeValue(parser, currentDepth + 1, structBuilder);
} else if (token == JsonToken.START_ARRAY) {
ListValue.Builder listValueBuilder = builder.getListValueBuilder();
ListValueMarshaller.INSTANCE.mergeValue(parser, currentDepth + 1, listValueBuilder);
} else {
throw new IllegalStateException("Unexpected json data: " + parser.getText());
}
}
@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());
}
@Test
public void testSimpleMapping() throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper m = new JsonMapperProvider().get();
assertTrue(m.canSerialize(Any.class));
Struct struct1 = Struct.newBuilder().putFields(
"some-key", Value.newBuilder().setStringValue("some-value").build()
).build();
Any source = Any.pack(struct1);
StringWriter buf = new StringWriter();
m.writer().writeValue(buf, source);
Any dest = m.reader().forType(Any.class).readValue(buf.toString());
assertEquals(source.getTypeUrl(), dest.getTypeUrl());
Struct struct2 = dest.unpack(Struct.class);
assertTrue(struct2.containsFields("some-key"));
assertEquals(
struct1.getFieldsOrThrow("some-key").getStringValue(),
struct2.getFieldsOrThrow("some-key").getStringValue()
);
}
/**
* Builds a {@link ConfigSource} for the given targetUri.
*
* @param channelType specifying "inproc" creates an Inprocess channel for testing.
*/
static ConfigSource buildConfigSource(String targetUri, String channelType) {
GoogleGrpc.Builder googleGrpcBuilder = GoogleGrpc.newBuilder().setTargetUri(targetUri);
if (channelType != null) {
Struct.Builder structBuilder = Struct.newBuilder();
structBuilder.putFields(
"channelType", Value.newBuilder().setStringValue(channelType).build());
googleGrpcBuilder.setConfig(structBuilder.build());
}
return ConfigSource.newBuilder()
.setApiConfigSource(
ApiConfigSource.newBuilder()
.setApiType(ApiConfigSource.ApiType.GRPC)
.addGrpcServices(
GrpcService.newBuilder().setGoogleGrpc(googleGrpcBuilder.build()).build())
.build())
.build();
}
private static LoadStatsRequest buildInitialRequest() {
return
LoadStatsRequest.newBuilder()
.setNode(
Node.newBuilder()
.setId("LRS test")
.setMetadata(
Struct.newBuilder()
.putFields(
"TRAFFICDIRECTOR_NETWORK_HOSTNAME",
Value.newBuilder().setStringValue("default").build())
.putFields(
LoadReportClient.TARGET_NAME_METADATA_KEY,
Value.newBuilder().setStringValue(TARGET_NAME).build())))
.build();
}
@Test
public void itReadsAllStructValueTypes() throws IOException {
String json = "{\"struct\":{\"null\":null,\"number\":1.5,\"string\":\"test\",\"boolean\":true,\"struct\":{\"key\":\"nested\"},\"list\":[\"nested\"]}}";
HasStruct message = camelCase().readValue(json, HasStruct.class);
assertThat(message.hasStruct()).isTrue();
Map<String, Value> map = message.getStruct().getFieldsMap();
Value nested = Value.newBuilder().setStringValue("nested").build();
Struct nestedStruct = Struct.newBuilder().putFields("key", nested).build();
ListValue list = ListValue.newBuilder().addValues(nested).build();
assertThat(map.size()).isEqualTo(6);
assertThat(map.get("null")).isEqualTo(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
assertThat(map.get("number")).isEqualTo(Value.newBuilder().setNumberValue(1.5).build());
assertThat(map.get("string")).isEqualTo(Value.newBuilder().setStringValue("test").build());
assertThat(map.get("boolean")).isEqualTo(Value.newBuilder().setBoolValue(true).build());
assertThat(map.get("struct")).isEqualTo(Value.newBuilder().setStructValue(nestedStruct).build());
assertThat(map.get("list")).isEqualTo(Value.newBuilder().setListValue(list).build());
}
@Test
public void itWritesMixedListValue() throws IOException {
Value nestedValue = Value.newBuilder().setStringValue("nested").build();
Struct struct = Struct.newBuilder().putFields("key", nestedValue).build();
ListValue nestedList = ListValue.newBuilder().addValues(nestedValue).build();
ListValue list = ListValue
.newBuilder()
.addValues(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.addValues(Value.newBuilder().setNumberValue(1.5d).build())
.addValues(Value.newBuilder().setStringValue("test").build())
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStructValue(struct).build())
.addValues(Value.newBuilder().setListValue(nestedList).build())
.build();
HasValue message = HasValue
.newBuilder()
.setValue(Value.newBuilder().setListValue(list).build())
.build();
String json = camelCase().writeValueAsString(message);
assertThat(json).isEqualTo("{\"value\":[null,1.5,\"test\",true,{\"key\":\"nested\"},[\"nested\"]]}");
}
@Test
public void itReadsMixedStruct() throws IOException {
String json = "{\"value\":{\"null\":null,\"number\":1.5,\"string\":\"test\",\"boolean\":true,\"struct\":{\"key\":\"nested\"},\"list\":[\"nested\"]}}";
HasValue message = camelCase().readValue(json, HasValue.class);
assertThat(message.hasValue()).isTrue();
Value value = message.getValue();
switch (value.getKindCase()) {
case STRUCT_VALUE:
Map<String, Value> map = value.getStructValue().getFieldsMap();
Value nested = Value.newBuilder().setStringValue("nested").build();
Struct nestedStruct = Struct.newBuilder().putFields("key", nested).build();
ListValue list = ListValue.newBuilder().addValues(nested).build();
assertThat(map.size()).isEqualTo(6);
assertThat(map.get("null")).isEqualTo(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
assertThat(map.get("number")).isEqualTo(Value.newBuilder().setNumberValue(1.5).build());
assertThat(map.get("string")).isEqualTo(Value.newBuilder().setStringValue("test").build());
assertThat(map.get("boolean")).isEqualTo(Value.newBuilder().setBoolValue(true).build());
assertThat(map.get("struct")).isEqualTo(Value.newBuilder().setStructValue(nestedStruct).build());
assertThat(map.get("list")).isEqualTo(Value.newBuilder().setListValue(list).build());
break;
default:
fail("Unexpected value kind: " + value.getKindCase());
}
}
@Test
public void itReadsMixedListValue() throws IOException {
String json = "{\"value\":[null,1.5,\"test\",true,{\"key\":\"nested\"},[\"nested\"]]}";
HasValue message = camelCase().readValue(json, HasValue.class);
assertThat(message.hasValue()).isTrue();
Value value = message.getValue();
switch (value.getKindCase()) {
case LIST_VALUE:
ListValue list = value.getListValue();
Value nested = Value.newBuilder().setStringValue("nested").build();
Struct struct = Struct.newBuilder().putFields("key", nested).build();
ListValue nestedList = ListValue.newBuilder().addValues(nested).build();
assertThat(list.getValuesCount()).isEqualTo(6);
assertThat(list.getValues(0)).isEqualTo(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
assertThat(list.getValues(1)).isEqualTo(Value.newBuilder().setNumberValue(1.5).build());
assertThat(list.getValues(2)).isEqualTo(Value.newBuilder().setStringValue("test").build());
assertThat(list.getValues(3)).isEqualTo(Value.newBuilder().setBoolValue(true).build());
assertThat(list.getValues(4)).isEqualTo(Value.newBuilder().setStructValue(struct).build());
assertThat(list.getValues(5)).isEqualTo(Value.newBuilder().setListValue(nestedList).build());
break;
default:
fail("Unexpected value kind: " + value.getKindCase());
}
}
@Test
public void itReadsMixedTypeValues() throws IOException {
String json = "{\"listValue\":[null,1.5,\"test\",true,{\"key\":\"value\"},[\"nested\"]]}";
HasListValue message = camelCase().readValue(json, HasListValue.class);
Struct struct = Struct.newBuilder().putFields("key", Value.newBuilder().setStringValue("value").build()).build();
ListValue list = ListValue.newBuilder().addValues(Value.newBuilder().setStringValue("nested")).build();
ListValue expected = ListValue
.newBuilder()
.addValues(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.addValues(Value.newBuilder().setNumberValue(1.5d).build())
.addValues(Value.newBuilder().setStringValue("test").build())
.addValues(Value.newBuilder().setBoolValue(true).build())
.addValues(Value.newBuilder().setStructValue(struct).build())
.addValues(Value.newBuilder().setListValue(list).build())
.build();
assertThat(message.hasListValue()).isTrue();
assertThat(message.getListValue()).isEqualTo(expected);
}
@Override
public Publisher<? extends Result> execute() {
if (this.statementType == StatementType.DDL) {
return this.client
.executeDdl(
this.config.getFullyQualifiedDatabaseName(),
Collections.singletonList(this.sql),
this.config.getDdlOperationTimeout(),
this.config.getDdlOperationPollInterval())
.map(operation -> new SpannerResult(Flux.empty(), Mono.just(0)));
} else if (this.statementType == StatementType.DML && !this.ctx.isTransactionPartitionedDml()) {
List<ExecuteBatchDmlRequest.Statement> dmlStatements =
this.statementBindings.getBindings().stream()
.map(struct ->
ExecuteBatchDmlRequest.Statement.newBuilder()
.setSql(this.sql)
.setParams(struct)
.putAllParamTypes(this.statementBindings.getTypes())
.build())
.collect(Collectors.toList());
return this.client.executeBatchDml(this.ctx, dmlStatements)
.map(partialResultSet -> Math.toIntExact(partialResultSet.getStats().getRowCountExact()))
.map(rowCount -> new SpannerResult(Flux.empty(), Mono.just(rowCount)));
}
Flux<Struct> structFlux = Flux.fromIterable(this.statementBindings.getBindings());
return structFlux.flatMap(this::runStreamingSql);
}
@Override
public Flux<PartialResultSet> executeStreamingSql(
StatementExecutionContext ctx,
String sql,
Struct params,
Map<String, Type> types) {
return Flux.defer(() -> {
Assert.requireNonNull(ctx.getSessionName(), "Session name must not be null");
ExecuteSqlRequest.Builder executeSqlRequest = buildSqlRequest(ctx, sql);
if (params != null) {
executeSqlRequest
.setParams(params)
.putAllParamTypes(types);
}
if (ctx.getTransactionId() != null) {
executeSqlRequest.setTransaction(
TransactionSelector.newBuilder().setId(ctx.getTransactionId())
.build());
executeSqlRequest.setSeqno(ctx.nextSeqNum());
}
return ObservableReactiveUtil.streamingCall(
obs -> this.spanner.executeStreamingSql(executeSqlRequest.build(), obs));
});
}
/**
* Constructs a {@link StatementBindings} object representing a list of bindings for a Spanner
* statement.
*/
public StatementBindings() {
this.currentStruct = Struct.newBuilder();
this.structList = new ArrayList<>();
this.resolvedCodecs = new HashMap<>();
this.typesMap = new HashMap<>();
}
/**
* Adds the current binding to the list of bindings for the statement and starts a new parameter
* binding.
*/
public void completeBinding() {
if (this.currentStruct.getFieldsCount() > 0) {
this.structList.add(this.currentStruct.build());
this.currentStruct = Struct.newBuilder();
}
}
/**
* Returns the built binding for the statement.
* @return list of {@link Struct} representing all the parameter bindings for the statement.
*/
public List<Struct> getBindings() {
completeBinding();
if (this.structList.isEmpty()) {
return Collections.singletonList(Struct.getDefaultInstance());
} else {
return this.structList;
}
}
@Test
public void noopMapOnUpdateQueriesWhenNoRowsAffected() {
String sql = "delete from Books where true";
ResultSet resultSet = ResultSet.newBuilder()
.setMetadata(ResultSetMetadata.getDefaultInstance())
.setStats(ResultSetStats.getDefaultInstance())
.build();
List<Statement> statementList = Collections.singletonList(
ExecuteBatchDmlRequest.Statement.newBuilder()
.setSql(sql)
.setParams(Struct.getDefaultInstance())
.build());
when(this.mockClient.executeBatchDml(this.mockContext, statementList))
.thenReturn(Flux.just(resultSet));
SpannerStatement statement =
new SpannerStatement(this.mockClient, this.mockContext, sql, TEST_CONFIG);
Flux<SpannerResult> result = (Flux<SpannerResult>) statement.execute();
StepVerifier.create(result.flatMap(
spannerResult -> spannerResult.map((row, rowMetadata) -> (String) row.get(0))
.collectList()))
.expectNext(Collections.emptyList())
.verifyComplete();
StepVerifier.create(result.flatMap(results -> Mono.from(results.getRowsUpdated())))
.expectNext(0)
.verifyComplete();
verify(this.mockClient, times(1))
.executeBatchDml(this.mockContext, statementList);
}
@Test
public void testNoopAddBinding() {
StatementBindings statementBindings = new StatementBindings();
statementBindings.completeBinding();
statementBindings.completeBinding();
statementBindings.completeBinding();
assertThat(statementBindings.getTypes()).isEmpty();
assertThat(statementBindings.getBindings()).containsExactly(Struct.getDefaultInstance());
}
/**
* Creates and completes a ReportStateAndNotification request
*
* @param actionsApp The SmartHomeApp instance to use to make the gRPC request
* @param userId The agent user ID
* @param deviceId The device ID
* @param states A JSON object of state keys and their values for the provided device ID
*/
public static void makeRequest(
SmartHomeApp actionsApp, String userId, String deviceId, JsonObject states) {
// Do state name replacement for ColorSetting trait
// See https://developers.google.com/assistant/smarthome/traits/colorsetting#device-states
JsonObject colorJson = states.getAsJsonObject("color");
if (colorJson != null && colorJson.has("spectrumRgb")) {
colorJson.add("spectrumRGB", colorJson.get("spectrumRgb"));
colorJson.remove("spectrumRgb");
}
Struct.Builder statesStruct = Struct.newBuilder();
try {
JsonFormat.parser().ignoringUnknownFields().merge(new Gson().toJson(states), statesStruct);
} catch (Exception e) {
LOGGER.error("FAILED TO BUILD");
}
HomeGraphApiServiceProto.ReportStateAndNotificationDevice.Builder deviceBuilder =
HomeGraphApiServiceProto.ReportStateAndNotificationDevice.newBuilder()
.setStates(
Struct.newBuilder()
.putFields(deviceId, Value.newBuilder().setStructValue(statesStruct).build()));
HomeGraphApiServiceProto.ReportStateAndNotificationRequest request =
HomeGraphApiServiceProto.ReportStateAndNotificationRequest.newBuilder()
.setRequestId(String.valueOf(Math.random()))
.setAgentUserId(userId) // our single user's id
.setPayload(
HomeGraphApiServiceProto.StateAndNotificationPayload.newBuilder()
.setDevices(deviceBuilder))
.build();
actionsApp.reportState(request);
}
private void transformDevices(com.google.protobuf.Struct.Builder builder, Model model) {
boolean whitelisted = this.whitelist.isWhitelisted(this.placeId);
ProductCatalogEntry prodCatEntry = VoiceUtil.getProduct(this.prodCat, model);
if (!StringUtils.isBlank(model.getId())) {
Map<String, Object> mapOfValue = Transformers.modelToStateMap(model, hubOffline, whitelisted, prodCatEntry);
if (!mapOfValue.containsKey(Constants.States.ERROR_CODE)) { // modelToStateMap returns an error code when the model isn't supported by Google Voice
builder.putFields(model.getAddress().toString(), TransformToGoogleValue.transformMapToValue(mapOfValue));
}
}
}
private static void structAsMessage(Struct struct, Message.Builder messageBuilder)
throws InvalidProtocolBufferException {
String json = JsonFormat.printer()
.preservingProtoFieldNames()
.print(struct);
JsonFormat.parser().merge(json, messageBuilder);
}
private static Struct messageAsStruct(MessageOrBuilder message) {
try {
String json = JsonFormat.printer()
.preservingProtoFieldNames()
.print(message);
Struct.Builder structBuilder = Struct.newBuilder();
JsonFormat.parser().merge(json, structBuilder);
return structBuilder.build();
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException("Failed to convert protobuf message to struct", e);
}
}
/** Converts a json map into a protobuf {@link Struct} builder object. */
private static Struct.Builder jsonToStructBuilder(Map<String, Object> json) {
Struct.Builder builder = Struct.newBuilder();
for (Map.Entry<String, Object> entry : json.entrySet()) {
Value structValue = value(entry.getValue());
builder.putFields(entry.getKey(), structValue);
}
return builder;
}
@Override
public void doMerge(JsonParser parser, int currentDepth, Message.Builder messageBuilder)
throws IOException {
Struct.Builder builder = (Struct.Builder) messageBuilder;
while (parser.nextValue() != JsonToken.END_OBJECT) {
builder.putFields(
parser.getCurrentName(), ValueMarshaller.INSTANCE.readValue(parser, currentDepth + 1));
}
}
@Override
protected void doWrite(Struct message, JsonGenerator gen) throws IOException {
for (Map.Entry<String, Value> entry : message.getFieldsMap().entrySet()) {
gen.writeFieldName(entry.getKey());
ValueMarshaller.INSTANCE.writeValue(entry.getValue(), gen);
}
}
@Test
public void struct() throws Exception {
// Build a struct with all possible values.
TestStruct.Builder builder = TestStruct.newBuilder();
Struct.Builder structBuilder = builder.getStructValueBuilder();
structBuilder.putFields("null_value", Value.newBuilder().setNullValueValue(0).build());
structBuilder.putFields("number_value", Value.newBuilder().setNumberValue(1.25).build());
structBuilder.putFields("string_value", Value.newBuilder().setStringValue("hello").build());
Struct.Builder subStructBuilder = Struct.newBuilder();
subStructBuilder.putFields("number_value", Value.newBuilder().setNumberValue(1234).build());
structBuilder.putFields(
"struct_value", Value.newBuilder().setStructValue(subStructBuilder.build()).build());
ListValue.Builder listBuilder = ListValue.newBuilder();
listBuilder.addValues(Value.newBuilder().setNumberValue(1.125).build());
listBuilder.addValues(Value.newBuilder().setNullValueValue(0).build());
structBuilder.putFields(
"list_value", Value.newBuilder().setListValue(listBuilder.build()).build());
TestStruct message = builder.build();
assertMatchesUpstream(message);
builder = TestStruct.newBuilder();
builder.setValue(Value.newBuilder().setNullValueValue(0).build());
message = builder.build();
assertMatchesUpstream(message);
builder = TestStruct.newBuilder();
listBuilder = builder.getListValueBuilder();
listBuilder.addValues(Value.newBuilder().setNumberValue(31831.125).build());
listBuilder.addValues(Value.newBuilder().setNullValueValue(0).build());
message = builder.build();
assertMatchesUpstream(message);
}
/**
* 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;
}
/** Validate check for protobuf struct type in KeyValueQuery not implemented */
@Test
public void findProjectStructTypeNotImplemented() {
LOGGER.info(
"check for protobuf struct type in KeyValueQuery not implemented test start................................");
// Validate check for struct Type not implemented
List<KeyValueQuery> predicates = new ArrayList<>();
Value numValue = Value.newBuilder().setNumberValue(17.1716586149719).build();
Struct.Builder struct = Struct.newBuilder();
struct.putFields("number_value", numValue);
struct.build();
Value structValue = Value.newBuilder().setStructValue(struct).build();
KeyValueQuery keyValueQuery =
KeyValueQuery.newBuilder()
.setKey("attributes.attribute_1")
.setValue(structValue)
.setOperator(OperatorEnum.Operator.LTE)
.build();
predicates.add(keyValueQuery);
FindProjects findProjects =
FindProjects.newBuilder()
.addProjectIds(project1.getId())
.addAllPredicates(predicates)
.build();
try {
projectServiceStub.findProjects(findProjects);
fail();
} catch (StatusRuntimeException exc) {
Status status = Status.fromThrowable(exc);
assertEquals(Status.UNIMPLEMENTED.getCode(), status.getCode());
}
LOGGER.info(
"check for protobuf struct type in KeyValueQuery not implemented test stop................................");
}