com.google.protobuf.Value Java Examples

The following examples show how to use com.google.protobuf.Value. 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: StructUtil.java    From rejoiner with Apache License 2.0 7 votes vote down vote up
/** 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);
                }
              }));
}
 
Example #2
Source File: ModelDBUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
public static List<KeyValueQuery> getKeyValueQueriesByWorkspaceDTO(WorkspaceDTO workspaceDTO) {
  List<KeyValueQuery> workspaceQueries = new ArrayList<>();
  if (workspaceDTO != null && workspaceDTO.getWorkspaceId() != null) {
    KeyValueQuery workspacePredicates =
        KeyValueQuery.newBuilder()
            .setKey(ModelDBConstants.WORKSPACE)
            .setValue(Value.newBuilder().setStringValue(workspaceDTO.getWorkspaceId()).build())
            .setOperator(OperatorEnum.Operator.EQ)
            .setValueType(ValueTypeEnum.ValueType.STRING)
            .build();
    workspaceQueries.add(workspacePredicates);
    KeyValueQuery workspaceTypePredicates =
        KeyValueQuery.newBuilder()
            .setKey(ModelDBConstants.WORKSPACE_TYPE)
            .setValue(
                Value.newBuilder()
                    .setNumberValue(workspaceDTO.getWorkspaceType().getNumber())
                    .build())
            .setOperator(OperatorEnum.Operator.EQ)
            .setValueType(ValueTypeEnum.ValueType.NUMBER)
            .build();
    workspaceQueries.add(workspaceTypePredicates);
  }
  return workspaceQueries;
}
 
Example #3
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 6 votes vote down vote up
@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());
  }
}
 
Example #4
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public void doWrite(Value message, JsonGenerator gen) throws IOException {
  switch (message.getKindCase()) {
    case NULL_VALUE:
      SerializeSupport.printNull(0, gen);
      break;
    case NUMBER_VALUE:
      SerializeSupport.printDouble(message.getNumberValue(), gen);
      break;
    case STRING_VALUE:
      SerializeSupport.printString(message.getStringValue(), gen);
      break;
    case BOOL_VALUE:
      SerializeSupport.printBool(message.getBoolValue(), gen);
      break;
    case STRUCT_VALUE:
      StructMarshaller.INSTANCE.writeValue(message.getStructValue(), gen);
      break;
    case LIST_VALUE:
      ListValueMarshaller.INSTANCE.writeValue(message.getListValue(), gen);
      break;
    case KIND_NOT_SET:
      SerializeSupport.printNull(0, gen);
      break;
  }
}
 
Example #5
Source File: StructTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public List<Project> getProjects(String key, String value, UserInfo userInfo)
    throws InvalidProtocolBufferException {
  FindProjects findProjects =
      FindProjects.newBuilder()
          .addPredicates(
              KeyValueQuery.newBuilder()
                  .setKey(key)
                  .setValue(Value.newBuilder().setStringValue(value).build())
                  .setOperator(OperatorEnum.Operator.EQ)
                  .setValueType(ValueTypeEnum.ValueType.STRING)
                  .build())
          .build();
  ProjectPaginationDTO projectPaginationDTO =
      findProjects(findProjects, null, userInfo, ProjectVisibility.PRIVATE);
  LOGGER.debug("Projects size is {}", projectPaginationDTO.getProjects().size());
  return projectPaginationDTO.getProjects();
}
 
Example #7
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 #8
Source File: LoadReportClientTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #9
Source File: AbstractProtoMapper.java    From conductor with Apache License 2.0 6 votes vote down vote up
public EventExecution fromProto(EventExecutionPb.EventExecution from) {
    EventExecution to = new EventExecution();
    to.setId( from.getId() );
    to.setMessageId( from.getMessageId() );
    to.setName( from.getName() );
    to.setEvent( from.getEvent() );
    to.setCreated( from.getCreated() );
    to.setStatus( fromProto( from.getStatus() ) );
    to.setAction( fromProto( from.getAction() ) );
    Map<String, Object> outputMap = new HashMap<String, Object>();
    for (Map.Entry<String, Value> pair : from.getOutputMap().entrySet()) {
        outputMap.put( pair.getKey(), fromProto( pair.getValue() ) );
    }
    to.setOutput(outputMap);
    return to;
}
 
Example #10
Source File: AbstractProtoMapper.java    From conductor with Apache License 2.0 6 votes vote down vote up
public EventHandler.StartWorkflow fromProto(EventHandlerPb.EventHandler.StartWorkflow from) {
    EventHandler.StartWorkflow to = new EventHandler.StartWorkflow();
    to.setName( from.getName() );
    to.setVersion( from.getVersion() );
    to.setCorrelationId( from.getCorrelationId() );
    Map<String, Object> inputMap = new HashMap<String, Object>();
    for (Map.Entry<String, Value> pair : from.getInputMap().entrySet()) {
        inputMap.put( pair.getKey(), fromProto( pair.getValue() ) );
    }
    to.setInput(inputMap);
    if (from.hasInputMessage()) {
        to.setInputMessage( fromProto( from.getInputMessage() ) );
    }
    to.setTaskToDomain( from.getTaskToDomainMap() );
    return to;
}
 
Example #11
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@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\"]]}");
}
 
Example #12
Source File: AbstractProtoMapper.java    From conductor with Apache License 2.0 6 votes vote down vote up
public TaskDef fromProto(TaskDefPb.TaskDef from) {
    TaskDef to = new TaskDef();
    to.setName( from.getName() );
    to.setDescription( from.getDescription() );
    to.setRetryCount( from.getRetryCount() );
    to.setTimeoutSeconds( from.getTimeoutSeconds() );
    to.setInputKeys( from.getInputKeysList().stream().collect(Collectors.toCollection(ArrayList::new)) );
    to.setOutputKeys( from.getOutputKeysList().stream().collect(Collectors.toCollection(ArrayList::new)) );
    to.setTimeoutPolicy( fromProto( from.getTimeoutPolicy() ) );
    to.setRetryLogic( fromProto( from.getRetryLogic() ) );
    to.setRetryDelaySeconds( from.getRetryDelaySeconds() );
    to.setResponseTimeoutSeconds( from.getResponseTimeoutSeconds() );
    to.setConcurrentExecLimit( from.getConcurrentExecLimit() );
    Map<String, Object> inputTemplateMap = new HashMap<String, Object>();
    for (Map.Entry<String, Value> pair : from.getInputTemplateMap().entrySet()) {
        inputTemplateMap.put( pair.getKey(), fromProto( pair.getValue() ) );
    }
    to.setInputTemplate(inputTemplateMap);
    to.setRateLimitPerFrequency( from.getRateLimitPerFrequency() );
    to.setRateLimitFrequencyInSeconds( from.getRateLimitFrequencyInSeconds() );
    to.setIsolationGroupId( from.getIsolationGroupId() );
    to.setExecutionNameSpace( from.getExecutionNameSpace() );
    to.setOwnerEmail( from.getOwnerEmail() );
    to.setPollTimeoutSeconds( from.getPollTimeoutSeconds() );
    return to;
}
 
Example #13
Source File: VcfToVariant.java    From genomewarp with Apache License 2.0 6 votes vote down vote up
private static Value createTypedValue(VCFHeaderLineType type, Object value) {
  if (type == VCFHeaderLineType.Flag) {
    return Value.newBuilder().setBoolValue((Boolean) value).build();
  }

  // Booleans are given as Boolean objects. Strangely, Floats and Integers
  // are given as String objects by HTSJDK.
  if (!(value instanceof String)) {
    throw new IllegalStateException("Received non-Boolean, non-List type in non-String format. "
        + "This is most likely due to a change in htsjdk's library.");
  }

  String stringValue = (String) value;
  boolean isNumeric = stringValue.matches("[-+]?\\d+(\\.\\d+)?");

  if (type == VCFHeaderLineType.Integer && isNumeric) {
    return Value.newBuilder().setNumberValue(Integer.parseInt(stringValue)).build();
  }

  if (type == VCFHeaderLineType.Float && isNumeric) {
    return Value.newBuilder().setNumberValue(Double.parseDouble(stringValue)).build();
  }


  return Value.newBuilder().setStringValue(stringValue).build();
}
 
Example #14
Source File: ListValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@Test
public void itReadsNestedListValues() throws IOException {
  String json = "{\"listValue\":[[\"nested\"]]}";
  HasListValue message = camelCase().readValue(json, HasListValue.class);
  assertThat(message.hasListValue()).isTrue();
  assertThat(message.getListValue().getValuesList()).hasSize(1);
  Value value = message.getListValue().getValues(0);
  ListValue list = ListValue.newBuilder().addValues(Value.newBuilder().setStringValue("nested")).build();
  switch (value.getKindCase()) {
    case LIST_VALUE:
      assertThat(value.getListValue()).isEqualToComparingFieldByField(list);
      break;
    default:
      fail("Unexpected value kind: " + value.getKindCase());
  }
}
 
Example #15
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@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());
  }
}
 
Example #16
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@Test
public void itReadsListValue() throws IOException {
  String json = "{\"value\":[\"test\"]}";
  HasValue valueWrapper = camelCase().readValue(json, HasValue.class);
  assertThat(valueWrapper.hasValue()).isTrue();

  Value value = valueWrapper.getValue();
  ListValue list = ListValue.newBuilder().addValues(Value.newBuilder().setStringValue("test").build()).build();
  switch (value.getKindCase()) {
    case LIST_VALUE:
      assertThat(value.getListValue()).isEqualTo(list);
      break;
    default:
      fail("Unexpected value kind: " + value.getKindCase());
  }
}
 
Example #17
Source File: SpannerResultTest.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
/**
 * Setup.
 */
@BeforeEach
public void setup() {

  this.resultSetMetadata =
      ResultSetMetadata.newBuilder()
          .setRowType(
              StructType.newBuilder().addFields(
                  Field.newBuilder()
                      .setName("first_column")
                      .setType(Type.newBuilder().setCode(TypeCode.STRING))))
          .build();

  SpannerRowMetadata metadata = new SpannerRowMetadata(this.resultSetMetadata);
  this.resultSet = Flux
      .just(new SpannerRow(
              Collections.singletonList(Value.newBuilder().setStringValue("key1").build()),
              metadata),
          new SpannerRow(
              Collections.singletonList(Value.newBuilder().setStringValue("key2").build()),
              metadata));
}
 
Example #18
Source File: DatasetDAORdbImpl.java    From modeldb with Apache License 2.0 6 votes vote down vote up
@Override
public List<Dataset> getDatasets(String key, String value, UserInfo userInfo)
    throws InvalidProtocolBufferException {
  FindDatasets findDatasets =
      FindDatasets.newBuilder()
          .addPredicates(
              KeyValueQuery.newBuilder()
                  .setKey(key)
                  .setValue(Value.newBuilder().setStringValue(value).build())
                  .setOperator(OperatorEnum.Operator.EQ)
                  .setValueType(ValueTypeEnum.ValueType.STRING)
                  .build())
          .build();
  DatasetPaginationDTO datasetPaginationDTO =
      findDatasets(findDatasets, userInfo, DatasetVisibility.PRIVATE);
  LOGGER.debug("Datasets size is {}", datasetPaginationDTO.getDatasets().size());
  return datasetPaginationDTO.getDatasets();
}
 
Example #19
Source File: DefaultCodecsTest.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
/** Validates that every supported type converts to expected value. */
@ParameterizedTest
@MethodSource("data")
public void codecsTest(Object val, Class<?> type, Type valueType) {
  Value value = this.codecs.encode(val);
  Value nullValue = this.codecs.encode(null);

  assertThat(this.codecs.decode(value, valueType, type)).isEqualTo(val);

  assertThat(this.codecs.decode(nullValue, valueType, type)).isNull();
}
 
Example #20
Source File: BentenMessage.java    From benten with MIT License 5 votes vote down vote up
public void setParameterstoJsonElement(Set<Map.Entry<String,com.google.protobuf.Value>> entrySet) {
        for (Map.Entry<String, Value> entry : entrySet) {
            if (entry.getValue().getKindCase().getNumber() == Value.STRING_VALUE_FIELD_NUMBER) {
                this.parameters.put(entry.getKey(), new JsonPrimitive(entry.getValue().getStringValue()));
            } else if (entry.getValue().getKindCase().getNumber() == Value.STRUCT_VALUE_FIELD_NUMBER) {
                this.parameters.put(entry.getKey(), new JsonPrimitive(String.valueOf(entry.getValue().getStructValue())));
            }
            else if (entry.getValue().getKindCase().getNumber() == Value.NUMBER_VALUE_FIELD_NUMBER) {
                this.parameters.put(entry.getKey(), new JsonPrimitive((int) entry.getValue().getNumberValue()));
            }
        }
}
 
Example #21
Source File: GraphQlStreamObserver.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(T value) {
  List<Value> path =
      dataFetchingEnvironment
          .getExecutionStepInfo()
          .getPath()
          .toList()
          .stream()
          .map(
              p ->
                  p instanceof Number
                      ? Value.newBuilder()
                          .setNumberValue(Double.parseDouble(p.toString()))
                          .build()
                      : Value.newBuilder().setStringValue(p.toString()).build())
          .collect(ImmutableList.toImmutableList());

  ListValue pathListVale =
      ListValue.newBuilder()
          .addAllValues(path)
          .addValues(Value.newBuilder().setNumberValue(pathIndex.incrementAndGet()))
          .build();

  R graphQlResponse = getData(value, pathListVale);

  rejoinerStreamingContext.responseStreamObserver().onNext(graphQlResponse);

  try {
    System.out.println(
        "Streaming response as Json: " + JsonFormat.printer().print(graphQlResponse));
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
}
 
Example #22
Source File: FindProjectEntitiesTest.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/** Validate check for protobuf struct type in KeyValueQuery not implemented */
@Test
public void findExperimentRunStructTypeNotImplemented() {
  LOGGER.info(
      "Check for protobuf struct type in KeyValueQuery not implemented test start.......");

  // Validate check for struct Type not implemented
  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("metrics.loss")
          .setValue(structValue)
          .setOperator(OperatorEnum.Operator.LTE)
          .build();

  FindExperimentRuns findExperimentRuns =
      FindExperimentRuns.newBuilder()
          .setProjectId(project1.getId())
          .setExperimentId(experiment1.getId())
          .addPredicates(keyValueQuery)
          .build();

  try {
    experimentRunServiceStub.findExperimentRuns(findExperimentRuns);
    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.......");
}
 
Example #23
Source File: RepeatedValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itReadsMixedTypeValues() throws IOException {
  String json = "{\"values\":[null,1.5,\"test\",true,{\"key\":\"value\"},[\"nested\"]]}";
  RepeatedValue message = camelCase().readValue(json, RepeatedValue.class);
  assertThat(message.getValuesCount()).isEqualTo(6);
  assertThat(message.getValues(0)).isEqualTo(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
  assertThat(message.getValues(1)).isEqualTo(Value.newBuilder().setNumberValue(1.5d).build());
  assertThat(message.getValues(2)).isEqualTo(Value.newBuilder().setStringValue("test").build());
  assertThat(message.getValues(3)).isEqualTo(Value.newBuilder().setBoolValue(true).build());
  assertThat(message.getValues(4)).isEqualTo(Value.newBuilder().setStructValue(STRUCT).build());
  assertThat(message.getValues(5)).isEqualTo(LIST);
}
 
Example #24
Source File: StructUtil.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private static ImmutableList<Object> toList(ListValue listValue) {
  return listValue
      .getValuesList()
      .stream()
      .map(
          value ->
              Value.KindCase.STRUCT_VALUE.equals(value.getKindCase())
                  ? toMap(value.getStructValue())
                  : getScalarValue(value))
      .collect(ImmutableList.toImmutableList());
}
 
Example #25
Source File: SpannerConnectionTest.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Test
public void executeStatementReturnsWorkingStatementWithCorrectQuery() {
  SpannerConnection connection
      = new SpannerConnection(this.mockClient, TEST_SESSION, TEST_CONFIG);
  String sql = "select book from library";
  PartialResultSet partialResultSet = PartialResultSet.newBuilder()
      .setMetadata(ResultSetMetadata.newBuilder().setRowType(StructType.newBuilder()
          .addFields(
              Field.newBuilder().setName("book")
                  .setType(Type.newBuilder().setCode(TypeCode.STRING)))))
      .addValues(Value.newBuilder().setStringValue("Odyssey"))
      .build();

  when(this.mockClient.executeStreamingSql(
        any(StatementExecutionContext.class), eq(sql), eq(EMPTY_STRUCT), eq(EMPTY_TYPE_MAP)))
      .thenReturn(Flux.just(makeBookPrs("Odyssey")));

  Statement statement = connection.createStatement(sql);
  assertThat(statement).isInstanceOf(SpannerStatement.class);

  StepVerifier.create(
      ((Flux<SpannerResult>) statement.execute())
          .flatMap(res -> res.map((r, m) -> (String) r.get(0))))
      .expectNext("Odyssey")
      .expectComplete()
      .verify();

  verify(this.mockClient).executeStreamingSql(any(StatementExecutionContext.class), eq(sql),
      eq(EMPTY_STRUCT), eq(EMPTY_TYPE_MAP));

  // Single use READ query doesn't need these round trips below.
  verify(this.mockClient, times(0)).beginTransaction(eq(TEST_SESSION_NAME), any());
  verify(this.mockClient, times(0)).commitTransaction(eq(TEST_SESSION_NAME), any());
}
 
Example #26
Source File: FindDatasetEntitiesTest.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/** Validate check for protobuf struct type in KeyValueQuery not implemented */
@Test
public void findDatasetVersionStructTypeNotImplemented() {
  LOGGER.info(
      "Check for protobuf struct type in KeyValueQuery not implemented test start........");

  // Validate check for struct Type not implemented
  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();

  FindDatasetVersions findDatasetVersions =
      FindDatasetVersions.newBuilder()
          .addDatasetVersionIds(datasetVersion1.getId())
          .addPredicates(keyValueQuery)
          .build();

  try {
    datasetVersionServiceStub.findDatasetVersions(findDatasetVersions);
    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........");
}
 
Example #27
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itReadsBooleanValue() throws IOException {
  String json = "{\"value\":true}";
  HasValue valueWrapper = camelCase().readValue(json, HasValue.class);
  assertThat(valueWrapper.hasValue()).isTrue();

  Value value = valueWrapper.getValue();
  switch (value.getKindCase()) {
    case BOOL_VALUE:
      assertThat(value.getBoolValue()).isTrue();
      break;
    default:
      fail("Unexpected value kind: " + value.getKindCase());
  }
}
 
Example #28
Source File: FindProjectEntitiesTest.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/** Find experimentRun with value of endTime */
@Test
public void findExperimentRunsWithoutProjectExperimentTest() {
  LOGGER.info(
      "FindExperimentRuns without project & experiment test start................................");

  Value stringValue =
      Value.newBuilder().setStringValue(String.valueOf(experimentRun22.getEndTime())).build();
  KeyValueQuery keyValueQuery =
      KeyValueQuery.newBuilder()
          .setKey("end_time")
          .setValue(stringValue)
          .setOperator(OperatorEnum.Operator.EQ)
          .build();

  FindExperimentRuns findExperimentRuns =
      FindExperimentRuns.newBuilder().addPredicates(keyValueQuery).build();

  FindExperimentRuns.Response response =
      experimentRunServiceStub.findExperimentRuns(findExperimentRuns);
  LOGGER.info("FindExperimentRuns Response : " + response.getExperimentRunsCount());
  assertEquals(
      "ExperimentRun count not match with expected experimentRun count",
      1,
      response.getExperimentRunsCount());
  assertEquals(
      "ExperimentRun not match with expected experimentRun",
      experimentRun22.getId(),
      response.getExperimentRunsList().get(0).getId());
  assertEquals(
      "Total records count not matched with expected records count",
      1,
      response.getTotalRecords());

  LOGGER.info(
      "FindExperimentRuns without project & experiment test stop................................");
}
 
Example #29
Source File: AbstractProtoMapper.java    From conductor with Apache License 2.0 5 votes vote down vote up
public EventHandler.TaskDetails fromProto(EventHandlerPb.EventHandler.TaskDetails from) {
    EventHandler.TaskDetails to = new EventHandler.TaskDetails();
    to.setWorkflowId( from.getWorkflowId() );
    to.setTaskRefName( from.getTaskRefName() );
    Map<String, Object> outputMap = new HashMap<String, Object>();
    for (Map.Entry<String, Value> pair : from.getOutputMap().entrySet()) {
        outputMap.put( pair.getKey(), fromProto( pair.getValue() ) );
    }
    to.setOutput(outputMap);
    if (from.hasOutputMessage()) {
        to.setOutputMessage( fromProto( from.getOutputMessage() ) );
    }
    to.setTaskId( from.getTaskId() );
    return to;
}
 
Example #30
Source File: IntegrationTest.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private CreateProject createProjectRequest() {
  String projectName = "project_" + Calendar.getInstance().getTimeInMillis();

  List<KeyValue> metadataList = new ArrayList<>();
  for (int count = 0; count < 5; count++) {
    Value stringValue =
        Value.newBuilder()
            .setStringValue(
                "attribute_" + count + "_" + Calendar.getInstance().getTimeInMillis() + "_value")
            .build();
    KeyValue keyValue =
        KeyValue.newBuilder()
            .setKey("attribute_" + count + "_" + Calendar.getInstance().getTimeInMillis())
            .setValue(stringValue)
            .setValueType(ValueType.STRING)
            .build();
    metadataList.add(keyValue);
  }

  return CreateProject.newBuilder()
      .setName(projectName)
      .setDescription("This is a project description.")
      .addTags("tag_" + Calendar.getInstance().getTimeInMillis())
      .addTags("tag_" + +Calendar.getInstance().getTimeInMillis())
      .addAllAttributes(metadataList)
      .build();
}