Java 类com.google.protobuf.util.JsonFormat 实例源码

项目:grpc-mate    文件:ProductDaoTest.java   
@Test
public void upsertProduct() throws Exception {
  Product product = Product.newBuilder()
      .setProductId(faker.number().randomNumber())
      .setProductName(faker.company().name())
      .setProductPrice(faker.number().randomDouble(2, 10, 100))
      .setProductStatus(ProductStatus.InStock)
      .build();
  productDao.upsertProduct(product);
  esClient.admin().indices().flush(Requests.flushRequest(INDEX)).actionGet();

  GetResponse getResponse = esClient.prepareGet(INDEX, TYPE, String.valueOf(product.getProductId())).get();
  JsonFormat.Parser jsonParser = injector.getInstance(JsonFormat.Parser.class);
  Product.Builder builder = Product.newBuilder();
  jsonParser.merge(getResponse.getSourceAsString(), builder);
  assertThat(builder.build()).isEqualTo(product);
}
项目:book_ldrtc    文件:RouteGuideUtil.java   
/**
 * Parses the JSON input file containing the list of features.
 */
public static List<Feature> parseFeatures(URL file) throws IOException {
  InputStream input = file.openStream();
  try {
    Reader reader = new InputStreamReader(input);
    try {
      FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
      JsonFormat.parser().merge(reader, database);
      return database.getFeatureList();
    } finally {
      reader.close();
    }
  } finally {
    input.close();
  }
}
项目:grpc-mate    文件:ElasticSearchModule.java   
@Override
protected void configure() {
  bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Singleton.class);
  bind(TransportClient.class).toProvider(TransportClientProvider.class).in(Singleton.class);
  bind(JsonFormat.Printer.class).toInstance(JsonFormat.printer());
  bind(JsonFormat.Parser.class).toInstance(JsonFormat.parser());
}
项目:teleport    文件:DatastoreToGcsTest.java   
@Test
public void testDatastoreToGcs_EntityToJson_noTransform() throws Exception {
  DoFnTester<Entity, String> fnTester = DoFnTester.of(EntityToJson.newBuilder()
      .setJsTransformPath(StaticValueProvider.of(null))
      .setJsTransformFunctionName(StaticValueProvider.of(null))
      .build());

  Builder entityBuilder = Entity.newBuilder();
  JsonFormat.parser().usingTypeRegistry(
      TypeRegistry.newBuilder()
          .add(Entity.getDescriptor())
          .build())
      .merge(mEntityJson, entityBuilder);

  Entity entity = entityBuilder.build();
  List<String> entityJsonOutputs = fnTester.processBundle(entity);
  Assert.assertEquals(mEntityJson, entityJsonOutputs.get(0));
}
项目:teleport    文件:DatastoreToGcsTest.java   
@Test
public void testDatastoreToGcs_EntityToJson_withTransform() throws Exception {
  DoFnTester<Entity, String> fnTester = DoFnTester.of(EntityToJson.newBuilder()
      .setJsTransformPath(StaticValueProvider.of(jsTransformPath))
      .setJsTransformFunctionName(StaticValueProvider.of("transform"))
      .build());

  Builder entityBuilder = Entity.newBuilder();
  JsonFormat.parser().usingTypeRegistry(
      TypeRegistry.newBuilder()
          .add(Entity.getDescriptor())
          .build())
      .merge(mEntityJson, entityBuilder);

  Entity entity = entityBuilder.build();
  List<String> entityJsonOutputs = fnTester.processBundle(entity);
  Assert.assertEquals(mTransformedEntityJson, entityJsonOutputs.get(0));
}
项目:teleport    文件:GcsToDatastoreTest.java   
@Test
public void testGcsToDatastore_EntityToJson_noTransform() throws Exception {
  DoFnTester<String, Entity> fnTester = DoFnTester.of(JsonToEntity.newBuilder()
      .setJsTransformPath(StaticValueProvider.of(null))
      .setJsTransformFunctionName(StaticValueProvider.of(null))
      .build());
  List<Entity> output = fnTester.processBundle(mEntityJson);
  Entity outputEntity = output.get(0);

  Printer printer = JsonFormat.printer()
      .omittingInsignificantWhitespace()
      .usingTypeRegistry(
          TypeRegistry.newBuilder()
              .add(Entity.getDescriptor())
              .build());
  Assert.assertEquals(mEntityJson, printer.print(outputEntity));
}
项目:teleport    文件:DatastoreToBqTest.java   
@Test
public void testDatastoreToBq_EntityToTableRow_notransform() throws Exception, IOException {
  DoFnTester<Entity, TableRow> fnTester = DoFnTester.of(EntityToTableRow.newBuilder()
      .setStrictCast(StaticValueProvider.of(true))
      .setTableSchemaJson(StaticValueProvider.of(mTableSchemaJson))
      .setJsTransformFunctionName(StaticValueProvider.of(null))
      .setJsTransformPath(StaticValueProvider.of(null))
  .build());

  Builder entityBuilder = Entity.newBuilder();
  JsonFormat.parser().usingTypeRegistry(
      TypeRegistry.newBuilder()
          .add(Entity.getDescriptor())
          .build())
      .merge(mEntityJson, entityBuilder);

  Entity entity = entityBuilder.build();
  List<TableRow> tableRows = fnTester.processBundle(entity);
  TableRow tr = tableRows.get(0);

  Assert.assertEquals(1, tableRows.size());
  Assert.assertEquals("key(Drawing, '31ce830e-91d0-405e-855a-abe416cadc1f')", tr.get("__key__"));
  Assert.assertEquals("79a1d9d9-e255-427a-9b09-f45157e97790", tr.get("canvasId"));
}
项目:outland    文件:FeatureSupportTest.java   
@Test
public void testToFeature() throws Exception {

  Feature feature = Feature.newBuilder()
      .setId("id1")
      .setKey("key1")
      .setGroup("app1")
      .setDescription("desc1")
      .setStatus(Status.off)
      .build();

  final String json = JsonFormat.printer().print(feature);

  final Feature feature1 = FeatureSupport.toFeature(json);

  assertEquals(feature.getId(), feature1.getId());
  assertEquals(feature.getKey(), feature1.getKey());
  assertEquals(feature.getGroup(), feature1.getGroup());
  assertEquals(feature.getDescription(), feature1.getDescription());
  assertEquals(feature.getStatus(), feature1.getStatus());

}
项目:ja-micro    文件:ProtobufUtil.java   
/**
 * Converts a protobuf message to a JSON object
 * <p>
 * Note: Preserves the field names as defined in the *.proto definition
 * Note:
 *
 * @param input the protobuf message to convert
 * @return the converted JSON object
 */
public static JsonObject protobufToJsonWithDefaultValues(Message input) {
    JsonObject object = new JsonObject();
    if (input == null) {
        logger.warn("Protobuf message was null");
    } else {
        try {
            String jsonString = JsonFormat.printer()
                .preservingProtoFieldNames()
                .includingDefaultValueFields()
                .print(input);
            object = new JsonParser().parse(jsonString).getAsJsonObject();
        } catch (Exception e) {
            throw new RuntimeException("Error deserializing protobuf to json", e);
        }
    }
    return object;
}
项目:sc2-java-api    文件:BaseSC2Client.java   
public synchronized ListenableFuture<Response> sendRawRequest(Request req) {
  SettableListenableFuture<Response> slf = new SettableListenableFuture<Response>();
  if(isConnected()) {
    try {
      if(log.isDebugEnabled()) {
        log.debug("Sending Message:{}",  JsonFormat.printer().omittingInsignificantWhitespace().print(req));
      }
    } catch (InvalidProtocolBufferException e) {
      throw new RuntimeException(e);
    }
    responseQueue.add(slf);
    client.write(WebSocketFrameParser.makeWebSocketFrame(req.toByteArray().length, WebSocketOpCode.Binary.getValue(), false).getRawFrame());
    client.write(ByteBuffer.wrap(req.toByteArray()));
    return slf;
  }
  slf.setFailure(new IOException("Client is not connected!"));
  return slf;
}
项目:endpoints-management-java    文件:ServiceConfigSupplierTest.java   
@Test
public void testFetchConfigWithWrongServiceName() throws InvalidProtocolBufferException {
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_NAME")).thenReturn(SERVICE_NAME);
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_VERSION")).thenReturn(SERVICE_VERSION);

  Service service = Service.newBuilder().setName("random-name").build();
  String content = JsonFormat.printer().print(service);
  testHttpTransport.addResponse(200, content);

  try {
    fetcher.get();
    fail();
  } catch (ServiceConfigException exception) {
    assertEquals(
        "Unexpected service name in service config: random-name", exception.getMessage());
  }
}
项目:endpoints-management-java    文件:ServiceConfigSupplierTest.java   
@Test
public void testFetchConfigWithWrongServiceVersion() throws InvalidProtocolBufferException {
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_NAME")).thenReturn(SERVICE_NAME);
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_VERSION")).thenReturn(SERVICE_VERSION);

  Service service = Service.newBuilder()
      .setName(SERVICE_NAME)
      .setId("random-version")
      .build();
  String content = JsonFormat.printer().print(service);
  testHttpTransport.addResponse(200, content);

  try {
    fetcher.get();
    fail();
  } catch (ServiceConfigException exception) {
    assertEquals(
        "Unexpected service version in service config: random-version", exception.getMessage());
  }
}
项目:grpc-sample    文件:RouteGuideUtil.java   
/**
 * Parses the JSON input file containing the list of features.
 */
public static List<Feature> parseFeatures(URL file) throws IOException {
  InputStream input = file.openStream();
  try {
    Reader reader = new InputStreamReader(input);
    try {
      FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
      JsonFormat.parser().merge(reader, database);
      return database.getFeatureList();
    } finally {
      reader.close();
    }
  } finally {
    input.close();
  }
}
项目:pokebattler-fight    文件:IndividualPokemonRepository.java   
public IndividualPokemonRepository(String file) throws Exception {
    String legacy = null;
    if (!file.equals(POKEMONGO_JSON)) {
        legacy = file.substring(0, 8);
    }
    final InputStream is = this.getClass().getResourceAsStream(file);
    if (is == null) {
        throw new IllegalArgumentException("Can not find " + file);
    }
    mapper = new ObjectMapper();
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    printer = JsonFormat.printer().includingDefaultValueFields();
    final RawData rawData = mapper.readValue(is, RawData.class);
    all = createPokemons(rawData, legacy);
    pokemonMap = all.getPokemonList().stream().collect(Collectors.toMap(p -> p.getPokemonId(), p -> p));
    log.info("Loaded {} pokemons", all.getPokemonCount());
}
项目:api-compiler    文件:VendorExtensionProtoConverter.java   
@SuppressWarnings("unchecked")
public <T extends Message> T convertJsonToProto(T prototype, String json, String extensionName) {
  try {
    Builder builder = prototype.newBuilderForType();
    JsonFormat.parser().merge(json, builder);
    return (T) builder.build();
  } catch (InvalidProtocolBufferException ex) {
    diagCollector.addDiag(
        Diag.error(
            new SimpleLocation(extensionName),
            "Extension %s cannot be converted into proto type %s. Details: %s",
            extensionName,
            prototype.getDescriptorForType().getFullName(),
            ex.getMessage()));
    return prototype;
  }
}
项目:seldon-server    文件:ClientRpcStore.java   
private JsonNode getDefaultRequestJSON(Message msg) throws JsonParseException, IOException
{
    Message.Builder o2 = DefaultCustomPredictRequest.newBuilder();
    TypeRegistry registry = TypeRegistry.newBuilder().add(o2.getDescriptorForType()).build();
    JsonFormat.Printer jPrinter = JsonFormat.printer();
    String result = jPrinter.usingTypeRegistry(registry).print(msg);
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(result);
    JsonNode jNode = mapper.readTree(parser);
    if (jNode.has(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD))
    {
        JsonNode values = jNode.get(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD).get("values");
        ((ObjectNode) jNode).set(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD, values);
    }
    return jNode;
}
项目:seldon-server    文件:ClientRpcStore.java   
public ClassificationReply getPredictReplyFromJson(String client,JsonNode json)
{
    RPCConfig config = services.get(client);
    try
    {
        TypeRegistry registry = null;
        if (config != null && config.replyClass != null && json.has(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD))
        {
            if (!json.get(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD).has("@type"))
                ((ObjectNode) json.get(PredictionBusinessServiceImpl.REPLY_CUSTOM_DATA_FIELD)).put("@type", "type.googleapis.com/" + config.replyClass.getName());
            Method m = config.replyBuilder;
            Message.Builder o = (Message.Builder) m.invoke(null);
            registry = TypeRegistry.newBuilder().add(o.getDescriptorForType()).build();
        }
        ClassificationReply.Builder builder = ClassificationReply.newBuilder();
        JsonFormat.Parser jFormatter = JsonFormat.parser();
        if (registry != null)
            jFormatter = jFormatter.usingTypeRegistry(registry);
        jFormatter.merge(json.toString(), builder);
        ClassificationReply reply = builder.build();
        return reply;
    } catch (Exception e) {
        logger.error("Failed to convert json "+json.toString()+" to PredictReply",e);
        return null;
    }
}
项目:seldon-server    文件:ClientRpcStore.java   
private ClassificationRequest getPredictRequestWithCustomDefaultFromJSON(JsonNode json) throws InvalidProtocolBufferException
  {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode data = mapper.createObjectNode();
    data.put("@type", "type.googleapis.com/" + DefaultCustomPredictRequest.class.getName());
    data.put("values", json.get(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD));
    ((ObjectNode) json).put(PredictionBusinessServiceImpl.REQUEST_CUSTOM_DATA_FIELD, data);
Message.Builder o = DefaultCustomPredictRequest.newBuilder();
TypeRegistry registry = TypeRegistry.newBuilder().add(o.getDescriptorForType()).build();
ClassificationRequest.Builder builder = ClassificationRequest.newBuilder();
JsonFormat.Parser jFormatter = JsonFormat.parser();
if (registry != null)
    jFormatter = jFormatter.usingTypeRegistry(registry);
jFormatter.merge(json.toString(), builder);
ClassificationRequest request = builder.build();
return request;
  }
项目:compliance    文件:ProtobufJsonTest.java   
@Test
@Category(ProtobufJsonTests.class)
public void ProtobufGeneratesSimpleJSONSearchVariantsRequest() throws Exception {

    SearchVariantsRequest svr = SearchVariantsRequest.newBuilder()
            .addAllCallSetIds(Arrays.asList("foo", "bar"))
            .setReferenceName("I.Am.The.Walrus")
            .setStart(500L)
            .setEnd(7654L)
            .setPageToken("snuffle.bunny")
            .setVariantSetId("great_variant_set_id")
            .build();
    String actual = JsonFormat.printer().print(svr);

    JSONAssert.assertEquals("{referenceName:I.Am.The.Walrus}", actual, false);
    JSONAssert.assertEquals("{callSetIds:[\"foo\", \"bar\"]}", actual, false);
    JSONAssert.assertEquals("{callSetIds:[\"bar\", \"foo\"]}", actual, false);
    JSONAssert.assertEquals("{variantSetId:\"great_variant_set_id\"}", actual, false);
}
项目:GDSC-SMLM    文件:SettingsManager.java   
/**
 * Write the message to a JSON string.
 *
 * @param message
 *            the message
 * @param flags
 *            the flags
 * @return the JSON string
 */
public static boolean toJSON(MessageOrBuilder message, Appendable output, int flags)
{
    try
    {
        if (printer == null)
            printer = JsonFormat.printer();
        Printer p = printer;
        if (BitFlags.anyNotSet(flags, FLAG_JSON_WHITESPACE))
            p = p.omittingInsignificantWhitespace();
        if (BitFlags.anySet(flags, FLAG_JSON_DEFAULT_VALUES))
            p = p.includingDefaultValueFields();
        p.appendTo(message, output);
        return true;
    }
    catch (IOException e)
    {
        if (BitFlags.anyNotSet(flags, FLAG_SILENT))
            IJ.log("Unable to write message: " + e.getMessage());
    }
    return false;
}
项目:GDSC-SMLM    文件:SettingsManager.java   
/**
 * Read the message from a JSON string.
 *
 * @param reader
 *            the reader
 * @param builder
 *            the builder
 * @param flags
 *            the flags
 * @return true, if successful
 */
public static boolean fromJSON(Reader reader, Message.Builder builder, int flags)
{
    try
    {
        if (parser == null)
            parser = JsonFormat.parser();
        parser.merge(reader, builder);
        return true;
    }
    catch (IOException e)
    {
        if (BitFlags.anyNotSet(flags, FLAG_SILENT))
            IJ.log("Unable to read message: " + e.getMessage());
    }
    return false;
}
项目:GDSC-SMLM    文件:FilePeakResults.java   
private Printer addMessage(StringBuilder sb, Printer printer, String name, MessageOrBuilder msg)
{
    try
    {
        if (printer == null)
            printer = JsonFormat.printer().omittingInsignificantWhitespace()
            //.includingDefaultValueFields()
            ;
        sb.append(String.format("#%s %s\n", name, printer.print(msg)));
    }
    catch (InvalidProtocolBufferException e)
    {
        // This shouldn't happen so throw it
        throw new NotImplementedException("Unable to serialise the " + name + " settings", e);
    }
    return printer;
}
项目:bazel    文件:JsonFormatFileTransportTest.java   
@Test
public void testCreatesFileAndWritesProtoJsonFormat() throws Exception {
  File output = tmp.newFile();

  BuildEventStreamProtos.BuildEvent started =
      BuildEventStreamProtos.BuildEvent.newBuilder()
          .setStarted(BuildStarted.newBuilder().setCommand("build"))
          .build();
  when(buildEvent.asStreamProto(Matchers.<BuildEventConverters>any())).thenReturn(started);
  JsonFormatFileTransport transport =
      new JsonFormatFileTransport(output.getAbsolutePath(), pathConverter);
  transport.sendBuildEvent(buildEvent, artifactGroupNamer);

  transport.close().get();
  try (InputStream in = new FileInputStream(output)) {
    Reader reader = new InputStreamReader(in);
    JsonFormat.Parser parser = JsonFormat.parser();
    BuildEventStreamProtos.BuildEvent.Builder builder =
        BuildEventStreamProtos.BuildEvent.newBuilder();
    parser.merge(reader, builder);
    assertThat(builder.build()).isEqualTo(started);
  }
}
项目:lumongo    文件:LumongoIndexManager.java   
public IndexCreateResponse createIndex(IndexCreateRequest request) throws Exception {
    globalLock.writeLock().lock();
    try {
        log.info("Creating index: <" + request.getIndexName() + ">:\n" + JsonFormat.printer().print(request));

        IndexConfig indexConfig = new IndexConfig(request);

        String indexName = indexConfig.getIndexName();
        if (indexMap.containsKey(indexName)) {
            throw new Exception("Index <" + indexName + "> already exist");
        }
        LumongoIndex i = LumongoIndex.createIndex(hazelcastManager, mongoConfig, clusterConfig, indexConfig);
        indexMap.put(indexConfig.getIndexName(), i);
        i.loadAllSegments();
        i.forceBalance(hazelcastManager.getMembers());

        log.info("Created index: <" + request.getIndexName() + ">");

        return IndexCreateResponse.newBuilder().build();
    }
    finally {
        globalLock.writeLock().unlock();
    }
}
项目:lumongo    文件:IndexResource.java   
@GET
@Produces({ MediaType.APPLICATION_JSON + ";charset=utf-8" })
public Response get(@Context Response response, @QueryParam(LumongoConstants.INDEX) String index, @QueryParam(LumongoConstants.PRETTY) boolean pretty) {

    try {
        StringBuilder responseBuilder = new StringBuilder();

        IndexConfig indexConfig = indexManager.getIndexConfig(index);

        responseBuilder.append("{");
        responseBuilder.append("\"indexName\": ");
        responseBuilder.append("\"");
        responseBuilder.append(indexConfig.getIndexName());
        responseBuilder.append("\"");
        responseBuilder.append(",");
        responseBuilder.append("\"numberOfSegments\": ");
        responseBuilder.append(indexConfig.getNumberOfSegments());
        responseBuilder.append(",");
        responseBuilder.append("\"indexSettings\": ");
        JsonFormat.Printer printer = JsonFormat.printer();
        responseBuilder.append(printer.print(indexConfig.getIndexSettings()));
        responseBuilder.append("}");

        String docString = responseBuilder.toString();

        if (pretty) {
            docString = JsonWriter.formatJson(docString);
        }

        return Response.status(LumongoConstants.SUCCESS).entity(docString).build();

    }
    catch (Exception e) {
        return Response.status(LumongoConstants.INTERNAL_ERROR).entity("Failed to get index names: " + e.getMessage()).build();
    }

}
项目:grpc-java    文件:RouteGuideUtil.java   
/**
 * Parses the JSON input file containing the list of features.
 */
public static List<Feature> parseFeatures(URL file) throws IOException {
  InputStream input = file.openStream();
  try {
    Reader reader = new InputStreamReader(input, Charset.forName("UTF-8"));
    try {
      FeatureDatabase.Builder database = FeatureDatabase.newBuilder();
      JsonFormat.parser().merge(reader, database);
      return database.getFeatureList();
    } finally {
      reader.close();
    }
  } finally {
    input.close();
  }
}
项目:teleport    文件:DatastoreToGcs.java   
private JsonFormat.Printer getJsonPrinter() {
  if (mJsonPrinter == null) {
    TypeRegistry typeRegistry = TypeRegistry.newBuilder()
        .add(Entity.getDescriptor())
        .build();

    mJsonPrinter = JsonFormat.printer()
        .usingTypeRegistry(typeRegistry)
        .omittingInsignificantWhitespace();
  }
  return mJsonPrinter;
}
项目:teleport    文件:GcsToDatastore.java   
private JsonFormat.Parser getJsonParser() {
  if (mJsonParser == null) {
    TypeRegistry typeRegistry = TypeRegistry.newBuilder()
        .add(Entity.getDescriptor())
        .build();

    mJsonParser = JsonFormat.parser()
        .usingTypeRegistry(typeRegistry);
  }
  return mJsonParser;
}
项目:rejoiner    文件:GraphQlStreamObserver.java   
@Override
public void onNext(T value) {
  List<Value> path =
      dataFetchingEnvironment
          .getFieldTypeInfo()
          .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);
  }
}
项目:outland    文件:ContentSupport.java   
byte[] toJsonBytes(Message message) {
  try {
    String json = JsonFormat.printer().preservingProtoFieldNames().print(message);
    return json.getBytes(StandardCharsets.UTF_8);
  } catch (Exception e) {
    throw new FeatureException(Problem.localProblem(e.getMessage(), ""), e);
  }
}
项目:outland    文件:GroupSupport.java   
public static Group toGroup(String json) {

    try {
      Group.Builder builder = Group.newBuilder();
      JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
      return builder.build();
    } catch (InvalidProtocolBufferException e) {
      throw new RuntimeException(e);
    }
  }
项目:outland    文件:Protobuf3Support.java   
public static String toJsonString(Message message) {
  try {
    return JsonFormat.printer()
        .includingDefaultValueFields()
        .preservingProtoFieldNames()
        .print(message);
  } catch (Exception e) {
    throw new RuntimeException(e.getMessage(), e);
  }
}
项目:outland    文件:FeatureSupport.java   
public static Feature toFeature(String json) {

    try {
      Feature.Builder builder = Feature.newBuilder();
      JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
      return builder.build();
    } catch (InvalidProtocolBufferException e) {
      throw new RuntimeException(e);
    }
  }
项目:ja-micro    文件:ProtobufUtil.java   
/**
 * Converts a protobuf message to a JSON object
 * <p>
 * Note: Preserves the field names as defined in the *.proto definition
 *
 * @param input the protobuf message to convert
 * @return the converted JSON object
 */
public static JsonObject protobufToJson(Message input) {
    JsonObject object = new JsonObject();
    if (input == null) {
        logger.warn("Protobuf message was null");
    } else {
        try {
            String jsonString = JsonFormat.printer().preservingProtoFieldNames().print(input);
            object = new JsonParser().parse(jsonString).getAsJsonObject();
        } catch (Exception e) {
            throw new RuntimeException("Error deserializing protobuf to json", e);
        }
    }
    return object;
}
项目:amazon-gamelift-serversdk-java    文件:AuxProxyMessageSender.java   
private Ack _createAckFunction(final SettableFuture<DescribePlayerSessionsOutcome> future) {
    return new Ack() {
        @Override
        public void call(Object... objects) {
            if (objects.length == 0 || objects[0] == null) {
                future.set(new DescribePlayerSessionsOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED)));
            }

            boolean value = (boolean) objects[0];

            if (value) {
                try {
                    Sdk.DescribePlayerSessionsResponse.Builder builder = Sdk.DescribePlayerSessionsResponse.newBuilder();
                    JsonFormat.parser().merge((String)objects[1], builder);

                    Sdk.DescribePlayerSessionsResponse response = builder.build();

                    DescribePlayerSessionsResult result = transformResponse(response);

                    future.set(new DescribePlayerSessionsOutcome(result));

                } catch (InvalidProtocolBufferException e) {
                    future.set(new DescribePlayerSessionsOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED, e)));
                }
            } else {
                future.set(new DescribePlayerSessionsOutcome(new GameLiftError(GameLiftErrorType.SERVICE_CALL_FAILED)));
            }
        }
    };
}
项目:endpoints-management-java    文件:ServiceConfigSupplier.java   
private static Service parseHttpResponse(HttpResponse httpResponse) {
  try {
    Builder builder = Service.newBuilder();
    JsonFormat.parser().merge(httpResponse.parseAsString(), builder);
    return builder.build();
  } catch (IOException exception) {
    throw new ServiceConfigException(
        "Failed to parse the HTTP response as service configuration",
        exception);
  }
}
项目:endpoints-management-java    文件:ServiceConfigSupplierTest.java   
@Test
public void testServiceVersionNotSet() throws IOException {
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_NAME")).thenReturn(SERVICE_NAME);
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_VERSION")).thenReturn(null);

  testHttpTransport.addResponse(
      200, "{\"serviceConfigs\": [{\"id\": \"" + SERVICE_VERSION + "\"}]}");
  String content = JsonFormat.printer().print(SERVICE);
  testHttpTransport.addResponse(200, content);

  assertEquals(SERVICE, fetcher.get());
}
项目:endpoints-management-java    文件:ServiceConfigSupplierTest.java   
@Test
public void testFetchSuccessfully() throws InvalidProtocolBufferException {
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_NAME")).thenReturn(SERVICE_NAME);
  when(mockEnvironment.getVariable("ENDPOINTS_SERVICE_VERSION")).thenReturn(SERVICE_VERSION);

  String content = JsonFormat.printer().print(SERVICE);
  testHttpTransport.addResponse(200, content);

  assertEquals(SERVICE, fetcher.get());
}
项目:endpoints-management-java    文件:ReportingRuleTest.java   
@Test
public void shouldCreateFromAServiceOk() throws IOException {
  String jsonText = Resources.toString(MONITORED_SERVICE_JSON, Charset.defaultCharset());
  Builder b = Service.newBuilder();
  JsonFormat.parser().merge(jsonText, b);
  ReportingRule rule =
      ReportingRule.fromService(b.build());
  assertThat(Arrays.asList(rule.getLabels())).containsExactlyElementsIn(WANTED_LABELS);
  assertThat(Arrays.asList(rule.getMetrics())).containsExactlyElementsIn(WANTED_METRICS);
  assertThat(Arrays.asList(rule.getLogs())).containsExactlyElementsIn(WANTED_LOGS);
}
项目:polyglot    文件:ConfigurationLoader.java   
/** Returns a loader backed by config set obtained from the supplied file. */
public static ConfigurationLoader forFile(Path configFile) {
  try {
    ConfigurationSet.Builder configSetBuilder = ConfigurationSet.newBuilder();
    String fileContent = Joiner.on('\n').join(Files.readAllLines(configFile));
    JsonFormat.parser().merge(fileContent, configSetBuilder);
    return ConfigurationLoader.forConfigSet(configSetBuilder.build());
  } catch (IOException e) {
    throw new RuntimeException("Unable to read config file: " + configFile.toString(), e);
  }
}