Java Code Examples for com.google.protobuf.Struct#Builder

The following examples show how to use com.google.protobuf.Struct#Builder . 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: SdsClientTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 2
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 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: 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 findExperimentsStructTypeNotImplemented() {
  LOGGER.info(
      "Check for protobuf struct type in KeyValueQuery not implemented in findExperiments 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);

  FindExperiments findExperiments =
      FindExperiments.newBuilder()
          .setProjectId(project1.getId())
          .addAllPredicates(predicates)
          .build();

  try {
    experimentServiceStub.findExperiments(findExperiments);
    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 in findExperiments test stop........");
}
 
Example 5
Source File: StructDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
protected void populate(
        Struct.Builder builder,
        JsonParser parser,
        DeserializationContext context
) throws IOException {
  List<Message> entries = readMap(builder, FIELDS_FIELD, parser, context);
  for (Message entry : entries) {
    builder.addRepeatedField(FIELDS_FIELD, entry);
  }
}
 
Example 6
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 7
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 8
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 findDatasetStructTypeNotImplemented() {
  LOGGER.info(
      "check for protobuf struct type in KeyValueQuery not implemented test start........");

  DatasetTest datasetTest = new DatasetTest();

  // 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();

  FindDatasets findDatasets =
      FindDatasets.newBuilder()
          .addDatasetIds(dataset1.getId())
          .addPredicates(keyValueQuery)
          .build();

  try {
    datasetServiceStub.findDatasets(findDatasets);
    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 start........");
}
 
Example 9
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 10
Source File: ReportState.java    From smart-home-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 11
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 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................................");
}
 
Example 12
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 13
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 {
  Struct.Builder builder = (Struct.Builder) messageBuilder;
  while (parser.nextValue() != JsonToken.END_OBJECT) {
    builder.putFields(
        parser.getCurrentName(), ValueMarshaller.INSTANCE.readValue(parser, currentDepth + 1));
  }
}
 
Example 14
Source File: QueryResponseToProtoJson.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example 15
Source File: TestResources.java    From java-control-plane with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 16
Source File: MessageMarshallerTest.java    From curiostack with MIT License 4 votes vote down vote up
@Test
public void anyFields() throws Exception {
  TestAllTypes content = TestAllTypes.newBuilder().setOptionalInt32(1234).build();
  TestAny message = TestAny.newBuilder().setAnyValue(Any.pack(content)).build();
  assertMatchesUpstream(message, TestAllTypes.getDefaultInstance());

  TestAny messageWithDefaultAnyValue =
      TestAny.newBuilder().setAnyValue(Any.getDefaultInstance()).build();
  assertMatchesUpstream(messageWithDefaultAnyValue);

  // Well-known types have a special formatting when embedded in Any.
  //
  // 1. Any in Any.
  Any anyMessage = Any.pack(Any.pack(content));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 2. Wrappers in Any.
  anyMessage = Any.pack(Int32Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(UInt32Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(Int64Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(UInt64Value.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(FloatValue.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(DoubleValue.newBuilder().setValue(12345).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(BoolValue.newBuilder().setValue(true).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage = Any.pack(StringValue.newBuilder().setValue("Hello").build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
  anyMessage =
      Any.pack(BytesValue.newBuilder().setValue(ByteString.copyFrom(new byte[] {1, 2})).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 3. Timestamp in Any.
  anyMessage = Any.pack(Timestamps.parse("1969-12-31T23:59:59Z"));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 4. Duration in Any
  anyMessage = Any.pack(Durations.parse("12345.10s"));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 5. FieldMask in Any
  anyMessage = Any.pack(FieldMaskUtil.fromString("foo.bar,baz"));
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 6. Struct in Any
  Struct.Builder structBuilder = Struct.newBuilder();
  structBuilder.putFields("number", Value.newBuilder().setNumberValue(1.125).build());
  anyMessage = Any.pack(structBuilder.build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 7. Value (number type) in Any
  Value.Builder valueBuilder = Value.newBuilder();
  valueBuilder.setNumberValue(1);
  anyMessage = Any.pack(valueBuilder.build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());

  // 8. Value (null type) in Any
  anyMessage = Any.pack(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
  assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance());
}
 
Example 17
Source File: Bootstrapper.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
@SuppressWarnings("deprecation")
static BootstrapInfo parseConfig(String rawData) throws IOException {
  XdsLogger logger = XdsLogger.withPrefix(LOG_PREFIX);
  logger.log(XdsLogLevel.INFO, "Reading bootstrap information");
  @SuppressWarnings("unchecked")
  Map<String, ?> rawBootstrap = (Map<String, ?>) JsonParser.parse(rawData);
  logger.log(XdsLogLevel.DEBUG, "Bootstrap configuration:\n{0}", rawBootstrap);

  List<ServerInfo> servers = new ArrayList<>();
  List<?> rawServerConfigs = JsonUtil.getList(rawBootstrap, "xds_servers");
  if (rawServerConfigs == null) {
    throw new IOException("Invalid bootstrap: 'xds_servers' does not exist.");
  }
  logger.log(XdsLogLevel.INFO, "Configured with {0} xDS servers", rawServerConfigs.size());
  List<Map<String, ?>> serverConfigList = JsonUtil.checkObjectList(rawServerConfigs);
  for (Map<String, ?> serverConfig : serverConfigList) {
    String serverUri = JsonUtil.getString(serverConfig, "server_uri");
    if (serverUri == null) {
      throw new IOException("Invalid bootstrap: 'xds_servers' contains unknown server.");
    }
    logger.log(XdsLogLevel.INFO, "xDS server URI: {0}", serverUri);
    List<ChannelCreds> channelCredsOptions = new ArrayList<>();
    List<?> rawChannelCredsList = JsonUtil.getList(serverConfig, "channel_creds");
    // List of channel creds is optional.
    if (rawChannelCredsList != null) {
      List<Map<String, ?>> channelCredsList = JsonUtil.checkObjectList(rawChannelCredsList);
      for (Map<String, ?> channelCreds : channelCredsList) {
        String type = JsonUtil.getString(channelCreds, "type");
        if (type == null) {
          throw new IOException("Invalid bootstrap: 'xds_servers' contains server with "
              + "unknown type 'channel_creds'.");
        }
        logger.log(XdsLogLevel.INFO, "Channel credentials option: {0}", type);
        ChannelCreds creds = new ChannelCreds(type, JsonUtil.getObject(channelCreds, "config"));
        channelCredsOptions.add(creds);
      }
    }
    servers.add(new ServerInfo(serverUri, channelCredsOptions));
  }

  Node.Builder nodeBuilder = Node.newBuilder();
  Map<String, ?> rawNode = JsonUtil.getObject(rawBootstrap, "node");
  if (rawNode != null) {
    String id = JsonUtil.getString(rawNode, "id");
    if (id != null) {
      logger.log(XdsLogLevel.INFO, "Node id: {0}", id);
      nodeBuilder.setId(id);
    }
    String cluster = JsonUtil.getString(rawNode, "cluster");
    if (cluster != null) {
      logger.log(XdsLogLevel.INFO, "Node cluster: {0}", cluster);
      nodeBuilder.setCluster(cluster);
    }
    Map<String, ?> metadata = JsonUtil.getObject(rawNode, "metadata");
    if (metadata != null) {
      Struct.Builder structBuilder = Struct.newBuilder();
      for (Map.Entry<String, ?> entry : metadata.entrySet()) {
        logger.log(
            XdsLogLevel.INFO,
            "Node metadata field {0}: {1}", entry.getKey(), entry.getValue());
        structBuilder.putFields(entry.getKey(), convertToValue(entry.getValue()));
      }
      nodeBuilder.setMetadata(structBuilder);
    }
    Map<String, ?> rawLocality = JsonUtil.getObject(rawNode, "locality");
    if (rawLocality != null) {
      Locality.Builder localityBuilder = Locality.newBuilder();
      if (rawLocality.containsKey("region")) {
        String region = JsonUtil.getString(rawLocality, "region");
        logger.log(XdsLogLevel.INFO, "Locality region: {0}", region);
        localityBuilder.setRegion(region);
      }
      if (rawLocality.containsKey("zone")) {
        String zone = JsonUtil.getString(rawLocality, "zone");
        logger.log(XdsLogLevel.INFO, "Locality zone: {0}", zone);
        localityBuilder.setZone(zone);
      }
      if (rawLocality.containsKey("sub_zone")) {
        String subZone = JsonUtil.getString(rawLocality, "sub_zone");
        logger.log(XdsLogLevel.INFO, "Locality sub_zone: {0}", subZone);
        localityBuilder.setSubZone(subZone);
      }
      nodeBuilder.setLocality(localityBuilder);
    }
  }
  GrpcBuildVersion buildVersion = GrpcUtil.getGrpcBuildVersion();
  logger.log(XdsLogLevel.INFO, "Build version: {0}", buildVersion);
  nodeBuilder.setBuildVersion(buildVersion.toString());
  nodeBuilder.setUserAgentName(buildVersion.getUserAgent());
  nodeBuilder.setUserAgentVersion(buildVersion.getImplementationVersion());
  nodeBuilder.addClientFeatures(CLIENT_FEATURE_DISABLE_OVERPROVISIONING);

  return new BootstrapInfo(servers, nodeBuilder.build());
}
 
Example 18
Source File: SdsClientFileBasedMetadataTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
static ConfigSource buildConfigSourceWithCreds(
    String targetUri,
    String channelType,
    String filename,
    String headerPrefix,
    String pluginName) {
  GoogleGrpc.Builder googleGrpcBuilder = GoogleGrpc.newBuilder().setTargetUri(targetUri);

  if (filename != null) {
    googleGrpcBuilder.setStatPrefix("sdsstat");
    googleGrpcBuilder.setCredentialsFactoryName(pluginName);
    googleGrpcBuilder.setChannelCredentials(
        ChannelCredentials.newBuilder()
            .setLocalCredentials(GoogleLocalCredentials.newBuilder())
            .build());

    Struct.Builder configStructBuilder =
        Struct.newBuilder()
            .putFields(
                "header_key",
                Value.newBuilder().setStringValue(K8S_SA_JWT_TOKEN_HEADER_KEYNAME).build())
            .putFields(
                FileBasedPluginCredential.SECRET_DATA,
                Value.newBuilder()
                    .setStructValue(
                        Struct.newBuilder()
                            .putFields(
                                FileBasedPluginCredential.FILENAME,
                                Value.newBuilder().setStringValue(filename).build()))
                    .build());

    if (headerPrefix != null) {
      configStructBuilder.putFields(
          FileBasedPluginCredential.HEADER_PREFIX,
          Value.newBuilder().setStringValue(headerPrefix).build());
    }

    MetadataCredentialsFromPlugin.Builder metadataCredBuilder =
            MetadataCredentialsFromPlugin.newBuilder().setName(pluginName);
    metadataCredBuilder.setConfig(configStructBuilder);

    CallCredentials.Builder callCredBuilder =
        CallCredentials.newBuilder().setFromPlugin(metadataCredBuilder);
    googleGrpcBuilder.addCallCredentials(callCredBuilder);
  }
  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();
}