• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "host/frontend/webrtc/lib/utils.h"
18 
19 #include <map>
20 
21 #include <json/json.h>
22 
23 namespace cuttlefish {
24 namespace webrtc_streaming {
25 
26 namespace {
27 
ValidateField(const Json::Value & obj,const std::string & type,const std::string & field_name,const Json::ValueType & field_type,bool required)28 std::string ValidateField(const Json::Value &obj, const std::string &type,
29                           const std::string &field_name,
30                           const Json::ValueType &field_type, bool required) {
31   if (!obj.isObject()) {
32     return "Expected object with name-value pairs";
33   }
34   if (!obj.isMember(field_name) && !required) {
35     return "";
36   }
37   if (!(obj.isMember(field_name) &&
38         obj[field_name].isConvertibleTo(field_type))) {
39     std::string error_msg = "Expected a field named '";
40     error_msg += field_name + "' of type '";
41     error_msg += std::to_string(field_type);
42     error_msg += "'";
43     if (!type.empty()) {
44       error_msg += " in message of type '" + type + "'";
45     }
46     error_msg += ".";
47     return error_msg;
48   }
49   return "";
50 }
51 
52 }  // namespace
53 
ValidateJsonObject(const Json::Value & obj,const std::string & type,const std::map<std::string,Json::ValueType> & required_fields,const std::map<std::string,Json::ValueType> & optional_fields)54 ValidationResult ValidationResult::ValidateJsonObject(
55     const Json::Value &obj, const std::string &type,
56     const std::map<std::string, Json::ValueType> &required_fields,
57     const std::map<std::string, Json::ValueType> &optional_fields) {
58   for (const auto &field_spec : required_fields) {
59     auto result =
60         ValidateField(obj, type, field_spec.first, field_spec.second, true);
61     if (!result.empty()) {
62       return {result};
63     }
64   }
65   for (const auto &field_spec : optional_fields) {
66     auto result =
67         ValidateField(obj, type, field_spec.first, field_spec.second, false);
68     if (!result.empty()) {
69       return {result};
70     }
71   }
72   return {};
73 }
74 
75 }  // namespace webrtc_streaming
76 }  // namespace cuttlefish
77