diff --git a/include/envoy/json/json_object.h b/include/envoy/json/json_object.h index f78331a1d0ef..57d24cf8d0fb 100644 --- a/include/envoy/json/json_object.h +++ b/include/envoy/json/json_object.h @@ -13,7 +13,7 @@ namespace Envoy { namespace Json { class Object; -typedef std::unique_ptr ObjectPtr; +typedef std::shared_ptr ObjectSharedPtr; // @return false if immediate exit from iteration required. typedef std::function ObjectCallback; @@ -36,9 +36,9 @@ class Object { /** * Convert a generic object into an array of objects. This is useful for dealing * with arrays of arrays. - * @return std::vector the converted object. + * @return std::vector the converted object. */ - virtual std::vector asObjectArray() const PURE; + virtual std::vector asObjectArray() const PURE; /** * Get a boolean value by name. @@ -75,16 +75,16 @@ class Object { * @param name supplies the key name. * @param allow_empty supplies whether to return an empty object if the key does not * exist. - * @return ObjectObjectPtr the sub-object. + * @return ObjectObjectSharedPtr the sub-object. */ - virtual ObjectPtr getObject(const std::string& name, bool allow_empty = false) const PURE; + virtual ObjectSharedPtr getObject(const std::string& name, bool allow_empty = false) const PURE; /** * Get an array by name. * @param name supplies the key name. - * @return std::vector the array of JSON objects. + * @return std::vector the array of JSON objects. */ - virtual std::vector getObjectArray(const std::string& name) const PURE; + virtual std::vector getObjectArray(const std::string& name) const PURE; /** * Get a string value by name. diff --git a/source/common/dynamo/dynamo_filter.cc b/source/common/dynamo/dynamo_filter.cc index cd7fb636230f..4bfef99d77e2 100644 --- a/source/common/dynamo/dynamo_filter.cc +++ b/source/common/dynamo/dynamo_filter.cc @@ -52,7 +52,7 @@ void DynamoFilter::onDecodeComplete(const Buffer::Instance& data) { std::string body = buildBody(decoder_callbacks_->decodingBuffer(), data); if (!body.empty()) { try { - Json::ObjectPtr json_body = Json::Factory::loadFromString(body); + Json::ObjectSharedPtr json_body = Json::Factory::loadFromString(body); table_descriptor_ = RequestParser::parseTable(operation_, *json_body); } catch (const Json::Exception& jsonEx) { // Body parsing failed. This should not happen, just put a stat for that. @@ -72,7 +72,7 @@ void DynamoFilter::onEncodeComplete(const Buffer::Instance& data) { std::string body = buildBody(encoder_callbacks_->encodingBuffer(), data); if (!body.empty()) { try { - Json::ObjectPtr json_body = Json::Factory::loadFromString(body); + Json::ObjectSharedPtr json_body = Json::Factory::loadFromString(body); chargeTablePartitionIdStats(*json_body); if (Http::CodeUtility::is4xx(status)) { diff --git a/source/common/dynamo/dynamo_request_parser.cc b/source/common/dynamo/dynamo_request_parser.cc index 853fd14d2dc3..7929749f9ecf 100644 --- a/source/common/dynamo/dynamo_request_parser.cc +++ b/source/common/dynamo/dynamo_request_parser.cc @@ -75,7 +75,7 @@ RequestParser::TableDescriptor RequestParser::parseTable(const std::string& oper table.table_name = json_data.getString("TableName", ""); } else if (find(BATCH_OPERATIONS.begin(), BATCH_OPERATIONS.end(), operation) != BATCH_OPERATIONS.end()) { - Json::ObjectPtr tables = json_data.getObject("RequestItems", true); + Json::ObjectSharedPtr tables = json_data.getObject("RequestItems", true); tables->iterate([&table](const std::string& key, const Json::Object&) { if (table.table_name.empty()) { table.table_name = key; @@ -94,7 +94,7 @@ RequestParser::TableDescriptor RequestParser::parseTable(const std::string& oper } std::vector RequestParser::parseBatchUnProcessedKeys(const Json::Object& json_data) { std::vector unprocessed_tables; - Json::ObjectPtr tables = json_data.getObject("UnprocessedKeys", true); + Json::ObjectSharedPtr tables = json_data.getObject("UnprocessedKeys", true); tables->iterate([&unprocessed_tables](const std::string& key, const Json::Object&) { unprocessed_tables.emplace_back(key); return true; @@ -126,7 +126,7 @@ std::vector RequestParser::parsePartitions(const Json::Object& json_data) { std::vector partition_descriptors; - Json::ObjectPtr partitions = + Json::ObjectSharedPtr partitions = json_data.getObject("ConsumedCapacity", true)->getObject("Partitions", true); partitions->iterate([&partition_descriptors, &partitions](const std::string& key, const Json::Object&) { diff --git a/source/common/filter/auth/client_ssl.cc b/source/common/filter/auth/client_ssl.cc index 9bd108460e33..ba541449b400 100644 --- a/source/common/filter/auth/client_ssl.cc +++ b/source/common/filter/auth/client_ssl.cc @@ -62,8 +62,8 @@ GlobalStats Config::generateStats(Stats::Store& store, const std::string& prefix void Config::parseResponse(const Http::Message& message) { AllowedPrincipalsSharedPtr new_principals(new AllowedPrincipals()); - Json::ObjectPtr loader = Json::Factory::loadFromString(message.bodyAsString()); - for (const Json::ObjectPtr& certificate : loader->getObjectArray("certificates")) { + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(message.bodyAsString()); + for (const Json::ObjectSharedPtr certificate : loader->getObjectArray("certificates")) { new_principals->add(certificate->getString("fingerprint_sha256")); } diff --git a/source/common/filter/ratelimit.cc b/source/common/filter/ratelimit.cc index 4db06de6b3bf..1f72f0620f14 100644 --- a/source/common/filter/ratelimit.cc +++ b/source/common/filter/ratelimit.cc @@ -18,9 +18,9 @@ Config::Config(const Json::Object& config, Stats::Store& stats_store, Runtime::L config.validateSchema(Json::Schema::RATELIMIT_NETWORK_FILTER_SCHEMA); - for (const Json::ObjectPtr& descriptor : config.getObjectArray("descriptors")) { + for (const Json::ObjectSharedPtr descriptor : config.getObjectArray("descriptors")) { Descriptor new_descriptor; - for (const Json::ObjectPtr& entry : descriptor->asObjectArray()) { + for (const Json::ObjectSharedPtr entry : descriptor->asObjectArray()) { new_descriptor.entries_.push_back({entry->getString("key"), entry->getString("value")}); } descriptors_.push_back(new_descriptor); diff --git a/source/common/filter/tcp_proxy.cc b/source/common/filter/tcp_proxy.cc index a27aa319c405..570976401d35 100644 --- a/source/common/filter/tcp_proxy.cc +++ b/source/common/filter/tcp_proxy.cc @@ -47,7 +47,7 @@ TcpProxyConfig::TcpProxyConfig(const Json::Object& config, : stats_(generateStats(config.getString("stat_prefix"), stats_store)) { config.validateSchema(Json::Schema::TCP_PROXY_NETWORK_FILTER_SCHEMA); - for (const Json::ObjectPtr& route_desc : + for (const Json::ObjectSharedPtr route_desc : config.getObject("route_config")->getObjectArray("routes")) { routes_.emplace_back(Route(*route_desc)); diff --git a/source/common/http/access_log/access_log_impl.cc b/source/common/http/access_log/access_log_impl.cc index 49fcb0c31768..0d4f1bab1bd9 100644 --- a/source/common/http/access_log/access_log_impl.cc +++ b/source/common/http/access_log/access_log_impl.cc @@ -109,7 +109,7 @@ bool RuntimeFilter::evaluate(const RequestInfo&, const HeaderMap& request_header } OperatorFilter::OperatorFilter(const Json::Object& json, Runtime::Loader& runtime) { - for (Json::ObjectPtr& filter : json.getObjectArray("filters")) { + for (Json::ObjectSharedPtr filter : json.getObjectArray("filters")) { filters_.emplace_back(FilterImpl::fromJson(*filter, runtime)); } } @@ -163,7 +163,7 @@ InstanceSharedPtr InstanceImpl::fromJson(Json::Object& json, Runtime::Loader& ru FilterPtr filter; if (json.hasObject("filter")) { - Json::ObjectPtr filterObject = json.getObject("filter"); + Json::ObjectSharedPtr filterObject = json.getObject("filter"); filter = FilterImpl::fromJson(*filterObject, runtime); } diff --git a/source/common/http/filter/fault_filter.cc b/source/common/http/filter/fault_filter.cc index f18df7ab496f..d3735ca7d764 100644 --- a/source/common/http/filter/fault_filter.cc +++ b/source/common/http/filter/fault_filter.cc @@ -27,8 +27,8 @@ FaultFilterConfig::FaultFilterConfig(const Json::Object& json_config, Runtime::L json_config.validateSchema(Json::Schema::FAULT_HTTP_FILTER_SCHEMA); - const Json::ObjectPtr config_abort = json_config.getObject("abort", true); - const Json::ObjectPtr config_delay = json_config.getObject("delay", true); + const Json::ObjectSharedPtr config_abort = json_config.getObject("abort", true); + const Json::ObjectSharedPtr config_delay = json_config.getObject("delay", true); if (config_abort->empty() && config_delay->empty()) { throw EnvoyException("fault filter must have at least abort or delay specified in the config."); @@ -51,8 +51,8 @@ FaultFilterConfig::FaultFilterConfig(const Json::Object& json_config, Runtime::L } if (json_config.hasObject("headers")) { - std::vector config_headers = json_config.getObjectArray("headers"); - for (const Json::ObjectPtr& header_map : config_headers) { + std::vector config_headers = json_config.getObjectArray("headers"); + for (const Json::ObjectSharedPtr header_map : config_headers) { fault_filter_headers_.push_back(*header_map); } } diff --git a/source/common/json/BUILD b/source/common/json/BUILD index 590a783ececa..3e11dc186cd8 100644 --- a/source/common/json/BUILD +++ b/source/common/json/BUILD @@ -19,7 +19,12 @@ envoy_cc_library( srcs = ["json_loader.cc"], hdrs = ["json_loader.h"], external_deps = ["rapidjson"], - deps = ["//include/envoy/json:json_object_interface"], + deps = [ + "//include/envoy/json:json_object_interface", + "//source/common/common:assert_lib", + "//source/common/common:utility_lib", + "//source/common/filesystem:filesystem_lib", + ], ) envoy_cc_library( diff --git a/source/common/json/json_loader.cc b/source/common/json/json_loader.cc index c5c646592b49..5965b6c4990b 100644 --- a/source/common/json/json_loader.cc +++ b/source/common/json/json_loader.cc @@ -2,242 +2,682 @@ #include #include +#include +#include +#include #include +#include #include +#include "common/common/assert.h" +#include "common/common/utility.h" +#include "common/filesystem/filesystem_impl.h" + #include "spdlog/spdlog.h" // Do not let RapidJson leak outside of this file. #include "rapidjson/document.h" #include "rapidjson/error/en.h" -#include "rapidjson/istreamwrapper.h" +#include "rapidjson/reader.h" #include "rapidjson/schema.h" +#include "rapidjson/stream.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" namespace Envoy { namespace Json { +namespace { /** - * Implementation of Object. + * Internal representation of Object. */ -class ObjectImplBase : public Object { +class Field; +typedef std::shared_ptr FieldSharedPtr; + +class Field : public Object, public std::enable_shared_from_this { public: - ObjectImplBase(const rapidjson::Value& value, const std::string& name) - : name_(name), value_(value) {} + void setLineNumberStart(uint64_t line_number) { line_number_start_ = line_number; } + void setLineNumberEnd(uint64_t line_number) { line_number_end_ = line_number; } - std::vector asObjectArray() const override { - if (!value_.IsArray()) { - throw Exception(fmt::format("'{}' is not an array", name_)); - } + // Container factories for handler. + // TODO(danielhochman): figure out how to do make_shared on private constructors + static FieldSharedPtr createObject() { return FieldSharedPtr{new Field(Type::Object)}; } + static FieldSharedPtr createArray() { return FieldSharedPtr{new Field(Type::Array)}; } + static FieldSharedPtr createNull() { return FieldSharedPtr{new Field(Type::Null)}; } - std::vector object_array; - object_array.reserve(value_.Size()); - for (auto& array_value : value_.GetArray()) { - object_array.emplace_back(new ObjectImplBase(array_value, name_ + " (array item)")); - } - return object_array; + bool isArray() const { return type_ == Type::Array; } + bool isObject() const { return type_ == Type::Object; } + + // Value factory. + template static FieldSharedPtr createValue(T value) { + return FieldSharedPtr{new Field(value)}; } - bool getBoolean(const std::string& name) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() || !member_itr->value.IsBool()) { - throw Exception(fmt::format("key '{}' missing or not a boolean in '{}'", name, name_)); - } - return member_itr->value.GetBool(); + void append(FieldSharedPtr field_ptr) { + checkType(Type::Array); + value_.array_value_.push_back(field_ptr); + } + void insert(const std::string& key, FieldSharedPtr field_ptr) { + checkType(Type::Object); + value_.object_value_[key] = field_ptr; } - bool getBoolean(const std::string& name, bool default_value) const override { - if (!value_.HasMember(name.c_str())) { - return default_value; - } else { - return getBoolean(name); + uint64_t hash() const override; + + bool getBoolean(const std::string& name) const override; + bool getBoolean(const std::string& name, bool default_value) const override; + double getDouble(const std::string& name) const override; + double getDouble(const std::string& name, double default_value) const override; + int64_t getInteger(const std::string& name) const override; + int64_t getInteger(const std::string& name, int64_t default_value) const override; + ObjectSharedPtr getObject(const std::string& name, bool allow_empty) const override; + std::vector getObjectArray(const std::string& name) const override; + std::string getString(const std::string& name) const override; + std::string getString(const std::string& name, const std::string& default_value) const override; + std::vector getStringArray(const std::string& name) const override; + std::vector asObjectArray() const override; + std::string asString() const override { return stringValue(); } + + bool empty() const override; + bool hasObject(const std::string& name) const override; + void iterate(const ObjectCallback& callback) const override; + void validateSchema(const std::string& schema) const override; + +private: + enum class Type { + Array, + Boolean, + Double, + Integer, + Null, + Object, + String, + }; + static const char* typeAsString(Type t) { + switch (t) { + case Type::Array: + return "Array"; + case Type::Boolean: + return "Boolean"; + case Type::Double: + return "Double"; + case Type::Integer: + return "Integer"; + case Type::Null: + return "Null"; + case Type::Object: + return "Object"; + case Type::String: + return "String"; } + + NOT_REACHED; } - int64_t getInteger(const std::string& name) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() || !member_itr->value.IsInt64()) { - throw Exception(fmt::format("key '{}' missing or not an integer in '{}'", name, name_)); + struct Value { + std::vector array_value_; + bool boolean_value_; + double double_value_; + int64_t integer_value_; + std::unordered_map object_value_; + std::string string_value_; + }; + + explicit Field(Type type) : type_(type) {} + explicit Field(const std::string& value) : type_(Type::String) { value_.string_value_ = value; } + explicit Field(int64_t value) : type_(Type::Integer) { value_.integer_value_ = value; } + explicit Field(double value) : type_(Type::Double) { value_.double_value_ = value; } + explicit Field(bool value) : type_(Type::Boolean) { value_.boolean_value_ = value; } + + bool isType(Type type) const { return type == type_; } + void checkType(Type type) const { + if (!isType(type)) { + throw Exception(fmt::format( + "JSON field from line {} accessed with type '{}' does not match actual type '{}'.", + line_number_start_, typeAsString(type), typeAsString(type_))); } - return member_itr->value.GetInt64(); } - int64_t getInteger(const std::string& name, int64_t default_value) const override { - if (!value_.HasMember(name.c_str())) { - return default_value; - } else { - return getInteger(name); - } + // Value return type functions. + std::string stringValue() const { + checkType(Type::String); + return value_.string_value_; + } + std::vector arrayValue() const { + checkType(Type::Array); + return value_.array_value_; + } + bool booleanValue() const { + checkType(Type::Boolean); + return value_.boolean_value_; + } + double doubleValue() const { + checkType(Type::Double); + return value_.double_value_; } + int64_t integerValue() const { + checkType(Type::Integer); + return value_.integer_value_; + } + + rapidjson::Document asRapidJsonDocument() const; + static void buildRapidJsonDocument(const Field& field, rapidjson::Value& value, + rapidjson::Document::AllocatorType& allocator); - ObjectPtr getObject(const std::string& name, bool allow_empty) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() && !allow_empty) { - throw Exception(fmt::format("key '{}' missing or not an integer in '{}'", name, name_)); - } else if (member_itr == value_.MemberEnd()) { - return ObjectPtr{new ObjectImplBase(empty_rapid_json_value_, name)}; + uint64_t line_number_start_; + uint64_t line_number_end_; + const Type type_; + Value value_; +}; + +/** + * Custom stream to allow access to the line number for each object. + */ +class LineCountingStringStream : public rapidjson::StringStream { + // Ch is typdef in parent class to handle character encoding. +public: + LineCountingStringStream(const Ch* src) : rapidjson::StringStream(src), line_number_(1) {} + Ch Take() { + Ch ret = rapidjson::StringStream::Take(); + if (ret == '\n') { + line_number_++; } - return ObjectPtr{new ObjectImplBase(member_itr->value, name)}; + return ret; } + uint64_t getLineNumber() const { return line_number_; } - std::vector getObjectArray(const std::string& name) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() || !member_itr->value.IsArray()) { - throw Exception(fmt::format("key '{}' missing or not a array in '{}'", name, name_)); - } +private: + uint64_t line_number_; +}; + +/** + * Consume events from SAX callbacks to build JSON Field. + */ +class ObjectHandler : public rapidjson::BaseReaderHandler, ObjectHandler> { +public: + ObjectHandler(LineCountingStringStream& stream) : state_(expectRoot), stream_(stream){}; + + bool StartObject(); + bool EndObject(rapidjson::SizeType); + bool Key(const char* value, rapidjson::SizeType size, bool); + bool StartArray(); + bool EndArray(rapidjson::SizeType); + bool Bool(bool value); + bool Double(double value); + bool Int(int value); + bool Uint(unsigned value); + bool Int64(int64_t value); + bool Uint64(uint64_t value); + bool Null(); + bool String(const char* value, rapidjson::SizeType size, bool); + bool RawNumber(const char*, rapidjson::SizeType, bool); + + ObjectSharedPtr getRoot() { return root_; } + +private: + bool handleValueEvent(FieldSharedPtr ptr); + + enum State { + expectRoot, + expectKeyOrEndObject, + expectValueOrStartObjectArray, + expectArrayValueOrEndArray, + expectFinished, + }; + State state_; + LineCountingStringStream& stream_; + + std::stack stack_; + std::string key_; + + FieldSharedPtr root_; +}; - std::vector object_array; - object_array.reserve(member_itr->value.Size()); - for (auto& array_value : member_itr->value.GetArray()) { - object_array.emplace_back(new ObjectImplBase(array_value, name + " (array item)")); +void Field::buildRapidJsonDocument(const Field& field, rapidjson::Value& value, + rapidjson::Document::AllocatorType& allocator) { + + switch (field.type_) { + case Type::Array: { + value.SetArray(); + value.Reserve(field.value_.array_value_.size(), allocator); + for (const auto& element : field.value_.array_value_) { + switch (element->type_) { + case Type::Array: + case Type::Object: { + rapidjson::Value nested_value; + buildRapidJsonDocument(*element, nested_value, allocator); + value.PushBack(nested_value, allocator); + break; + } + case Type::Boolean: + value.PushBack(element->value_.boolean_value_, allocator); + break; + case Type::Double: + value.PushBack(element->value_.double_value_, allocator); + break; + case Type::Integer: + value.PushBack(element->value_.integer_value_, allocator); + break; + case Type::Null: + value.PushBack(rapidjson::Value(), allocator); + break; + case Type::String: + value.PushBack(rapidjson::StringRef(element->value_.string_value_.c_str()), allocator); + } } - return object_array; + break; } - - std::string getString(const std::string& name) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() || !member_itr->value.IsString()) { - throw Exception(fmt::format("key '{}' missing or not a string in '{}'", name, name_)); + case Type::Object: { + value.SetObject(); + for (const auto& item : field.value_.object_value_) { + auto name = rapidjson::StringRef(item.first.c_str()); + + switch (item.second->type_) { + case Type::Array: + case Type::Object: { + rapidjson::Value nested_value; + buildRapidJsonDocument(*item.second, nested_value, allocator); + value.AddMember(name, nested_value, allocator); + break; + } + case Type::Boolean: + value.AddMember(name, item.second->value_.boolean_value_, allocator); + break; + case Type::Double: + value.AddMember(name, item.second->value_.double_value_, allocator); + break; + case Type::Integer: + value.AddMember(name, item.second->value_.integer_value_, allocator); + break; + case Type::Null: + value.AddMember(name, rapidjson::Value(), allocator); + break; + case Type::String: + value.AddMember(name, rapidjson::StringRef(item.second->value_.string_value_.c_str()), + allocator); + break; + } } - return member_itr->value.GetString(); + break; + } + default: + NOT_REACHED; } +} - std::string getString(const std::string& name, const std::string& default_value) const override { - if (!value_.HasMember(name.c_str())) { - return default_value; - } else { - return getString(name); - } +rapidjson::Document Field::asRapidJsonDocument() const { + rapidjson::Document document; + rapidjson::Document::AllocatorType& allocator = document.GetAllocator(); + buildRapidJsonDocument(*this, document, allocator); + return document; +} + +uint64_t Field::hash() const { + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + asRapidJsonDocument().Accept(writer); + return std::hash{}(buffer.GetString()); +} + +bool Field::getBoolean(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Boolean)) { + throw Exception(fmt::format("key '{}' missing or not a boolean from lines {}-{}", name, + line_number_start_, line_number_end_)); } + return value_itr->second->booleanValue(); +} - std::vector getStringArray(const std::string& name) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() || !member_itr->value.IsArray()) { - throw Exception(fmt::format("key '{}' missing or not an array in '{}'", name, name_)); - } +bool Field::getBoolean(const std::string& name, bool default_value) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr != value_.object_value_.end()) { + return getBoolean(name); + } else { + return default_value; + } +} - std::vector string_array; - string_array.reserve(member_itr->value.Size()); - for (auto& array_value : member_itr->value.GetArray()) { - if (!array_value.IsString()) { - throw Exception(fmt::format("array '{}' does not contain all strings", name)); - } - string_array.push_back(array_value.GetString()); - } - return string_array; +double Field::getDouble(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Double)) { + throw Exception(fmt::format("key '{}' missing or not a double from lines {}-{}", name, + line_number_start_, line_number_end_)); } + return value_itr->second->doubleValue(); +} - double getDouble(const std::string& name) const override { - rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); - if (member_itr == value_.MemberEnd() || !member_itr->value.IsDouble()) { - throw Exception(fmt::format("key '{}' missing or not a double in '{}'", name, name_)); - } - return member_itr->value.GetDouble(); +double Field::getDouble(const std::string& name, double default_value) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr != value_.object_value_.end()) { + return getDouble(name); + } else { + return default_value; } +} - double getDouble(const std::string& name, double default_value) const override { - if (!value_.HasMember(name.c_str())) { - return default_value; +int64_t Field::getInteger(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Integer)) { + throw Exception(fmt::format("key '{}' missing or not an integer from lines {}-{}", name, + line_number_start_, line_number_end_)); + } + return value_itr->second->integerValue(); +} + +int64_t Field::getInteger(const std::string& name, int64_t default_value) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr != value_.object_value_.end()) { + return getInteger(name); + } else { + return default_value; + } +} + +ObjectSharedPtr Field::getObject(const std::string& name, bool allow_empty) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end()) { + if (allow_empty) { + return createObject(); } else { - return getDouble(name); + throw Exception(fmt::format("key '{}' missing from lines {}-{}", name, line_number_start_, + line_number_end_)); } + } else if (!value_itr->second->isType(Type::Object)) { + throw Exception(fmt::format("key '{}' not an object from line {}", name, + value_itr->second->line_number_start_)); + } else { + return value_itr->second; } +} - uint64_t hash() const override { - rapidjson::StringBuffer buffer; - rapidjson::Writer writer(buffer); - value_.Accept(writer); - return std::hash{}(buffer.GetString()); +std::vector Field::getObjectArray(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Array)) { + throw Exception(fmt::format("key '{}' missing or not an array from lines {}-{}", name, + line_number_start_, line_number_end_)); } - void iterate(const ObjectCallback& callback) const override { - for (auto& member : value_.GetObject()) { - ObjectImplBase object(member.value, member.name.GetString()); - bool need_continue = callback(member.name.GetString(), object); - if (!need_continue) { - break; - } + std::vector array_value = value_itr->second->arrayValue(); + return {array_value.begin(), array_value.end()}; +} + +std::string Field::getString(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::String)) { + throw Exception(fmt::format("key '{}' missing or not a string from lines {}-{}", name, + line_number_start_, line_number_end_)); + } + return value_itr->second->stringValue(); +} + +std::string Field::getString(const std::string& name, const std::string& default_value) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr != value_.object_value_.end()) { + return getString(name); + } else { + return default_value; + } +} + +std::vector Field::getStringArray(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Array)) { + throw Exception(fmt::format("key '{}' missing or not an array from lines {}-{}", name, + line_number_start_, line_number_end_)); + } + + std::vector array = value_itr->second->arrayValue(); + std::vector string_array; + string_array.reserve(array.size()); + for (const auto& element : array) { + if (!element->isType(Type::String)) { + throw Exception(fmt::format("JSON array '{}' from line {} does not contain all strings", name, + line_number_start_)); } + string_array.push_back(element->stringValue()); } - bool hasObject(const std::string& name) const override { return value_.HasMember(name.c_str()); } + return string_array; +} + +std::vector Field::asObjectArray() const { + checkType(Type::Array); + return {value_.array_value_.begin(), value_.array_value_.end()}; +} - void validateSchema(const std::string& schema) const override { - rapidjson::Document document; - if (document.Parse<0>(schema.c_str()).HasParseError()) { - throw std::invalid_argument(fmt::format("invalid schema \n Effor(offset {}) : {}\n", - document.GetErrorOffset(), - GetParseError_En(document.GetParseError()))); +bool Field::empty() const { + if (isType(Type::Object)) { + return value_.object_value_.empty(); + } else if (isType(Type::Array)) { + return value_.array_value_.empty(); + } else { + throw Exception( + fmt::format("Json does not support empty() on types other than array and object")); + } +} + +bool Field::hasObject(const std::string& name) const { + checkType(Type::Object); + auto value_itr = value_.object_value_.find(name); + return value_itr != value_.object_value_.end(); +} + +void Field::iterate(const ObjectCallback& callback) const { + checkType(Type::Object); + for (const auto& item : value_.object_value_) { + bool stop_iteration = !callback(item.first, *item.second); + if (stop_iteration) { + break; } + } +} + +void Field::validateSchema(const std::string& schema) const { + rapidjson::Document schema_document; + if (schema_document.Parse<0>(schema.c_str()).HasParseError()) { + throw std::invalid_argument(fmt::format( + "Schema supplied to validateSchema is not valid JSON\n Error(offset {}) : {}\n", + schema_document.GetErrorOffset(), GetParseError_En(schema_document.GetParseError()))); + } - rapidjson::SchemaDocument schema_document(document); - rapidjson::SchemaValidator schema_validator(schema_document); + rapidjson::SchemaDocument schema_document_for_validator(schema_document); + rapidjson::SchemaValidator schema_validator(schema_document_for_validator); - if (!value_.Accept(schema_validator)) { - // TODO(mattklein123): Improve errors by switching to SAX API. - rapidjson::StringBuffer schema_string_buffer; - rapidjson::StringBuffer document_string_buffer; + if (!asRapidJsonDocument().Accept(schema_validator)) { + rapidjson::StringBuffer schema_string_buffer; + rapidjson::StringBuffer document_string_buffer; - schema_validator.GetInvalidSchemaPointer().StringifyUriFragment(schema_string_buffer); - schema_validator.GetInvalidDocumentPointer().StringifyUriFragment(document_string_buffer); + schema_validator.GetInvalidSchemaPointer().StringifyUriFragment(schema_string_buffer); + schema_validator.GetInvalidDocumentPointer().StringifyUriFragment(document_string_buffer); - throw Exception(fmt::format( - "JSON object doesn't conform to schema.\n Invalid schema: {}.\n Invalid keyword: " - "{}.\n Invalid document key: {}", - schema_string_buffer.GetString(), schema_validator.GetInvalidSchemaKeyword(), - document_string_buffer.GetString())); + throw Exception(fmt::format( + "JSON at lines {}-{} does not conform to schema.\n Invalid schema: {}\n" + " Schema violation: {}\n" + " Offending document key: {}", + line_number_start_, line_number_end_, schema_string_buffer.GetString(), + schema_validator.GetInvalidSchemaKeyword(), document_string_buffer.GetString())); + } +} + +bool ObjectHandler::StartObject() { + FieldSharedPtr object = Field::createObject(); + object->setLineNumberStart(stream_.getLineNumber()); + + switch (state_) { + case expectValueOrStartObjectArray: + stack_.top()->insert(key_, object); + stack_.push(object); + state_ = expectKeyOrEndObject; + return true; + case expectArrayValueOrEndArray: + stack_.top()->append(object); + stack_.push(object); + state_ = expectKeyOrEndObject; + return true; + case expectRoot: + root_ = object; + stack_.push(object); + state_ = expectKeyOrEndObject; + return true; + default: + NOT_REACHED; + } +} + +bool ObjectHandler::EndObject(rapidjson::SizeType) { + switch (state_) { + case expectKeyOrEndObject: + stack_.top()->setLineNumberEnd(stream_.getLineNumber()); + stack_.pop(); + + if (stack_.empty()) { + state_ = expectFinished; + } else if (stack_.top()->isObject()) { + state_ = expectKeyOrEndObject; + } else if (stack_.top()->isArray()) { + state_ = expectArrayValueOrEndArray; } + return true; + default: + NOT_REACHED; } +} - std::string asString() const override { - if (!value_.IsString()) { - throw Exception(fmt::format("'{}' is not a string", name_)); +bool ObjectHandler::Key(const char* value, rapidjson::SizeType size, bool) { + switch (state_) { + case expectKeyOrEndObject: + key_ = std::string(value, size); + state_ = expectValueOrStartObjectArray; + return true; + default: + NOT_REACHED; + } +} + +bool ObjectHandler::StartArray() { + FieldSharedPtr array = Field::createArray(); + array->setLineNumberStart(stream_.getLineNumber()); + + switch (state_) { + case expectValueOrStartObjectArray: + stack_.top()->insert(key_, array); + stack_.push(array); + state_ = expectArrayValueOrEndArray; + return true; + case expectArrayValueOrEndArray: + stack_.top()->append(array); + stack_.push(array); + return true; + case expectRoot: + root_ = array; + stack_.push(array); + state_ = expectArrayValueOrEndArray; + return true; + default: + NOT_REACHED; + } +} + +bool ObjectHandler::EndArray(rapidjson::SizeType) { + switch (state_) { + case expectArrayValueOrEndArray: + stack_.top()->setLineNumberEnd(stream_.getLineNumber()); + stack_.pop(); + + if (stack_.empty()) { + state_ = expectFinished; + } else if (stack_.top()->isObject()) { + state_ = expectKeyOrEndObject; + } else if (stack_.top()->isArray()) { + state_ = expectArrayValueOrEndArray; } - return value_.GetString(); + + return true; + default: + NOT_REACHED; } +} - bool empty() const override { return value_.IsObject() && value_.ObjectEmpty(); } +// Value handlers +bool ObjectHandler::Bool(bool value) { return handleValueEvent(Field::createValue(value)); } +bool ObjectHandler::Double(double value) { return handleValueEvent(Field::createValue(value)); } +bool ObjectHandler::Int(int value) { + return handleValueEvent(Field::createValue(static_cast(value))); +} +bool ObjectHandler::Uint(unsigned value) { + return handleValueEvent(Field::createValue(static_cast(value))); +} +bool ObjectHandler::Int64(int64_t value) { return handleValueEvent(Field::createValue(value)); } +bool ObjectHandler::Uint64(uint64_t value) { + if (value > std::numeric_limits::max()) { + throw Exception(fmt::format("JSON value from line {} is larger than int64_t (not supported)", + stream_.getLineNumber())); + } + return handleValueEvent(Field::createValue(static_cast(value))); +} -private: - const std::string name_; - const rapidjson::Value& value_; +bool ObjectHandler::Null() { return handleValueEvent(Field::createNull()); } - static const rapidjson::Value empty_rapid_json_value_; -}; +bool ObjectHandler::String(const char* value, rapidjson::SizeType size, bool) { + return handleValueEvent(Field::createValue(std::string(value, size))); +} -const rapidjson::Value ObjectImplBase::empty_rapid_json_value_(rapidjson::kObjectType); +bool ObjectHandler::RawNumber(const char*, rapidjson::SizeType, bool) { + // Only called if kParseNumbersAsStrings is set as a parse flag, which it is not. + NOT_REACHED; +} -/** - * Holds the root Object reference. - */ -class ObjectImplRoot : public ObjectImplBase { -public: - ObjectImplRoot(rapidjson::Document&& document) - : ObjectImplBase(root_, "root"), root_(std::move(document)) {} +bool ObjectHandler::handleValueEvent(FieldSharedPtr ptr) { + ptr->setLineNumberStart(stream_.getLineNumber()); + + switch (state_) { + case expectValueOrStartObjectArray: + state_ = expectKeyOrEndObject; + stack_.top()->insert(key_, ptr); + return true; + case expectArrayValueOrEndArray: + stack_.top()->append(ptr); + return true; + default: + NOT_REACHED; + } +} -private: - rapidjson::Document root_; -}; +} // namespace -ObjectPtr Factory::loadFromFile(const std::string& file_path) { - rapidjson::Document document; - std::ifstream file_stream(file_path); - rapidjson::IStreamWrapper stream_wrapper(file_stream); - if (document.ParseStream(stream_wrapper).HasParseError()) { - throw Exception(fmt::format("Error(offset {}): {}\n", document.GetErrorOffset(), - GetParseError_En(document.GetParseError()))); +ObjectSharedPtr Factory::loadFromFile(const std::string& file_path) { + try { + return loadFromString(Filesystem::fileReadToEnd(file_path)); + } catch (EnvoyException& e) { + throw Exception(e.what()); } - return ObjectPtr{new ObjectImplRoot(std::move(document))}; } -ObjectPtr Factory::loadFromString(const std::string& json) { - rapidjson::Document document; - if (document.Parse<0>(json.c_str()).HasParseError()) { - throw Exception(fmt::format("Error(offset {}): {}\n", document.GetErrorOffset(), - GetParseError_En(document.GetParseError()))); +ObjectSharedPtr Factory::loadFromString(const std::string& json) { + LineCountingStringStream json_stream(json.c_str()); + + ObjectHandler handler(json_stream); + rapidjson::Reader reader; + reader.Parse(json_stream, handler); + + if (reader.HasParseError()) { + throw Exception(fmt::format("JSON supplied is not valid. Error(offset {}, line {}): {}\n", + reader.GetErrorOffset(), json_stream.getLineNumber(), + GetParseError_En(reader.GetParseErrorCode()))); } - return ObjectPtr{new ObjectImplRoot(std::move(document))}; + + return handler.getRoot(); } const std::string Factory::listAsJsonString(const std::list& items) { diff --git a/source/common/json/json_loader.h b/source/common/json/json_loader.h index 7ded781dd641..27019c955964 100644 --- a/source/common/json/json_loader.h +++ b/source/common/json/json_loader.h @@ -10,15 +10,15 @@ namespace Json { class Factory { public: - /* + /** * Constructs a Json Object from a File. */ - static ObjectPtr loadFromFile(const std::string& file_path); + static ObjectSharedPtr loadFromFile(const std::string& file_path); - /* + /** * Constructs a Json Object from a String. */ - static ObjectPtr loadFromString(const std::string& json); + static ObjectSharedPtr loadFromString(const std::string& json); static const std::string listAsJsonString(const std::list& items); }; diff --git a/source/common/mongo/utility.cc b/source/common/mongo/utility.cc index 4cfc63a1f7d0..48874522581b 100644 --- a/source/common/mongo/utility.cc +++ b/source/common/mongo/utility.cc @@ -85,7 +85,7 @@ std::string QueryMessageInfo::parseCallingFunction(const QueryMessage& query) { std::string QueryMessageInfo::parseCallingFunctionJson(const std::string& json_string) { try { - Json::ObjectPtr json = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json = Json::Factory::loadFromString(json_string); return json->getString("callingFunction"); } catch (Json::Exception&) { return ""; diff --git a/source/common/router/config_impl.cc b/source/common/router/config_impl.cc index 117fc6327b8c..7ec0ec99cde4 100644 --- a/source/common/router/config_impl.cc +++ b/source/common/router/config_impl.cc @@ -114,13 +114,13 @@ RouteEntryImplBase::RouteEntryImplBase(const VirtualHostImpl& vhost, const Json: if (have_weighted_clusters) { uint64_t total_weight = 0UL; - const Json::ObjectPtr weighted_clusters_json = route.getObject("weighted_clusters"); - const std::vector cluster_list = + const Json::ObjectSharedPtr weighted_clusters_json = route.getObject("weighted_clusters"); + const std::vector cluster_list = weighted_clusters_json->getObjectArray("clusters"); const std::string runtime_key_prefix = weighted_clusters_json->getString("runtime_key_prefix", EMPTY_STRING); - for (const Json::ObjectPtr& cluster : cluster_list) { + for (const Json::ObjectSharedPtr cluster : cluster_list) { const std::string cluster_name = cluster->getString("name"); std::unique_ptr cluster_entry( new WeightedClusterEntry(this, runtime_key_prefix + "." + cluster_name, loader_, @@ -136,8 +136,8 @@ RouteEntryImplBase::RouteEntryImplBase(const VirtualHostImpl& vhost, const Json: } if (route.hasObject("headers")) { - std::vector config_headers = route.getObjectArray("headers"); - for (const Json::ObjectPtr& header_map : config_headers) { + std::vector config_headers = route.getObjectArray("headers"); + for (const Json::ObjectSharedPtr header_map : config_headers) { config_headers_.push_back(*header_map); } } @@ -147,7 +147,7 @@ RouteEntryImplBase::RouteEntryImplBase(const VirtualHostImpl& vhost, const Json: } if (route.hasObject("request_headers_to_add")) { - for (const Json::ObjectPtr& header : route.getObjectArray("request_headers_to_add")) { + for (const Json::ObjectSharedPtr header : route.getObjectArray("request_headers_to_add")) { request_headers_to_add_.push_back( {Http::LowerCaseString(header->getString("key")), header->getString("value")}); } @@ -248,7 +248,7 @@ std::multimap RouteEntryImplBase::parseOpaqueConfig(const Json::Object& route) { std::multimap ret; if (route.hasObject("opaque_config")) { - Json::ObjectPtr obj = route.getObject("opaque_config"); + Json::ObjectSharedPtr obj = route.getObject("opaque_config"); obj->iterate([&ret](const std::string& name, const Json::Object& value) { ret.emplace(name, value.asString()); return true; @@ -417,13 +417,14 @@ VirtualHostImpl::VirtualHostImpl(const Json::Object& virtual_host, } if (virtual_host.hasObject("request_headers_to_add")) { - for (const Json::ObjectPtr& header : virtual_host.getObjectArray("request_headers_to_add")) { + for (const Json::ObjectSharedPtr header : + virtual_host.getObjectArray("request_headers_to_add")) { request_headers_to_add_.push_back( {Http::LowerCaseString(header->getString("key")), header->getString("value")}); } } - for (const Json::ObjectPtr& route : virtual_host.getObjectArray("routes")) { + for (const Json::ObjectSharedPtr route : virtual_host.getObjectArray("routes")) { bool has_prefix = route->hasObject("prefix"); bool has_path = route->hasObject("path"); if (!(has_prefix ^ has_path)) { @@ -449,7 +450,8 @@ VirtualHostImpl::VirtualHostImpl(const Json::Object& virtual_host, } if (virtual_host.hasObject("virtual_clusters")) { - for (const Json::ObjectPtr& virtual_cluster : virtual_host.getObjectArray("virtual_clusters")) { + for (const Json::ObjectSharedPtr virtual_cluster : + virtual_host.getObjectArray("virtual_clusters")) { virtual_clusters_.push_back(VirtualClusterEntry(*virtual_cluster)); } } @@ -501,7 +503,8 @@ RouteMatcher::RouteMatcher(const Json::Object& json_config, const ConfigImpl& gl json_config.validateSchema(Json::Schema::ROUTE_CONFIGURATION_SCHEMA); - for (const Json::ObjectPtr& virtual_host_config : json_config.getObjectArray("virtual_hosts")) { + for (const Json::ObjectSharedPtr virtual_host_config : + json_config.getObjectArray("virtual_hosts")) { VirtualHostSharedPtr virtual_host(new VirtualHostImpl(*virtual_host_config, global_route_config, runtime, cm, validate_clusters)); uses_runtime_ |= virtual_host->usesRuntime(); @@ -611,7 +614,7 @@ ConfigImpl::ConfigImpl(const Json::Object& config, Runtime::Loader& runtime, } if (config.hasObject("response_headers_to_add")) { - for (const Json::ObjectPtr& header : config.getObjectArray("response_headers_to_add")) { + for (const Json::ObjectSharedPtr header : config.getObjectArray("response_headers_to_add")) { response_headers_to_add_.push_back( {Http::LowerCaseString(header->getString("key")), header->getString("value")}); } @@ -624,7 +627,7 @@ ConfigImpl::ConfigImpl(const Json::Object& config, Runtime::Loader& runtime, } if (config.hasObject("request_headers_to_add")) { - for (const Json::ObjectPtr& header : config.getObjectArray("request_headers_to_add")) { + for (const Json::ObjectSharedPtr header : config.getObjectArray("request_headers_to_add")) { request_headers_to_add_.push_back( {Http::LowerCaseString(header->getString("key")), header->getString("value")}); } diff --git a/source/common/router/config_impl.h b/source/common/router/config_impl.h index 3448ed2ebcef..98b3bb16393b 100644 --- a/source/common/router/config_impl.h +++ b/source/common/router/config_impl.h @@ -327,6 +327,8 @@ class RouteEntryImplBase : public RouteEntry, std::vector weighted_clusters_; std::unique_ptr hash_policy_; std::list> request_headers_to_add_; + + // TODO(danielhochman): refactor multimap into unordered_map since JSON is unordered map. const std::multimap opaque_config_; }; diff --git a/source/common/router/rds_impl.cc b/source/common/router/rds_impl.cc index 753aadf5ed10..2f600bda73bd 100644 --- a/source/common/router/rds_impl.cc +++ b/source/common/router/rds_impl.cc @@ -30,7 +30,7 @@ RouteConfigProviderPtr RouteConfigProviderUtil::create( return RouteConfigProviderPtr{ new StaticRouteConfigProviderImpl(*config.getObject("route_config"), runtime, cm)}; } else { - Json::ObjectPtr rds_config = config.getObject("rds"); + Json::ObjectSharedPtr rds_config = config.getObject("rds"); rds_config->validateSchema(Json::Schema::RDS_CONFIGURATION_SCHEMA); std::unique_ptr provider{new RdsRouteConfigProviderImpl( *rds_config, runtime, cm, dispatcher, random, local_info, scope, stat_prefix, tls)}; @@ -86,7 +86,7 @@ void RdsRouteConfigProviderImpl::createRequest(Http::Message& request) { void RdsRouteConfigProviderImpl::parseResponse(const Http::Message& response) { log_debug("rds: parsing response"); - Json::ObjectPtr response_json = Json::Factory::loadFromString(response.bodyAsString()); + Json::ObjectSharedPtr response_json = Json::Factory::loadFromString(response.bodyAsString()); uint64_t new_hash = response_json->hash(); if (new_hash != last_config_hash_ || !initialized_) { response_json->validateSchema(Json::Schema::ROUTE_CONFIGURATION_SCHEMA); diff --git a/source/common/router/router_ratelimit.cc b/source/common/router/router_ratelimit.cc index 954f06a8cbc1..4649c06d7274 100644 --- a/source/common/router/router_ratelimit.cc +++ b/source/common/router/router_ratelimit.cc @@ -65,8 +65,8 @@ bool GenericKeyAction::populateDescriptor(const Router::RouteEntry&, HeaderValueMatchAction::HeaderValueMatchAction(const Json::Object& action) : descriptor_value_(action.getString("descriptor_value")), expect_match_(action.getBoolean("expect_match", true)) { - std::vector config_headers = action.getObjectArray("headers"); - for (const Json::ObjectPtr& header_map : config_headers) { + std::vector config_headers = action.getObjectArray("headers"); + for (const Json::ObjectSharedPtr header_map : config_headers) { action_headers_.push_back(*header_map); } } @@ -87,7 +87,7 @@ RateLimitPolicyEntryImpl::RateLimitPolicyEntryImpl(const Json::Object& config) : Json::Validator(config, Json::Schema::HTTP_RATE_LIMITS_CONFIGURATION_SCHEMA), disable_key_(config.getString("disable_key", "")), stage_(static_cast(config.getInteger("stage", 0))) { - for (const Json::ObjectPtr& action : config.getObjectArray("actions")) { + for (const Json::ObjectSharedPtr action : config.getObjectArray("actions")) { std::string type = action->getString("type"); if (type == "source_cluster") { actions_.emplace_back(new SourceClusterAction()); @@ -130,7 +130,7 @@ void RateLimitPolicyEntryImpl::populateDescriptors(const Router::RouteEntry& rou RateLimitPolicyImpl::RateLimitPolicyImpl(const Json::Object& config) : rate_limit_entries_reference_(RateLimitPolicyImpl::MAX_STAGE_NUMBER + 1) { if (config.hasObject("rate_limits")) { - for (const Json::ObjectPtr& rate_limit : config.getObjectArray("rate_limits")) { + for (const Json::ObjectSharedPtr rate_limit : config.getObjectArray("rate_limits")) { std::unique_ptr rate_limit_policy_entry( new RateLimitPolicyEntryImpl(*rate_limit)); uint64_t stage = rate_limit_policy_entry->stage(); diff --git a/source/common/upstream/cds_api_impl.cc b/source/common/upstream/cds_api_impl.cc index a19a786be620..4ac20cf56746 100644 --- a/source/common/upstream/cds_api_impl.cc +++ b/source/common/upstream/cds_api_impl.cc @@ -47,9 +47,9 @@ void CdsApiImpl::createRequest(Http::Message& request) { void CdsApiImpl::parseResponse(const Http::Message& response) { log_debug("cds: parsing response"); - Json::ObjectPtr response_json = Json::Factory::loadFromString(response.bodyAsString()); + Json::ObjectSharedPtr response_json = Json::Factory::loadFromString(response.bodyAsString()); response_json->validateSchema(Json::Schema::CDS_SCHEMA); - std::vector clusters = response_json->getObjectArray("clusters"); + std::vector clusters = response_json->getObjectArray("clusters"); // We need to keep track of which clusters we might need to remove. ClusterManager::ClusterInfoMap clusters_to_remove = cm_.clusters(); diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index e38e0520c9bd..b1dcadb603cd 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -189,7 +189,7 @@ ClusterManagerImpl::ClusterManagerImpl(const Json::Object& config, ClusterManage cds_api_ = factory_.createCds(config, *this); init_helper_.setCds(cds_api_.get()); - for (const Json::ObjectPtr& cluster : config.getObjectArray("clusters")) { + for (const Json::ObjectSharedPtr cluster : config.getObjectArray("clusters")) { loadCluster(*cluster, false); } diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index e3eab222a4ab..731c6ae1ded8 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -351,10 +351,10 @@ ProdHttpHealthCheckerImpl::createCodecClient(Upstream::Host::CreateConnectionDat } TcpHealthCheckMatcher::MatchSegments -TcpHealthCheckMatcher::loadJsonBytes(const std::vector& byte_array) { +TcpHealthCheckMatcher::loadJsonBytes(const std::vector& byte_array) { MatchSegments result; - for (const Json::ObjectPtr& entry : byte_array) { + for (const Json::ObjectSharedPtr entry : byte_array) { std::string hex_string = entry->getString("binary"); result.push_back(Hex::decode(hex_string)); } diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index 52001b9702ac..5fe7c81d65d8 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -255,7 +255,7 @@ class TcpHealthCheckMatcher { public: typedef std::list> MatchSegments; - static MatchSegments loadJsonBytes(const std::vector& byte_array); + static MatchSegments loadJsonBytes(const std::vector& byte_array); static bool match(const MatchSegments& expected, const Buffer::Instance& buffer); }; diff --git a/source/common/upstream/logical_dns_cluster.cc b/source/common/upstream/logical_dns_cluster.cc index 9f9194012f4b..f974a50574f8 100644 --- a/source/common/upstream/logical_dns_cluster.cc +++ b/source/common/upstream/logical_dns_cluster.cc @@ -21,7 +21,7 @@ LogicalDnsCluster::LogicalDnsCluster(const Json::Object& config, Runtime::Loader tls_(tls), tls_slot_(tls.allocateSlot()), initialized_(false), resolve_timer_(dispatcher.createTimer([this]() -> void { startResolve(); })) { - std::vector hosts_json = config.getObjectArray("hosts"); + std::vector hosts_json = config.getObjectArray("hosts"); if (hosts_json.size() != 1) { throw EnvoyException("logical_dns clusters must have a single host"); } diff --git a/source/common/upstream/sds.cc b/source/common/upstream/sds.cc index f7ba3261c2af..928874f6c799 100644 --- a/source/common/upstream/sds.cc +++ b/source/common/upstream/sds.cc @@ -23,10 +23,10 @@ SdsClusterImpl::SdsClusterImpl(const Json::Object& config, Runtime::Loader& runt local_info_(local_info), service_name_(config.getString("service_name")) {} void SdsClusterImpl::parseResponse(const Http::Message& response) { - Json::ObjectPtr json = Json::Factory::loadFromString(response.bodyAsString()); + Json::ObjectSharedPtr json = Json::Factory::loadFromString(response.bodyAsString()); json->validateSchema(Json::Schema::SDS_SCHEMA); std::vector new_hosts; - for (const Json::ObjectPtr& host : json->getObjectArray("hosts")) { + for (const Json::ObjectSharedPtr host : json->getObjectArray("hosts")) { bool canary = false; uint32_t weight = 1; std::string zone = ""; diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index 72a0b5342a21..9289f793c119 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -254,7 +254,8 @@ ResourceManagerImplPtr ClusterInfoImpl::ResourceManagers::load(const Json::Objec uint64_t max_retries = 3; std::string runtime_prefix = fmt::format("circuit_breakers.{}.{}.", cluster_name, priority); - Json::ObjectPtr settings = config.getObject("circuit_breakers", true)->getObject(priority, true); + Json::ObjectSharedPtr settings = + config.getObject("circuit_breakers", true)->getObject(priority, true); max_connections = settings->getInteger("max_connections", max_connections); max_pending_requests = settings->getInteger("max_pending_requests", max_pending_requests); max_requests = settings->getInteger("max_requests", max_requests); @@ -267,9 +268,9 @@ ResourceManagerImplPtr ClusterInfoImpl::ResourceManagers::load(const Json::Objec StaticClusterImpl::StaticClusterImpl(const Json::Object& config, Runtime::Loader& runtime, Stats::Store& stats, Ssl::ContextManager& ssl_context_manager) : ClusterImplBase(config, runtime, stats, ssl_context_manager) { - std::vector hosts_json = config.getObjectArray("hosts"); + std::vector hosts_json = config.getObjectArray("hosts"); HostVectorSharedPtr new_hosts(new std::vector()); - for (Json::ObjectPtr& host : hosts_json) { + for (Json::ObjectSharedPtr host : hosts_json) { new_hosts->emplace_back(HostSharedPtr{new HostImpl( info_, "", Network::Utility::resolveUrl(host->getString("url")), false, 1, "")}); } @@ -369,7 +370,7 @@ StrictDnsClusterImpl::StrictDnsClusterImpl(const Json::Object& config, Runtime:: : BaseDynamicClusterImpl(config, runtime, stats, ssl_context_manager), dns_resolver_(dns_resolver), dns_refresh_rate_ms_(std::chrono::milliseconds( config.getInteger("dns_refresh_rate_ms", 5000))) { - for (Json::ObjectPtr& host : config.getObjectArray("hosts")) { + for (Json::ObjectSharedPtr host : config.getObjectArray("hosts")) { resolve_targets_.emplace_back(new ResolveTarget(*this, dispatcher, host->getString("url"))); } // We have to first construct resolve_targets_ before invoking startResolve(), diff --git a/source/server/config/network/http_connection_manager.cc b/source/server/config/network/http_connection_manager.cc index c2a3e474addc..252b41b94571 100644 --- a/source/server/config/network/http_connection_manager.cc +++ b/source/server/config/network/http_connection_manager.cc @@ -93,7 +93,7 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig(const Json::Object& con } if (config.hasObject("tracing")) { - Json::ObjectPtr tracing_config = config.getObject("tracing"); + Json::ObjectSharedPtr tracing_config = config.getObject("tracing"); const std::string operation_name = tracing_config->getString("operation_name"); Tracing::OperationName tracing_operation_name; @@ -121,7 +121,7 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig(const Json::Object& con } if (config.hasObject("access_log")) { - for (Json::ObjectPtr& access_log : config.getObjectArray("access_log")) { + for (Json::ObjectSharedPtr access_log : config.getObjectArray("access_log")) { Http::AccessLog::InstanceSharedPtr current_access_log = Http::AccessLog::InstanceImpl::fromJson(*access_log, server.runtime(), server.accessLogManager()); @@ -141,11 +141,11 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig(const Json::Object& con codec_type_ = CodecType::AUTO; } - std::vector filters = config.getObjectArray("filters"); + std::vector filters = config.getObjectArray("filters"); for (size_t i = 0; i < filters.size(); i++) { std::string string_type = filters[i]->getString("type"); std::string string_name = filters[i]->getString("name"); - Json::ObjectPtr config_object = filters[i]->getObject("config"); + Json::ObjectSharedPtr config_object = filters[i]->getObject("config"); log().info(" filter #{}", i); log().info(" type: {}", string_type); diff --git a/source/server/configuration_impl.cc b/source/server/configuration_impl.cc index 6ff825e7781a..d98f8e605734 100644 --- a/source/server/configuration_impl.cc +++ b/source/server/configuration_impl.cc @@ -48,7 +48,7 @@ void MainImpl::initialize(const Json::Object& json) { server_.threadLocal(), server_.runtime(), server_.random(), server_.localInfo(), server_.accessLogManager())); - std::vector listeners = json.getObjectArray("listeners"); + std::vector listeners = json.getObjectArray("listeners"); log().info("loading {} listener(s)", listeners.size()); for (size_t i = 0; i < listeners.size(); i++) { log().info("listener #{}:", i); @@ -79,7 +79,7 @@ void MainImpl::initialize(const Json::Object& json) { initializeTracers(json); if (json.hasObject("rate_limit_service")) { - Json::ObjectPtr rate_limit_service_config = json.getObject("rate_limit_service"); + Json::ObjectSharedPtr rate_limit_service_config = json.getObject("rate_limit_service"); std::string type = rate_limit_service_config->getString("type"); ASSERT(type == "grpc_service"); UNREFERENCED_PARAMETER(type); @@ -98,7 +98,7 @@ void MainImpl::initializeTracers(const Json::Object& configuration) { return; } - Json::ObjectPtr tracing_configuration = configuration.getObject("tracing"); + Json::ObjectSharedPtr tracing_configuration = configuration.getObject("tracing"); if (!tracing_configuration->hasObject("http")) { http_tracer_.reset(new Tracing::HttpNullTracer()); return; @@ -110,8 +110,8 @@ void MainImpl::initializeTracers(const Json::Object& configuration) { } // Initialize tracing driver. - Json::ObjectPtr http_tracer_config = tracing_configuration->getObject("http"); - Json::ObjectPtr driver = http_tracer_config->getObject("driver"); + Json::ObjectSharedPtr http_tracer_config = tracing_configuration->getObject("http"); + Json::ObjectSharedPtr driver = http_tracer_config->getObject("driver"); std::string type = driver->getString("type"); log().info(fmt::format(" loading tracing driver: {}", type)); @@ -119,7 +119,7 @@ void MainImpl::initializeTracers(const Json::Object& configuration) { Envoy::Runtime::RandomGenerator& rand = server_.random(); if (type == "lightstep") { - Json::ObjectPtr lightstep_config = driver->getObject("config"); + Json::ObjectSharedPtr lightstep_config = driver->getObject("config"); std::unique_ptr opts(new lightstep::TracerOptions()); opts->access_token = @@ -172,11 +172,11 @@ MainImpl::ListenerConfig::ListenerConfig(MainImpl& parent, Json::Object& json) : per_connection_buffer_limit_bytes_ = json.getInteger("per_connection_buffer_limit_bytes", 1024 * 1024); - std::vector filters = json.getObjectArray("filters"); + std::vector filters = json.getObjectArray("filters"); for (size_t i = 0; i < filters.size(); i++) { std::string string_type = filters[i]->getString("type"); std::string string_name = filters[i]->getString("name"); - Json::ObjectPtr config = filters[i]->getObject("config"); + Json::ObjectSharedPtr config = filters[i]->getObject("config"); log().info(" filter #{}:", i); log().info(" type: {}", string_type); log().info(" name: {}", string_name); @@ -216,7 +216,7 @@ bool MainImpl::ListenerConfig::createFilterChain(Network::Connection& connection } InitialImpl::InitialImpl(const Json::Object& json) { - Json::ObjectPtr admin = json.getObject("admin"); + Json::ObjectSharedPtr admin = json.getObject("admin"); admin_.access_log_path_ = admin->getString("access_log_path"); admin_.profile_path_ = admin->getString("profile_path", "/var/log/envoy/envoy.prof"); admin_.address_ = Network::Utility::resolveUrl(admin->getString("address")); diff --git a/source/server/server.cc b/source/server/server.cc index 9f643e39239d..c6ec2352b060 100644 --- a/source/server/server.cc +++ b/source/server/server.cc @@ -176,7 +176,7 @@ void InstanceImpl::initialize(Options& options, TestHooks& hooks, restarter_.version()); // Handle configuration that needs to take place prior to the main configuration load. - Json::ObjectPtr config_json = Json::Factory::loadFromFile(options.configPath()); + Json::ObjectSharedPtr config_json = Json::Factory::loadFromFile(options.configPath()); config_json->validateSchema(Json::Schema::TOP_LEVEL_CONFIG_SCHEMA); Configuration::InitialImpl initial_config(*config_json); log().info("admin address: {}", initial_config.admin().address()->asString()); diff --git a/test/common/dynamo/dynamo_request_parser_test.cc b/test/common/dynamo/dynamo_request_parser_test.cc index ed12e8effac4..7b5d8ade42a6 100644 --- a/test/common/dynamo/dynamo_request_parser_test.cc +++ b/test/common/dynamo/dynamo_request_parser_test.cc @@ -53,7 +53,7 @@ TEST(DynamoRequestParser, parseTableNameSingleOperation) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); // Supported operation for (const std::string& operation : supported_single_operations) { @@ -65,7 +65,7 @@ TEST(DynamoRequestParser, parseTableNameSingleOperation) { } { - Json::ObjectPtr json_data = Json::Factory::loadFromString("{\"TableName\":\"Pets\"}"); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString("{\"TableName\":\"Pets\"}"); EXPECT_EQ("Pets", RequestParser::parseTable("GetItem", *json_data).table_name); } } @@ -104,7 +104,7 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchGetItem", *json_data); EXPECT_EQ("", table.table_name); @@ -120,7 +120,7 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchGetItem", *json_data); EXPECT_EQ("table_2", table.table_name); @@ -137,7 +137,7 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchGetItem", *json_data); EXPECT_EQ("", table.table_name); @@ -153,7 +153,7 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchWriteItem", *json_data); EXPECT_EQ("table_2", table.table_name); @@ -161,7 +161,7 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } { - Json::ObjectPtr json_data = Json::Factory::loadFromString("{}"); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString("{}"); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchWriteItem", *Json::Factory::loadFromString("{}")); EXPECT_EQ("", table.table_name); @@ -169,14 +169,14 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } { - Json::ObjectPtr json_data = Json::Factory::loadFromString("{\"RequestItems\":{}}"); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString("{\"RequestItems\":{}}"); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchWriteItem", *json_data); EXPECT_EQ("", table.table_name); EXPECT_TRUE(table.is_single_table); } { - Json::ObjectPtr json_data = Json::Factory::loadFromString("{}"); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString("{}"); RequestParser::TableDescriptor table = RequestParser::parseTable("BatchGetItem", *json_data); EXPECT_EQ("", table.table_name); EXPECT_TRUE(table.is_single_table); @@ -184,7 +184,7 @@ TEST(DynamoRequestParser, parseTableNameBatchOperation) { } TEST(DynamoRequestParser, parseBatchUnProcessedKeys) { { - Json::ObjectPtr json_data = Json::Factory::loadFromString("{}"); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString("{}"); std::vector unprocessed_tables = RequestParser::parseBatchUnProcessedKeys(*json_data); EXPECT_EQ(0u, unprocessed_tables.size()); @@ -211,7 +211,7 @@ TEST(DynamoRequestParser, parseBatchUnProcessedKeys) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); std::vector unprocessed_tables = RequestParser::parseBatchUnProcessedKeys(*json_data); @@ -250,7 +250,7 @@ TEST(DynamoRequestParser, parsePartitionIds) { } } )EOF"; - Json::ObjectPtr json_data = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_data = Json::Factory::loadFromString(json_string); std::vector partitions = RequestParser::parsePartitions(*json_data); diff --git a/test/common/filter/auth/client_ssl_test.cc b/test/common/filter/auth/client_ssl_test.cc index 366b15541268..276e46996b37 100644 --- a/test/common/filter/auth/client_ssl_test.cc +++ b/test/common/filter/auth/client_ssl_test.cc @@ -53,7 +53,7 @@ class ClientSslAuthFilterTest : public testing::Test { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_CALL(cm_, get("vpn")); setupRequest(); config_ = Config::create(*loader, tls_, cm_, dispatcher_, stats_store_, random_); @@ -100,7 +100,7 @@ TEST_F(ClientSslAuthFilterTest, NoCluster) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_CALL(cm_, get("bad_cluster")).WillOnce(Return(nullptr)); EXPECT_THROW(Config::create(*loader, tls_, cm_, dispatcher_, stats_store_, random_), EnvoyException); @@ -116,7 +116,7 @@ TEST_F(ClientSslAuthFilterTest, BadClientSslAuthConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); EXPECT_THROW(Config::create(*json_config, tls_, cm_, dispatcher_, stats_store_, random_), Json::Exception); } diff --git a/test/common/filter/ratelimit_test.cc b/test/common/filter/ratelimit_test.cc index 3a74d0c92aaa..439ed7e2fff1 100644 --- a/test/common/filter/ratelimit_test.cc +++ b/test/common/filter/ratelimit_test.cc @@ -45,7 +45,7 @@ class RateLimitFilterTest : public testing::Test { ON_CALL(runtime_.snapshot_, featureEnabled("ratelimit.tcp_filter_enforcing", 100)) .WillByDefault(Return(true)); - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); config_.reset(new Config(*config, stats_store_, runtime_)); client_ = new MockClient(); filter_.reset(new Instance(config_, ClientPtr{client_})); @@ -77,7 +77,7 @@ TEST_F(RateLimitFilterTest, BadRatelimitConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); EXPECT_THROW(Config(*json_config, stats_store_, runtime_), Json::Exception); } diff --git a/test/common/filter/tcp_proxy_test.cc b/test/common/filter/tcp_proxy_test.cc index 6869b04b67ed..2d65ae04d443 100644 --- a/test/common/filter/tcp_proxy_test.cc +++ b/test/common/filter/tcp_proxy_test.cc @@ -34,7 +34,7 @@ TEST(TcpProxyConfigTest, NoRouteConfig) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock cluster_manager; EXPECT_THROW(TcpProxyConfig(*config, cluster_manager, cluster_manager.thread_local_cluster_.cluster_.info_->stats_store_), @@ -55,7 +55,7 @@ TEST(TcpProxyConfigTest, NoCluster) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock cluster_manager; EXPECT_CALL(cluster_manager, get("fake_cluster")).WillOnce(Return(nullptr)); EXPECT_THROW(TcpProxyConfig(*config, cluster_manager, @@ -77,7 +77,7 @@ TEST(TcpProxyConfigTest, BadTcpProxyConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock cluster_manager; EXPECT_THROW(TcpProxyConfig(*json_config, cluster_manager, cluster_manager.thread_local_cluster_.cluster_.info_->stats_store_), @@ -127,7 +127,7 @@ TEST(TcpProxyConfigTest, Routes) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json); NiceMock cm_; TcpProxyConfig config_obj(*json_config, cm_, @@ -283,7 +283,7 @@ TEST(TcpProxyConfigTest, EmptyRouteConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json); NiceMock cm_; TcpProxyConfig config_obj(*json_config, cm_, @@ -309,7 +309,7 @@ class TcpProxyTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); config_.reset( new TcpProxyConfig(*config, cluster_manager_, cluster_manager_.thread_local_cluster_.cluster_.info_->stats_store_)); @@ -480,7 +480,7 @@ class TcpProxyRoutingTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); config_.reset( new TcpProxyConfig(*config, cluster_manager_, cluster_manager_.thread_local_cluster_.cluster_.info_->stats_store_)); diff --git a/test/common/http/access_log/access_log_impl_test.cc b/test/common/http/access_log/access_log_impl_test.cc index 49cbaca94bc6..1ac269c32121 100644 --- a/test/common/http/access_log/access_log_impl_test.cc +++ b/test/common/http/access_log/access_log_impl_test.cc @@ -97,7 +97,7 @@ TEST_F(AccessLogImplTest, LogMoreData) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); @@ -120,7 +120,7 @@ TEST_F(AccessLogImplTest, EnvoyUpstreamServiceTime) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); @@ -139,7 +139,7 @@ TEST_F(AccessLogImplTest, NoFilter) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); @@ -160,7 +160,7 @@ TEST_F(AccessLogImplTest, UpstreamHost) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); @@ -182,7 +182,7 @@ TEST_F(AccessLogImplTest, WithFilterMiss) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)).Times(0); @@ -205,7 +205,7 @@ TEST_F(AccessLogImplTest, WithFilterHit) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)).Times(3); @@ -227,7 +227,7 @@ TEST_F(AccessLogImplTest, RuntimeFilter) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); // Value is taken from random generator. @@ -259,7 +259,7 @@ TEST_F(AccessLogImplTest, PathRewrite) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); @@ -277,7 +277,7 @@ TEST_F(AccessLogImplTest, healthCheckTrue) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); TestHeaderMapImpl header_map{}; @@ -295,7 +295,7 @@ TEST_F(AccessLogImplTest, healthCheckFalse) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); TestHeaderMapImpl header_map{}; @@ -321,7 +321,7 @@ TEST_F(AccessLogImplTest, requestTracing) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); { @@ -354,7 +354,7 @@ TEST(AccessLogImplTestCtor, FiltersMissingInOrAndFilter) { "filter": {"type": "logical_or"} } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(InstanceImpl::fromJson(*loader, runtime, log_manager), EnvoyException); } @@ -366,7 +366,7 @@ TEST(AccessLogImplTestCtor, FiltersMissingInOrAndFilter) { "filter": {"type": "logical_and"} } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(InstanceImpl::fromJson(*loader, runtime, log_manager), EnvoyException); } @@ -384,7 +384,7 @@ TEST_F(AccessLogImplTest, andFilter) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); request_info_.response_code_.value(500); @@ -415,7 +415,7 @@ TEST_F(AccessLogImplTest, orFilter) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); request_info_.response_code_.value(500); @@ -449,7 +449,7 @@ TEST_F(AccessLogImplTest, multipleOperators) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); request_info_.response_code_.value(500); @@ -476,10 +476,10 @@ TEST(AccessLogFilterTest, DurationWithRuntimeKey) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(filter_json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(filter_json); NiceMock runtime; - Json::ObjectPtr filter_object = loader->getObject("filter"); + Json::ObjectSharedPtr filter_object = loader->getObject("filter"); DurationFilter filter(*filter_object, runtime); TestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/"}}; TestRequestInfo request_info; @@ -508,10 +508,10 @@ TEST(AccessLogFilterTest, StatusCodeWithRuntimeKey) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(filter_json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(filter_json); NiceMock runtime; - Json::ObjectPtr filter_object = loader->getObject("filter"); + Json::ObjectSharedPtr filter_object = loader->getObject("filter"); StatusCodeFilter filter(*filter_object, runtime); TestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/"}}; diff --git a/test/common/http/filter/fault_filter_test.cc b/test/common/http/filter/fault_filter_test.cc index 3256725d00a2..d5d3ad000b70 100644 --- a/test/common/http/filter/fault_filter_test.cc +++ b/test/common/http/filter/fault_filter_test.cc @@ -97,7 +97,7 @@ class FaultFilterTest : public testing::Test { )EOF"; void SetUpTest(const std::string json) { - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); config_.reset(new FaultFilterConfig(*config, runtime_, "", stats_)); filter_.reset(new FaultFilter(config_)); filter_->setDecoderFilterCallbacks(filter_callbacks_); @@ -126,7 +126,7 @@ TEST(FaultFilterBadConfigTest, EmptyConfig) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } @@ -142,7 +142,7 @@ TEST(FaultFilterBadConfigTest, BadAbortPercent) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } @@ -157,7 +157,7 @@ TEST(FaultFilterBadConfigTest, MissingHTTPStatus) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } @@ -174,7 +174,7 @@ TEST(FaultFilterBadConfigTest, BadDelayType) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } @@ -191,7 +191,7 @@ TEST(FaultFilterBadConfigTest, BadDelayPercent) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } @@ -208,7 +208,7 @@ TEST(FaultFilterBadConfigTest, BadDelayDuration) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } @@ -224,7 +224,7 @@ TEST(FaultFilterBadConfigTest, MissingDelayDuration) { )EOF"; Stats::IsolatedStoreImpl stats; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock runtime; EXPECT_THROW(FaultFilterConfig(*config, runtime, "", stats), EnvoyException); } diff --git a/test/common/http/filter/ratelimit_test.cc b/test/common/http/filter/ratelimit_test.cc index c9decdae3a36..1393abc40f53 100644 --- a/test/common/http/filter/ratelimit_test.cc +++ b/test/common/http/filter/ratelimit_test.cc @@ -44,7 +44,7 @@ class HttpRateLimitFilterTest : public testing::Test { } void SetUpTest(const std::string json) { - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); config_.reset(new FilterConfig(*config, local_info_, stats_store_, runtime_, cm_)); client_ = new Envoy::RateLimit::MockClient(); @@ -89,7 +89,7 @@ TEST_F(HttpRateLimitFilterTest, BadConfig) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(filter_config); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(filter_config); EXPECT_THROW(FilterConfig(*config, local_info_, stats_store_, runtime_, cm_), Json::Exception); } diff --git a/test/common/http/utility_test.cc b/test/common/http/utility_test.cc index 84d3f3097938..19fb67724189 100644 --- a/test/common/http/utility_test.cc +++ b/test/common/http/utility_test.cc @@ -92,18 +92,18 @@ TEST(HttpUtility, createSslRedirectPath) { TEST(HttpUtility, parseCodecOptions) { { - Json::ObjectPtr json = Json::Factory::loadFromString("{}"); + Json::ObjectSharedPtr json = Json::Factory::loadFromString("{}"); EXPECT_EQ(0UL, Utility::parseCodecOptions(*json)); } { - Json::ObjectPtr json = + Json::ObjectSharedPtr json = Json::Factory::loadFromString("{\"http_codec_options\": \"no_compression\"}"); EXPECT_EQ(CodecOptions::NoCompression, Utility::parseCodecOptions(*json)); } { - Json::ObjectPtr json = Json::Factory::loadFromString("{\"http_codec_options\": \"foo\"}"); + Json::ObjectSharedPtr json = Json::Factory::loadFromString("{\"http_codec_options\": \"foo\"}"); EXPECT_THROW(Utility::parseCodecOptions(*json), EnvoyException); } } diff --git a/test/common/json/BUILD b/test/common/json/BUILD index 88d5229dd10d..aa3928a65846 100644 --- a/test/common/json/BUILD +++ b/test/common/json/BUILD @@ -25,5 +25,8 @@ envoy_cc_test( envoy_cc_test( name = "json_loader_test", srcs = ["json_loader_test.cc"], - deps = ["//source/common/json:json_loader_lib"], + deps = [ + "//source/common/json:json_loader_lib", + "//test/test_common:utility_lib", + ], ) diff --git a/test/common/json/config_schemas_test.cc b/test/common/json/config_schemas_test.cc index 0d81c72f96ca..13dd421ed004 100644 --- a/test/common/json/config_schemas_test.cc +++ b/test/common/json/config_schemas_test.cc @@ -29,7 +29,7 @@ std::vector generateTestInputs() { class ConfigSchemasTest : public ::testing::TestWithParam {}; TEST_P(ConfigSchemasTest, CheckValidationExpectation) { - ObjectPtr json = Factory::loadFromFile(GetParam()); + ObjectSharedPtr json = Factory::loadFromFile(GetParam()); // lookup schema in test input std::string schema, schema_name{json->getString("schema")}; diff --git a/test/common/json/json_loader_test.cc b/test/common/json/json_loader_test.cc index 9e94005708fc..57fd1c22056a 100644 --- a/test/common/json/json_loader_test.cc +++ b/test/common/json/json_loader_test.cc @@ -3,6 +3,8 @@ #include "common/json/json_loader.h" +#include "test/test_common/utility.h" + #include "gtest/gtest.h" namespace Envoy { @@ -13,42 +15,73 @@ TEST(JsonLoaderTest, Basic) { EXPECT_THROW(Factory::loadFromString("{"), Exception); { - ObjectPtr json = Factory::loadFromString("{\"hello\":123}"); + ObjectSharedPtr json = Factory::loadFromString("{\"hello\":123}"); EXPECT_TRUE(json->hasObject("hello")); EXPECT_FALSE(json->hasObject("world")); EXPECT_FALSE(json->empty()); EXPECT_THROW(json->getObject("world"), Exception); + EXPECT_THROW(json->getObject("hello"), Exception); EXPECT_THROW(json->getBoolean("hello"), Exception); EXPECT_THROW(json->getObjectArray("hello"), Exception); EXPECT_THROW(json->getString("hello"), Exception); + + EXPECT_THROW_WITH_MESSAGE(json->getString("hello"), Exception, + "key 'hello' missing or not a string from lines 1-1"); } { - ObjectPtr json = Factory::loadFromString("{\"hello\":\"123\"}"); - EXPECT_THROW(json->getInteger("hello"), Exception); + ObjectSharedPtr json = Factory::loadFromString("{\"hello\":\"123\"\n}"); + EXPECT_THROW_WITH_MESSAGE(json->getInteger("hello"), Exception, + "key 'hello' missing or not an integer from lines 1-2"); } { - ObjectPtr json = Factory::loadFromString("{\"hello\":true}"); + ObjectSharedPtr json = Factory::loadFromString("{\"hello\":true}"); EXPECT_TRUE(json->getBoolean("hello")); EXPECT_TRUE(json->getBoolean("hello", false)); EXPECT_FALSE(json->getBoolean("world", false)); } { - ObjectPtr json = Factory::loadFromString("{\"hello\": [\"a\", \"b\", 3]}"); + ObjectSharedPtr json = Factory::loadFromString("{\"hello\": [\"a\", \"b\", 3]}"); EXPECT_THROW(json->getStringArray("hello"), Exception); EXPECT_THROW(json->getStringArray("world"), Exception); } { - ObjectPtr json = Factory::loadFromString("{\"hello\":123}"); + ObjectSharedPtr json = Factory::loadFromString("{\"hello\":123}"); EXPECT_EQ(123, json->getInteger("hello", 456)); EXPECT_EQ(456, json->getInteger("world", 456)); } { - ObjectPtr json = Factory::loadFromString("{\"1\":{\"11\":\"111\"},\"2\":{\"22\":\"222\"}}"); + ObjectSharedPtr json = Factory::loadFromString("{\"hello\": \n[123]}"); + + EXPECT_THROW_WITH_MESSAGE( + json->getObjectArray("hello").at(0)->getString("hello"), Exception, + "JSON field from line 2 accessed with type 'Object' does not match actual type 'Integer'."); + } + + { + EXPECT_THROW_WITH_MESSAGE( + Factory::loadFromString("{\"hello\": \n\n\"world\""), Exception, + "JSON supplied is not valid. Error(offset 19, line 3): Missing a comma or " + "'}' after an object member.\n"); + } + + { + ObjectSharedPtr json_object = Factory::loadFromString("[\"foo\",\"bar\"]"); + EXPECT_FALSE(json_object->empty()); + } + + { + ObjectSharedPtr json_object = Factory::loadFromString("[]"); + EXPECT_TRUE(json_object->empty()); + } + + { + ObjectSharedPtr json = + Factory::loadFromString("{\"1\":{\"11\":\"111\"},\"2\":{\"22\":\"222\"}}"); int pos = 0; json->iterate([&pos](const std::string& key, const Json::Object& value) { EXPECT_TRUE(key == "1" || key == "2"); @@ -67,7 +100,8 @@ TEST(JsonLoaderTest, Basic) { } { - ObjectPtr json = Factory::loadFromString("{\"1\":{\"11\":\"111\"},\"2\":{\"22\":\"222\"}}"); + ObjectSharedPtr json = + Factory::loadFromString("{\"1\":{\"11\":\"111\"},\"2\":{\"22\":\"222\"}}"); int pos = 0; json->iterate([&pos](const std::string& key, const Json::Object& value) { EXPECT_TRUE(key == "1" || key == "2"); @@ -95,7 +129,7 @@ TEST(JsonLoaderTest, Basic) { } )EOF"; - ObjectPtr config = Factory::loadFromString(json); + ObjectSharedPtr config = Factory::loadFromString(json); EXPECT_EQ(2U, config->getObjectArray("descriptors")[0]->asObjectArray().size()); EXPECT_EQ(1U, config->getObjectArray("descriptors")[1]->asObjectArray().size()); } @@ -107,89 +141,152 @@ TEST(JsonLoaderTest, Basic) { } )EOF"; - ObjectPtr config = Factory::loadFromString(json); - std::vector array = config->getObjectArray("descriptors"); + ObjectSharedPtr config = Factory::loadFromString(json); + std::vector array = config->getObjectArray("descriptors"); EXPECT_THROW(array[0]->asObjectArray(), Exception); } { - std::string json = R"EOF( - { - } - )EOF"; - - ObjectPtr config = Factory::loadFromString(json); - ObjectPtr object = config->getObject("foo", true); + std::string json = R"EOF({})EOF"; + ObjectSharedPtr config = Factory::loadFromString(json); + ObjectSharedPtr object = config->getObject("foo", true); EXPECT_EQ(2, object->getInteger("bar", 2)); EXPECT_TRUE(object->empty()); } + + { + std::string json = R"EOF({"foo": []})EOF"; + ObjectSharedPtr config = Factory::loadFromString(json); + EXPECT_TRUE(config->getStringArray("foo").empty()); + } + + { + std::string json = R"EOF({"foo": ["bar", "baz"]})EOF"; + ObjectSharedPtr config = Factory::loadFromString(json); + EXPECT_FALSE(config->getStringArray("foo").empty()); + } + + { + ObjectSharedPtr json = Factory::loadFromString("{\"hello\": \n[2.0]}"); + EXPECT_THROW(json->getObjectArray("hello").at(0)->getDouble("foo"), Exception); + } + + { + ObjectSharedPtr json = Factory::loadFromString("{\"hello\": \n[null]}"); + EXPECT_THROW(json->getObjectArray("hello").at(0)->getDouble("foo"), Exception); + } } TEST(JsonLoaderTest, Integer) { { - ObjectPtr json = + ObjectSharedPtr json = Factory::loadFromString("{\"max\":9223372036854775807, \"min\":-9223372036854775808}"); EXPECT_EQ(std::numeric_limits::max(), json->getInteger("max")); EXPECT_EQ(std::numeric_limits::min(), json->getInteger("min")); } { - ObjectPtr json_max = Factory::loadFromString("{\"val\":9223372036854775808}"); - EXPECT_THROW(json_max->getInteger("val"), Exception); - ObjectPtr json_min = Factory::loadFromString("{\"val\":-9223372036854775809}"); - EXPECT_THROW(json_min->getInteger("val"), Exception); + EXPECT_THROW(Factory::loadFromString("{\"val\":9223372036854775808}"), EnvoyException); + + // I believe this is a bug with rapidjson. + // It silently eats numbers below min int64_t with no exception. + // Fail when reading key instead of on parse. + ObjectSharedPtr json = Factory::loadFromString("{\"val\":-9223372036854775809}"); + EXPECT_THROW(json->getInteger("val"), EnvoyException); } } TEST(JsonLoaderTest, Double) { { - ObjectPtr json = Factory::loadFromString("{\"value1\": 10.5, \"value2\": -12.3}"); + ObjectSharedPtr json = Factory::loadFromString("{\"value1\": 10.5, \"value2\": -12.3}"); EXPECT_EQ(10.5, json->getDouble("value1")); EXPECT_EQ(-12.3, json->getDouble("value2")); } { - ObjectPtr json = Factory::loadFromString("{\"foo\": 13.22}"); + ObjectSharedPtr json = Factory::loadFromString("{\"foo\": 13.22}"); EXPECT_EQ(13.22, json->getDouble("foo", 0)); EXPECT_EQ(0, json->getDouble("bar", 0)); } { - ObjectPtr json = Factory::loadFromString("{\"foo\": \"bar\"}"); + ObjectSharedPtr json = Factory::loadFromString("{\"foo\": \"bar\"}"); EXPECT_THROW(json->getDouble("foo"), Exception); } } TEST(JsonLoaderTest, Hash) { - ObjectPtr json1 = Factory::loadFromString("{\"value1\": 10.5, \"value2\": -12.3}"); - ObjectPtr json2 = Factory::loadFromString("{\"value2\": -12.3, \"value1\": 10.5}"); - ObjectPtr json3 = Factory::loadFromString(" { \"value2\": -12.3, \"value1\": 10.5} "); + ObjectSharedPtr json1 = Factory::loadFromString("{\"value1\": 10.5, \"value2\": -12.3}"); + ObjectSharedPtr json2 = Factory::loadFromString("{\"value2\": -12.3, \"value1\": 10.5}"); + ObjectSharedPtr json3 = Factory::loadFromString(" { \"value2\": -12.3, \"value1\": 10.5} "); EXPECT_NE(json1->hash(), json2->hash()); EXPECT_EQ(json2->hash(), json3->hash()); } TEST(JsonLoaderTest, Schema) { - std::string invalid_json_schema = R"EOF( { - "properties": {"value1"} - } - )EOF"; + std::string invalid_json_schema = R"EOF( + { + "properties": {"value1"} + } + )EOF"; - std::string invalid_schema = R"EOF( - { - "properties" : { - "value1": {"type" : "faketype"} + std::string invalid_schema = R"EOF( + { + "properties" : { + "value1": {"type" : "faketype"} + } } + )EOF"; + + std::string different_schema = R"EOF( + { + "properties" : { + "value1" : {"type" : "number"} + }, + "additionalProperties" : false + } + )EOF"; + + std::string valid_schema = R"EOF( + { + "properties": { + "value1": {"type" : "number"}, + "value2": {"type": "string"} + }, + "additionalProperties": false + } + )EOF"; + + std::string json_string = R"EOF( + { + "value1": 10, + "value2" : "test" + } + )EOF"; + + ObjectSharedPtr json = Factory::loadFromString(json_string); + EXPECT_THROW(json->validateSchema(invalid_json_schema), std::invalid_argument); + EXPECT_THROW(json->validateSchema(invalid_schema), Exception); + EXPECT_THROW(json->validateSchema(different_schema), Exception); + EXPECT_NO_THROW(json->validateSchema(valid_schema)); } - )EOF"; - std::string different_schema = R"EOF( { - "properties" : { - "value1" : {"type" : "number"} - }, - "additionalProperties" : false + std::string json_string = R"EOF( + { + "value1": [false, 2.01, 3, null], + "value2" : "test" + } + )EOF"; + + std::string empty_schema = R"EOF({})EOF"; + + ObjectSharedPtr json = Factory::loadFromString(json_string); + EXPECT_NO_THROW(json->validateSchema(empty_schema)); } - )EOF"; +} + +TEST(JsonLoaderTest, NestedSchema) { - std::string valid_schema = R"EOF( + std::string schema = R"EOF( { "properties": { "value1": {"type" : "number"}, @@ -200,22 +297,25 @@ TEST(JsonLoaderTest, Schema) { )EOF"; std::string json_string = R"EOF( - { - "value1": 10, - "value2" : "test" + { + "bar": "baz", + "foo": { + "value1": "should have been a number", + "value2" : "test" + } } )EOF"; - ObjectPtr json = Factory::loadFromString(json_string); + ObjectSharedPtr json = Factory::loadFromString(json_string); - EXPECT_THROW(json->validateSchema(invalid_json_schema), std::invalid_argument); - EXPECT_THROW(json->validateSchema(invalid_schema), Exception); - EXPECT_THROW(json->validateSchema(different_schema), Exception); - EXPECT_NO_THROW(json->validateSchema(valid_schema)); + EXPECT_THROW_WITH_MESSAGE(json->getObject("foo")->validateSchema(schema), Exception, + "JSON at lines 4-7 does not conform to schema.\n Invalid schema: " + "#/properties/value1\n Schema violation: type\n Offending document " + "key: #/value1"); } TEST(JsonLoaderTest, AsString) { - ObjectPtr json = Factory::loadFromString("{\"name1\": \"value1\", \"name2\": true}"); + ObjectSharedPtr json = Factory::loadFromString("{\"name1\": \"value1\", \"name2\": true}"); json->iterate([&](const std::string& key, const Json::Object& value) { EXPECT_TRUE(key == "name1" || key == "name2"); @@ -231,23 +331,26 @@ TEST(JsonLoaderTest, AsString) { TEST(JsonLoaderTest, ListAsString) { { std::list list = {}; - Json::ObjectPtr json = Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); - std::vector output = json->asObjectArray(); + Json::ObjectSharedPtr json = + Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); + std::vector output = json->asObjectArray(); EXPECT_TRUE(output.empty()); } { std::list list = {"one"}; - Json::ObjectPtr json = Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); - std::vector output = json->asObjectArray(); + Json::ObjectSharedPtr json = + Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); + std::vector output = json->asObjectArray(); EXPECT_EQ(1, output.size()); EXPECT_EQ("one", output[0]->asString()); } { std::list list = {"one", "two", "three", "four"}; - Json::ObjectPtr json = Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); - std::vector output = json->asObjectArray(); + Json::ObjectSharedPtr json = + Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); + std::vector output = json->asObjectArray(); EXPECT_EQ(4, output.size()); EXPECT_EQ("one", output[0]->asString()); EXPECT_EQ("two", output[1]->asString()); @@ -257,8 +360,9 @@ TEST(JsonLoaderTest, ListAsString) { { std::list list = {"127.0.0.1:46465", "127.0.0.1:52211", "127.0.0.1:58941"}; - Json::ObjectPtr json = Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); - std::vector output = json->asObjectArray(); + Json::ObjectSharedPtr json = + Json::Factory::loadFromString(Json::Factory::listAsJsonString(list)); + std::vector output = json->asObjectArray(); EXPECT_EQ(3, output.size()); EXPECT_EQ("127.0.0.1:46465", output[0]->asString()); EXPECT_EQ("127.0.0.1:52211", output[1]->asString()); diff --git a/test/common/mongo/codec_impl_test.cc b/test/common/mongo/codec_impl_test.cc index b3d567f1334d..2e4b478f81be 100644 --- a/test/common/mongo/codec_impl_test.cc +++ b/test/common/mongo/codec_impl_test.cc @@ -100,6 +100,7 @@ TEST_F(MongoCodecImplTest, Query) { query2.query(Bson::DocumentImpl::create()->addString("string2", "string2_value")); query2.returnFieldsSelector(Bson::DocumentImpl::create()->addDouble("double2", -2.3)); + Json::Factory::loadFromString(query.toString(true)); EXPECT_NO_THROW(Json::Factory::loadFromString(query.toString(true))); EXPECT_NO_THROW(Json::Factory::loadFromString(query.toString(false))); EXPECT_NO_THROW(Json::Factory::loadFromString(query2.toString(true))); diff --git a/test/common/network/filter_manager_impl_test.cc b/test/common/network/filter_manager_impl_test.cc index c5f51ec8b000..75d4b392e228 100644 --- a/test/common/network/filter_manager_impl_test.cc +++ b/test/common/network/filter_manager_impl_test.cc @@ -117,7 +117,7 @@ TEST_F(NetworkFilterManagerTest, RateLimitAndTcpProxy) { ON_CALL(runtime.snapshot_, featureEnabled("ratelimit.tcp_filter_enforcing", 100)) .WillByDefault(Return(true)); - Json::ObjectPtr rl_config_loader = Json::Factory::loadFromString(rl_json); + Json::ObjectSharedPtr rl_config_loader = Json::Factory::loadFromString(rl_json); RateLimit::TcpFilter::ConfigSharedPtr rl_config( new RateLimit::TcpFilter::Config(*rl_config_loader, stats_store, runtime)); @@ -138,7 +138,7 @@ TEST_F(NetworkFilterManagerTest, RateLimitAndTcpProxy) { } )EOF"; - Json::ObjectPtr tcp_proxy_config_loader = Json::Factory::loadFromString(tcp_proxy_json); + Json::ObjectSharedPtr tcp_proxy_config_loader = Json::Factory::loadFromString(tcp_proxy_json); Envoy::Filter::TcpProxyConfigSharedPtr tcp_proxy_config( new Envoy::Filter::TcpProxyConfig(*tcp_proxy_config_loader, cm, stats_store)); manager.addReadFilter(ReadFilterSharedPtr{new Envoy::Filter::TcpProxy(tcp_proxy_config, cm)}); diff --git a/test/common/network/utility_test.cc b/test/common/network/utility_test.cc index 598302f68f86..3d4093b59287 100644 --- a/test/common/network/utility_test.cc +++ b/test/common/network/utility_test.cc @@ -23,7 +23,7 @@ TEST(IpListTest, Errors) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW({ IpList wl(*loader, "ip_white_list"); }, EnvoyException); } @@ -34,7 +34,7 @@ TEST(IpListTest, Errors) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW({ IpList wl(*loader, "ip_white_list"); }, EnvoyException); } @@ -45,7 +45,7 @@ TEST(IpListTest, Errors) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW({ IpList wl(*loader, "ip_white_list"); }, EnvoyException); } @@ -56,7 +56,7 @@ TEST(IpListTest, Errors) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW({ IpList wl(*loader, "ip_white_list"); }, EnvoyException); } } @@ -72,7 +72,7 @@ TEST(IpListTest, Normal) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); IpList wl(*loader, "ip_white_list"); EXPECT_TRUE(wl.contains(Address::Ipv4Instance("192.168.3.0"))); @@ -103,7 +103,7 @@ TEST(IpListTest, MatchAny) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); IpList wl(*loader, "ip_white_list"); EXPECT_TRUE(wl.contains(Address::Ipv4Instance("192.168.3.3"))); diff --git a/test/common/ratelimit/ratelimit_impl_test.cc b/test/common/ratelimit/ratelimit_impl_test.cc index 05ae1b6b0fd7..545ad1fd1846 100644 --- a/test/common/ratelimit/ratelimit_impl_test.cc +++ b/test/common/ratelimit/ratelimit_impl_test.cc @@ -131,7 +131,7 @@ TEST(RateLimitGrpcFactoryTest, NoCluster) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); Upstream::MockClusterManager cm; EXPECT_CALL(cm, get("foo")).WillOnce(Return(nullptr)); @@ -145,7 +145,7 @@ TEST(RateLimitGrpcFactoryTest, Create) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); Upstream::MockClusterManager cm; EXPECT_CALL(cm, get("foo")).Times(AtLeast(1)); diff --git a/test/common/redis/conn_pool_impl_test.cc b/test/common/redis/conn_pool_impl_test.cc index 649eb884a61a..9f96e0b550ec 100644 --- a/test/common/redis/conn_pool_impl_test.cc +++ b/test/common/redis/conn_pool_impl_test.cc @@ -53,7 +53,7 @@ class RedisClientImplTest : public testing::Test, public DecoderFactory { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); config_.reset(new ConfigImpl(*json_config)); upstream_connection_ = new NiceMock(); @@ -319,7 +319,7 @@ TEST(RedisClientFactoryImplTest, Basic) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); ClientFactoryImpl factory; Upstream::MockHost::MockCreateConnectionData conn_info; @@ -341,7 +341,7 @@ class RedisConnPoolImplTest : public testing::Test, public ClientFactory { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); conn_pool_.reset(new InstanceImpl(cluster_name_, cm_, *this, tls_, *json_config)); } diff --git a/test/common/redis/proxy_filter_test.cc b/test/common/redis/proxy_filter_test.cc index 367ec31c5f0f..b6b2835eb693 100644 --- a/test/common/redis/proxy_filter_test.cc +++ b/test/common/redis/proxy_filter_test.cc @@ -35,7 +35,7 @@ TEST(RedisProxyFilterConfigTest, Normal) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock cm; Stats::IsolatedStoreImpl store; ProxyFilterConfig config(*json_config, cm, store); @@ -51,7 +51,7 @@ TEST(RedisProxyFilterConfigTest, InvalidCluster) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock cm; Stats::IsolatedStoreImpl store; EXPECT_CALL(cm, get("fake_cluster")).WillOnce(Return(nullptr)); @@ -66,7 +66,7 @@ TEST(RedisProxyFilterConfigTest, BadRedisProxyConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock cm; Stats::IsolatedStoreImpl store; EXPECT_THROW(ProxyFilterConfig(*json_config, cm, store), Json::Exception); @@ -83,7 +83,7 @@ class RedisProxyFilterTest : public testing::Test, public DecoderFactory { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock cm; config_.reset(new ProxyFilterConfig(*json_config, cm, store_)); filter_.reset(new ProxyFilter(*this, EncoderPtr{encoder_}, splitter_, config_)); diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index 6964cbb50e50..3544da4ea7a6 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -162,7 +162,7 @@ TEST(RouteMatcherTest, TestRoutes) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -443,7 +443,7 @@ TEST(RouteMatcherTest, TestAddRemoveReqRespHeaders) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -524,7 +524,7 @@ TEST(RouteMatcherTest, Priority) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -569,7 +569,7 @@ TEST(RouteMatcherTest, NoHostRewriteAndAutoRewrite) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl(*loader, runtime, cm, true), EnvoyException); @@ -629,7 +629,7 @@ TEST(RouteMatcherTest, HeaderMatchedRouting) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -709,7 +709,7 @@ TEST(RouterMatcherTest, HashPolicy) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -757,7 +757,7 @@ TEST(RouteMatcherTest, ClusterHeader) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -815,7 +815,7 @@ TEST(RouteMatcherTest, ContentType) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -866,7 +866,7 @@ TEST(RouteMatcherTest, Runtime) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; Runtime::MockSnapshot snapshot; @@ -907,7 +907,7 @@ TEST(RouteMatcherTest, ShadowClusterNotFound) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_CALL(cm, get("www2")).WillRepeatedly(Return(&cm.thread_local_cluster_)); @@ -934,7 +934,7 @@ TEST(RouteMatcherTest, ClusterNotFound) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_CALL(cm, get("www2")).WillRepeatedly(Return(nullptr)); @@ -960,7 +960,7 @@ TEST(RouteMatcherTest, ClusterNotFoundNotChecking) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_CALL(cm, get("www2")).WillRepeatedly(Return(nullptr)); @@ -1001,7 +1001,7 @@ TEST(RouteMatcherTest, Shadow) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1070,7 +1070,7 @@ TEST(RouteMatcherTest, Retry) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1151,7 +1151,7 @@ TEST(RouteMatcherTest, TestBadDefaultConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl config(*loader, runtime, cm, true), EnvoyException); @@ -1185,7 +1185,7 @@ TEST(RouteMatcherTest, TestDuplicateDomainConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl config(*loader, runtime, cm, true), EnvoyException); @@ -1251,7 +1251,7 @@ TEST(RouteMatcherTest, Redirect) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1323,7 +1323,7 @@ TEST(RouteMatcherTest, ExclusiveRouteEntryOrRedirectEntry) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1371,7 +1371,7 @@ TEST(RouteMatcherTest, ExclusiveWeightedClustersEntryOrRedirectEntry) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1431,7 +1431,7 @@ TEST(RouteMatcherTest, WeightedClusters) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1510,7 +1510,7 @@ TEST(RouteMatcherTest, ExclusiveWeightedClustersOrClusterConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl(*loader, runtime, cm, true), EnvoyException); @@ -1536,7 +1536,7 @@ TEST(RouteMatcherTest, WeightedClustersMissingClusterList) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl(*loader, runtime, cm, true), EnvoyException); @@ -1563,7 +1563,7 @@ TEST(RouteMatcherTest, WeightedClustersEmptyClustersList) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl(*loader, runtime, cm, true), EnvoyException); @@ -1593,7 +1593,7 @@ TEST(RouteMatcherTest, WeightedClustersSumOFWeightsNotEqualToMax) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl(*loader, runtime, cm, true), EnvoyException); @@ -1623,7 +1623,7 @@ TEST(RouteMatcherTest, TestWeightedClusterWithMissingWeights) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_THROW(ConfigImpl(*loader, runtime, cm, true), EnvoyException); @@ -1653,7 +1653,7 @@ TEST(RouteMatcherTest, TestWeightedClusterInvalidClusterName) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; EXPECT_CALL(cm, get("cluster1")).WillRepeatedly(Return(&cm.thread_local_cluster_)); @@ -1692,7 +1692,7 @@ TEST(BadHttpRouteConfigurationsTest, BadRouteConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; @@ -1720,7 +1720,7 @@ TEST(BadHttpRouteConfigurationsTest, BadVirtualHostConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; @@ -1746,7 +1746,7 @@ TEST(BadHttpRouteConfigurationsTest, BadRouteEntryConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; @@ -1772,7 +1772,7 @@ TEST(BadHttpRouteConfigurationsTest, BadRouteEntryConfigPrefixAndPath) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; @@ -1792,8 +1792,7 @@ TEST(RouteMatcherTest, TestOpaqueConfig) { "cluster": "ats", "opaque_config" : { "name1": "value1", - "name2": "value2", - "name1": "value3" + "name2": "value2" } } ] @@ -1802,7 +1801,7 @@ TEST(RouteMatcherTest, TestOpaqueConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; ConfigImpl config(*loader, runtime, cm, true); @@ -1810,14 +1809,8 @@ TEST(RouteMatcherTest, TestOpaqueConfig) { const std::multimap& opaque_config = config.route(genHeaders("api.lyft.com", "/api", "GET"), 0)->routeEntry()->opaqueConfig(); - EXPECT_EQ(2u, opaque_config.count("name1")); - auto range = opaque_config.equal_range("name1"); - auto it = range.first; - EXPECT_EQ("value1", it->second); - ++it; - EXPECT_EQ("value3", it->second); - - EXPECT_EQ("value2", opaque_config.find("name2")->second); + EXPECT_EQ(opaque_config.find("name1")->second, "value1"); + EXPECT_EQ(opaque_config.find("name2")->second, "value2"); } TEST(RoutePropertyTest, excludeVHRateLimits) { @@ -1838,7 +1831,7 @@ TEST(RoutePropertyTest, excludeVHRateLimits) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock runtime; NiceMock cm; Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); diff --git a/test/common/router/rds_impl_test.cc b/test/common/router/rds_impl_test.cc index 1ff43ef1d052..a7f0f7284b4a 100644 --- a/test/common/router/rds_impl_test.cc +++ b/test/common/router/rds_impl_test.cc @@ -40,7 +40,7 @@ class RdsImplTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(config_json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); interval_timer_ = new Event::MockTimer(&dispatcher_); EXPECT_CALL(init_manager_, registerTarget(_)); @@ -88,7 +88,7 @@ TEST_F(RdsImplTest, RdsAndStatic) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(config_json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); EXPECT_THROW(RouteConfigProviderUtil::create(*config, runtime_, cm_, dispatcher_, random_, local_info_, store_, "foo.", tls_, init_manager_), EnvoyException); @@ -104,7 +104,7 @@ TEST_F(RdsImplTest, LocalInfoNotDefined) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(config_json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); local_info_.cluster_name_ = ""; local_info_.node_name_ = ""; interval_timer_ = new Event::MockTimer(&dispatcher_); @@ -123,7 +123,7 @@ TEST_F(RdsImplTest, UnknownCluster) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(config_json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); ON_CALL(cm_, get("foo_cluster")).WillByDefault(Return(nullptr)); interval_timer_ = new Event::MockTimer(&dispatcher_); EXPECT_THROW(RouteConfigProviderUtil::create(*config, runtime_, cm_, dispatcher_, random_, diff --git a/test/common/router/router_ratelimit_test.cc b/test/common/router/router_ratelimit_test.cc index bc2edf1a0961..fdb112503197 100644 --- a/test/common/router/router_ratelimit_test.cc +++ b/test/common/router/router_ratelimit_test.cc @@ -97,7 +97,7 @@ static Http::TestHeaderMapImpl genHeaders(const std::string& host, const std::st class RateLimitConfiguration : public testing::Test { public: void SetUpTest(const std::string json) { - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); config_.reset(new ConfigImpl(*loader, runtime_, cm_, true)); } @@ -338,7 +338,7 @@ TEST_F(RateLimitConfiguration, Stages) { class RateLimitPolicyEntryTest : public testing::Test { public: void SetUpTest(const std::string json) { - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); rate_limit_entry_.reset(new RateLimitPolicyEntryImpl(*loader)); descriptors_.clear(); } diff --git a/test/common/ssl/connection_impl_test.cc b/test/common/ssl/connection_impl_test.cc index 101571e8639a..16e94217fcb1 100644 --- a/test/common/ssl/connection_impl_test.cc +++ b/test/common/ssl/connection_impl_test.cc @@ -38,7 +38,7 @@ void testUtil(const std::string& client_ctx_json, const std::string& server_ctx_ Stats::IsolatedStoreImpl stats_store; Runtime::MockLoader runtime; - Json::ObjectPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); + Json::ObjectSharedPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); ContextConfigImpl server_ctx_config(*server_ctx_loader); ContextManagerImpl manager(runtime); ServerContextPtr server_ctx(manager.createSslServerContext(stats_store, server_ctx_config)); @@ -51,7 +51,7 @@ void testUtil(const std::string& client_ctx_json, const std::string& server_ctx_ dispatcher.createSslListener(connection_handler, *server_ctx, socket, callbacks, stats_store, Network::ListenerOptions::listenerOptionsWithBindToPort()); - Json::ObjectPtr client_ctx_loader = TestEnvironment::jsonLoadFromString(client_ctx_json); + Json::ObjectSharedPtr client_ctx_loader = TestEnvironment::jsonLoadFromString(client_ctx_json); ContextConfigImpl client_ctx_config(*client_ctx_loader); ClientContextPtr client_ctx(manager.createSslClientContext(stats_store, client_ctx_config)); Network::ClientConnectionPtr client_connection = @@ -180,7 +180,7 @@ TEST_P(SslConnectionImplTest, ClientAuthBadVerification) { } )EOF"; - Json::ObjectPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); + Json::ObjectSharedPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); ContextConfigImpl server_ctx_config(*server_ctx_loader); ContextManagerImpl manager(runtime); ServerContextPtr server_ctx(manager.createSslServerContext(stats_store, server_ctx_config)); @@ -200,7 +200,7 @@ TEST_P(SslConnectionImplTest, ClientAuthBadVerification) { } )EOF"; - Json::ObjectPtr client_ctx_loader = TestEnvironment::jsonLoadFromString(client_ctx_json); + Json::ObjectSharedPtr client_ctx_loader = TestEnvironment::jsonLoadFromString(client_ctx_json); ContextConfigImpl client_ctx_config(*client_ctx_loader); ClientContextPtr client_ctx(manager.createSslClientContext(stats_store, client_ctx_config)); Network::ClientConnectionPtr client_connection = @@ -237,7 +237,7 @@ TEST_P(SslConnectionImplTest, SslError) { } )EOF"; - Json::ObjectPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); + Json::ObjectSharedPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); ContextConfigImpl server_ctx_config(*server_ctx_loader); ContextManagerImpl manager(runtime); ServerContextPtr server_ctx(manager.createSslServerContext(stats_store, server_ctx_config)); @@ -293,7 +293,7 @@ class SslReadBufferLimitTest : public SslCertsTest, "ca_cert_file": "{{ test_rundir }}/test/common/ssl/test_data/ca_cert.pem" } )EOF"; - Json::ObjectPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); + Json::ObjectSharedPtr server_ctx_loader = TestEnvironment::jsonLoadFromString(server_ctx_json); ContextConfigImpl server_ctx_config(*server_ctx_loader); Runtime::MockLoader runtime; ContextManagerImpl manager(runtime); @@ -313,7 +313,7 @@ class SslReadBufferLimitTest : public SslCertsTest, } )EOF"; - Json::ObjectPtr client_ctx_loader = TestEnvironment::jsonLoadFromString(client_ctx_json); + Json::ObjectSharedPtr client_ctx_loader = TestEnvironment::jsonLoadFromString(client_ctx_json); ContextConfigImpl client_ctx_config(*client_ctx_loader); ClientContextPtr client_ctx(manager.createSslClientContext(stats_store, client_ctx_config)); diff --git a/test/common/ssl/context_impl_test.cc b/test/common/ssl/context_impl_test.cc index 73643d6f50f6..b696e06ee678 100644 --- a/test/common/ssl/context_impl_test.cc +++ b/test/common/ssl/context_impl_test.cc @@ -75,7 +75,7 @@ TEST_F(SslContextImplTest, TestCipherSuites) { } )EOF"; - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(json); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(json); ContextConfigImpl cfg(*loader); Runtime::MockLoader runtime; ContextManagerImpl manager(runtime); @@ -91,7 +91,7 @@ TEST_F(SslContextImplTest, TestExpiringCert) { } )EOF"; - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(json); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(json); ContextConfigImpl cfg(*loader); Runtime::MockLoader runtime; ContextManagerImpl manager(runtime); @@ -114,7 +114,7 @@ TEST_F(SslContextImplTest, TestExpiredCert) { } )EOF"; - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(json); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(json); ContextConfigImpl cfg(*loader); Runtime::MockLoader runtime; ContextManagerImpl manager(runtime); @@ -132,7 +132,7 @@ TEST_F(SslContextImplTest, TestGetCertInformation) { } )EOF"; - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(json); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(json); ContextConfigImpl cfg(*loader); Runtime::MockLoader runtime; ContextManagerImpl manager(runtime); @@ -158,7 +158,7 @@ TEST_F(SslContextImplTest, TestGetCertInformation) { } TEST_F(SslContextImplTest, TestNoCert) { - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString("{}"); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString("{}"); ContextConfigImpl cfg(*loader); Runtime::MockLoader runtime; ContextManagerImpl manager(runtime); diff --git a/test/common/tracing/lightstep_tracer_impl_test.cc b/test/common/tracing/lightstep_tracer_impl_test.cc index f89159b720fb..ebfb63d7f9a1 100644 --- a/test/common/tracing/lightstep_tracer_impl_test.cc +++ b/test/common/tracing/lightstep_tracer_impl_test.cc @@ -60,7 +60,7 @@ class LightStepDriverTest : public Test { std::string valid_config = R"EOF( {"collector_cluster": "fake_cluster"} )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); setup(*loader, true); } @@ -87,14 +87,14 @@ TEST_F(LightStepDriverTest, InitializeDriver) { std::string invalid_config = R"EOF( {"fake" : "fake"} )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(invalid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(invalid_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } { std::string empty_config = "{}"; - Json::ObjectPtr loader = Json::Factory::loadFromString(empty_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(empty_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } @@ -106,7 +106,7 @@ TEST_F(LightStepDriverTest, InitializeDriver) { std::string valid_config = R"EOF( {"collector_cluster": "fake_cluster"} )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } @@ -119,7 +119,7 @@ TEST_F(LightStepDriverTest, InitializeDriver) { std::string valid_config = R"EOF( {"collector_cluster": "fake_cluster"} )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } @@ -132,7 +132,7 @@ TEST_F(LightStepDriverTest, InitializeDriver) { std::string valid_config = R"EOF( {"collector_cluster": "fake_cluster"} )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); setup(*loader, true); } diff --git a/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc b/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc index 7a1e36a53940..f28e70058980 100644 --- a/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc +++ b/test/common/tracing/zipkin/zipkin_tracer_impl_test.cc @@ -56,7 +56,7 @@ class ZipkinDriverTest : public Test { "collector_endpoint": "/api/v1/spans" } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); setup(*loader, true); } @@ -82,14 +82,14 @@ TEST_F(ZipkinDriverTest, InitializeDriver) { std::string invalid_config = R"EOF( {"fake" : "fake"} )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(invalid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(invalid_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } { std::string empty_config = "{}"; - Json::ObjectPtr loader = Json::Factory::loadFromString(empty_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(empty_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } @@ -104,7 +104,7 @@ TEST_F(ZipkinDriverTest, InitializeDriver) { "collector_endpoint": "/api/v1/spans" } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); EXPECT_THROW(setup(*loader, false), EnvoyException); } @@ -120,7 +120,7 @@ TEST_F(ZipkinDriverTest, InitializeDriver) { "collector_endpoint": "/api/v1/spans" } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(valid_config); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(valid_config); setup(*loader, true); } diff --git a/test/common/upstream/cds_api_impl_test.cc b/test/common/upstream/cds_api_impl_test.cc index a9409ec41542..283d36bdd9c0 100644 --- a/test/common/upstream/cds_api_impl_test.cc +++ b/test/common/upstream/cds_api_impl_test.cc @@ -38,7 +38,7 @@ class CdsApiImplTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(config_json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); cds_ = CdsApiImpl::create(*config, cm_, dispatcher_, random_, local_info_, store_); cds_->setInitializedCb([this]() -> void { initialized_.ready(); }); @@ -100,7 +100,7 @@ TEST_F(CdsApiImplTest, InvalidOptions) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(config_json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(config_json); local_info_.cluster_name_ = ""; local_info_.node_name_ = ""; EXPECT_THROW(CdsApiImpl::create(*config, cm_, dispatcher_, random_, local_info_, store_), diff --git a/test/common/upstream/cluster_manager_impl_test.cc b/test/common/upstream/cluster_manager_impl_test.cc index 72a9455a9360..335eb864204e 100644 --- a/test/common/upstream/cluster_manager_impl_test.cc +++ b/test/common/upstream/cluster_manager_impl_test.cc @@ -103,7 +103,7 @@ TEST_F(ClusterManagerImplTest, OutlierEventLog) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_CALL(log_manager_, createAccessLog("foo")); create(*loader); } @@ -121,7 +121,7 @@ TEST_F(ClusterManagerImplTest, NoSdsConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(create(*loader), EnvoyException); } @@ -138,7 +138,7 @@ TEST_F(ClusterManagerImplTest, UnknownClusterType) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(create(*loader), EnvoyException); } @@ -164,7 +164,7 @@ TEST_F(ClusterManagerImplTest, LocalClusterNotDefined) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(create(*loader), EnvoyException); } @@ -179,7 +179,7 @@ TEST_F(ClusterManagerImplTest, BadClusterManagerConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(create(*loader), Json::Exception); } @@ -212,7 +212,7 @@ TEST_F(ClusterManagerImplTest, LocalClusterDefined) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); EXPECT_EQ(3UL, factory_.stats_.counter("cluster_manager.cluster_added").value()); @@ -242,7 +242,7 @@ TEST_F(ClusterManagerImplTest, DuplicateCluster) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(create(*loader), EnvoyException); } @@ -263,7 +263,7 @@ TEST_F(ClusterManagerImplTest, UnknownHcType) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(create(*loader), EnvoyException); } @@ -277,11 +277,11 @@ TEST_F(ClusterManagerImplTest, MaxClusterName) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW_WITH_MESSAGE(create(*loader), Json::Exception, - "JSON object doesn't conform to schema.\n Invalid schema: " - "#/properties/name.\n Invalid keyword: maxLength.\n Invalid document " - "key: #/name"); + "JSON at lines 4-6 does not conform to schema.\n Invalid schema: " + "#/properties/name\n Schema violation: maxLength\n Offending " + "document key: #/name"); } TEST_F(ClusterManagerImplTest, InvalidClusterNameChars) { @@ -294,10 +294,10 @@ TEST_F(ClusterManagerImplTest, InvalidClusterNameChars) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW_WITH_MESSAGE(create(*loader), Json::Exception, - "JSON object doesn't conform to schema.\n Invalid schema: " - "#/properties/name.\n Invalid keyword: pattern.\n Invalid document " + "JSON at lines 4-6 does not conform to schema.\n Invalid schema: " + "#/properties/name\n Schema violation: pattern\n Offending document " "key: #/name"); } @@ -328,7 +328,7 @@ TEST_F(ClusterManagerImplTest, TcpHealthChecker) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); Network::MockClientConnection* connection = new NiceMock(); EXPECT_CALL(factory_.dispatcher_, createClientConnection_(PointeesEq(Network::Utility::resolveUrl( "tcp://127.0.0.1:11001")))).WillOnce(Return(connection)); @@ -350,7 +350,7 @@ TEST_F(ClusterManagerImplTest, UnknownCluster) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); EXPECT_EQ(nullptr, cluster_manager_->get("hello")); EXPECT_EQ(nullptr, @@ -378,7 +378,7 @@ TEST_F(ClusterManagerImplTest, VerifyBufferLimits) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); Network::MockClientConnection* connection = new NiceMock(); EXPECT_CALL(*connection, setReadBufferLimit(8192)); @@ -402,7 +402,7 @@ TEST_F(ClusterManagerImplTest, ShutdownOrder) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); const Cluster& cluster = cluster_manager_->clusters().begin()->second; EXPECT_EQ("cluster_1", cluster.info()->name()); @@ -458,7 +458,7 @@ TEST_F(ClusterManagerImplTest, InitializeOrder) { EXPECT_CALL(factory_, clusterFromJson_(_, _, _, _)).WillOnce(Return(cluster2)); ON_CALL(*cluster2, initializePhase()).WillByDefault(Return(Cluster::InitializePhase::Secondary)); - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); ReadyWatcher initialized; @@ -485,7 +485,7 @@ TEST_F(ClusterManagerImplTest, InitializeOrder) { } )EOF"; - Json::ObjectPtr loader_api = Json::Factory::loadFromString(json_api); + Json::ObjectSharedPtr loader_api = Json::Factory::loadFromString(json_api); EXPECT_CALL(factory_, clusterFromJson_(_, _, _, _)).WillOnce(Return(cluster3)); ON_CALL(*cluster3, initializePhase()).WillByDefault(Return(Cluster::InitializePhase::Secondary)); cluster_manager_->addOrUpdatePrimaryCluster(*loader_api); @@ -534,7 +534,7 @@ TEST_F(ClusterManagerImplTest, DynamicAddRemove) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); InSequence s; @@ -548,7 +548,7 @@ TEST_F(ClusterManagerImplTest, DynamicAddRemove) { } )EOF"; - Json::ObjectPtr loader_api = Json::Factory::loadFromString(json_api); + Json::ObjectSharedPtr loader_api = Json::Factory::loadFromString(json_api); MockCluster* cluster1 = new NiceMock(); EXPECT_CALL(factory_, clusterFromJson_(_, _, _, _)).WillOnce(Return(cluster1)); EXPECT_CALL(*cluster1, initializePhase()).Times(0); @@ -626,7 +626,7 @@ TEST_F(ClusterManagerImplTest, AddOrUpdatePrimaryClusterStaticExists) { ON_CALL(*cluster1, initializePhase()).WillByDefault(Return(Cluster::InitializePhase::Primary)); EXPECT_CALL(*cluster1, initialize()); - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); create(*loader); ReadyWatcher initialized; @@ -641,7 +641,7 @@ TEST_F(ClusterManagerImplTest, AddOrUpdatePrimaryClusterStaticExists) { } )EOF"; - Json::ObjectPtr loader_api = Json::Factory::loadFromString(json_api); + Json::ObjectSharedPtr loader_api = Json::Factory::loadFromString(json_api); EXPECT_FALSE(cluster_manager_->addOrUpdatePrimaryCluster(*loader_api)); // Attempt to remove a static cluster. @@ -664,7 +664,7 @@ TEST_F(ClusterManagerImplTest, DynamicHostRemove) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); Network::DnsResolver::ResolveCb dns_callback; Event::MockTimer* dns_timer_ = new NiceMock(&factory_.dispatcher_); diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index e5279bc48731..a87ec9aae325 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -46,7 +46,7 @@ TEST(HealthCheckerFactoryTest, createRedis) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); NiceMock cluster; Runtime::MockLoader runtime; Runtime::MockRandomGenerator random; @@ -99,7 +99,7 @@ class HttpHealthCheckerImplTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); health_checker_.reset( new TestHttpHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_)); health_checker_->addHostCheckCompleteCb([this](HostSharedPtr host, bool changed_state) @@ -120,7 +120,7 @@ class HttpHealthCheckerImplTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); health_checker_.reset( new TestHttpHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_)); health_checker_->addHostCheckCompleteCb([this](HostSharedPtr host, bool changed_state) @@ -611,7 +611,7 @@ TEST(TcpHealthCheckMatcher, loadJsonBytes) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); TcpHealthCheckMatcher::MatchSegments segments = TcpHealthCheckMatcher::loadJsonBytes(config->getObjectArray("bytes")); EXPECT_EQ(2U, segments.size()); @@ -626,7 +626,7 @@ TEST(TcpHealthCheckMatcher, loadJsonBytes) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); EXPECT_THROW(TcpHealthCheckMatcher::loadJsonBytes(config->getObjectArray("bytes")), EnvoyException); } @@ -640,7 +640,7 @@ TEST(TcpHealthCheckMatcher, loadJsonBytes) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); EXPECT_THROW(TcpHealthCheckMatcher::loadJsonBytes(config->getObjectArray("bytes")), EnvoyException); } @@ -660,7 +660,7 @@ TEST(TcpHealthCheckMatcher, match) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); TcpHealthCheckMatcher::MatchSegments segments = TcpHealthCheckMatcher::loadJsonBytes(config->getObjectArray("bytes")); @@ -706,7 +706,7 @@ class TcpHealthCheckerImplTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); health_checker_.reset( new TcpHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_)); } @@ -724,7 +724,7 @@ class TcpHealthCheckerImplTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); health_checker_.reset( new TcpHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_)); } @@ -860,7 +860,7 @@ class RedisHealthCheckerImplTest : public testing::Test, public Redis::ConnPool: } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); health_checker_.reset( new RedisHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_, *this)); } diff --git a/test/common/upstream/logical_dns_cluster_test.cc b/test/common/upstream/logical_dns_cluster_test.cc index 9d6f7033b076..97ff34a999b5 100644 --- a/test/common/upstream/logical_dns_cluster_test.cc +++ b/test/common/upstream/logical_dns_cluster_test.cc @@ -26,7 +26,7 @@ namespace Upstream { class LogicalDnsClusterTest : public testing::Test { public: void setup(const std::string& json) { - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); resolve_timer_ = new Event::MockTimer(&dispatcher_); cluster_.reset(new LogicalDnsCluster(*config, runtime_, stats_store_, ssl_context_manager_, dns_resolver_, tls_, dispatcher_)); diff --git a/test/common/upstream/outlier_detection_impl_test.cc b/test/common/upstream/outlier_detection_impl_test.cc index 59db9160dd81..a809469c09d1 100644 --- a/test/common/upstream/outlier_detection_impl_test.cc +++ b/test/common/upstream/outlier_detection_impl_test.cc @@ -30,7 +30,7 @@ namespace Upstream { namespace Outlier { TEST(OutlierDetectorImplFactoryTest, NoDetector) { - Json::ObjectPtr loader = Json::Factory::loadFromString("{}"); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString("{}"); NiceMock cluster; NiceMock dispatcher; NiceMock runtime; @@ -45,7 +45,7 @@ TEST(OutlierDetectorImplFactoryTest, Detector) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock cluster; NiceMock dispatcher; NiceMock runtime; @@ -86,7 +86,7 @@ class OutlierDetectorImplTest : public testing::Test { CallbackChecker checker_; MockMonotonicTimeSource time_source_; std::shared_ptr event_logger_{new MockEventLogger()}; - Json::ObjectPtr loader_ = Json::Factory::loadFromString("{}"); + Json::ObjectSharedPtr loader_ = Json::Factory::loadFromString("{}"); }; TEST_F(OutlierDetectorImplTest, DetectorStaticConfig) { @@ -104,7 +104,7 @@ TEST_F(OutlierDetectorImplTest, DetectorStaticConfig) { } )EOF"; - Json::ObjectPtr custom_config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr custom_config = Json::Factory::loadFromString(json); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(100))); std::shared_ptr detector(DetectorImpl::create( cluster_, *custom_config, dispatcher_, runtime_, time_source_, event_logger_)); diff --git a/test/common/upstream/sds_test.cc b/test/common/upstream/sds_test.cc index e78a7034e11d..3800239f8cbe 100644 --- a/test/common/upstream/sds_test.cc +++ b/test/common/upstream/sds_test.cc @@ -45,7 +45,7 @@ class SdsTest : public testing::Test { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(raw_config); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(raw_config); timer_ = new Event::MockTimer(&dispatcher_); local_info_.zone_name_ = "us-east-1a"; diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index 19d0a5b7ce9a..8f4101751823 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -86,7 +86,7 @@ TEST(StrictDnsClusterImplTest, ImmediateResolve) { cb(TestUtility::makeDnsResponse({"127.0.0.1", "127.0.0.2"})); return nullptr; })); - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); StrictDnsClusterImpl cluster(*loader, runtime, stats, ssl_context_manager, dns_resolver, dispatcher); cluster.setInitializedCb([&]() -> void { initialized.ready(); }); @@ -133,7 +133,7 @@ TEST(StrictDnsClusterImplTest, Basic) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); StrictDnsClusterImpl cluster(*loader, runtime, stats, ssl_context_manager, dns_resolver, dispatcher); EXPECT_EQ(43U, cluster.info()->resourceManager(ResourcePriority::Default).connections().max()); @@ -277,7 +277,7 @@ TEST(StaticClusterImplTest, EmptyHostname) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); StaticClusterImpl cluster(*config, runtime, stats, ssl_context_manager); EXPECT_EQ(1UL, cluster.healthyHosts().size()); EXPECT_EQ("", cluster.hosts()[0]->hostname()); @@ -297,7 +297,7 @@ TEST(StaticClusterImplTest, RingHash) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); StaticClusterImpl cluster(*config, runtime, stats, ssl_context_manager); EXPECT_EQ(1UL, cluster.healthyHosts().size()); EXPECT_EQ(LoadBalancerType::RingHash, cluster.info()->lbType()); @@ -318,7 +318,7 @@ TEST(StaticClusterImplTest, OutlierDetector) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); StaticClusterImpl cluster(*config, runtime, stats, ssl_context_manager); Outlier::MockDetector* detector = new Outlier::MockDetector(); @@ -359,7 +359,7 @@ TEST(StaticClusterImplTest, HealthyStat) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); StaticClusterImpl cluster(*config, runtime, stats, ssl_context_manager); Outlier::MockDetector* outlier_detector = new NiceMock(); @@ -417,7 +417,7 @@ TEST(StaticClusterImplTest, UrlConfig) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); StaticClusterImpl cluster(*config, runtime, stats, ssl_context_manager); EXPECT_EQ(1024U, cluster.info()->resourceManager(ResourcePriority::Default).connections().max()); EXPECT_EQ(1024U, @@ -453,7 +453,7 @@ TEST(StaticClusterImplTest, UnsupportedLBType) { } )EOF"; - Json::ObjectPtr config = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr config = Json::Factory::loadFromString(json); EXPECT_THROW(StaticClusterImpl(*config, runtime, stats, ssl_context_manager), EnvoyException); } @@ -469,7 +469,7 @@ TEST(ClusterDefinitionTest, BadClusterConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); EXPECT_THROW(loader->validateSchema(Json::Schema::CLUSTER_SCHEMA), Json::Exception); } diff --git a/test/config_test/config_test.cc b/test/config_test/config_test.cc index 22e3a9a9fdff..69a79dc36a5d 100644 --- a/test/config_test/config_test.cc +++ b/test/config_test/config_test.cc @@ -29,7 +29,7 @@ class ConfigTest { ON_CALL(server_.api_, fileReadToEnd("lightstep_access_token")) .WillByDefault(Return("access_token")); - Json::ObjectPtr config_json = Json::Factory::loadFromFile(file_path); + Json::ObjectSharedPtr config_json = Json::Factory::loadFromFile(file_path); Server::Configuration::InitialImpl initial_config(*config_json); Server::Configuration::MainImpl main_config(server_); diff --git a/test/integration/integration_admin_test.cc b/test/integration/integration_admin_test.cc index 5a5dc4753add..8675fe8edfff 100644 --- a/test/integration/integration_admin_test.cc +++ b/test/integration/integration_admin_test.cc @@ -131,8 +131,8 @@ TEST_F(IntegrationTest, Admin) { EXPECT_TRUE(response->complete()); EXPECT_STREQ("200", response->headers().Status()->value().c_str()); - Json::ObjectPtr json = Json::Factory::loadFromString(response->body()); - std::vector listener_info = json->asObjectArray(); + Json::ObjectSharedPtr json = Json::Factory::loadFromString(response->body()); + std::vector listener_info = json->asObjectArray(); for (std::size_t index = 0; index < listener_info.size(); index++) { EXPECT_EQ(test_server_->server().getListenSocketByIndex(index)->localAddress()->asString(), listener_info[index]->asString()); diff --git a/test/integration/ssl_integration_test.cc b/test/integration/ssl_integration_test.cc index afe7377d4b78..aa589379f9fc 100644 --- a/test/integration/ssl_integration_test.cc +++ b/test/integration/ssl_integration_test.cc @@ -61,7 +61,7 @@ ServerContextPtr SslIntegrationTest::createUpstreamSslContext() { } )EOF"; - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(json); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(json); ContextConfigImpl cfg(*loader); return context_manager_->createSslServerContext(*upstream_stats_store, cfg); } @@ -109,7 +109,7 @@ ClientContextPtr SslIntegrationTest::createClientSslContext(bool alpn, bool san) } else { target = san ? json_san : json_plain; } - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(target); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(target); ContextConfigImpl cfg(*loader); static auto* client_stats_store = new Stats::TestIsolatedStoreImpl(); return context_manager_->createSslClientContext(*client_stats_store, cfg); diff --git a/test/server/config/http/config_test.cc b/test/server/config/http/config_test.cc index 2bea905684bd..42f8e3bb39b0 100644 --- a/test/server/config/http/config_test.cc +++ b/test/server/config/http/config_test.cc @@ -28,7 +28,7 @@ TEST(HttpFilterConfigTest, BufferFilter) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; BufferFilterConfig factory; HttpFilterFactoryCb cb = factory.tryCreateFilterFactory(HttpFilterType::Decoder, "buffer", @@ -46,7 +46,7 @@ TEST(HttpFilterConfigTest, BadBufferFilterConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; BufferFilterConfig factory; EXPECT_THROW(factory.tryCreateFilterFactory(HttpFilterType::Decoder, "buffer", *json_config, @@ -60,7 +60,7 @@ TEST(HttpFilterConfigTest, DynamoFilter) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; DynamoFilterConfig factory; HttpFilterFactoryCb cb = factory.tryCreateFilterFactory( @@ -81,7 +81,7 @@ TEST(HttpFilterConfigTest, FaultFilter) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; FaultFilterConfig factory; HttpFilterFactoryCb cb = factory.tryCreateFilterFactory(HttpFilterType::Decoder, "fault", @@ -97,7 +97,7 @@ TEST(HttpFilterConfigTest, GrpcHttp1BridgeFilter) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; GrpcHttp1BridgeFilterConfig factory; HttpFilterFactoryCb cb = factory.tryCreateFilterFactory(HttpFilterType::Both, "grpc_http1_bridge", @@ -115,7 +115,7 @@ TEST(HttpFilterConfigTest, HealthCheckFilter) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; HealthCheckFilterConfig factory; HttpFilterFactoryCb cb = factory.tryCreateFilterFactory(HttpFilterType::Both, "health_check", @@ -134,7 +134,7 @@ TEST(HttpFilterConfigTest, BadHealthCheckFilterConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; HealthCheckFilterConfig factory; EXPECT_THROW(factory.tryCreateFilterFactory(HttpFilterType::Both, "health_check", *json_config, @@ -149,7 +149,7 @@ TEST(HttpFilterConfigTest, RouterFilter) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; RouterFilterConfig factory; HttpFilterFactoryCb cb = factory.tryCreateFilterFactory(HttpFilterType::Decoder, "router", @@ -167,7 +167,7 @@ TEST(HttpFilterConfigTest, BadRouterFilterConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; RouterFilterConfig factory; EXPECT_THROW(factory.tryCreateFilterFactory(HttpFilterType::Decoder, "router", *json_config, diff --git a/test/server/config/network/config_test.cc b/test/server/config/network/config_test.cc index 7d5bbc222ca7..fcae5c40ff43 100644 --- a/test/server/config/network/config_test.cc +++ b/test/server/config/network/config_test.cc @@ -30,7 +30,7 @@ TEST(NetworkFilterConfigTest, RedisProxy) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; RedisProxyFilterConfigFactory factory; NetworkFilterFactoryCb cb = @@ -48,7 +48,7 @@ TEST(NetworkFilterConfigTest, MongoProxy) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; MongoProxyFilterConfigFactory factory; NetworkFilterFactoryCb cb = @@ -67,7 +67,7 @@ TEST(NetworkFilterConfigTest, BadMongoProxyConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; MongoProxyFilterConfigFactory factory; EXPECT_THROW( @@ -103,7 +103,7 @@ TEST(NetworkFilterConfigTest, TcpProxy) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; TcpProxyConfigFactory factory; NetworkFilterFactoryCb cb = @@ -125,7 +125,7 @@ TEST(NetworkFilterConfigTest, ClientSslAuth) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; ClientSslAuthConfigFactory factory; NetworkFilterFactoryCb cb = factory.tryCreateFilterFactory( @@ -144,7 +144,7 @@ TEST(NetworkFilterConfigTest, Ratelimit) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); NiceMock server; RateLimitConfigFactory factory; NetworkFilterFactoryCb cb = @@ -177,7 +177,7 @@ TEST(NetworkFilterConfigTest, BadHttpConnectionMangerConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); HttpConnectionManagerFilterConfigFactory factory; NiceMock server; EXPECT_THROW(factory.tryCreateFilterFactory(NetworkFilterType::Read, "http_connection_manager", @@ -220,7 +220,7 @@ TEST(NetworkFilterConfigTest, BadAccessLogConfig) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); HttpConnectionManagerFilterConfigFactory factory; NiceMock server; EXPECT_THROW(factory.tryCreateFilterFactory(NetworkFilterType::Read, "http_connection_manager", @@ -265,7 +265,7 @@ TEST(NetworkFilterConfigTest, BadAccessLogType) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); HttpConnectionManagerFilterConfigFactory factory; NiceMock server; EXPECT_THROW(factory.tryCreateFilterFactory(NetworkFilterType::Read, "http_connection_manager", @@ -320,7 +320,7 @@ TEST(NetworkFilterConfigTest, BadAccessLogNestedTypes) { } )EOF"; - Json::ObjectPtr json_config = Json::Factory::loadFromString(json_string); + Json::ObjectSharedPtr json_config = Json::Factory::loadFromString(json_string); HttpConnectionManagerFilterConfigFactory factory; NiceMock server; EXPECT_THROW(factory.tryCreateFilterFactory(NetworkFilterType::Read, "http_connection_manager", diff --git a/test/server/configuration_impl_test.cc b/test/server/configuration_impl_test.cc index 22fecf06d729..7bcb89e8ed62 100644 --- a/test/server/configuration_impl_test.cc +++ b/test/server/configuration_impl_test.cc @@ -51,7 +51,7 @@ TEST(ConfigurationImplTest, DefaultStatsFlushInterval) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -73,7 +73,7 @@ TEST(ConfigurationImplTest, CustomStatsFlushInterval) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -97,7 +97,7 @@ TEST(ConfigurationImplTest, EmptyFilter) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -121,7 +121,7 @@ TEST(ConfigurationImplTest, DefaultListenerPerConnectionBufferLimit) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -146,7 +146,7 @@ TEST(ConfigurationImplTest, SetListenerPerConnectionBufferLimit) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -178,7 +178,7 @@ TEST(ConfigurationImplTest, VerifySubjectAltNameConfig) { } )EOF"; - Json::ObjectPtr loader = TestEnvironment::jsonLoadFromString(json); + Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString(json); NiceMock server; MainImpl config(server); @@ -208,7 +208,7 @@ TEST(ConfigurationImplTest, SetUpstreamClusterPerConnectionBufferLimit) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -240,7 +240,7 @@ TEST(ConfigurationImplTest, BadListenerConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -268,7 +268,7 @@ TEST(ConfigurationImplTest, BadFilterConfig) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; MainImpl config(server); @@ -300,7 +300,7 @@ TEST(ConfigurationImplTest, ServiceClusterNotSetWhenLSTracing) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; server.local_info_.cluster_name_ = ""; @@ -323,7 +323,7 @@ TEST(ConfigurationImplTest, NullTracerSetWhenTracingConfigurationAbsent) { } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; server.local_info_.cluster_name_ = ""; @@ -358,7 +358,7 @@ TEST(ConfigurationImplTest, NullTracerSetWhenHttpKeyAbsentFromTracerConfiguratio } )EOF"; - Json::ObjectPtr loader = Json::Factory::loadFromString(json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromString(json); NiceMock server; server.local_info_.cluster_name_ = ""; diff --git a/test/server/http/health_check_test.cc b/test/server/http/health_check_test.cc index abd60c674b29..49755cd24864 100644 --- a/test/server/http/health_check_test.cc +++ b/test/server/http/health_check_test.cc @@ -204,7 +204,7 @@ TEST_F(HealthCheckFilterCachingTest, NotHcRequest) { TEST(HealthCheckFilterConfig, failsWhenNotPassThroughButTimeoutSet) { Server::Configuration::HealthCheckFilterConfig healthCheckFilterConfig; - Json::ObjectPtr config = Json::Factory::loadFromString( + Json::ObjectSharedPtr config = Json::Factory::loadFromString( "{\"pass_through_mode\":false, \"cache_time_ms\":234, \"endpoint\":\"foo\"}"); NiceMock serverMock; @@ -216,7 +216,7 @@ TEST(HealthCheckFilterConfig, failsWhenNotPassThroughButTimeoutSet) { TEST(HealthCheckFilterConfig, notFailingWhenNotPassThroughAndTimeoutNotSet) { Server::Configuration::HealthCheckFilterConfig healthCheckFilterConfig; - Json::ObjectPtr config = + Json::ObjectSharedPtr config = Json::Factory::loadFromString("{\"pass_through_mode\":false, \"endpoint\":\"foo\"}"); NiceMock serverMock; diff --git a/test/test_common/environment.cc b/test/test_common/environment.cc index 3dcf2593b41b..2feaa8c83679 100644 --- a/test/test_common/environment.cc +++ b/test/test_common/environment.cc @@ -163,7 +163,7 @@ std::string TestEnvironment::temporaryFileSubstitute(const std::string& path, return out_json_path; } -Json::ObjectPtr TestEnvironment::jsonLoadFromString(const std::string& json) { +Json::ObjectSharedPtr TestEnvironment::jsonLoadFromString(const std::string& json) { return Json::Factory::loadFromString(substitute(json)); } diff --git a/test/test_common/environment.h b/test/test_common/environment.h index 26f4e5e12a00..2026134d8f2b 100644 --- a/test/test_common/environment.h +++ b/test/test_common/environment.h @@ -128,9 +128,9 @@ class TestEnvironment { /** * Build JSON object from a string subject to environment path substitution. * @param json JSON with template patterns including {{ test_certs }}. - * @return Json::ObjectPtr with built JSON object. + * @return Json::ObjectSharedPtr with built JSON object. */ - static Json::ObjectPtr jsonLoadFromString(const std::string& json); + static Json::ObjectSharedPtr jsonLoadFromString(const std::string& json); /** * Execute a program under ::system. Any failure is fatal. diff --git a/test/tools/router_check/router.cc b/test/tools/router_check/router.cc index df2b93179307..74f565e5b767 100644 --- a/test/tools/router_check/router.cc +++ b/test/tools/router_check/router.cc @@ -9,8 +9,8 @@ namespace Envoy { // static -ToolConfig ToolConfig::create(const Json::ObjectPtr& check_config) { - Json::ObjectPtr input = check_config->getObject("input"); +ToolConfig ToolConfig::create(const Json::ObjectSharedPtr check_config) { + Json::ObjectSharedPtr input = check_config->getObject("input"); int random_value = input->getInteger("random_value", 0); // Add header field values @@ -25,7 +25,7 @@ ToolConfig ToolConfig::create(const Json::ObjectPtr& check_config) { } if (input->hasObject("additional_headers")) { - for (const Json::ObjectPtr& header_config : input->getObjectArray("additional_headers")) { + for (const Json::ObjectSharedPtr header_config : input->getObjectArray("additional_headers")) { headers->addViaCopy(header_config->getString("field"), header_config->getString("value")); } } @@ -39,7 +39,7 @@ ToolConfig::ToolConfig(std::unique_ptr headers, int ran // static RouterCheckTool RouterCheckTool::create(const std::string& router_config_json) { // TODO(hennna): Allow users to load a full config and extract the route configuration from it. - Json::ObjectPtr loader = Json::Factory::loadFromFile(router_config_json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromFile(router_config_json); loader->validateSchema(Json::Schema::ROUTE_CONFIGURATION_SCHEMA); std::unique_ptr> runtime(new NiceMock()); @@ -56,11 +56,11 @@ RouterCheckTool::RouterCheckTool(std::unique_ptr> : runtime_(std::move(runtime)), cm_(std::move(cm)), config_(std::move(config)) {} bool RouterCheckTool::compareEntriesInJson(const std::string& expected_route_json) { - Json::ObjectPtr loader = Json::Factory::loadFromFile(expected_route_json); + Json::ObjectSharedPtr loader = Json::Factory::loadFromFile(expected_route_json); loader->validateSchema(Json::ToolSchema::routerCheckSchema()); bool no_failures = true; - for (const Json::ObjectPtr& check_config : loader->asObjectArray()) { + for (const Json::ObjectSharedPtr check_config : loader->asObjectArray()) { ToolConfig tool_config = ToolConfig::create(check_config); tool_config.route_ = config_->route(*tool_config.headers_, tool_config.random_value_); @@ -68,7 +68,7 @@ bool RouterCheckTool::compareEntriesInJson(const std::string& expected_route_jso if (details_) { std::cout << test_name << std::endl; } - Json::ObjectPtr validate = check_config->getObject("validate"); + Json::ObjectSharedPtr validate = check_config->getObject("validate"); const std::unordered_map> checkers = { @@ -102,7 +102,7 @@ bool RouterCheckTool::compareEntriesInJson(const std::string& expected_route_jso } if (validate->hasObject("header_fields")) { - for (const Json::ObjectPtr& header_field : validate->getObjectArray("header_fields")) { + for (const Json::ObjectSharedPtr header_field : validate->getObjectArray("header_fields")) { if (!compareHeaderField(tool_config, header_field->getString("field"), header_field->getString("value"))) { no_failures = false; diff --git a/test/tools/router_check/router.h b/test/tools/router_check/router.h index 6a2d12b7089a..987392d74326 100644 --- a/test/tools/router_check/router.h +++ b/test/tools/router_check/router.h @@ -29,7 +29,7 @@ struct ToolConfig { * @return ToolConfig a ToolConfig instance with member variables set by the tool config json * file. */ - static ToolConfig create(const Json::ObjectPtr& check_config); + static ToolConfig create(const Json::ObjectSharedPtr check_config); std::unique_ptr headers_; Router::RouteConstSharedPtr route_; diff --git a/test/tools/router_check/test/route_tests.sh b/test/tools/router_check/test/route_tests.sh index a354a5a22bf4..bddc74e4e321 100755 --- a/test/tools/router_check/test/route_tests.sh +++ b/test/tools/router_check/test/route_tests.sh @@ -18,7 +18,7 @@ done # Bad config file BAD_CONFIG_OUTPUT=$(("${PATH_BIN}" "${PATH_CONFIG}/Redirect.golden.json" "${PATH_CONFIG}/TestRoutes.json") 2>&1) || - if [[ "${BAD_CONFIG_OUTPUT}" == *"JSON object doesn't conform to schema."* ]]; then + if [[ "${BAD_CONFIG_OUTPUT}" == *"does not conform to schema."* ]]; then echo testing bad config output echo ${BAD_CONFIG_OUTPUT} else