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.isMember(field_name) && !required) {
32 return "";
33 }
34 if (!(obj.isMember(field_name) &&
35 obj[field_name].isConvertibleTo(field_type))) {
36 std::string error_msg = "Expected a field named '";
37 error_msg += field_name + "' of type '";
38 error_msg += std::to_string(field_type);
39 error_msg += "'";
40 if (!type.empty()) {
41 error_msg += " in message of type '" + type + "'";
42 }
43 error_msg += ".";
44 return error_msg;
45 }
46 return "";
47 }
48
49 } // namespace
50
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)51 ValidationResult ValidationResult::ValidateJsonObject(
52 const Json::Value &obj, const std::string &type,
53 const std::map<std::string, Json::ValueType> &required_fields,
54 const std::map<std::string, Json::ValueType> &optional_fields) {
55 for (const auto &field_spec : required_fields) {
56 auto result =
57 ValidateField(obj, type, field_spec.first, field_spec.second, true);
58 if (!result.empty()) {
59 return {result};
60 }
61 }
62 for (const auto &field_spec : optional_fields) {
63 auto result =
64 ValidateField(obj, type, field_spec.first, field_spec.second, false);
65 if (!result.empty()) {
66 return {result};
67 }
68 }
69 return {};
70 }
71
72 } // namespace webrtc_streaming
73 } // namespace cuttlefish
74