1 //
2 //
3 // Copyright 2016 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18
19 #include "test/cpp/qps/parse_json.h"
20
21 #include <string>
22
23 #include "absl/log/check.h"
24 #include "absl/log/log.h"
25 #include "absl/strings/str_format.h"
26 #include "src/core/util/crash.h"
27
28 namespace grpc {
29 namespace testing {
30
ParseJson(const std::string & json,const std::string & type,GRPC_CUSTOM_MESSAGE * msg)31 void ParseJson(const std::string& json, const std::string& type,
32 GRPC_CUSTOM_MESSAGE* msg) {
33 std::unique_ptr<protobuf::json::TypeResolver> type_resolver(
34 protobuf::json::NewTypeResolverForDescriptorPool(
35 "type.googleapis.com", protobuf::DescriptorPool::generated_pool()));
36 std::string binary;
37 auto status = JsonToBinaryString(
38 type_resolver.get(), "type.googleapis.com/" + type, json, &binary);
39 if (!status.ok()) {
40 std::string errmsg(status.message());
41 LOG(ERROR) << "Failed to convert json to binary: errcode=" << status.code()
42 << " msg=" << errmsg;
43 grpc_core::Crash(absl::StrFormat("JSON: %s", json.c_str()));
44 }
45 CHECK(msg->ParseFromString(binary));
46 }
47
SerializeJson(const GRPC_CUSTOM_MESSAGE & msg,const std::string & type)48 std::string SerializeJson(const GRPC_CUSTOM_MESSAGE& msg,
49 const std::string& type) {
50 std::unique_ptr<protobuf::json::TypeResolver> type_resolver(
51 protobuf::json::NewTypeResolverForDescriptorPool(
52 "type.googleapis.com", protobuf::DescriptorPool::generated_pool()));
53 std::string binary;
54 std::string json_string;
55 msg.SerializeToString(&binary);
56 auto status =
57 BinaryToJsonString(type_resolver.get(), type, binary, &json_string);
58 CHECK_OK(status);
59 return json_string;
60 }
61
62 } // namespace testing
63 } // namespace grpc
64