com.google.protobuf.ListValue Java Examples

The following examples show how to use com.google.protobuf.ListValue. 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: StatementBindingsTest.java    From cloud-spanner-r2dbc with Apache License 2.0 8 votes vote down vote up
@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());
}
 
Example #2
Source File: GenomeWarpTestUtils.java    From genomewarp with Apache License 2.0 6 votes vote down vote up
private static VariantCall makeVariantCall(
    String name, int[] g, double[] gl, boolean isPhased, Map<String, ListValue> info) {
  VariantCall.Builder vcBuilder = VariantCall.newBuilder().setCallSetName(name);
  if (g != null) {
    for (int i = 0; i < g.length; i++) {
      vcBuilder.addGenotype(g[i]);
    }
    if (isPhased && g.length > 1) {
      vcBuilder.setPhaseset("*");
    }
  }
  if (gl != null) {
    for (int i = 0; i < gl.length; i++) {
      vcBuilder.addGenotypeLikelihood(gl[i]);
    }
  }
  if (info != null) {
    vcBuilder.getMutableInfo().putAll(info);
  }

  return vcBuilder.build();
}
 
Example #3
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 #4
Source File: VcfToVariant.java    From genomewarp with Apache License 2.0 6 votes vote down vote up
private static boolean parseInlineGenotypeFields(String field, VariantCall.Builder vcBuilder,
    ListValue.Builder lvBuilder, IntGenotypeFieldAccessors.Accessor accessor, Genotype g) {

  final int[] intValues = accessor.getValues(g);
  if (intValues == null || intValues.length == 0) {
    return false;
  }

  if (field.equals(VCFConstants.GENOTYPE_PL_KEY)) {
    // HTSJDK folds GL's into PL's. We only use PL's to store genotype likelihood.
    for (int i = 0; i < intValues.length; i++) {
      // We add 0.0 to remove the possiblity of getting -0.0.
      vcBuilder.addGenotypeLikelihood(-(double) intValues[i] / 10.0 + 0.0);
    }
    return false;
  }

  for (int i = 0; i < intValues.length; i++) {
    lvBuilder.addValues(Value.newBuilder().setNumberValue(intValues[i]));
  }
  return true;
}
 
Example #5
Source File: VerifyBamIdTest.java    From dataflow-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAlleleFreq() throws Exception {
  DoFnTester<Variant, KV<Position, AlleleFreq>> getAlleleFreq = DoFnTester.of(
      new GetAlleleFreq());
  Position pos = Position.newBuilder()
      .setReferenceName("1")
      .setPosition(123L)
      .build();
  Variant.Builder vBuild = Variant.newBuilder()
      .setReferenceName("1")
      .setStart(123L)
      .setReferenceBases("C")
      .addAlternateBases("T");
  vBuild.getMutableInfo().put("AF", ListValue.newBuilder()
      .addValues(Value.newBuilder().setStringValue("0.25").build()).build());
  AlleleFreq af = new AlleleFreq();
  af.setAltBases(Lists.newArrayList("T"));
  af.setRefBases("C");
  af.setRefFreq(0.25);
  Assert.assertThat(getAlleleFreq.processBundle(vBuild.build()),
      CoreMatchers.hasItems(KV.of(pos, af)));
}
 
Example #6
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 #7
Source File: VerifyBamId.java    From dataflow-java with Apache License 2.0 6 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext c) throws Exception {
  ListValue lv = c.element().getInfo().get("AF");
  if (lv != null && lv.getValuesCount() > 0) {
    Position position = Position.newBuilder()
        .setPosition(c.element().getStart())
        .setReferenceName(c.element().getReferenceName())
        .build();
    AlleleFreq af = new AlleleFreq();
    af.setRefFreq(Double.parseDouble(lv.getValues(0).getStringValue()));
    af.setAltBases(c.element().getAlternateBasesList());
    af.setRefBases(c.element().getReferenceBases());
    c.output(KV.of(position, af));
  } else {
    // AF field wasn't populated in info, so we don't have frequency information
    // for this Variant.
    // TODO instead of straight throwing an exception, log a warning.  If at the end of this
    // step the number of AlleleFreqs retrieved is below a given threshold, then throw an
    // exception.
    throw new IllegalArgumentException("Variant " + c.element().getId() + " does not have "
       + "allele frequency information stored in INFO field AF.");
  }
}
 
Example #8
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 #9
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 #10
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 #11
Source File: HelloWorldSchemaModule.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Query("sayHello")
HelloReply sayHello(
    HelloRequest request,
    StreamingGreeterGrpc.StreamingGreeterStub client,
    DataFetchingEnvironment dataFetchingEnvironment) {
  client.sayHelloStreaming(
      request,
      new GraphQlStreamObserver<HelloReply, GraphQlResponse>(dataFetchingEnvironment) {
        @Override
        protected GraphQlResponse getData(HelloReply value, ListValue path) {
          // TODO: how can this be improved?
          QueryType data =
              QueryType.newBuilder()
                  .setHelloReply(
                      io.grpc.examples.graphql.HelloReply.newBuilder()
                          .setMessage(value.getMessage())
                          .build())
                  .build();

          return GraphQlResponse.newBuilder().setPath(path).setData(data).build();
        }
      });

  return null;
}
 
Example #12
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@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());
  }
}
 
Example #13
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 #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: ListValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: VcfToVariantTest.java    From genomewarp with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInfo() throws Exception {
  File vcfFile =
      new File(VcfToVariant.class.getClassLoader().getResource(VALID_VCF_4_1).getFile());
  VCFFileReader vcfReader = new VCFFileReader(vcfFile, false);
  VCFHeader vcfHeader = vcfReader.getFileHeader();
  int currVariant = 0;

  for (final VariantContext vc : vcfReader) {
    Map<String, ListValue> info = VcfToVariant.getInfo(vc, vcfHeader);
    assertEquals(info, TRUTH.get(currVariant).getInfo());
    currVariant++;
  }
}
 
Example #17
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itWritesListValue() throws IOException {
  ListValue list = ListValue.newBuilder().addValues(Value.newBuilder().setStringValue("test").build()).build();
  HasValue message = HasValue
          .newBuilder()
          .setValue(Value.newBuilder().setListValue(list).build())
          .build();
  String json = camelCase().writeValueAsString(message);
  assertThat(json).isEqualTo("{\"value\":[\"test\"]}");
}
 
Example #18
Source File: Bootstrapper.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Converts Java representation of the given JSON value to protobuf's {@link
 * com.google.protobuf.Value} representation.
 *
 * <p>The given {@code rawObject} must be a valid JSON value in Java representation, which is
 * either a {@code Map<String, ?>}, {@code List<?>}, {@code String}, {@code Double},
 * {@code Boolean}, or {@code null}.
 */
private static Value convertToValue(Object rawObject) {
  Value.Builder valueBuilder = Value.newBuilder();
  if (rawObject == null) {
    valueBuilder.setNullValue(NullValue.NULL_VALUE);
  } else if (rawObject instanceof Double) {
    valueBuilder.setNumberValue((Double) rawObject);
  } else if (rawObject instanceof String) {
    valueBuilder.setStringValue((String) rawObject);
  } else if (rawObject instanceof Boolean) {
    valueBuilder.setBoolValue((Boolean) rawObject);
  } else if (rawObject instanceof Map) {
    Struct.Builder structBuilder = Struct.newBuilder();
    @SuppressWarnings("unchecked")
    Map<String, ?> map = (Map<String, ?>) rawObject;
    for (Map.Entry<String, ?> entry : map.entrySet()) {
      structBuilder.putFields(entry.getKey(), convertToValue(entry.getValue()));
    }
    valueBuilder.setStructValue(structBuilder);
  } else if (rawObject instanceof List) {
    ListValue.Builder listBuilder = ListValue.newBuilder();
    List<?> list = (List<?>) rawObject;
    for (Object obj : list) {
      listBuilder.addValues(convertToValue(obj));
    }
    valueBuilder.setListValue(listBuilder);
  }
  return valueBuilder.build();
}
 
Example #19
Source File: ListValueDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
protected void populate(
        ListValue.Builder builder,
        JsonParser parser,
        DeserializationContext context
) throws IOException {
  List<Object> values = readArray(builder, VALUES_FIELD, null, parser, context);
  for (Object value : values) {
    builder.addRepeatedField(VALUES_FIELD, value);
  }
}
 
Example #20
Source File: ListValueSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
        ListValue listValue,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  generator.writeStartArray();
  for (Value value : listValue.getValuesList()) {
    writeValue(VALUES_FIELD, value, generator, serializerProvider);
  }
  generator.writeEndArray();
}
 
Example #21
Source File: StructTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itWritesAllStructValueTypes() throws IOException {
  Value nestedValue = Value.newBuilder().setStringValue("nested").build();
  Struct nestedStruct = Struct.newBuilder().putFields("key", nestedValue).build();
  ListValue list = ListValue.newBuilder().addValues(nestedValue).build();
  Struct struct = Struct
          .newBuilder()
          .putFields("null", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
          .putFields("number", Value.newBuilder().setNumberValue(1.5d).build())
          .putFields("string", Value.newBuilder().setStringValue("test").build())
          .putFields("boolean", Value.newBuilder().setBoolValue(true).build())
          .putFields("struct", Value.newBuilder().setStructValue(nestedStruct).build())
          .putFields("list", Value.newBuilder().setListValue(list).build())
          .build();
  HasStruct message = HasStruct
          .newBuilder()
          .setStruct(struct)
          .build();
  String json = camelCase().writeValueAsString(message);
  JsonNode node = camelCase().readTree(json).get("struct");
  assertThat(node.get("null").isNull()).isTrue();
  assertThat(node.get("number").isNumber()).isTrue();
  assertThat(node.get("number").numberValue().doubleValue()).isEqualTo(1.5d);
  assertThat(node.get("string").isTextual()).isTrue();
  assertThat(node.get("string").textValue()).isEqualTo("test");
  assertThat(node.get("boolean").isBoolean()).isTrue();
  assertThat(node.get("boolean").booleanValue()).isTrue();
  assertThat(node.get("struct").isObject()).isTrue();
  assertThat(node.get("struct").size()).isEqualTo(1);
  assertThat(node.get("struct").get("key").isTextual()).isTrue();
  assertThat(node.get("struct").get("key").textValue()).isEqualTo("nested");
  assertThat(node.get("list").isArray()).isTrue();
  assertThat(node.get("list").size()).isEqualTo(1);
  assertThat(node.get("list").get(0).isTextual()).isTrue();
  assertThat(node.get("list").get(0).textValue()).isEqualTo("nested");
}
 
Example #22
Source File: ValueUtils.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
static Object decodeValue(Type fieldType, com.google.protobuf.Value proto) {
  if (proto.getKindCase() == KindCase.NULL_VALUE) {
    return null;
  }
  switch (fieldType.getCode()) {
    case BOOL:
      checkType(fieldType, proto, KindCase.BOOL_VALUE);
      return parseBoolean(proto);
    case INT64:
      checkType(fieldType, proto, KindCase.STRING_VALUE);
      return parseLong(proto);
    case FLOAT64:
      return valueProtoToFloat64(proto);
    case STRING:
      checkType(fieldType, proto, KindCase.STRING_VALUE);
      return proto.getStringValue();
    case BYTES:
      checkType(fieldType, proto, KindCase.STRING_VALUE);
      return parseBytes(proto);
    case TIMESTAMP:
      checkType(fieldType, proto, KindCase.STRING_VALUE);
      return parseTimestamp(proto);
    case DATE:
      checkType(fieldType, proto, KindCase.STRING_VALUE);
      return parseDate(proto);
    case ARRAY:
      checkType(fieldType, proto, KindCase.LIST_VALUE);
      ListValue listValue = proto.getListValue();
      return decodeArrayValue(fieldType.getArrayElementType(), listValue);
    default:
      throw new AssertionError("Unhandled type code: " + fieldType.getCode());
  }
}
 
Example #23
Source File: ValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itWritesMixedStruct() throws IOException {
  Value nestedValue = Value.newBuilder().setStringValue("nested").build();
  Struct nestedStruct = Struct.newBuilder().putFields("key", nestedValue).build();
  ListValue list = ListValue.newBuilder().addValues(nestedValue).build();
  Struct struct = Struct
          .newBuilder()
          .putFields("null", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
          .putFields("number", Value.newBuilder().setNumberValue(1.5d).build())
          .putFields("string", Value.newBuilder().setStringValue("test").build())
          .putFields("boolean", Value.newBuilder().setBoolValue(true).build())
          .putFields("struct", Value.newBuilder().setStructValue(nestedStruct).build())
          .putFields("list", Value.newBuilder().setListValue(list).build())
          .build();
  HasValue message = HasValue
          .newBuilder()
          .setValue(Value.newBuilder().setStructValue(struct).build())
          .build();
  String json = camelCase().writeValueAsString(message);
  JsonNode node = camelCase().readTree(json).get("value");
  assertThat(node.get("null").isNull()).isTrue();
  assertThat(node.get("number").isNumber()).isTrue();
  assertThat(node.get("number").numberValue().doubleValue()).isEqualTo(1.5d);
  assertThat(node.get("string").isTextual()).isTrue();
  assertThat(node.get("string").textValue()).isEqualTo("test");
  assertThat(node.get("boolean").isBoolean()).isTrue();
  assertThat(node.get("boolean").booleanValue()).isTrue();
  assertThat(node.get("struct").isObject()).isTrue();
  assertThat(node.get("struct").size()).isEqualTo(1);
  assertThat(node.get("struct").get("key").isTextual()).isTrue();
  assertThat(node.get("struct").get("key").textValue()).isEqualTo("nested");
  assertThat(node.get("list").isArray()).isTrue();
  assertThat(node.get("list").size()).isEqualTo(1);
  assertThat(node.get("list").get(0).isTextual()).isTrue();
  assertThat(node.get("list").get(0).textValue()).isEqualTo("nested");
}
 
Example #24
Source File: ListValueTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void itSetsListValueWhenEmptyInJson() throws IOException {
  String json = "{\"listValue\":[]}";
  HasListValue message = camelCase().readValue(json, HasListValue.class);
  assertThat(message.hasListValue()).isTrue();
  assertThat(message.getListValue()).isEqualTo(ListValue.getDefaultInstance());
}
 
Example #25
Source File: ArrayCodec.java    From cloud-spanner-r2dbc with Apache License 2.0 5 votes vote down vote up
@Override
Value doEncode(A[] value) {
  Builder builder = ListValue.newBuilder();
  for (A val : value) {
    builder.addValues(this.codecs.encode(val));
  }
  return Value.newBuilder().setListValue(builder.build()).build();
}
 
Example #26
Source File: MessageMarshallerTest.java    From curiostack with MIT License 5 votes vote down vote up
@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);
}
 
Example #27
Source File: GenomeWarpTestUtils.java    From genomewarp with Apache License 2.0 5 votes vote down vote up
private static ListValue listFromObject(Object obj) {
  ListValue.Builder lvBuilder = ListValue.newBuilder();
  if (!(obj instanceof List)) {
    lvBuilder.addValues(valueFromObject(obj));
  } else {
    List<Object> objList = (List<Object>) obj;

    for (int i = 0; i < objList.size(); i++) {
      lvBuilder.addValues(valueFromObject(objList.get(i)));
    }
  }

  return lvBuilder.build();
}
 
Example #28
Source File: TypesBuilderFromDescriptor.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Creates additional types (Value, Struct and ListValue) to be added to the Service config.
 * TODO (guptasu): Fix this hack. Find a better way to add the predefined types.
 * TODO (guptasu): Add them only when required and not in all cases.
 */

static Iterable<Type> createAdditionalServiceTypes() {
  Map<String, DescriptorProto> additionalMessages = Maps.newHashMap();
  additionalMessages.put(Struct.getDescriptor().getFullName(),
      Struct.getDescriptor().toProto());
  additionalMessages.put(Value.getDescriptor().getFullName(),
      Value.getDescriptor().toProto());
  additionalMessages.put(ListValue.getDescriptor().getFullName(),
      ListValue.getDescriptor().toProto());
  additionalMessages.put(Empty.getDescriptor().getFullName(),
      Empty.getDescriptor().toProto());
  additionalMessages.put(Int32Value.getDescriptor().getFullName(),
      Int32Value.getDescriptor().toProto());
  additionalMessages.put(DoubleValue.getDescriptor().getFullName(),
      DoubleValue.getDescriptor().toProto());
  additionalMessages.put(BoolValue.getDescriptor().getFullName(),
      BoolValue.getDescriptor().toProto());
  additionalMessages.put(StringValue.getDescriptor().getFullName(),
      StringValue.getDescriptor().toProto());

  for (Descriptor descriptor : Struct.getDescriptor().getNestedTypes()) {
    additionalMessages.put(descriptor.getFullName(), descriptor.toProto());
  }

  // TODO (guptasu): Remove this hard coding. Without this, creation of Model from Service throws.
  // Needs investigation.
  String fileName = "struct.proto";
  List<Type> additionalTypes = Lists.newArrayList();
  for (String typeName : additionalMessages.keySet()) {
    additionalTypes.add(TypesBuilderFromDescriptor.createType(typeName,
        additionalMessages.get(typeName), fileName));
  }
  return additionalTypes;
}
 
Example #29
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public void doWrite(ListValue message, JsonGenerator gen) throws IOException {
  List<Value> values = message.getValuesList();
  int numElements = values.size();
  gen.writeStartArray(numElements);
  for (int i = 0; i < numElements; i++) {
    ValueMarshaller.INSTANCE.writeValue(values.get(i), gen);
  }
  gen.writeEndArray();
}
 
Example #30
Source File: WellKnownTypeMarshaller.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public void doMerge(JsonParser parser, int currentDepth, Message.Builder messageBuilder)
    throws IOException {
  JsonToken token = parser.currentToken();
  if (token != JsonToken.START_ARRAY) {
    throw new InvalidProtocolBufferException("Expect an array but found: " + parser.getText());
  }
  ListValue.Builder builder = (ListValue.Builder) messageBuilder;
  while (parser.nextValue() != JsonToken.END_ARRAY) {
    Value.Builder valueBuilder = builder.addValuesBuilder();
    ValueMarshaller.INSTANCE.mergeValue(parser, currentDepth + 1, valueBuilder);
  }
}