• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <google/protobuf/util/json_util.h>
24 #include <google/protobuf/util/type_resolver_util.h>
25 #include <grpc/support/log.h>
26 
27 namespace grpc {
28 namespace testing {
29 
ParseJson(const grpc::string & json,const grpc::string & type,GRPC_CUSTOM_MESSAGE * msg)30 void ParseJson(const grpc::string& json, const grpc::string& type,
31                GRPC_CUSTOM_MESSAGE* msg) {
32   std::unique_ptr<google::protobuf::util::TypeResolver> type_resolver(
33       google::protobuf::util::NewTypeResolverForDescriptorPool(
34           "type.googleapis.com",
35           google::protobuf::DescriptorPool::generated_pool()));
36   grpc::string binary;
37   auto status = JsonToBinaryString(
38       type_resolver.get(), "type.googleapis.com/" + type, json, &binary);
39   if (!status.ok()) {
40     grpc::string errmsg(status.error_message());
41     gpr_log(GPR_ERROR, "Failed to convert json to binary: errcode=%d msg=%s",
42             status.error_code(), errmsg.c_str());
43     gpr_log(GPR_ERROR, "JSON: %s", json.c_str());
44     abort();
45   }
46   GPR_ASSERT(msg->ParseFromString(binary));
47 }
48 
SerializeJson(const GRPC_CUSTOM_MESSAGE & msg,const grpc::string & type)49 grpc::string SerializeJson(const GRPC_CUSTOM_MESSAGE& msg,
50                            const grpc::string& type) {
51   std::unique_ptr<google::protobuf::util::TypeResolver> type_resolver(
52       google::protobuf::util::NewTypeResolverForDescriptorPool(
53           "type.googleapis.com",
54           google::protobuf::DescriptorPool::generated_pool()));
55   grpc::string binary;
56   grpc::string json_string;
57   msg.SerializeToString(&binary);
58   auto status =
59       BinaryToJsonString(type_resolver.get(), type, binary, &json_string);
60   GPR_ASSERT(status.ok());
61   return json_string;
62 }
63 
64 }  // namespace testing
65 }  // namespace grpc
66