Cleanup whitespace.

This commit is contained in:
Tristan Penman
2014-03-01 09:03:39 +11:00
parent 46ac9159bd
commit 5b29f915a1
25 changed files with 616 additions and 617 deletions

View File

@@ -13,7 +13,7 @@
* - PropertiesConstraint * - PropertiesConstraint
* - RequiredConstraint * - RequiredConstraint
* - TypeConstraint * - TypeConstraint
* *
* The MinimumConstraint class provides support for the exclusiveMinimum and * The MinimumConstraint class provides support for the exclusiveMinimum and
* minimum keywords in JSON Schema. And the PropertiesConstraint class provides * minimum keywords in JSON Schema. And the PropertiesConstraint class provides
* support for the properties, patternProperties, and additionalProperties * support for the properties, patternProperties, and additionalProperties
@@ -88,10 +88,10 @@ using valijson::constraints::TypeConstraint;
void addPropertiesConstraint(Schema &schema) void addPropertiesConstraint(Schema &schema)
{ {
PropertiesConstraint::PropertySchemaMap propertySchemaMap; PropertiesConstraint::PropertySchemaMap propertySchemaMap;
PropertiesConstraint::PropertySchemaMap patternPropertiesSchemaMap; PropertiesConstraint::PropertySchemaMap patternPropertiesSchemaMap;
{ {
// Create a child schema for the 'category' property that requires one // Create a child schema for the 'category' property that requires one
// of several possible values. // of several possible values.
@@ -103,14 +103,14 @@ void addPropertiesConstraint(Schema &schema)
enumConstraintValues.push_back(new RapidJsonFrozenValue("video")); enumConstraintValues.push_back(new RapidJsonFrozenValue("video"));
propertySchema.addConstraint(new EnumConstraint(enumConstraintValues)); propertySchema.addConstraint(new EnumConstraint(enumConstraintValues));
} }
{ {
// Create a child schema for the 'description' property that requires // Create a child schema for the 'description' property that requires
// a string, but does not enforce any length constraints. // a string, but does not enforce any length constraints.
Schema &propertySchema = propertySchemaMap["description"]; Schema &propertySchema = propertySchemaMap["description"];
propertySchema.addConstraint(new TypeConstraint(TypeConstraint::kString)); propertySchema.addConstraint(new TypeConstraint(TypeConstraint::kString));
} }
{ {
// Create a child schema for the 'price' property, that requires a // Create a child schema for the 'price' property, that requires a
// number with a value greater than zero. // number with a value greater than zero.
@@ -118,7 +118,7 @@ void addPropertiesConstraint(Schema &schema)
propertySchema.addConstraint(new MinimumConstraint(0.0, true)); propertySchema.addConstraint(new MinimumConstraint(0.0, true));
propertySchema.addConstraint(new TypeConstraint(TypeConstraint::kNumber)); propertySchema.addConstraint(new TypeConstraint(TypeConstraint::kNumber));
} }
{ {
// Create a child schema for the 'title' property that requires a string // Create a child schema for the 'title' property that requires a string
// that is between 1 and 200 characters in length. // that is between 1 and 200 characters in length.
@@ -148,7 +148,7 @@ void addRequiredConstraint(Schema &schema)
void addTypeConstraint(Schema &schema) void addTypeConstraint(Schema &schema)
{ {
// Add a TypeConstraint to the schema, specifying that the root of the // Add a TypeConstraint to the schema, specifying that the root of the
// document must be an object. // document must be an object.
schema.addConstraint(new TypeConstraint(TypeConstraint::kObject)); schema.addConstraint(new TypeConstraint(TypeConstraint::kObject));
} }
@@ -167,7 +167,7 @@ int main(int argc, char *argv[])
addPropertiesConstraint(schema); addPropertiesConstraint(schema);
addRequiredConstraint(schema); addRequiredConstraint(schema);
addTypeConstraint(schema); addTypeConstraint(schema);
// Perform validation // Perform validation
Validator validator(schema); Validator validator(schema);
ValidationResults results; ValidationResults results;

View File

@@ -31,13 +31,13 @@ public:
/// Typedef for callback function supplied to applyToObject. /// Typedef for callback function supplied to applyToObject.
typedef boost::function<bool (const std::string &, const Adapter &)> typedef boost::function<bool (const std::string &, const Adapter &)>
ObjectMemberCallback; ObjectMemberCallback;
/** /**
* @brief Virtual destructor defined to ensure deletion via base-class * @brief Virtual destructor defined to ensure deletion via base-class
* pointers is safe. * pointers is safe.
*/ */
virtual ~Adapter() { }; virtual ~Adapter() { };
/** /**
* @brief Apply a callback function to each value in an array. * @brief Apply a callback function to each value in an array.
* *
@@ -59,11 +59,11 @@ public:
* *
* @param fn Callback function to invoke * @param fn Callback function to invoke
* *
* @returns true if Adapter contains an object, and callback function * @returns true if Adapter contains an object, and callback function
* returns true for each member in the object, false otherwise. * returns true for each member in the object, false otherwise.
*/ */
virtual bool applyToObject(ObjectMemberCallback fn) const = 0; virtual bool applyToObject(ObjectMemberCallback fn) const = 0;
/** /**
* @brief Return the boolean representation of the contained value. * @brief Return the boolean representation of the contained value.
* *
@@ -76,11 +76,11 @@ public:
* @returns Boolean representation of contained value. * @returns Boolean representation of contained value.
*/ */
virtual bool asBool() const = 0; virtual bool asBool() const = 0;
/** /**
* @brief Retrieve the boolean representation of the contained value. * @brief Retrieve the boolean representation of the contained value.
* *
* This function shall retrieve a boolean value if the Adapter contains * This function shall retrieve a boolean value if the Adapter contains
* either an actual boolean value, or one of the strings 'true' or 'false'. * either an actual boolean value, or one of the strings 'true' or 'false'.
* The string comparison is case sensitive. * The string comparison is case sensitive.
* *
@@ -89,27 +89,27 @@ public:
* @param result reference to a bool to set with retrieved value. * @param result reference to a bool to set with retrieved value.
* *
* @returns true if the value could be retrieved, false otherwise * @returns true if the value could be retrieved, false otherwise
*/ */
virtual bool asBool(bool &result) const = 0; virtual bool asBool(bool &result) const = 0;
/** /**
* @brief Return the double representation of the contained value. * @brief Return the double representation of the contained value.
* *
* This function shall return a double value if the Adapter contains either * This function shall return a double value if the Adapter contains either
* an actual double, an integer, or a string that contains a valid * an actual double, an integer, or a string that contains a valid
* representation of a numeric value (according to the C++ Std Library). * representation of a numeric value (according to the C++ Std Library).
* *
* An exception shall be thrown if the value cannot be cast to a double. * An exception shall be thrown if the value cannot be cast to a double.
* *
* @returns Double representation of contained value. * @returns Double representation of contained value.
*/ */
virtual double asDouble() const = 0; virtual double asDouble() const = 0;
/** /**
* @brief Retrieve the double representation of the contained value. * @brief Retrieve the double representation of the contained value.
* *
* This function shall retrieve a double value if the Adapter contains either * This function shall retrieve a double value if the Adapter contains either
* an actual double, an integer, or a string that contains a valid * an actual double, an integer, or a string that contains a valid
* representation of a numeric value (according to the C++ Std Library). * representation of a numeric value (according to the C++ Std Library).
* *
* The retrieved value is returned via reference. * The retrieved value is returned via reference.
@@ -117,9 +117,9 @@ public:
* @param result reference to a double to set with retrieved value. * @param result reference to a double to set with retrieved value.
* *
* @returns true if the value could be retrieved, false otherwise * @returns true if the value could be retrieved, false otherwise
*/ */
virtual bool asDouble(double &result) const = 0; virtual bool asDouble(double &result) const = 0;
/** /**
* @brief Return the int64_t representation of the contained value. * @brief Return the int64_t representation of the contained value.
* *
@@ -130,14 +130,14 @@ public:
* An exception shall be thrown if the value cannot be cast to an int64_t. * An exception shall be thrown if the value cannot be cast to an int64_t.
* *
* @returns int64_t representation of contained value. * @returns int64_t representation of contained value.
*/ */
virtual int64_t asInteger() const = 0; virtual int64_t asInteger() const = 0;
/** /**
* @brief Retrieve the int64_t representation of the contained value. * @brief Retrieve the int64_t representation of the contained value.
* *
* This function shall retrieve an int64_t value if the Adapter contains * This function shall retrieve an int64_t value if the Adapter contains
* either an actual integer, or a string that contains a valid * either an actual integer, or a string that contains a valid
* representation of an integer value (according to the C++ Std Library). * representation of an integer value (according to the C++ Std Library).
* *
* The retrieved value is returned via reference. * The retrieved value is returned via reference.
@@ -147,7 +147,7 @@ public:
* @returns true if the value could be retrieved, false otherwise * @returns true if the value could be retrieved, false otherwise
*/ */
virtual bool asInteger(int64_t &result) const = 0; virtual bool asInteger(int64_t &result) const = 0;
/** /**
* @brief Return the string representation of the contained value. * @brief Return the string representation of the contained value.
* *
@@ -158,9 +158,9 @@ public:
* An exception shall be thrown if the value cannot be cast to a string. * An exception shall be thrown if the value cannot be cast to a string.
* *
* @returns string representation of contained value. * @returns string representation of contained value.
*/ */
virtual std::string asString() const = 0; virtual std::string asString() const = 0;
/** /**
* @brief Retrieve the string representation of the contained value. * @brief Retrieve the string representation of the contained value.
* *
@@ -212,14 +212,14 @@ public:
* result value shall not be set. This applies even if the value could be * result value shall not be set. This applies even if the value could be
* cast to an empty array. The calling code is expected to handles those * cast to an empty array. The calling code is expected to handles those
* cases manually. * cases manually.
* *
* @param result reference to size_t variable to set with result. * @param result reference to size_t variable to set with result.
* *
* @return true if value retrieved successfully, false otherwise. * @return true if value retrieved successfully, false otherwise.
*/ */
virtual bool getArraySize(size_t &result) const = 0; virtual bool getArraySize(size_t &result) const = 0;
/** /**
* @brief Return the contained boolean value. * @brief Return the contained boolean value.
* *
* This function shall throw an exception if the contained value is not a * This function shall throw an exception if the contained value is not a
@@ -241,7 +241,7 @@ public:
*/ */
virtual bool getBool(bool &result) const = 0; virtual bool getBool(bool &result) const = 0;
/** /**
* @brief Return the contained double value. * @brief Return the contained double value.
* *
* This function shall throw an exception if the contained value is not a * This function shall throw an exception if the contained value is not a
@@ -263,7 +263,7 @@ public:
*/ */
virtual bool getDouble(double &result) const = 0; virtual bool getDouble(double &result) const = 0;
/** /**
* @brief Return the contained integer value. * @brief Return the contained integer value.
* *
* This function shall throw an exception if the contained value is not a * This function shall throw an exception if the contained value is not a
@@ -285,7 +285,7 @@ public:
*/ */
virtual bool getInteger(int64_t &result) const = 0; virtual bool getInteger(int64_t &result) const = 0;
/** /**
* @brief Return the contained numeric value as a double. * @brief Return the contained numeric value as a double.
* *
* This function shall throw an exception if the contained value is not a * This function shall throw an exception if the contained value is not a
@@ -298,14 +298,14 @@ public:
/** /**
* @brief Retrieve the contained numeric value as a double. * @brief Retrieve the contained numeric value as a double.
* *
* This function shall retrieve the double or integral value contained by * This function shall retrieve the double or integral value contained by
* this Adapter, and store it in the result variable that was passed by * this Adapter, and store it in the result variable that was passed by
* reference. * reference.
* *
* @param result reference to double variable to set with result. * @param result reference to double variable to set with result.
* *
* @returns true if the value was retrieved, false otherwise. * @returns true if the value was retrieved, false otherwise.
*/ */
virtual bool getNumber(double &result) const = 0; virtual bool getNumber(double &result) const = 0;
/** /**
@@ -314,7 +314,7 @@ public:
* Throws an exception if the value is not an object. * Throws an exception if the value is not an object.
* *
* @return number of members if value is an object * @return number of members if value is an object
*/ */
virtual size_t getObjectSize() const = 0; virtual size_t getObjectSize() const = 0;
/** /**
@@ -329,7 +329,7 @@ public:
* @param result reference to size_t variable to set with result. * @param result reference to size_t variable to set with result.
* *
* @return true if value retrieved successfully, false otherwise. * @return true if value retrieved successfully, false otherwise.
*/ */
virtual bool getObjectSize(size_t &result) const = 0; virtual bool getObjectSize(size_t &result) const = 0;
/** /**
@@ -354,7 +354,7 @@ public:
* @returns true if string was retrieved, false otherwise * @returns true if string was retrieved, false otherwise
*/ */
virtual bool getString(std::string &result) const = 0; virtual bool getString(std::string &result) const = 0;
/** /**
* @brief Returns whether or not this Adapter supports strict types. * @brief Returns whether or not this Adapter supports strict types.
* *
@@ -365,17 +365,17 @@ public:
* For example, the PropertyTreeAdapter implementation stores POD values as * For example, the PropertyTreeAdapter implementation stores POD values as
* strings, effectively discarding any other type information. If you were * strings, effectively discarding any other type information. If you were
* to call isDouble() on a double stored by this Adapter, the result would * to call isDouble() on a double stored by this Adapter, the result would
* be false. The maybeDouble(), asDouble() and various related functions * be false. The maybeDouble(), asDouble() and various related functions
* are provided to perform type checking based on value rather than on type. * are provided to perform type checking based on value rather than on type.
* *
* The BasicAdapter template class provides implementations for the type- * The BasicAdapter template class provides implementations for the type-
* casting functions so that Adapter implementations are semantically * casting functions so that Adapter implementations are semantically
* equivalent in their type-casting behaviour. * equivalent in their type-casting behaviour.
* *
* @returns true if Adapter supports strict types, false otherwise * @returns true if Adapter supports strict types, false otherwise
*/ */
virtual bool hasStrictTypes() const = 0; virtual bool hasStrictTypes() const = 0;
/// Returns true if the contained value is definitely an array. /// Returns true if the contained value is definitely an array.
virtual bool isArray() const = 0; virtual bool isArray() const = 0;
@@ -399,11 +399,11 @@ public:
/// Returns true if the contained value is definitely a string. /// Returns true if the contained value is definitely a string.
virtual bool isString() const = 0; virtual bool isString() const = 0;
/** /**
* @brief Returns true if the contained value can be cast to an array. * @brief Returns true if the contained value can be cast to an array.
* *
* @returns true if the contained value is an array, an empty string, or an * @returns true if the contained value is an array, an empty string, or an
* empty object. * empty object.
*/ */
virtual bool maybeArray() const = 0; virtual bool maybeArray() const = 0;
@@ -411,8 +411,8 @@ public:
/** /**
* @brief Returns true if the contained value can be cast to a boolean. * @brief Returns true if the contained value can be cast to a boolean.
* *
* @returns true if the contained value is a boolean, or one of the strings * @returns true if the contained value is a boolean, or one of the strings
* 'true' or 'false'. Note that numeric values are not to be cast * 'true' or 'false'. Note that numeric values are not to be cast
* to boolean values. * to boolean values.
*/ */
virtual bool maybeBool() const = 0; virtual bool maybeBool() const = 0;

View File

@@ -27,25 +27,25 @@ namespace adapters {
* the exception throwing behaviour that is expected by other parts of the * the exception throwing behaviour that is expected by other parts of the
* Valijson library. * Valijson library.
* *
* @tparam AdapterType Self-referential name of the Adapter being * @tparam AdapterType Self-referential name of the Adapter being
* specialised. * specialised.
* @tparam ArrayType Name of the type that will be returned by the * @tparam ArrayType Name of the type that will be returned by the
* getArray() function. Instances of this type should * getArray() function. Instances of this type should
* provide begin(), end() and size() functions so * provide begin(), end() and size() functions so
* that it is possible to iterate over the values in * that it is possible to iterate over the values in
* the array. * the array.
* @tparam ObjectMemberType Name of the type exposed when iterating over the * @tparam ObjectMemberType Name of the type exposed when iterating over the
* contents of an object returned by getObject(). * contents of an object returned by getObject().
* @tparam ObjectType Name of the type that will be returned by the * @tparam ObjectType Name of the type that will be returned by the
* getObject() function. Instances of this type * getObject() function. Instances of this type
* should provide begin(), end(), find() and size() * should provide begin(), end(), find() and size()
* functions so that it is possible to iterate over * functions so that it is possible to iterate over
* the members of the object. * the members of the object.
* @tparam ValueType Name of the type that provides a consistent * @tparam ValueType Name of the type that provides a consistent
* interface to a JSON value for a parser. For * interface to a JSON value for a parser. For
* example, this type should provide the getDouble() * example, this type should provide the getDouble()
* and isDouble() functions. But it does not need to * and isDouble() functions. But it does not need to
* know how to cast values from one type to another - * know how to cast values from one type to another -
* that functionality is provided by this template * that functionality is provided by this template
* class. * class.
*/ */
@@ -101,7 +101,7 @@ protected:
if (itr == end) { if (itr == end) {
return false; return false;
} }
return AdapterType(*itr++).equalTo(adapter, strict); return AdapterType(*itr++).equalTo(adapter, strict);
} }
@@ -112,7 +112,7 @@ protected:
/// Iterator for one-past the last element of the array /// Iterator for one-past the last element of the array
typename ArrayType::const_iterator end; typename ArrayType::const_iterator end;
/// Flag to use strict type comparison /// Flag to use strict type comparison
const bool strict; const bool strict;
}; };
@@ -130,7 +130,7 @@ protected:
* value provided to the () operator. * value provided to the () operator.
* *
* This functor is designed to be passed to the applyToObject() function * This functor is designed to be passed to the applyToObject() function
* of an Adapter object. * of an Adapter object.
*/ */
class ObjectComparisonFunctor class ObjectComparisonFunctor
{ {
@@ -146,7 +146,7 @@ protected:
const ObjectType &object, bool strict) const ObjectType &object, bool strict)
: object(object), : object(object),
strict(strict) { } strict(strict) { }
/** /**
* @brief Find a key in the object and compare its value. * @brief Find a key in the object and compare its value.
* *
@@ -164,12 +164,12 @@ protected:
return (*itr).second.equalTo(value, strict); return (*itr).second.equalTo(value, strict);
} }
private: private:
/// Object to be used as a comparison baseline /// Object to be used as a comparison baseline
const ObjectType &object; const ObjectType &object;
/// Flag to use strict type-checking /// Flag to use strict type-checking
bool strict; bool strict;
}; };
@@ -202,15 +202,15 @@ public:
*/ */
BasicAdapter(const ValueType &value) BasicAdapter(const ValueType &value)
: value(value) { } : value(value) { }
virtual bool applyToArray(ArrayValueCallback fn) const virtual bool applyToArray(ArrayValueCallback fn) const
{ {
if (!maybeArray()) { if (!maybeArray()) {
return false; return false;
} }
// Due to the fact that the only way a value can be 'maybe an array' is // Due to the fact that the only way a value can be 'maybe an array' is
// if it is an empty string or empty object, we only need to go to // if it is an empty string or empty object, we only need to go to
// effort of constructing an ArrayType instance if the value is // effort of constructing an ArrayType instance if the value is
// definitely an array. // definitely an array.
if (value.isArray()) { if (value.isArray()) {
@@ -230,7 +230,7 @@ public:
if (!maybeObject()) { if (!maybeObject()) {
return false; return false;
} }
if (value.isObject()) { if (value.isObject()) {
const boost::optional<Object> object = value.getObjectOptional(); const boost::optional<Object> object = value.getObjectOptional();
BOOST_FOREACH( const ObjectMemberType member, *object ) { BOOST_FOREACH( const ObjectMemberType member, *object ) {
@@ -239,9 +239,9 @@ public:
} }
} }
} }
return true; return true;
} }
/** /**
* @brief Return an ArrayType instance containing an array representation * @brief Return an ArrayType instance containing an array representation
@@ -273,7 +273,7 @@ public:
return ArrayType(); return ArrayType();
} }
} }
throw std::runtime_error("JSON value cannot be cast to an array."); throw std::runtime_error("JSON value cannot be cast to an array.");
} }
@@ -283,7 +283,7 @@ public:
if (asBool(result)) { if (asBool(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value cannot be cast to a boolean."); throw std::runtime_error("JSON value cannot be cast to a boolean.");
} }
@@ -303,20 +303,20 @@ public:
} }
} }
} }
return false; return false;
} }
virtual double asDouble() const virtual double asDouble() const
{ {
double result; double result;
if (asDouble(result)) { if (asDouble(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value cannot be cast to a double."); throw std::runtime_error("JSON value cannot be cast to a double.");
} }
virtual bool asDouble(double &result) const virtual bool asDouble(double &result) const
{ {
if (value.isDouble()) { if (value.isDouble()) {
@@ -339,20 +339,20 @@ public:
} }
} }
} }
return false; return false;
} }
virtual int64_t asInteger() const virtual int64_t asInteger() const
{ {
int64_t result; int64_t result;
if (asInteger(result)) { if (asInteger(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value cannot be cast as an integer."); throw std::runtime_error("JSON value cannot be cast as an integer.");
} }
virtual bool asInteger(int64_t &result) const virtual bool asInteger(int64_t &result) const
{ {
if (value.isInteger()) { if (value.isInteger()) {
@@ -369,10 +369,10 @@ public:
} }
} }
} }
return false; return false;
} }
/** /**
* @brief Return an ObjectType instance containing an array representation * @brief Return an ObjectType instance containing an array representation
* of the value held by this Adapter. * of the value held by this Adapter.
@@ -400,20 +400,20 @@ public:
return ObjectType(); return ObjectType();
} }
} }
throw std::runtime_error("JSON value cannot be cast to an object."); throw std::runtime_error("JSON value cannot be cast to an object.");
} }
virtual std::string asString() const virtual std::string asString() const
{ {
std::string result; std::string result;
if (asString(result)) { if (asString(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value cannot be cast to a string."); throw std::runtime_error("JSON value cannot be cast to a string.");
} }
virtual bool asString(std::string &result) const virtual bool asString(std::string &result) const
{ {
if (value.isString()) { if (value.isString()) {
@@ -456,10 +456,10 @@ public:
} catch (boost::bad_lexical_cast &) { } } catch (boost::bad_lexical_cast &) { }
} }
} }
return false; return false;
} }
virtual bool equalTo(const Adapter &other, bool strict) const virtual bool equalTo(const Adapter &other, bool strict) const
{ {
if (isNull() || (!strict && maybeNull())) { if (isNull() || (!strict && maybeNull())) {
@@ -470,10 +470,10 @@ public:
} else if (isNumber() && strict) { } else if (isNumber() && strict) {
return other.isNumber() && other.getNumber() == getNumber(); return other.isNumber() && other.getNumber() == getNumber();
} else if (!strict && maybeDouble()) { } else if (!strict && maybeDouble()) {
return (other.maybeDouble() && return (other.maybeDouble() &&
other.asDouble() == asDouble()); other.asDouble() == asDouble());
} else if (!strict && maybeInteger()) { } else if (!strict && maybeInteger()) {
return (other.maybeInteger() && return (other.maybeInteger() &&
other.asInteger() == asInteger()); other.asInteger() == asInteger());
} else if (isString() || (!strict && maybeString())) { } else if (isString() || (!strict && maybeString())) {
return (other.isString() || (!strict && other.maybeString())) && return (other.isString() || (!strict && other.maybeString())) &&
@@ -499,10 +499,10 @@ public:
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* @brief Return an ArrayType instance representing the array contained * @brief Return an ArrayType instance representing the array contained
* by this Adapter instance. * by this Adapter instance.
@@ -523,20 +523,20 @@ public:
if (arrayValue) { if (arrayValue) {
return *arrayValue; return *arrayValue;
} }
throw std::runtime_error("JSON value is not an array."); throw std::runtime_error("JSON value is not an array.");
} }
virtual size_t getArraySize() const virtual size_t getArraySize() const
{ {
size_t result; size_t result;
if (value.getArraySize(result)) { if (value.getArraySize(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not an array."); throw std::runtime_error("JSON value is not an array.");
} }
virtual bool getArraySize(size_t &result) const virtual bool getArraySize(size_t &result) const
{ {
return value.getArraySize(result); return value.getArraySize(result);
@@ -548,7 +548,7 @@ public:
if (getBool(result)) { if (getBool(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not a boolean."); throw std::runtime_error("JSON value is not a boolean.");
} }
@@ -563,22 +563,22 @@ public:
if (getDouble(result)) { if (getDouble(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not a double."); throw std::runtime_error("JSON value is not a double.");
} }
virtual bool getDouble(double &result) const virtual bool getDouble(double &result) const
{ {
return value.getDouble(result); return value.getDouble(result);
} }
virtual int64_t getInteger() const virtual int64_t getInteger() const
{ {
int64_t result; int64_t result;
if (getInteger(result)) { if (getInteger(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not an integer."); throw std::runtime_error("JSON value is not an integer.");
} }
@@ -586,17 +586,17 @@ public:
{ {
return value.getInteger(result); return value.getInteger(result);
} }
virtual double getNumber() const virtual double getNumber() const
{ {
double result; double result;
if (getNumber(result)) { if (getNumber(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not a number."); throw std::runtime_error("JSON value is not a number.");
} }
virtual bool getNumber(double &result) const virtual bool getNumber(double &result) const
{ {
if (isDouble()) { if (isDouble()) {
@@ -608,10 +608,10 @@ public:
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* @brief Return an ObjectType instance representing the object contained * @brief Return an ObjectType instance representing the object contained
* by this Adapter instance. * by this Adapter instance.
@@ -632,32 +632,32 @@ public:
if (objectValue) { if (objectValue) {
return *objectValue; return *objectValue;
} }
throw std::runtime_error("JSON value is not an object."); throw std::runtime_error("JSON value is not an object.");
} }
virtual size_t getObjectSize() const virtual size_t getObjectSize() const
{ {
size_t result; size_t result;
if (getObjectSize(result)) { if (getObjectSize(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not an object."); throw std::runtime_error("JSON value is not an object.");
} }
virtual bool getObjectSize(size_t &result) const virtual bool getObjectSize(size_t &result) const
{ {
return value.getObjectSize(result); return value.getObjectSize(result);
} }
virtual std::string getString() const virtual std::string getString() const
{ {
std::string result; std::string result;
if (getString(result)) { if (getString(result)) {
return result; return result;
} }
throw std::runtime_error("JSON value is not a string."); throw std::runtime_error("JSON value is not a string.");
} }
@@ -665,52 +665,52 @@ public:
{ {
return value.getString(result); return value.getString(result);
} }
virtual FrozenValue * freeze() const virtual FrozenValue * freeze() const
{ {
return value.freeze(); return value.freeze();
} }
virtual bool hasStrictTypes() const virtual bool hasStrictTypes() const
{ {
return ValueType::hasStrictTypes(); return ValueType::hasStrictTypes();
} }
virtual bool isArray() const virtual bool isArray() const
{ {
return value.isArray(); return value.isArray();
} }
virtual bool isBool() const virtual bool isBool() const
{ {
return value.isBool(); return value.isBool();
} }
virtual bool isDouble() const virtual bool isDouble() const
{ {
return value.isDouble(); return value.isDouble();
} }
virtual bool isInteger() const virtual bool isInteger() const
{ {
return value.isInteger(); return value.isInteger();
} }
virtual bool isNull() const virtual bool isNull() const
{ {
return value.isNull(); return value.isNull();
} }
virtual bool isNumber() const virtual bool isNumber() const
{ {
return value.isInteger() || value.isDouble(); return value.isInteger() || value.isDouble();
} }
virtual bool isObject() const virtual bool isObject() const
{ {
return value.isObject(); return value.isObject();
} }
virtual bool isString() const virtual bool isString() const
{ {
return value.isString(); return value.isString();
@@ -726,7 +726,7 @@ public:
return true; return true;
} }
} }
return false; return false;
} }
@@ -742,7 +742,7 @@ public:
} }
} }
} }
return false; return false;
} }
@@ -798,8 +798,8 @@ public:
} }
} }
} }
return false; return false;
} }
virtual bool maybeObject() const virtual bool maybeObject() const
@@ -812,10 +812,10 @@ public:
return true; return true;
} }
} }
return true; return true;
} }
virtual bool maybeString() const virtual bool maybeString() const
{ {
if (value.isString() || value.isBool() || value.isInteger() || if (value.isString() || value.isBool() || value.isInteger() ||
@@ -835,11 +835,11 @@ public:
return false; return false;
} }
private: private:
const ValueType value; const ValueType value;
}; };
} // namespace adapters } // namespace adapters

View File

@@ -9,7 +9,7 @@ namespace adapters {
/** /**
* @brief An interface that provides minimal access to a stored JSON value. * @brief An interface that provides minimal access to a stored JSON value.
* *
* The main reason that this interface exists is to support the 'enum' * The main reason that this interface exists is to support the 'enum'
* constraint. Each Adapter type is expected to provide an implementation of * constraint. Each Adapter type is expected to provide an implementation of
* this interface. That class should be able to maintain its own copy of a * this interface. That class should be able to maintain its own copy of a
* JSON value, independent of the original document. * JSON value, independent of the original document.
@@ -35,7 +35,7 @@ public:
* object containing the value. * object containing the value.
*/ */
virtual FrozenValue *clone() const = 0; virtual FrozenValue *clone() const = 0;
/** /**
* @brief Return true if the stored value is equal to the value contained * @brief Return true if the stored value is equal to the value contained
* by an Adapter instance. * by an Adapter instance.

View File

@@ -15,7 +15,7 @@
* - JsonCppObjectMemberIterator * - JsonCppObjectMemberIterator
* - JsonCppValue * - JsonCppValue
* *
* Due to the dependencies that exist between these classes, the ordering of * Due to the dependencies that exist between these classes, the ordering of
* class declarations and definitions may be a bit confusing. The best place to * class declarations and definitions may be a bit confusing. The best place to
* start is JsonCppAdapter. This class definition is actually very small, * start is JsonCppAdapter. This class definition is actually very small,
* since most of the functionality is inherited from the BasicAdapter class. * since most of the functionality is inherited from the BasicAdapter class.
@@ -50,11 +50,11 @@ typedef std::pair<std::string, JsonCppAdapter> JsonCppObjectMember;
* @brief Light weight wrapper for a JsonCpp array value. * @brief Light weight wrapper for a JsonCpp array value.
* *
* This class is light weight wrapper for a JsonCpp array. It provides a * This class is light weight wrapper for a JsonCpp array. It provides a
* minimum set of container functions and typedefs that allow it to be used as * minimum set of container functions and typedefs that allow it to be used as
* an iterable container. * an iterable container.
* *
* An instance of this class contains a single reference to the underlying * An instance of this class contains a single reference to the underlying
* JsonCpp value, assumed to be an array, so there is very little overhead * JsonCpp value, assumed to be an array, so there is very little overhead
* associated with copy construction and passing by value. * associated with copy construction and passing by value.
*/ */
class JsonCppArray class JsonCppArray
@@ -68,7 +68,7 @@ public:
JsonCppArray() JsonCppArray()
: value(emptyArray()) { } : value(emptyArray()) { }
/** /**
* @brief Construct a JsonCppArray referencing a specific JsonCpp value. * @brief Construct a JsonCppArray referencing a specific JsonCpp value.
* *
* @param value reference to a JsonCpp value * @param value reference to a JsonCpp value
@@ -83,7 +83,7 @@ public:
throw std::runtime_error("Value is not an array."); throw std::runtime_error("Value is not an array.");
} }
} }
/** /**
* @brief Return an iterator for the first element of the array. * @brief Return an iterator for the first element of the array.
* *
@@ -91,7 +91,7 @@ public:
* returned by the underlying JsonCpp implementation. * returned by the underlying JsonCpp implementation.
*/ */
JsonCppArrayValueIterator begin() const; JsonCppArrayValueIterator begin() const;
/** /**
* @brief Return an iterator for one-past the last element of the array. * @brief Return an iterator for one-past the last element of the array.
* *
@@ -99,13 +99,13 @@ public:
* returned by the underlying JsonCpp implementation. * returned by the underlying JsonCpp implementation.
*/ */
JsonCppArrayValueIterator end() const; JsonCppArrayValueIterator end() const;
/// Return the number of elements in the array. /// Return the number of elements in the array.
size_t size() const size_t size() const
{ {
return value.size(); return value.size();
} }
private: private:
/** /**
@@ -120,7 +120,7 @@ private:
} }
/// Reference to the contained array /// Reference to the contained array
const Json::Value &value; const Json::Value &value;
}; };
@@ -128,7 +128,7 @@ private:
* @brief Light weight wrapper for a JsonCpp object. * @brief Light weight wrapper for a JsonCpp object.
* *
* This class is light weight wrapper for a JsonCpp object. It provides a * This class is light weight wrapper for a JsonCpp object. It provides a
* minimum set of container functions and typedefs that allow it to be used as * minimum set of container functions and typedefs that allow it to be used as
* an iterable container. * an iterable container.
* *
* An instance of this class contains a single reference to the underlying * An instance of this class contains a single reference to the underlying
@@ -161,24 +161,24 @@ public:
throw std::runtime_error("Value is not an object."); throw std::runtime_error("Value is not an object.");
} }
} }
/** /**
* @brief Return an iterator for this first object member * @brief Return an iterator for this first object member
* *
* The iterator return by this function is effectively a wrapper around * The iterator return by this function is effectively a wrapper around
* the iterator value returned by the underlying JsonCpp implementation. * the iterator value returned by the underlying JsonCpp implementation.
*/ */
JsonCppObjectMemberIterator begin() const; JsonCppObjectMemberIterator begin() const;
/** /**
* @brief Return an iterator for an invalid object member that indicates * @brief Return an iterator for an invalid object member that indicates
* the end of the collection. * the end of the collection.
* *
* The iterator return by this function is effectively a wrapper around * The iterator return by this function is effectively a wrapper around
* the iterator value returned by the underlying JsonCpp implementation. * the iterator value returned by the underlying JsonCpp implementation.
*/ */
JsonCppObjectMemberIterator end() const; JsonCppObjectMemberIterator end() const;
/** /**
* @brief Return an iterator for a member/property with the given name * @brief Return an iterator for a member/property with the given name
* *
@@ -187,13 +187,13 @@ public:
* @returns a valid iterator if found, or an invalid iterator if not found * @returns a valid iterator if found, or an invalid iterator if not found
*/ */
JsonCppObjectMemberIterator find(const std::string &propertyName) const; JsonCppObjectMemberIterator find(const std::string &propertyName) const;
/// Return the number of members in the object /// Return the number of members in the object
size_t size() const size_t size() const
{ {
return value.size(); return value.size();
} }
private: private:
/// Return a reference to an empty JsonCpp object /// Return a reference to an empty JsonCpp object
@@ -246,9 +246,9 @@ private:
* *
* This class is passed as an argument to the BasicAdapter template class, * This class is passed as an argument to the BasicAdapter template class,
* and is used to provide access to a JsonCpp value. This class is responsible * and is used to provide access to a JsonCpp value. This class is responsible
* for the mechanics of actually reading a JsonCpp value, whereas the * for the mechanics of actually reading a JsonCpp value, whereas the
* BasicAdapter class is responsible for the semantics of type comparisons * BasicAdapter class is responsible for the semantics of type comparisons
* and conversions. * and conversions.
* *
* The functions that need to be provided by this class are defined implicitly * The functions that need to be provided by this class are defined implicitly
* by the implementation of the BasicAdapter template class. * by the implementation of the BasicAdapter template class.
@@ -266,19 +266,19 @@ public:
/// Construct a wrapper for a specific JsonCpp value /// Construct a wrapper for a specific JsonCpp value
JsonCppValue(const Json::Value &value) JsonCppValue(const Json::Value &value)
: value(value) { } : value(value) { }
/** /**
* @brief Create a new JsonCppFrozenValue instance that contains the * @brief Create a new JsonCppFrozenValue instance that contains the
* value referenced by this JsonCppValue instance. * value referenced by this JsonCppValue instance.
* *
* @returns pointer to a new JsonCppFrozenValue instance, belonging to the * @returns pointer to a new JsonCppFrozenValue instance, belonging to the
* caller. * caller.
*/ */
FrozenValue * freeze() const FrozenValue * freeze() const
{ {
return new JsonCppFrozenValue(value); return new JsonCppFrozenValue(value);
} }
/** /**
* @brief Optionally return a JsonCppArray instance. * @brief Optionally return a JsonCppArray instance.
* *
@@ -293,10 +293,10 @@ public:
if (value.isArray()) { if (value.isArray()) {
return boost::make_optional(JsonCppArray(value)); return boost::make_optional(JsonCppArray(value));
} }
return boost::none; return boost::none;
} }
/** /**
* @brief Retrieve the number of elements in the array * @brief Retrieve the number of elements in the array
* *
@@ -314,40 +314,40 @@ public:
result = value.size(); result = value.size();
return true; return true;
} }
return false; return false;
} }
bool getBool(bool &result) const bool getBool(bool &result) const
{ {
if (value.isBool()) { if (value.isBool()) {
result = value.asBool(); result = value.asBool();
return true; return true;
} }
return false; return false;
} }
bool getDouble(double &result) const bool getDouble(double &result) const
{ {
if (value.isDouble()) { if (value.isDouble()) {
result = value.asDouble(); result = value.asDouble();
return true; return true;
} }
return false; return false;
} }
bool getInteger(int64_t &result) const bool getInteger(int64_t &result) const
{ {
if (value.isIntegral()) { if (value.isIntegral()) {
result = static_cast<int64_t>(value.asInt()); result = static_cast<int64_t>(value.asInt());
return true; return true;
} }
return false; return false;
} }
/** /**
* @brief Optionally return a JsonCppObject instance. * @brief Optionally return a JsonCppObject instance.
* *
@@ -362,7 +362,7 @@ public:
if (value.isObject()) { if (value.isObject()) {
return boost::make_optional(JsonCppObject(value)); return boost::make_optional(JsonCppObject(value));
} }
return boost::none; return boost::none;
} }
@@ -383,7 +383,7 @@ public:
result = value.size(); result = value.size();
return true; return true;
} }
return false; return false;
} }
@@ -393,50 +393,50 @@ public:
result = value.asString(); result = value.asString();
return true; return true;
} }
return false; return false;
} }
static bool hasStrictTypes() static bool hasStrictTypes()
{ {
return true; return true;
} }
bool isArray() const bool isArray() const
{ {
return value.isArray() && !value.isNull(); return value.isArray() && !value.isNull();
} }
bool isBool() const bool isBool() const
{ {
return value.isBool(); return value.isBool();
} }
bool isDouble() const bool isDouble() const
{ {
return value.isDouble(); return value.isDouble();
} }
bool isInteger() const bool isInteger() const
{ {
return value.isIntegral() && !value.isBool(); return value.isIntegral() && !value.isBool();
} }
bool isNull() const bool isNull() const
{ {
return value.isNull(); return value.isNull();
} }
bool isNumber() const bool isNumber() const
{ {
return value.isNumeric() && !value.isBool(); return value.isNumeric() && !value.isBool();
} }
bool isObject() const bool isObject() const
{ {
return value.isObject() && !value.isNull(); return value.isObject() && !value.isNull();
} }
bool isString() const bool isString() const
{ {
return value.isString(); return value.isString();
@@ -488,7 +488,7 @@ public:
* This class provides a JSON array iterator that dereferences as an instance of * This class provides a JSON array iterator that dereferences as an instance of
* JsonCppAdapter representing a value stored in the array. It has been * JsonCppAdapter representing a value stored in the array. It has been
* implemented using the boost iterator_facade template. * implemented using the boost iterator_facade template.
* *
* @see JsonCppArray * @see JsonCppArray
*/ */
class JsonCppArrayValueIterator: class JsonCppArrayValueIterator:
@@ -509,12 +509,12 @@ public:
JsonCppArrayValueIterator(const Json::Value::const_iterator &itr) JsonCppArrayValueIterator(const Json::Value::const_iterator &itr)
: itr(itr) { } : itr(itr) { }
/// Returns a JsonCppAdapter that contains the value of the current element. /// Returns a JsonCppAdapter that contains the value of the current element.
JsonCppAdapter dereference() const JsonCppAdapter dereference() const
{ {
return JsonCppAdapter(*itr); return JsonCppAdapter(*itr);
} }
/** /**
* @brief Compare this iterator against another iterator. * @brief Compare this iterator against another iterator.
* *
@@ -530,17 +530,17 @@ public:
{ {
return itr == rhs.itr; return itr == rhs.itr;
} }
void increment() void increment()
{ {
itr++; itr++;
} }
void decrement() void decrement()
{ {
itr--; itr--;
} }
void advance(std::ptrdiff_t n) void advance(std::ptrdiff_t n)
{ {
if (n > 0) { if (n > 0) {
@@ -565,7 +565,7 @@ private:
* This class provides a JSON object iterator that dereferences as an instance * This class provides a JSON object iterator that dereferences as an instance
* of JsonCppObjectMember representing one of the members of the object. It has * of JsonCppObjectMember representing one of the members of the object. It has
* been implemented using the boost iterator_facade template. * been implemented using the boost iterator_facade template.
* *
* @see JsonCppObject * @see JsonCppObject
* @see JsonCppObjectMember * @see JsonCppObjectMember
*/ */
@@ -594,7 +594,7 @@ public:
{ {
return JsonCppObjectMember(itr.key().asString(), *itr); return JsonCppObjectMember(itr.key().asString(), *itr);
} }
/** /**
* @brief Compare this iterator with another iterator. * @brief Compare this iterator with another iterator.
* *
@@ -610,12 +610,12 @@ public:
{ {
return itr == rhs.itr; return itr == rhs.itr;
} }
void increment() void increment()
{ {
itr++; itr++;
} }
void decrement() void decrement()
{ {
itr--; itr--;
@@ -632,7 +632,7 @@ template<>
struct AdapterTraits<valijson::adapters::JsonCppAdapter> struct AdapterTraits<valijson::adapters::JsonCppAdapter>
{ {
typedef Json::Value DocumentType; typedef Json::Value DocumentType;
static std::string adapterName() static std::string adapterName()
{ {
return "JsonCppAdapter"; return "JsonCppAdapter";

View File

@@ -15,7 +15,7 @@
* - PropertyTreeObjectMemberIterator * - PropertyTreeObjectMemberIterator
* - PropertyTreeValue * - PropertyTreeValue
* *
* Due to the dependencies that exist between these classes, the ordering of * Due to the dependencies that exist between these classes, the ordering of
* class declarations and definitions may be a bit confusing. The best place to * class declarations and definitions may be a bit confusing. The best place to
* start is PropertyTreeAdapter. This class definition is actually very small, * start is PropertyTreeAdapter. This class definition is actually very small,
* since most of the functionality is inherited from the BasicAdapter class. * since most of the functionality is inherited from the BasicAdapter class.
@@ -49,7 +49,7 @@ typedef std::pair<std::string, PropertyTreeAdapter> PropertyTreeObjectMember;
* array-like data. * array-like data.
* *
* This class is light weight wrapper for a Boost property tree. It provides a * This class is light weight wrapper for a Boost property tree. It provides a
* minimum set of container functions and typedefs that allow it to be used as * minimum set of container functions and typedefs that allow it to be used as
* an iterable container. * an iterable container.
* *
* An instance of this class contains a single reference to a Boost property * An instance of this class contains a single reference to a Boost property
@@ -76,22 +76,22 @@ public:
* *
* It is assumed that this value contains array-like data, but this is not * It is assumed that this value contains array-like data, but this is not
* checked due to runtime cost. * checked due to runtime cost.
*/ */
PropertyTreeArray(const boost::property_tree::ptree &array) PropertyTreeArray(const boost::property_tree::ptree &array)
: array(array) { } : array(array) { }
/// Return an iterator for the first element in the array. /// Return an iterator for the first element in the array.
PropertyTreeArrayValueIterator begin() const; PropertyTreeArrayValueIterator begin() const;
/// Return an iterator for one-past the last element of the array. /// Return an iterator for one-past the last element of the array.
PropertyTreeArrayValueIterator end() const; PropertyTreeArrayValueIterator end() const;
/// Return the number of elements in the array /// Return the number of elements in the array
size_t size() const size_t size() const
{ {
return array.size(); return array.size();
} }
private: private:
/** /**
@@ -115,11 +115,11 @@ private:
* object-like data. * object-like data.
* *
* This class is light weight wrapper for a Boost property tree. It provides a * This class is light weight wrapper for a Boost property tree. It provides a
* minimum set of container functions and typedefs that allow it to be used as * minimum set of container functions and typedefs that allow it to be used as
* an iterable container. * an iterable container.
* *
* An instance of this class contains a single reference to the underlying * An instance of this class contains a single reference to the underlying
* property tree value, assumed to be object-like, so there is very little * property tree value, assumed to be object-like, so there is very little
* overhead associated with copy construction and passing by value. * overhead associated with copy construction and passing by value.
*/ */
class PropertyTreeObject class PropertyTreeObject
@@ -144,22 +144,22 @@ public:
*/ */
PropertyTreeObject(const boost::property_tree::ptree &object) PropertyTreeObject(const boost::property_tree::ptree &object)
: object(object) { } : object(object) { }
/** /**
* @brief Return an iterator for this first object member * @brief Return an iterator for this first object member
* *
* The iterator return by this function is effectively a wrapper around * The iterator return by this function is effectively a wrapper around
* the iterator value returned by the underlying property tree * the iterator value returned by the underlying property tree
* implementation. * implementation.
*/ */
PropertyTreeObjectMemberIterator begin() const; PropertyTreeObjectMemberIterator begin() const;
/** /**
* @brief Return an iterator for an invalid object member that indicates * @brief Return an iterator for an invalid object member that indicates
* the end of the collection. * the end of the collection.
* *
* The iterator return by this function is effectively a wrapper around * The iterator return by this function is effectively a wrapper around
* the pointer value returned by the underlying property tree * the pointer value returned by the underlying property tree
* implementation. * implementation.
*/ */
PropertyTreeObjectMemberIterator end() const; PropertyTreeObjectMemberIterator end() const;
@@ -172,15 +172,15 @@ public:
* returned will be the same as the iterator returned by the end() function. * returned will be the same as the iterator returned by the end() function.
* *
* @param property property name to search for * @param property property name to search for
*/ */
PropertyTreeObjectMemberIterator find(const std::string &property) const; PropertyTreeObjectMemberIterator find(const std::string &property) const;
/// Returns the number of members belonging to this object. /// Returns the number of members belonging to this object.
size_t size() const size_t size() const
{ {
return object.size(); return object.size();
} }
private: private:
/** /**
@@ -196,13 +196,13 @@ private:
/// Reference to the contained object /// Reference to the contained object
const boost::property_tree::ptree &object; const boost::property_tree::ptree &object;
}; };
/** /**
* @brief Stores an independent copy of a Boost property tree. * @brief Stores an independent copy of a Boost property tree.
* *
* This class allows a property tree value to be stored independent of its * This class allows a property tree value to be stored independent of its
* original 'document'. Boost property trees make this easy to do, as they do * original 'document'. Boost property trees make this easy to do, as they do
* not perform any custom memory management. * not perform any custom memory management.
* *
@@ -245,10 +245,10 @@ private:
* @brief Light weight wrapper for a Boost property tree. * @brief Light weight wrapper for a Boost property tree.
* *
* This class is passed as an argument to the BasicAdapter template class, * This class is passed as an argument to the BasicAdapter template class,
* and is used to provide access to a Boost property tree value. This class * and is used to provide access to a Boost property tree value. This class
* is responsible for the mechanics of actually reading a property tree, whereas * is responsible for the mechanics of actually reading a property tree, whereas
* BasicAdapter class is responsible for the semantics of type comparisons * BasicAdapter class is responsible for the semantics of type comparisons
* and conversions. * and conversions.
* *
* The functions that need to be provided by this class are defined implicitly * The functions that need to be provided by this class are defined implicitly
* by the implementation of the BasicAdapter template class. * by the implementation of the BasicAdapter template class.
@@ -290,7 +290,7 @@ public:
break; break;
} }
} }
if (isArray) { if (isArray) {
array = tree; array = tree;
} else { } else {
@@ -323,8 +323,8 @@ public:
/** /**
* @brief Return an instance of PropertyTreeArrayAdapter. * @brief Return an instance of PropertyTreeArrayAdapter.
* *
* If the referenced property tree value is an array, this function will * If the referenced property tree value is an array, this function will
* return a boost::optional containing a PropertyTreeArray instance * return a boost::optional containing a PropertyTreeArray instance
* referencing the array. * referencing the array.
* *
* Otherwise it will return boost::none. * Otherwise it will return boost::none.
@@ -334,46 +334,46 @@ public:
if (array) { if (array) {
return boost::make_optional(PropertyTreeArray(*array)); return boost::make_optional(PropertyTreeArray(*array));
} }
return boost::none; return boost::none;
} }
/** /**
* @brief Retrieve the number of elements in the array * @brief Retrieve the number of elements in the array
* *
* If the referenced property tree value is an array, this function will * If the referenced property tree value is an array, this function will
* retrieve the number of elements in the array and store it in the output * retrieve the number of elements in the array and store it in the output
* variable provided. * variable provided.
* *
* @param result reference to size_t to set with result * @param result reference to size_t to set with result
* *
* @returns true if the number of elements was retrieved, false otherwise. * @returns true if the number of elements was retrieved, false otherwise.
*/ */
bool getArraySize(size_t &result) const bool getArraySize(size_t &result) const
{ {
if (array) { if (array) {
result = array->size(); result = array->size();
return true; return true;
} }
return false; return false;
} }
bool getBool(bool &result) const bool getBool(bool &result) const
{ {
return false; return false;
} }
bool getDouble(double &result) const bool getDouble(double &result) const
{ {
return false; return false;
} }
bool getInteger(int64_t &result) const bool getInteger(int64_t &result) const
{ {
return false; return false;
} }
/** /**
* @brief Optionally return a PropertyTreeObject instance. * @brief Optionally return a PropertyTreeObject instance.
* *
@@ -382,16 +382,16 @@ public:
* object. * object.
* *
* Otherwise it will return boost::none. * Otherwise it will return boost::none.
*/ */
boost::optional<PropertyTreeObject> getObjectOptional() const boost::optional<PropertyTreeObject> getObjectOptional() const
{ {
if (object) { if (object) {
return boost::make_optional(PropertyTreeObject(*object)); return boost::make_optional(PropertyTreeObject(*object));
} }
return boost::none; return boost::none;
} }
/** /**
* @brief Retrieve the number of members in the object * @brief Retrieve the number of members in the object
* *
@@ -409,7 +409,7 @@ public:
result = object->size(); result = object->size();
return true; return true;
} }
return false; return false;
} }
@@ -419,55 +419,55 @@ public:
result = *value; result = *value;
return true; return true;
} }
return false; return false;
} }
static bool hasStrictTypes() static bool hasStrictTypes()
{ {
return false; return false;
} }
bool isArray() const bool isArray() const
{ {
return array != boost::none; return array != boost::none;
} }
bool isBool() const bool isBool() const
{ {
return false; return false;
} }
bool isDouble() const bool isDouble() const
{ {
return false; return false;
} }
bool isInteger() const bool isInteger() const
{ {
return false; return false;
} }
bool isNull() const bool isNull() const
{ {
return false; return false;
} }
bool isNumber() const bool isNumber() const
{ {
return false; return false;
} }
bool isObject() const bool isObject() const
{ {
return object != boost::none; return object != boost::none;
} }
bool isString() const bool isString() const
{ {
return value != boost::none; return value != boost::none;
} }
private: private:
static const boost::property_tree::ptree & emptyTree() static const boost::property_tree::ptree & emptyTree()
@@ -520,7 +520,7 @@ public:
* This class provides a JSON array iterator that dereferences as an instance of * This class provides a JSON array iterator that dereferences as an instance of
* PropertyTreeAdapter representing a value stored in the array. It has been * PropertyTreeAdapter representing a value stored in the array. It has been
* implemented using the boost iterator_facade template. * implemented using the boost iterator_facade template.
* *
* @see PropertyTreeArray * @see PropertyTreeArray
*/ */
class PropertyTreeArrayValueIterator: class PropertyTreeArrayValueIterator:
@@ -542,13 +542,13 @@ public:
const boost::property_tree::ptree::const_iterator &itr) const boost::property_tree::ptree::const_iterator &itr)
: itr(itr) { } : itr(itr) { }
/// Returns a PropertyTreeAdapter that contains the value of the current /// Returns a PropertyTreeAdapter that contains the value of the current
/// element. /// element.
PropertyTreeAdapter dereference() const PropertyTreeAdapter dereference() const
{ {
return PropertyTreeAdapter(itr->second); return PropertyTreeAdapter(itr->second);
} }
/** /**
* @brief Compare this iterator against another iterator. * @brief Compare this iterator against another iterator.
* *
@@ -559,22 +559,22 @@ public:
* @param rhs iterator to compare against * @param rhs iterator to compare against
* *
* @returns true if the iterators are equal, false otherwise. * @returns true if the iterators are equal, false otherwise.
*/ */
bool equal(const PropertyTreeArrayValueIterator &rhs) const bool equal(const PropertyTreeArrayValueIterator &rhs) const
{ {
return itr == rhs.itr; return itr == rhs.itr;
} }
void increment() void increment()
{ {
itr++; itr++;
} }
void decrement() void decrement()
{ {
itr--; itr--;
} }
void advance(std::ptrdiff_t n) void advance(std::ptrdiff_t n)
{ {
if (n > 0) { if (n > 0) {
@@ -599,7 +599,7 @@ private:
* This class provides a JSON object iterator that dereferences as an instance * This class provides a JSON object iterator that dereferences as an instance
* of PropertyTreeObjectMember representing one of the members of the object. * of PropertyTreeObjectMember representing one of the members of the object.
* It has been implemented using the boost iterator_facade template. * It has been implemented using the boost iterator_facade template.
* *
* @see PropertyTreeObject * @see PropertyTreeObject
* @see PropertyTreeObjectMember * @see PropertyTreeObjectMember
*/ */
@@ -622,14 +622,14 @@ public:
: itr(itr) { } : itr(itr) { }
/** /**
* @brief Returns a PropertyTreeObjectMember that contains the key and * @brief Returns a PropertyTreeObjectMember that contains the key and
* value belonging to the object member identified by the iterator. * value belonging to the object member identified by the iterator.
*/ */
PropertyTreeObjectMember dereference() const PropertyTreeObjectMember dereference() const
{ {
return PropertyTreeObjectMember(itr->first, itr->second); return PropertyTreeObjectMember(itr->first, itr->second);
} }
/** /**
* @brief Compare this iterator with another iterator. * @brief Compare this iterator with another iterator.
* *
@@ -640,17 +640,17 @@ public:
* @param rhs Iterator to compare with * @param rhs Iterator to compare with
* *
* @returns true if the underlying iterators are equal, false otherwise * @returns true if the underlying iterators are equal, false otherwise
*/ */
bool equal(const PropertyTreeObjectMemberIterator &rhs) const bool equal(const PropertyTreeObjectMemberIterator &rhs) const
{ {
return itr == rhs.itr; return itr == rhs.itr;
} }
void increment() void increment()
{ {
itr++; itr++;
} }
void decrement() void decrement()
{ {
itr--; itr--;
@@ -666,7 +666,7 @@ template<>
struct AdapterTraits<valijson::adapters::PropertyTreeAdapter> struct AdapterTraits<valijson::adapters::PropertyTreeAdapter>
{ {
typedef boost::property_tree::ptree DocumentType; typedef boost::property_tree::ptree DocumentType;
static std::string adapterName() static std::string adapterName()
{ {
return "PropertyTreeAdapter"; return "PropertyTreeAdapter";
@@ -703,7 +703,7 @@ inline PropertyTreeObjectMemberIterator PropertyTreeObject::find(
{ {
const boost::property_tree::ptree::const_assoc_iterator const boost::property_tree::ptree::const_assoc_iterator
itr = object.find(propertyName); itr = object.find(propertyName);
if (itr != object.not_found()) { if (itr != object.not_found()) {
return itr; return itr;
} }
@@ -715,4 +715,3 @@ inline PropertyTreeObjectMemberIterator PropertyTreeObject::find(
} // namespace valijson } // namespace valijson
#endif #endif

View File

@@ -15,7 +15,7 @@
* - RapidJsonObjectMemberIterator * - RapidJsonObjectMemberIterator
* - RapidJsonValue * - RapidJsonValue
* *
* Due to the dependencies that exist between these classes, the ordering of * Due to the dependencies that exist between these classes, the ordering of
* class declarations and definitions may be a bit confusing. The best place to * class declarations and definitions may be a bit confusing. The best place to
* start is RapidJsonAdapter. This class definition is actually very small, * start is RapidJsonAdapter. This class definition is actually very small,
* since most of the functionality is inherited from the BasicAdapter class. * since most of the functionality is inherited from the BasicAdapter class.
@@ -50,11 +50,11 @@ typedef std::pair<std::string, RapidJsonAdapter> RapidJsonObjectMember;
* @brief Light weight wrapper for a RapidJson array value. * @brief Light weight wrapper for a RapidJson array value.
* *
* This class is light weight wrapper for a RapidJson array. It provides a * This class is light weight wrapper for a RapidJson array. It provides a
* minimum set of container functions and typedefs that allow it to be used as * minimum set of container functions and typedefs that allow it to be used as
* an iterable container. * an iterable container.
* *
* An instance of this class contains a single reference to an underlying * An instance of this class contains a single reference to an underlying
* RapidJson value, assumed to be an array, so there is very little overhead * RapidJson value, assumed to be an array, so there is very little overhead
* associated with copy construction and passing by value. * associated with copy construction and passing by value.
*/ */
class RapidJsonArray class RapidJsonArray
@@ -63,11 +63,11 @@ public:
typedef RapidJsonArrayValueIterator const_iterator; typedef RapidJsonArrayValueIterator const_iterator;
typedef RapidJsonArrayValueIterator iterator; typedef RapidJsonArrayValueIterator iterator;
/// Construct a RapidJsonArray referencing an empty array singleton. /// Construct a RapidJsonArray referencing an empty array singleton.
RapidJsonArray() RapidJsonArray()
: value(emptyArray()) { } : value(emptyArray()) { }
/** /**
* @brief Construct a RapidJsonArray referencing a specific RapidJson * @brief Construct a RapidJsonArray referencing a specific RapidJson
* value. * value.
@@ -84,19 +84,19 @@ public:
throw std::runtime_error("Value is not an array."); throw std::runtime_error("Value is not an array.");
} }
} }
/// Return an iterator for the first element in the array. /// Return an iterator for the first element in the array.
RapidJsonArrayValueIterator begin() const; RapidJsonArrayValueIterator begin() const;
/// Return an iterator for one-past the last element of the array. /// Return an iterator for one-past the last element of the array.
RapidJsonArrayValueIterator end() const; RapidJsonArrayValueIterator end() const;
/// Return the number of elements in the array /// Return the number of elements in the array
size_t size() const size_t size() const
{ {
return value.Size(); return value.Size();
} }
private: private:
/** /**
@@ -118,11 +118,11 @@ private:
* @brief Light weight wrapper for a RapidJson object. * @brief Light weight wrapper for a RapidJson object.
* *
* This class is light weight wrapper for a RapidJson object. It provides a * This class is light weight wrapper for a RapidJson object. It provides a
* minimum set of container functions and typedefs that allow it to be used as * minimum set of container functions and typedefs that allow it to be used as
* an iterable container. * an iterable container.
* *
* An instance of this class contains a single reference to the underlying * An instance of this class contains a single reference to the underlying
* RapidJson value, assumed to be an object, so there is very little overhead * RapidJson value, assumed to be an object, so there is very little overhead
* associated with copy construction and passing by value. * associated with copy construction and passing by value.
*/ */
class RapidJsonObject class RapidJsonObject
@@ -152,7 +152,7 @@ public:
throw std::runtime_error("Value is not an object."); throw std::runtime_error("Value is not an object.");
} }
} }
/** /**
* @brief Return an iterator for this first object member * @brief Return an iterator for this first object member
* *
@@ -162,7 +162,7 @@ public:
RapidJsonObjectMemberIterator begin() const; RapidJsonObjectMemberIterator begin() const;
/** /**
* @brief Return an iterator for an invalid object member that indicates * @brief Return an iterator for an invalid object member that indicates
* the end of the collection. * the end of the collection.
* *
* The iterator return by this function is effectively a wrapper around * The iterator return by this function is effectively a wrapper around
@@ -180,13 +180,13 @@ public:
* @param property property name to search for * @param property property name to search for
*/ */
RapidJsonObjectMemberIterator find(const std::string &property) const; RapidJsonObjectMemberIterator find(const std::string &property) const;
/// Returns the number of members belonging to this object. /// Returns the number of members belonging to this object.
size_t size() const size_t size() const
{ {
return value.MemberEnd() - value.MemberBegin(); return value.MemberEnd() - value.MemberBegin();
} }
private: private:
/** /**
@@ -306,10 +306,10 @@ private:
return false; return false;
} }
/// Local memory allocator for RapidJson value /// Local memory allocator for RapidJson value
rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator> allocator; rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator> allocator;
/// Local RapidJson value /// Local RapidJson value
rapidjson::Value value; rapidjson::Value value;
}; };
@@ -319,7 +319,7 @@ private:
* *
* This class is passed as an argument to the BasicAdapter template class, * This class is passed as an argument to the BasicAdapter template class,
* and is used to provide access to a RapidJson value. This class is responsible * and is used to provide access to a RapidJson value. This class is responsible
* for the mechanics of actually reading a RapidJson value, whereas the * for the mechanics of actually reading a RapidJson value, whereas the
* BasicAdapter class is responsible for the semantics of type comparisons * BasicAdapter class is responsible for the semantics of type comparisons
* and conversions. * and conversions.
* *
@@ -339,14 +339,14 @@ public:
/// Construct a wrapper for a specific RapidJson value /// Construct a wrapper for a specific RapidJson value
RapidJsonValue(const rapidjson::Value &value) RapidJsonValue(const rapidjson::Value &value)
: value(value) { } : value(value) { }
/** /**
* @brief Create a new RapidJsonFrozenValue instance that contains the * @brief Create a new RapidJsonFrozenValue instance that contains the
* value referenced by this RapidJsonValue instance. * value referenced by this RapidJsonValue instance.
* *
* @returns pointer to a new RapidJsonFrozenValue instance, belonging to * @returns pointer to a new RapidJsonFrozenValue instance, belonging to
* the caller. * the caller.
*/ */
FrozenValue * freeze() const FrozenValue * freeze() const
{ {
return new RapidJsonFrozenValue(value); return new RapidJsonFrozenValue(value);
@@ -366,15 +366,15 @@ public:
if (value.IsArray()) { if (value.IsArray()) {
return boost::make_optional(RapidJsonArray(value)); return boost::make_optional(RapidJsonArray(value));
} }
return boost::none; return boost::none;
} }
/** /**
* @brief Retrieve the number of elements in the array * @brief Retrieve the number of elements in the array
* *
* If the referenced RapidJson value is an array, this function will * If the referenced RapidJson value is an array, this function will
* retrieve the number of elements in the array and store it in the output * retrieve the number of elements in the array and store it in the output
* variable provided. * variable provided.
* *
* @param result reference to size_t to set with result * @param result reference to size_t to set with result
@@ -387,30 +387,30 @@ public:
result = value.Size(); result = value.Size();
return true; return true;
} }
return false; return false;
} }
bool getBool(bool &result) const bool getBool(bool &result) const
{ {
if (value.IsBool()) { if (value.IsBool()) {
result = value.GetBool(); result = value.GetBool();
return true; return true;
} }
return false; return false;
} }
bool getDouble(double &result) const bool getDouble(double &result) const
{ {
if (value.IsDouble()) { if (value.IsDouble()) {
result = value.GetDouble(); result = value.GetDouble();
return true; return true;
} }
return false; return false;
} }
bool getInteger(int64_t &result) const bool getInteger(int64_t &result) const
{ {
if (value.IsInt()) { if (value.IsInt()) {
@@ -426,10 +426,10 @@ public:
result = static_cast<int64_t>(value.GetUint64()); result = static_cast<int64_t>(value.GetUint64());
return true; return true;
} }
return false; return false;
} }
/** /**
* @brief Optionally return a RapidJsonObject instance. * @brief Optionally return a RapidJsonObject instance.
* *
@@ -438,13 +438,13 @@ public:
* object. * object.
* *
* Otherwise it will return boost::none. * Otherwise it will return boost::none.
*/ */
boost::optional<RapidJsonObject> getObjectOptional() const boost::optional<RapidJsonObject> getObjectOptional() const
{ {
if (value.IsObject()) { if (value.IsObject()) {
return boost::make_optional(RapidJsonObject(value)); return boost::make_optional(RapidJsonObject(value));
} }
return boost::none; return boost::none;
} }
@@ -465,7 +465,7 @@ public:
result = value.MemberEnd() - value.MemberBegin(); result = value.MemberEnd() - value.MemberBegin();
return true; return true;
} }
return false; return false;
} }
@@ -475,56 +475,56 @@ public:
result.assign(value.GetString(), value.GetStringLength()); result.assign(value.GetString(), value.GetStringLength());
return true; return true;
} }
return false; return false;
} }
static bool hasStrictTypes() static bool hasStrictTypes()
{ {
return true; return true;
} }
bool isArray() const bool isArray() const
{ {
return value.IsArray(); return value.IsArray();
} }
bool isBool() const bool isBool() const
{ {
return value.IsBool(); return value.IsBool();
} }
bool isDouble() const bool isDouble() const
{ {
return value.IsDouble(); return value.IsDouble();
} }
bool isInteger() const bool isInteger() const
{ {
return value.IsInt() || value.IsInt64() || value.IsUint() || return value.IsInt() || value.IsInt64() || value.IsUint() ||
value.IsUint64(); value.IsUint64();
} }
bool isNull() const bool isNull() const
{ {
return value.IsNull(); return value.IsNull();
} }
bool isNumber() const bool isNumber() const
{ {
return value.IsNumber(); return value.IsNumber();
} }
bool isObject() const bool isObject() const
{ {
return value.IsObject(); return value.IsObject();
} }
bool isString() const bool isString() const
{ {
return value.IsString(); return value.IsString();
} }
private: private:
/// Return a reference to an empty object singleton /// Return a reference to an empty object singleton
@@ -571,7 +571,7 @@ public:
* This class provides a JSON array iterator that dereferences as an instance of * This class provides a JSON array iterator that dereferences as an instance of
* RapidJsonAdapter representing a value stored in the array. It has been * RapidJsonAdapter representing a value stored in the array. It has been
* implemented using the boost iterator_facade template. * implemented using the boost iterator_facade template.
* *
* @see RapidJsonArray * @see RapidJsonArray
*/ */
class RapidJsonArrayValueIterator: class RapidJsonArrayValueIterator:
@@ -599,7 +599,7 @@ public:
{ {
return RapidJsonAdapter(*itr); return RapidJsonAdapter(*itr);
} }
/** /**
* @brief Compare this iterator against another iterator. * @brief Compare this iterator against another iterator.
* *
@@ -610,27 +610,27 @@ public:
* @param other iterator to compare against * @param other iterator to compare against
* *
* @returns true if the iterators are equal, false otherwise. * @returns true if the iterators are equal, false otherwise.
*/ */
bool equal(const RapidJsonArrayValueIterator &other) const bool equal(const RapidJsonArrayValueIterator &other) const
{ {
return itr == other.itr; return itr == other.itr;
} }
void increment() void increment()
{ {
itr++; itr++;
} }
void decrement() void decrement()
{ {
itr--; itr--;
} }
void advance(std::ptrdiff_t n) void advance(std::ptrdiff_t n)
{ {
itr += n; itr += n;
} }
std::ptrdiff_t difference(const RapidJsonArrayValueIterator &other) std::ptrdiff_t difference(const RapidJsonArrayValueIterator &other)
{ {
return std::distance(itr, other.itr); return std::distance(itr, other.itr);
@@ -647,7 +647,7 @@ private:
* This class provides a JSON object iterator that dereferences as an instance * This class provides a JSON object iterator that dereferences as an instance
* of RapidJsonObjectMember representing one of the members of the object. It * of RapidJsonObjectMember representing one of the members of the object. It
* has been implemented using the boost iterator_facade template. * has been implemented using the boost iterator_facade template.
* *
* @see RapidJsonObject * @see RapidJsonObject
* @see RapidJsonObjectMember * @see RapidJsonObjectMember
*/ */
@@ -679,7 +679,7 @@ public:
std::string(itr->name.GetString(), itr->name.GetStringLength()), std::string(itr->name.GetString(), itr->name.GetStringLength()),
itr->value); itr->value);
} }
/** /**
* @brief Compare this iterator with another iterator. * @brief Compare this iterator with another iterator.
* *
@@ -690,7 +690,7 @@ public:
* @param other Iterator to compare with * @param other Iterator to compare with
* *
* @returns true if the underlying iterators are equal, false otherwise * @returns true if the underlying iterators are equal, false otherwise
*/ */
bool equal(const RapidJsonObjectMemberIterator &other) const bool equal(const RapidJsonObjectMemberIterator &other) const
{ {
return itr == other.itr; return itr == other.itr;
@@ -705,7 +705,7 @@ public:
{ {
itr--; itr--;
} }
std::ptrdiff_t difference(const RapidJsonObjectMemberIterator &other) std::ptrdiff_t difference(const RapidJsonObjectMemberIterator &other)
{ {
return std::distance(itr, other.itr); return std::distance(itr, other.itr);
@@ -720,9 +720,9 @@ private:
/// RapidJson specialisation of the AdapterTraits template struct. /// RapidJson specialisation of the AdapterTraits template struct.
template<> template<>
struct AdapterTraits<valijson::adapters::RapidJsonAdapter> struct AdapterTraits<valijson::adapters::RapidJsonAdapter>
{ {
typedef rapidjson::Document DocumentType; typedef rapidjson::Document DocumentType;
static std::string adapterName() static std::string adapterName()
{ {
return "RapidJsonAdapter"; return "RapidJsonAdapter";
@@ -759,7 +759,7 @@ inline RapidJsonObjectMemberIterator RapidJsonObject::find(
{ {
const rapidjson::Value::ConstMemberIterator const rapidjson::Value::ConstMemberIterator
itr = value.FindMember(propertyName.c_str()); itr = value.FindMember(propertyName.c_str());
return itr ? itr : value.MemberEnd(); return itr ? itr : value.MemberEnd();
} }

View File

@@ -80,7 +80,7 @@ struct DependenciesConstraint: BasicConstraint<DependenciesConstraint>
// A mapping from property names to the set of names of their dependencies // A mapping from property names to the set of names of their dependencies
typedef std::set<std::string> Dependencies; typedef std::set<std::string> Dependencies;
typedef std::map<std::string, Dependencies> PropertyDependenciesMap; typedef std::map<std::string, Dependencies> PropertyDependenciesMap;
// A mapping from property names to dependent schemas // A mapping from property names to dependent schemas
typedef boost::ptr_map<std::string, Schema> PropertyDependentSchemasMap; typedef boost::ptr_map<std::string, Schema> PropertyDependentSchemasMap;
@@ -103,40 +103,40 @@ struct DependenciesConstraint: BasicConstraint<DependenciesConstraint>
struct EnumConstraint: BasicConstraint<EnumConstraint> struct EnumConstraint: BasicConstraint<EnumConstraint>
{ {
typedef boost::ptr_vector<adapters::FrozenValue> Values; typedef boost::ptr_vector<adapters::FrozenValue> Values;
EnumConstraint(const Values &values) // Copy each of the frozen values EnumConstraint(const Values &values) // Copy each of the frozen values
: values(values) { } : values(values) { }
const Values values; const Values values;
}; };
/** /**
* @brief Represents a pair of 'items' and 'additionalItems' constraints. * @brief Represents a pair of 'items' and 'additionalItems' constraints.
*/ */
struct ItemsConstraint: BasicConstraint<ItemsConstraint> struct ItemsConstraint: BasicConstraint<ItemsConstraint>
{ {
typedef boost::ptr_vector<Schema> Schemas; typedef boost::ptr_vector<Schema> Schemas;
/** /**
* @brief Construct a singular item constraint that allows no additional * @brief Construct a singular item constraint that allows no additional
* items * items
* *
* @param itemSchema * @param itemSchema
*/ */
ItemsConstraint(const Schema &itemSchema) ItemsConstraint(const Schema &itemSchema)
: itemSchema(new Schema(itemSchema)) { } : itemSchema(new Schema(itemSchema)) { }
/** /**
* @brief Construct a singular item schema that allows additional items * @brief Construct a singular item schema that allows additional items
* *
* @param itemSchema * @param itemSchema
* @param additionalItemsSchema * @param additionalItemsSchema
*/ */
ItemsConstraint(const Schema &itemSchema, ItemsConstraint(const Schema &itemSchema,
const Schema &additionalItemsSchema) const Schema &additionalItemsSchema)
: itemSchema(new Schema(itemSchema)), : itemSchema(new Schema(itemSchema)),
additionalItemsSchema(new Schema(additionalItemsSchema)) { } additionalItemsSchema(new Schema(additionalItemsSchema)) { }
/** /**
* @brief Construct a plural items constraint that does not allow for * @brief Construct a plural items constraint that does not allow for
* additional item schemas * additional item schemas
@@ -145,7 +145,7 @@ struct ItemsConstraint: BasicConstraint<ItemsConstraint>
*/ */
ItemsConstraint(const Schemas &itemSchemas) ItemsConstraint(const Schemas &itemSchemas)
: itemSchemas(new Schemas(itemSchemas)) { } : itemSchemas(new Schemas(itemSchemas)) { }
/** /**
* @brief Construct a plural items constraint that allows additional items * @brief Construct a plural items constraint that allows additional items
* *
@@ -156,7 +156,7 @@ struct ItemsConstraint: BasicConstraint<ItemsConstraint>
const Schema &additionalItemsSchema) const Schema &additionalItemsSchema)
: itemSchemas(new Schemas(itemSchemas)), : itemSchemas(new Schemas(itemSchemas)),
additionalItemsSchema(new Schema(additionalItemsSchema)) { } additionalItemsSchema(new Schema(additionalItemsSchema)) { }
/** /**
* @brief Copy constructor * @brief Copy constructor
*/ */
@@ -164,7 +164,7 @@ struct ItemsConstraint: BasicConstraint<ItemsConstraint>
: itemSchema(other.itemSchema ? new Schema(*other.itemSchema.get()) : NULL), : itemSchema(other.itemSchema ? new Schema(*other.itemSchema.get()) : NULL),
itemSchemas(other.itemSchemas ? new Schemas(*other.itemSchemas.get()) : NULL), itemSchemas(other.itemSchemas ? new Schemas(*other.itemSchemas.get()) : NULL),
additionalItemsSchema(other.additionalItemsSchema ? new Schema(*other.additionalItemsSchema.get()) : NULL) { } additionalItemsSchema(other.additionalItemsSchema ? new Schema(*other.additionalItemsSchema.get()) : NULL) { }
const boost::scoped_ptr<const Schema> itemSchema; const boost::scoped_ptr<const Schema> itemSchema;
const boost::scoped_ptr<const Schemas> itemSchemas; const boost::scoped_ptr<const Schemas> itemSchemas;
const boost::scoped_ptr<const Schema> additionalItemsSchema; const boost::scoped_ptr<const Schema> additionalItemsSchema;
@@ -212,7 +212,7 @@ struct MaxPropertiesConstraint: BasicConstraint<MaxPropertiesConstraint>
{ {
MaxPropertiesConstraint(int64_t maxProperties) MaxPropertiesConstraint(int64_t maxProperties)
: maxProperties(maxProperties) { } : maxProperties(maxProperties) { }
const int64_t maxProperties; const int64_t maxProperties;
}; };
@@ -258,7 +258,7 @@ struct MinPropertiesConstraint: BasicConstraint<MinPropertiesConstraint>
{ {
MinPropertiesConstraint(int64_t minProperties) MinPropertiesConstraint(int64_t minProperties)
: minProperties(minProperties) { } : minProperties(minProperties) { }
const int64_t minProperties; const int64_t minProperties;
}; };
@@ -282,10 +282,10 @@ struct NotConstraint: BasicConstraint<NotConstraint>
{ {
NotConstraint(const Schema &schema) NotConstraint(const Schema &schema)
: schema(new Schema(schema)) { } : schema(new Schema(schema)) { }
NotConstraint(const NotConstraint &other) NotConstraint(const NotConstraint &other)
: schema(other.schema ? new Schema(*other.schema) : NULL) { } : schema(other.schema ? new Schema(*other.schema) : NULL) { }
const boost::scoped_ptr<const Schema> schema; const boost::scoped_ptr<const Schema> schema;
}; };
@@ -322,7 +322,7 @@ struct PropertiesConstraint: BasicConstraint<PropertiesConstraint> {
typedef boost::ptr_map<std::string, Schema> PropertySchemaMap; typedef boost::ptr_map<std::string, Schema> PropertySchemaMap;
PropertiesConstraint(const PropertySchemaMap &properties, PropertiesConstraint(const PropertySchemaMap &properties,
const PropertySchemaMap &patternProperties) const PropertySchemaMap &patternProperties)
: properties(properties), : properties(properties),
patternProperties(patternProperties) { } patternProperties(patternProperties) { }
@@ -343,7 +343,7 @@ struct PropertiesConstraint: BasicConstraint<PropertiesConstraint> {
const PropertySchemaMap properties; const PropertySchemaMap properties;
const PropertySchemaMap patternProperties; const PropertySchemaMap patternProperties;
const boost::scoped_ptr<const Schema> additionalProperties; const boost::scoped_ptr<const Schema> additionalProperties;
}; };
/** /**
@@ -379,7 +379,7 @@ struct TypeConstraint: BasicConstraint<TypeConstraint>
}; };
typedef std::set<JsonType> JsonTypes; typedef std::set<JsonType> JsonTypes;
typedef boost::ptr_vector<Schema> Schemas; typedef boost::ptr_vector<Schema> Schemas;
TypeConstraint(const JsonType jsonType) TypeConstraint(const JsonType jsonType)
@@ -387,7 +387,7 @@ struct TypeConstraint: BasicConstraint<TypeConstraint>
TypeConstraint(const JsonTypes jsonTypes) TypeConstraint(const JsonTypes jsonTypes)
: jsonTypes(jsonTypes) { } : jsonTypes(jsonTypes) { }
TypeConstraint(const JsonTypes jsonTypes, TypeConstraint(const JsonTypes jsonTypes,
const Schemas &schemas) const Schemas &schemas)
: jsonTypes(jsonTypes), : jsonTypes(jsonTypes),
@@ -419,7 +419,7 @@ struct TypeConstraint: BasicConstraint<TypeConstraint>
} else if (typeName.compare("string") == 0) { } else if (typeName.compare("string") == 0) {
return kString; return kString;
} }
throw std::runtime_error("Unrecognised JSON type name '" + typeName + "'"); throw std::runtime_error("Unrecognised JSON type name '" + typeName + "'");
} }

View File

@@ -38,7 +38,7 @@ struct Constraint {
* @returns an owning-pointer to the new constraint. * @returns an owning-pointer to the new constraint.
*/ */
virtual Constraint * clone() const = 0; virtual Constraint * clone() const = 0;
}; };
inline Constraint * new_clone(const Constraint &constraint) inline Constraint * new_clone(const Constraint &constraint)

View File

@@ -112,7 +112,7 @@ public:
/** /**
* @brief Invoke a function on each constraint in the schema. * @brief Invoke a function on each constraint in the schema.
* *
* This is a stricter version of the apply() function that will return * This is a stricter version of the apply() function that will return
* immediately if any of the invokations return false. * immediately if any of the invokations return false.
* *
* @returns true if all invokations of the callback function are * @returns true if all invokations of the callback function are
@@ -134,7 +134,7 @@ public:
if (id) { if (id) {
return *id; return *id;
} }
throw std::runtime_error("id has not been set"); throw std::runtime_error("id has not been set");
} }
@@ -142,7 +142,7 @@ public:
{ {
return std::string(); return std::string();
} }
std::string getUri() const std::string getUri() const
{ {
return std::string(); return std::string();
@@ -162,7 +162,7 @@ public:
if (title) { if (title) {
return *title; return *title;
} }
throw std::runtime_error("Schema does not have a title."); throw std::runtime_error("Schema does not have a title.");
} }
@@ -178,7 +178,7 @@ public:
} }
/** /**
* @brief Returns a boolean value that indicates whether the schema title * @brief Returns a boolean value that indicates whether the schema title
* has been set or not. * has been set or not.
* *
* @return boolean value * @return boolean value
@@ -219,10 +219,10 @@ private:
/// Id to apply when resolving the schema URI. /// Id to apply when resolving the schema URI.
boost::optional<std::string> id; boost::optional<std::string> id;
/// Scope inherited from a parent schema, or an empty string by default /// Scope inherited from a parent schema, or an empty string by default
boost::optional<std::string> parentScope; boost::optional<std::string> parentScope;
/// Title string associated with the schema (optional). /// Title string associated with the schema (optional).
boost::optional<std::string> title; boost::optional<std::string> title;
}; };

View File

@@ -17,7 +17,7 @@ namespace valijson {
* The SchemaParser class supports Drafts 3 and 4 of JSON Schema, however * The SchemaParser class supports Drafts 3 and 4 of JSON Schema, however
* Draft 3 support should be considered deprecated. * Draft 3 support should be considered deprecated.
* *
* The functions provided by this class have been templated so that they can * The functions provided by this class have been templated so that they can
* be used with different Adapter types. * be used with different Adapter types.
*/ */
class SchemaParser class SchemaParser
@@ -36,7 +36,7 @@ public:
/** /**
* @brief Construct a new SchemaParser for a given version of JSON Schema. * @brief Construct a new SchemaParser for a given version of JSON Schema.
* *
* @param version Version of JSON Schema that will be expected * @param version Version of JSON Schema that will be expected
*/ */
SchemaParser(const Version version = kDraft4) SchemaParser(const Version version = kDraft4)
: version(version) { } : version(version) { }
@@ -80,18 +80,18 @@ public:
const typename AdapterType::Object object = node.asObject(); const typename AdapterType::Object object = node.asObject();
typename AdapterType::Object::const_iterator itr(object.end()); typename AdapterType::Object::const_iterator itr(object.end());
if ((itr = object.find("id")) != object.end()) { if ((itr = object.find("id")) != object.end()) {
if (itr->second.maybeString()) { if (itr->second.maybeString()) {
schema.setId(itr->second.asString()); schema.setId(itr->second.asString());
} }
} }
if ((itr = object.find("allOf")) != object.end()) { if ((itr = object.find("allOf")) != object.end()) {
const AdapterType &childNode = resolveReference<AdapterType>(deref, schema, itr->second); const AdapterType &childNode = resolveReference<AdapterType>(deref, schema, itr->second);
schema.addConstraint(makeAllOfConstraint(childNode, deref)); schema.addConstraint(makeAllOfConstraint(childNode, deref));
} }
if ((itr = object.find("anyOf")) != object.end()) { if ((itr = object.find("anyOf")) != object.end()) {
schema.addConstraint(makeAnyOfConstraint(itr->second, deref)); schema.addConstraint(makeAnyOfConstraint(itr->second, deref));
} }
@@ -99,11 +99,11 @@ public:
if ((itr = object.find("dependencies")) != object.end()) { if ((itr = object.find("dependencies")) != object.end()) {
schema.addConstraint(makeDependenciesConstraint(itr->second, deref)); schema.addConstraint(makeDependenciesConstraint(itr->second, deref));
} }
if ((itr = object.find("enum")) != object.end()) { if ((itr = object.find("enum")) != object.end()) {
schema.addConstraint(makeEnumConstraint(itr->second)); schema.addConstraint(makeEnumConstraint(itr->second));
} }
{ {
// Check for schema keywords that require the creation of a // Check for schema keywords that require the creation of a
// ItemsConstraint instance. // ItemsConstraint instance.
@@ -118,7 +118,7 @@ public:
deref)); deref));
} }
} }
if ((itr = object.find("maximum")) != object.end()) { if ((itr = object.find("maximum")) != object.end()) {
typename AdapterType::Object::const_iterator exclusiveMaximumItr = object.find("exclusiveMaximum"); typename AdapterType::Object::const_iterator exclusiveMaximumItr = object.find("exclusiveMaximum");
if (exclusiveMaximumItr == object.end()) { if (exclusiveMaximumItr == object.end()) {
@@ -129,19 +129,19 @@ public:
} else if (object.find("exclusiveMaximum") != object.end()) { } else if (object.find("exclusiveMaximum") != object.end()) {
// throw exception // throw exception
} }
if ((itr = object.find("maxItems")) != object.end()) { if ((itr = object.find("maxItems")) != object.end()) {
schema.addConstraint(makeMaxItemsConstraint(itr->second)); schema.addConstraint(makeMaxItemsConstraint(itr->second));
} }
if ((itr = object.find("maxLength")) != object.end()) { if ((itr = object.find("maxLength")) != object.end()) {
schema.addConstraint(makeMaxLengthConstraint(itr->second)); schema.addConstraint(makeMaxLengthConstraint(itr->second));
} }
if ((itr = object.find("maxProperties")) != object.end()) { if ((itr = object.find("maxProperties")) != object.end()) {
schema.addConstraint(makeMaxPropertiesConstraint(itr->second)); schema.addConstraint(makeMaxPropertiesConstraint(itr->second));
} }
if ((itr = object.find("minimum")) != object.end()) { if ((itr = object.find("minimum")) != object.end()) {
typename AdapterType::Object::const_iterator exclusiveMinimumItr = object.find("exclusiveMinimum"); typename AdapterType::Object::const_iterator exclusiveMinimumItr = object.find("exclusiveMinimum");
if (exclusiveMinimumItr == object.end()) { if (exclusiveMinimumItr == object.end()) {
@@ -152,31 +152,31 @@ public:
} else if (object.find("exclusiveMinimum") != object.end()) { } else if (object.find("exclusiveMinimum") != object.end()) {
// throw exception // throw exception
} }
if ((itr = object.find("minItems")) != object.end()) { if ((itr = object.find("minItems")) != object.end()) {
schema.addConstraint(makeMinItemsConstraint(itr->second)); schema.addConstraint(makeMinItemsConstraint(itr->second));
} }
if ((itr = object.find("minLength")) != object.end()) { if ((itr = object.find("minLength")) != object.end()) {
schema.addConstraint(makeMinLengthConstraint(itr->second)); schema.addConstraint(makeMinLengthConstraint(itr->second));
} }
if ((itr = object.find("minProperties")) != object.end()) { if ((itr = object.find("minProperties")) != object.end()) {
schema.addConstraint(makeMinPropertiesConstraint(itr->second)); schema.addConstraint(makeMinPropertiesConstraint(itr->second));
} }
if ((itr = object.find("not")) != object.end()) { if ((itr = object.find("not")) != object.end()) {
schema.addConstraint(makeNotConstraint(itr->second, deref)); schema.addConstraint(makeNotConstraint(itr->second, deref));
} }
if ((itr = object.find("oneOf")) != object.end()) { if ((itr = object.find("oneOf")) != object.end()) {
schema.addConstraint(makeOneOfConstraint(itr->second, deref)); schema.addConstraint(makeOneOfConstraint(itr->second, deref));
} }
if ((itr = object.find("pattern")) != object.end()) { if ((itr = object.find("pattern")) != object.end()) {
schema.addConstraint(makePatternConstraint(itr->second)); schema.addConstraint(makePatternConstraint(itr->second));
} }
{ {
// Check for schema keywords that require the creation of a // Check for schema keywords that require the creation of a
// PropertiesConstraint instance. // PropertiesConstraint instance.
@@ -208,15 +208,15 @@ public:
schema.addConstraint(makeRequiredConstraint(itr->second)); schema.addConstraint(makeRequiredConstraint(itr->second));
} }
} }
if ((itr = object.find("title")) != object.end()) { if ((itr = object.find("title")) != object.end()) {
} }
if ((itr = object.find("type")) != object.end()) { if ((itr = object.find("type")) != object.end()) {
schema.addConstraint(makeTypeConstraint(itr->second, deref)); schema.addConstraint(makeTypeConstraint(itr->second, deref));
} }
if ((itr = object.find("uniqueItems")) != object.end()) { if ((itr = object.find("uniqueItems")) != object.end()) {
constraints::Constraint *constraint = makeUniqueItemsConstraint(itr->second); constraints::Constraint *constraint = makeUniqueItemsConstraint(itr->second);
if (constraint) { if (constraint) {
@@ -268,7 +268,7 @@ private:
const AdapterType &node) const AdapterType &node)
{ {
typedef typename AdapterType::Object Object; typedef typename AdapterType::Object Object;
if (node.isObject()) { if (node.isObject()) {
const Object object = node.getObject(); const Object object = node.getObject();
const typename Object::const_iterator itr = object.find("$ref"); const typename Object::const_iterator itr = object.find("$ref");
@@ -297,7 +297,7 @@ private:
* @return pointer to a new AllOfConstraint object that belongs to the * @return pointer to a new AllOfConstraint object that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::AllOfConstraint* makeAllOfConstraint( constraints::AllOfConstraint* makeAllOfConstraint(
const AdapterType &node, const AdapterType &node,
boost::optional<DereferenceFunction<AdapterType> > deref) boost::optional<DereferenceFunction<AdapterType> > deref)
@@ -315,11 +315,11 @@ private:
throw std::runtime_error("Expected array element to be an object value in 'allOf' constraint."); throw std::runtime_error("Expected array element to be an object value in 'allOf' constraint.");
} }
} }
/// @todo: bypass deep copy of the child schemas /// @todo: bypass deep copy of the child schemas
return new constraints::AllOfConstraint(childSchemas); return new constraints::AllOfConstraint(childSchemas);
} }
/** /**
* @brief Make a new AnyOfConstraint object. * @brief Make a new AnyOfConstraint object.
* *
@@ -329,7 +329,7 @@ private:
* @return pointer to a new AnyOfConstraint object that belongs to the * @return pointer to a new AnyOfConstraint object that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::AnyOfConstraint* makeAnyOfConstraint( constraints::AnyOfConstraint* makeAnyOfConstraint(
const AdapterType &node, const AdapterType &node,
boost::optional<DereferenceFunction<AdapterType> > deref) boost::optional<DereferenceFunction<AdapterType> > deref)
@@ -347,11 +347,11 @@ private:
throw std::runtime_error("Expected array element to be an object value in 'anyOf' constraint."); throw std::runtime_error("Expected array element to be an object value in 'anyOf' constraint.");
} }
} }
/// @todo: bypass deep copy of the child schemas /// @todo: bypass deep copy of the child schemas
return new constraints::AnyOfConstraint(childSchemas); return new constraints::AnyOfConstraint(childSchemas);
} }
/** /**
* @brief Make a new DependenciesConstraint object. * @brief Make a new DependenciesConstraint object.
* *
@@ -362,21 +362,21 @@ private:
* - an object that specifies a schema which must be satisfied if the * - an object that specifies a schema which must be satisfied if the
* dependent property is present * dependent property is present
* *
* When parsing a Draft 3 schema, in addition to the formats above, the * When parsing a Draft 3 schema, in addition to the formats above, the
* following format can be used: * following format can be used:
* - a string that names a single property that must be present if the * - a string that names a single property that must be present if the
* dependent property is presnet * dependent property is presnet
* *
* Multiple methods can be used in the same dependency constraint. * Multiple methods can be used in the same dependency constraint.
* *
* If the format of any part of the the dependency node does not match one * If the format of any part of the the dependency node does not match one
* of these formats, an exception will be thrown. * of these formats, an exception will be thrown.
* *
* @param node JSON node containing an object that defines a mapping of * @param node JSON node containing an object that defines a mapping of
* properties to their dependencies. * properties to their dependencies.
* @param deref Optional functor for resolving JSON References. * @param deref Optional functor for resolving JSON References.
* *
* @return pointer to a new DependencyConstraint that belongs to the * @return pointer to a new DependencyConstraint that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
@@ -390,16 +390,16 @@ private:
constraints::DependenciesConstraint::PropertyDependenciesMap pdm; constraints::DependenciesConstraint::PropertyDependenciesMap pdm;
constraints::DependenciesConstraint::PropertyDependentSchemasMap pdsm; constraints::DependenciesConstraint::PropertyDependentSchemasMap pdsm;
// Process each of the dependency mappings defined by the object // Process each of the dependency mappings defined by the object
BOOST_FOREACH ( const typename AdapterType::ObjectMember member, node.asObject() ) { BOOST_FOREACH ( const typename AdapterType::ObjectMember member, node.asObject() ) {
// First, we attempt to parse the value of the dependency mapping // First, we attempt to parse the value of the dependency mapping
// as an array of strings. If the Adapter type does not support // as an array of strings. If the Adapter type does not support
// strict types, then an empty string or empty object will be cast // strict types, then an empty string or empty object will be cast
// to an array, and the resulting dependency list will be empty. // to an array, and the resulting dependency list will be empty.
// This is equivalent to using an empty object, but does mean that // This is equivalent to using an empty object, but does mean that
// if the user provides an actual string then this error will not // if the user provides an actual string then this error will not
// be detected. // be detected.
if (member.second.maybeArray()) { if (member.second.maybeArray()) {
// Parse an array of dependency names // Parse an array of dependency names
@@ -408,14 +408,14 @@ private:
if (dependencyName.maybeString()) { if (dependencyName.maybeString()) {
dependencies.insert(dependencyName.getString()); dependencies.insert(dependencyName.getString());
} else { } else {
throw std::runtime_error("Expected string value in dependency list of property '" + throw std::runtime_error("Expected string value in dependency list of property '" +
member.first + "' in 'dependencies' constraint."); member.first + "' in 'dependencies' constraint.");
} }
} }
// If the value of dependency mapping could not be processed as an // If the value of dependency mapping could not be processed as an
// array, we'll try to process it as an object instead. Note that // array, we'll try to process it as an object instead. Note that
// strict type comparison is used here, since we've already // strict type comparison is used here, since we've already
// exercised the flexibility by loosely-typed Adapter types. If the // exercised the flexibility by loosely-typed Adapter types. If the
// value of the dependency mapping is an object, then we'll try to // value of the dependency mapping is an object, then we'll try to
// process it as a dependent schema. // process it as a dependent schema.
@@ -435,10 +435,10 @@ private:
throw std::runtime_error("Invalid dependencies definition."); throw std::runtime_error("Invalid dependencies definition.");
} }
} }
return new constraints::DependenciesConstraint(pdm, pdsm); return new constraints::DependenciesConstraint(pdm, pdsm);
} }
/** /**
* @brief Make a new EnumConstraint object. * @brief Make a new EnumConstraint object.
* *
@@ -456,21 +456,21 @@ private:
BOOST_FOREACH( const AdapterType value, node.getArray() ) { BOOST_FOREACH( const AdapterType value, node.getArray() ) {
values.push_back(value.freeze()); values.push_back(value.freeze());
} }
/// @todo This will make another copy of the values while constructing /// @todo This will make another copy of the values while constructing
/// the EnumConstraint. Move semantics in C++11 should make it possible /// the EnumConstraint. Move semantics in C++11 should make it possible
/// to avoid these copies without complicating the implementation of the /// to avoid these copies without complicating the implementation of the
/// EnumConstraint class. /// EnumConstraint class.
return new constraints::EnumConstraint(values); return new constraints::EnumConstraint(values);
} }
/** /**
* @brief Make a new ItemsConstraint object. * @brief Make a new ItemsConstraint object.
* *
* @param items Optional pointer to a JSON node containing * @param items Optional pointer to a JSON node containing
* an object mapping property names to schemas. * an object mapping property names to schemas.
* @param additionalItems Optional pointer to a JSON node containing * @param additionalItems Optional pointer to a JSON node containing
* an additional properties schema or a boolean * an additional properties schema or a boolean
* value. * value.
* @param deref Optional functor for resolving JSON References. * @param deref Optional functor for resolving JSON References.
* *
@@ -495,7 +495,7 @@ private:
} }
} else if (additionalItems->maybeObject()) { } else if (additionalItems->maybeObject()) {
// If the value of the additionalItems property is an object, // If the value of the additionalItems property is an object,
// then it should be parsed into a Schema object, which will be // then it should be parsed into a Schema object, which will be
// used to validate additional array items. // used to validate additional array items.
additionalItemsSchema.reset(new Schema()); additionalItemsSchema.reset(new Schema());
populateSchema<AdapterType>(*additionalItems, *additionalItemsSchema, deref); populateSchema<AdapterType>(*additionalItems, *additionalItemsSchema, deref);
@@ -510,7 +510,7 @@ private:
// satisfy any constraints. // satisfy any constraints.
additionalItemsSchema.reset(new Schema()); additionalItemsSchema.reset(new Schema());
} }
// Construct a Schema object for each item in the items array, if an // Construct a Schema object for each item in the items array, if an
// array is provided, or a single Schema object, in an object value is // array is provided, or a single Schema object, in an object value is
// provided. If the items constraint is not provided, then array items // provided. If the items constraint is not provided, then array items
@@ -519,8 +519,8 @@ private:
if (items) { if (items) {
if (items->isArray()) { if (items->isArray()) {
// If the items constraint contains an array, then it should // If the items constraint contains an array, then it should
// contain a list of child schemas which will be used to // contain a list of child schemas which will be used to
// validate the values at the corresponding indexes in a target // validate the values at the corresponding indexes in a target
// array. // array.
BOOST_FOREACH( const AdapterType v, items->getArray() ) { BOOST_FOREACH( const AdapterType v, items->getArray() ) {
itemSchemas.push_back(new Schema()); itemSchemas.push_back(new Schema());
@@ -539,7 +539,7 @@ private:
} else if (items->isObject()) { } else if (items->isObject()) {
// If the items constraint contains an object value, then it // If the items constraint contains an object value, then it
// should contain a Schema that will be used to validate all // should contain a Schema that will be used to validate all
// items in a target array. Any schema defined by the // items in a target array. Any schema defined by the
// additionalItems constraint will be ignored. // additionalItems constraint will be ignored.
Schema childSchema; Schema childSchema;
populateSchema<AdapterType>(*items, childSchema, deref); populateSchema<AdapterType>(*items, childSchema, deref);
@@ -548,7 +548,7 @@ private:
} else { } else {
return new constraints::ItemsConstraint(childSchema); return new constraints::ItemsConstraint(childSchema);
} }
} else if (items->maybeObject()) { } else if (items->maybeObject()) {
// If a loosely-typed Adapter type is being used, then we'll // If a loosely-typed Adapter type is being used, then we'll
// assume that an empty schema has been provided. // assume that an empty schema has been provided.
@@ -564,20 +564,20 @@ private:
throw std::runtime_error("Expected array or object value for 'items'."); throw std::runtime_error("Expected array or object value for 'items'.");
} }
} }
Schema emptySchema; Schema emptySchema;
if (additionalItemsSchema) { if (additionalItemsSchema) {
return new constraints::ItemsConstraint(emptySchema, *additionalItemsSchema); return new constraints::ItemsConstraint(emptySchema, *additionalItemsSchema);
} }
return new constraints::ItemsConstraint(emptySchema); return new constraints::ItemsConstraint(emptySchema);
} }
/** /**
* @brief Make a new MaximumConstraint object. * @brief Make a new MaximumConstraint object.
* *
* @param node JSON node containing the maximum value. * @param node JSON node containing the maximum value.
* @param exclusiveMaximum Optional pointer to a JSON boolean value that * @param exclusiveMaximum Optional pointer to a JSON boolean value that
* indicates whether maximum value is excluded * indicates whether maximum value is excluded
* from the range of permitted values. * from the range of permitted values.
* *
@@ -601,10 +601,10 @@ private:
double maximumValue = node.asDouble(); double maximumValue = node.asDouble();
return new constraints::MaximumConstraint(maximumValue, exclusiveMaximumValue); return new constraints::MaximumConstraint(maximumValue, exclusiveMaximumValue);
} }
throw std::runtime_error("Expected numeric value for maximum constraint."); throw std::runtime_error("Expected numeric value for maximum constraint.");
} }
/** /**
* @brief Make a new MaxItemsConstraint object. * @brief Make a new MaxItemsConstraint object.
* *
@@ -620,10 +620,10 @@ private:
if (node.maybeInteger()) { if (node.maybeInteger()) {
int64_t value = node.asInteger(); int64_t value = node.asInteger();
if (value >= 0) { if (value >= 0) {
return new constraints::MaxItemsConstraint(value); return new constraints::MaxItemsConstraint(value);
} }
} }
throw std::runtime_error("Expected positive integer value for maxItems constraint."); throw std::runtime_error("Expected positive integer value for maxItems constraint.");
} }
@@ -648,7 +648,7 @@ private:
throw std::runtime_error("Expected a positive integer value for maxLength constraint."); throw std::runtime_error("Expected a positive integer value for maxLength constraint.");
} }
/** /**
* @brief Make a new MaxPropertiesConstraint object. * @brief Make a new MaxPropertiesConstraint object.
* *
@@ -656,9 +656,9 @@ private:
* maximum number of properties that may be contained by an * maximum number of properties that may be contained by an
* object. * object.
* *
* @return pointer to a new MaxPropertiesConstraint that belongs to the * @return pointer to a new MaxPropertiesConstraint that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::MaxPropertiesConstraint* makeMaxPropertiesConstraint( constraints::MaxPropertiesConstraint* makeMaxPropertiesConstraint(
const AdapterType &node) const AdapterType &node)
@@ -669,22 +669,22 @@ private:
return new constraints::MaxPropertiesConstraint(value); return new constraints::MaxPropertiesConstraint(value);
} }
} }
throw std::runtime_error("Expected a positive integer for 'maxProperties' constraint."); throw std::runtime_error("Expected a positive integer for 'maxProperties' constraint.");
} }
/** /**
* @brief Make a new MinimumConstraint object. * @brief Make a new MinimumConstraint object.
* *
* @param node JSON node containing an integer, representing * @param node JSON node containing an integer, representing
* the minimum value. * the minimum value.
* *
* @param exclusiveMaximum Optional pointer to a JSON boolean value that * @param exclusiveMaximum Optional pointer to a JSON boolean value that
* indicates whether the minimum value is * indicates whether the minimum value is
* excluded from the range of permitted values. * excluded from the range of permitted values.
* *
* @return pointer to a new MinimumConstraint that belongs to the caller * @return pointer to a new MinimumConstraint that belongs to the caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::MinimumConstraint* makeMinimumConstraint( constraints::MinimumConstraint* makeMinimumConstraint(
const AdapterType &node, const AdapterType &node,
@@ -703,10 +703,10 @@ private:
double minimumValue = node.asDouble(); double minimumValue = node.asDouble();
return new constraints::MinimumConstraint(minimumValue, exclusiveMinimumValue); return new constraints::MinimumConstraint(minimumValue, exclusiveMinimumValue);
} }
throw std::runtime_error("Expected numeric value for 'minimum' constraint."); throw std::runtime_error("Expected numeric value for 'minimum' constraint.");
} }
/** /**
* @brief Make a new MinItemsConstraint object. * @brief Make a new MinItemsConstraint object.
* *
@@ -714,7 +714,7 @@ private:
* minimum number of items that may be contained by an array. * minimum number of items that may be contained by an array.
* *
* @return pointer to a new MinItemsConstraint that belongs to the caller * @return pointer to a new MinItemsConstraint that belongs to the caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::MinItemsConstraint* makeMinItemsConstraint( constraints::MinItemsConstraint* makeMinItemsConstraint(
const AdapterType &node) const AdapterType &node)
@@ -728,7 +728,7 @@ private:
throw std::runtime_error("Expected a positive integer value for 'minItems' constraint."); throw std::runtime_error("Expected a positive integer value for 'minItems' constraint.");
} }
/** /**
* @brief Make a new MinLengthConstraint object. * @brief Make a new MinLengthConstraint object.
* *
@@ -736,7 +736,7 @@ private:
* minimum length of a string. * minimum length of a string.
* *
* @return pointer to a new MinLengthConstraint that belongs to the caller * @return pointer to a new MinLengthConstraint that belongs to the caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::MinLengthConstraint* makeMinLengthConstraint( constraints::MinLengthConstraint* makeMinLengthConstraint(
const AdapterType &node) const AdapterType &node)
@@ -749,9 +749,9 @@ private:
} }
throw std::runtime_error("Expected a positive integer value for 'minLength' constraint."); throw std::runtime_error("Expected a positive integer value for 'minLength' constraint.");
} }
/** /**
* @brief Make a new MaxPropertiesConstraint object. * @brief Make a new MaxPropertiesConstraint object.
* *
@@ -759,9 +759,9 @@ private:
* minimum number of properties that may be contained by an * minimum number of properties that may be contained by an
* object. * object.
* *
* @return pointer to a new MinPropertiesConstraint that belongs to the * @return pointer to a new MinPropertiesConstraint that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::MinPropertiesConstraint* makeMinPropertiesConstraint( constraints::MinPropertiesConstraint* makeMinPropertiesConstraint(
const AdapterType &node) const AdapterType &node)
@@ -772,10 +772,10 @@ private:
return new constraints::MinPropertiesConstraint(value); return new constraints::MinPropertiesConstraint(value);
} }
} }
throw std::runtime_error("Expected a positive integer for 'minProperties' constraint."); throw std::runtime_error("Expected a positive integer for 'minProperties' constraint.");
} }
/** /**
* @brief Make a new NotConstraint object. * @brief Make a new NotConstraint object.
* *
@@ -796,7 +796,7 @@ private:
throw std::runtime_error("Expected object value for 'not' constraint."); throw std::runtime_error("Expected object value for 'not' constraint.");
} }
/** /**
* @brief Make a new OneOfConstraint object. * @brief Make a new OneOfConstraint object.
* *
@@ -805,7 +805,7 @@ private:
* *
* @return pointer to a new OneOfConstraint that belongs to the caller * @return pointer to a new OneOfConstraint that belongs to the caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::OneOfConstraint* makeOneOfConstraint( constraints::OneOfConstraint* makeOneOfConstraint(
const AdapterType &node, const AdapterType &node,
boost::optional<DereferenceFunction<AdapterType> > deref) boost::optional<DereferenceFunction<AdapterType> > deref)
@@ -817,18 +817,18 @@ private:
schemaNode, childSchemas.back(), schemaNode, childSchemas.back(),
deref); deref);
} }
/// @todo: bypass deep copy of the child schemas /// @todo: bypass deep copy of the child schemas
return new constraints::OneOfConstraint(childSchemas); return new constraints::OneOfConstraint(childSchemas);
} }
/** /**
* @brief Make a new PatternConstraint object. * @brief Make a new PatternConstraint object.
* *
* @param node JSON node containing a pattern string * @param node JSON node containing a pattern string
* @param deref Optional functor for resolving JSON References. * @param deref Optional functor for resolving JSON References.
* *
* @return pointer to a new PatternConstraint object that belongs to the * @return pointer to a new PatternConstraint object that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
@@ -837,20 +837,20 @@ private:
{ {
return new constraints::PatternConstraint(node.getString()); return new constraints::PatternConstraint(node.getString());
} }
/** /**
* @brief Make a new Properties object. * @brief Make a new Properties object.
* *
* @param properties Optional pointer to a JSON node containing * @param properties Optional pointer to a JSON node containing
* an object mapping property names to * an object mapping property names to
* schemas. * schemas.
* @param patternProperties Optional pointer to a JSON node containing * @param patternProperties Optional pointer to a JSON node containing
* an object mapping pattern property names * an object mapping pattern property names
* to schemas. * to schemas.
* @param additionalProperties Optional pointer to a JSON node containing * @param additionalProperties Optional pointer to a JSON node containing
* an additional properties schema or a * an additional properties schema or a
* boolean value. * boolean value.
* @param deref Optional functor for resolving JSON * @param deref Optional functor for resolving JSON
* References. * References.
* @param parentSchema Optional pointer to the Schema of the * @param parentSchema Optional pointer to the Schema of the
* parent object, to support the 'required' * parent object, to support the 'required'
@@ -882,7 +882,7 @@ private:
parentSchema, &propertyName); // Optional parentSchema, &propertyName); // Optional
} }
} }
// Populate a PropertySchemaMap for each of the properties defined by // Populate a PropertySchemaMap for each of the properties defined by
// the 'patternProperties' keyword // the 'patternProperties' keyword
PSM patternPropertySchemas; PSM patternPropertySchemas;
@@ -896,18 +896,18 @@ private:
parentSchema, &propertyName); // Optional parentSchema, &propertyName); // Optional
} }
} }
// Populate an additionalItems schema if required // Populate an additionalItems schema if required
boost::scoped_ptr<Schema> additionalPropertiesSchema; boost::scoped_ptr<Schema> additionalPropertiesSchema;
if (additionalProperties) { if (additionalProperties) {
// If additionalProperties has been set, check for a boolean value. // If additionalProperties has been set, check for a boolean value.
// Setting 'additionalProperties' to true allows the values of // Setting 'additionalProperties' to true allows the values of
// additional properties to take any form. Setting it false // additional properties to take any form. Setting it false
// prohibits the use of additional properties. // prohibits the use of additional properties.
// If additionalProperties is instead an object, it should be // If additionalProperties is instead an object, it should be
// parsed as a schema. If additionalProperties has any other type, // parsed as a schema. If additionalProperties has any other type,
// then the schema is not valid. // then the schema is not valid.
if (additionalProperties->isBool() || if (additionalProperties->isBool() ||
additionalProperties->maybeBool()) { additionalProperties->maybeBool()) {
// If it has a boolean value that is 'true', then an empty // If it has a boolean value that is 'true', then an empty
// schema should be used. // schema should be used.
@@ -929,29 +929,29 @@ private:
// default value is an empty schema. // default value is an empty schema.
additionalPropertiesSchema.reset(new Schema()); additionalPropertiesSchema.reset(new Schema());
} }
if (additionalPropertiesSchema) { if (additionalPropertiesSchema) {
// If an additionalProperties schema has been created, construct a // If an additionalProperties schema has been created, construct a
// new PropertiesConstraint object using that schema. // new PropertiesConstraint object using that schema.
return new constraints::PropertiesConstraint( return new constraints::PropertiesConstraint(
propertySchemas, patternPropertySchemas, propertySchemas, patternPropertySchemas,
*additionalPropertiesSchema); *additionalPropertiesSchema);
} }
return new constraints::PropertiesConstraint( return new constraints::PropertiesConstraint(
propertySchemas, patternPropertySchemas); propertySchemas, patternPropertySchemas);
} }
/** /**
* @brief Make a new RequiredConstraint. * @brief Make a new RequiredConstraint.
* *
* This function is used to create new RequiredContraint objects for * This function is used to create new RequiredContraint objects for
* Draft 3 schemas. * Draft 3 schemas.
* *
* @param node Node containing a boolean value. * @param node Node containing a boolean value.
* @param name Name of the required attribute. * @param name Name of the required attribute.
* *
* @return pointer to a new RequiredConstraint object that belongs to the * @return pointer to a new RequiredConstraint object that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
@@ -962,27 +962,27 @@ private:
if (!node.maybeBool()) { if (!node.maybeBool()) {
throw std::runtime_error("Expected boolean value for 'required' attribute."); throw std::runtime_error("Expected boolean value for 'required' attribute.");
} }
if (node.getBool()) { if (node.getBool()) {
constraints::RequiredConstraint::RequiredProperties requiredProperties; constraints::RequiredConstraint::RequiredProperties requiredProperties;
requiredProperties.insert(name); requiredProperties.insert(name);
return new constraints::RequiredConstraint(requiredProperties); return new constraints::RequiredConstraint(requiredProperties);
} }
return NULL; return NULL;
} }
/** /**
* @brief Make a new RequiredConstraint. * @brief Make a new RequiredConstraint.
* *
* This function is used to create new RequiredContraint objects for * This function is used to create new RequiredContraint objects for
* Draft 4 schemas. * Draft 4 schemas.
* *
* @param node Node containing an array of strings. * @param node Node containing an array of strings.
* *
* @return pointer to a new RequiredConstraint object that belongs to the * @return pointer to a new RequiredConstraint object that belongs to the
* caller * caller
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::RequiredConstraint* makeRequiredConstraint( constraints::RequiredConstraint* makeRequiredConstraint(
const AdapterType &node) const AdapterType &node)
@@ -994,10 +994,10 @@ private:
} }
requiredProperties.insert(v.getString()); requiredProperties.insert(v.getString());
} }
return new constraints::RequiredConstraint(requiredProperties); return new constraints::RequiredConstraint(requiredProperties);
} }
/** /**
* @brief Make a new TypeConstraint object. * @brief Make a new TypeConstraint object.
* *
@@ -1015,14 +1015,14 @@ private:
TC::JsonTypes jsonTypes; TC::JsonTypes jsonTypes;
TC::Schemas schemas; TC::Schemas schemas;
if (node.isString()) { if (node.isString()) {
const TC::JsonType jsonType = TC::jsonTypeFromString(node.getString()); const TC::JsonType jsonType = TC::jsonTypeFromString(node.getString());
if (jsonType == TC::kAny && version == kDraft4) { if (jsonType == TC::kAny && version == kDraft4) {
throw std::runtime_error("'any' type is not supported in version 4 schemas."); throw std::runtime_error("'any' type is not supported in version 4 schemas.");
} }
jsonTypes.insert(jsonType); jsonTypes.insert(jsonType);
} else if (node.isArray()) { } else if (node.isArray()) {
BOOST_FOREACH( const AdapterType v, node.getArray() ) { BOOST_FOREACH( const AdapterType v, node.getArray() ) {
if (v.isString()) { if (v.isString()) {
@@ -1046,10 +1046,10 @@ private:
} else { } else {
throw std::runtime_error("Type name should be a string."); throw std::runtime_error("Type name should be a string.");
} }
return new constraints::TypeConstraint(jsonTypes, schemas); return new constraints::TypeConstraint(jsonTypes, schemas);
} }
/** /**
* @brief Make a new UniqueItemsConstraint object. * @brief Make a new UniqueItemsConstraint object.
* *
@@ -1057,14 +1057,14 @@ private:
* *
* @return pointer to a new UniqueItemsConstraint object that belongs to * @return pointer to a new UniqueItemsConstraint object that belongs to
* the caller, or NULL if the boolean value is false. * the caller, or NULL if the boolean value is false.
*/ */
template<typename AdapterType> template<typename AdapterType>
constraints::UniqueItemsConstraint* makeUniqueItemsConstraint( constraints::UniqueItemsConstraint* makeUniqueItemsConstraint(
const AdapterType &node) const AdapterType &node)
{ {
if (node.isBool() || node.maybeBool()) { if (node.isBool() || node.maybeBool()) {
// If the boolean value is true, this function will return a pointer // If the boolean value is true, this function will return a pointer
// to a new UniqueItemsConstraint object. If it is value, then the // to a new UniqueItemsConstraint object. If it is value, then the
// constraint is redundant, so NULL is returned instead. // constraint is redundant, so NULL is returned instead.
if (node.getBool()) { if (node.getBool()) {
return new constraints::UniqueItemsConstraint(); return new constraints::UniqueItemsConstraint();
@@ -1072,10 +1072,10 @@ private:
return NULL; return NULL;
} }
} }
throw std::runtime_error("Expected boolean value for 'uniqueItems' constraint."); throw std::runtime_error("Expected boolean value for 'uniqueItems' constraint.");
} }
}; };
} // namespace valijson } // namespace valijson

View File

@@ -26,12 +26,12 @@ inline bool loadFile(const std::string &path, std::string &dest)
file.seekg(0, std::ios::end); file.seekg(0, std::ios::end);
dest.clear(); dest.clear();
dest.reserve(file.tellg()); dest.reserve(file.tellg());
// Assign file contents to destination string // Assign file contents to destination string
file.seekg(0, std::ios::beg); file.seekg(0, std::ios::beg);
dest.assign(std::istreambuf_iterator<char>(file), dest.assign(std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>()); std::istreambuf_iterator<char>());
return true; return true;
} }

View File

@@ -24,7 +24,7 @@ inline bool loadDocument(const std::string &path, Json::Value &document)
<< reader.getFormatedErrorMessages(); << reader.getFormatedErrorMessages();
return false; return false;
} }
return true; return true;
} }

View File

@@ -22,7 +22,7 @@ inline bool loadDocument(const std::string &path, boost::property_tree::ptree &d
std::cerr << "Failed to load json from file '" << path << "'." << std::endl; std::cerr << "Failed to load json from file '" << path << "'." << std::endl;
return false; return false;
} }
std::istringstream is(file); std::istringstream is(file);
try { try {
boost::property_tree::read_json(is, document); boost::property_tree::read_json(is, document);
@@ -31,7 +31,7 @@ inline bool loadDocument(const std::string &path, boost::property_tree::ptree &d
std::cerr << e.what() << std::endl; std::cerr << e.what() << std::endl;
return false; return false;
} }
return true; return true;
} }

View File

@@ -25,7 +25,7 @@ inline bool loadDocument(const std::string &path, rapidjson::Document &document)
std::cerr << "Near: " << file.substr(std::max(size_t(0), document.GetErrorOffset() - 20), 40) << std::endl; std::cerr << "Near: " << file.substr(std::max(size_t(0), document.GetErrorOffset() - 20), 40) << std::endl;
return false; return false;
} }
return true; return true;
} }

View File

@@ -29,17 +29,17 @@ public:
* @brief Construct an Error object with no context or description. * @brief Construct an Error object with no context or description.
*/ */
Error() { } Error() { }
/** /**
* @brief Construct an Error object using a context and description. * @brief Construct an Error object using a context and description.
* *
* @param context Context string to use * @param context Context string to use
* @param description Description string to use * @param description Description string to use
*/ */
Error(const std::string &context, const std::string &description) Error(const std::string &context, const std::string &description)
: context(context), : context(context),
description(description) { } description(description) { }
/// Path to the node that failed validation. /// Path to the node that failed validation.
std::string context; std::string context;
@@ -76,10 +76,10 @@ public:
{ {
errors.push_back(Error(context, description)); errors.push_back(Error(context, description));
} }
/** /**
* @brief Pop an error from the front of the queue. * @brief Pop an error from the front of the queue.
* *
* @param error Reference to an Error object to populate. * @param error Reference to an Error object to populate.
* *
* @returns true if an Error was popped, false otherwise. * @returns true if an Error was popped, false otherwise.
@@ -90,7 +90,7 @@ public:
if (errors.empty()) { if (errors.empty()) {
return false; return false;
} }
error = errors.front(); error = errors.front();
errors.pop_front(); errors.pop_front();
return true; return true;

View File

@@ -52,7 +52,7 @@ public:
* with error descriptions added to the ValidationResults object. * with error descriptions added to the ValidationResults object.
* *
* If a pointer to a ValidationResults instance is not provided, validation * If a pointer to a ValidationResults instance is not provided, validation
* will only continue for as long as the constraints are validated * will only continue for as long as the constraints are validated
* successfully. * successfully.
* *
* @param schema Schema that the target must validate against * @param schema Schema that the target must validate against
@@ -108,11 +108,11 @@ public:
{ {
// Flag used to track validation status if errors are non-fatal // Flag used to track validation status if errors are non-fatal
bool validated = true; bool validated = true;
// Validate against each child schema // Validate against each child schema
unsigned int index = 0; unsigned int index = 0;
BOOST_FOREACH( const Schema &schema, constraint.schemas ) { BOOST_FOREACH( const Schema &schema, constraint.schemas ) {
// Ensure that the target validates against child schema // Ensure that the target validates against child schema
if (!validateSchema(schema)) { if (!validateSchema(schema)) {
if (results) { if (results) {
@@ -124,7 +124,7 @@ public:
return false; return false;
} }
} }
index++; index++;
} }
@@ -136,10 +136,10 @@ public:
* AnyOfConstraint object. * AnyOfConstraint object.
* *
* An anyOf constraint provides a set of child schemas, any of which the * An anyOf constraint provides a set of child schemas, any of which the
* target may be validated against in order for the constraint to the * target may be validated against in order for the constraint to the
* satifisfied. * satifisfied.
* *
* Because an anyOf constraint does not require the target to validate * Because an anyOf constraint does not require the target to validate
* against all child schemas, if validation against a single schema fails, * against all child schemas, if validation against a single schema fails,
* the results will not be added to a ValidationResults object. Only if * the results will not be added to a ValidationResults object. Only if
* validation fails for all child schemas will an error be added to the * validation fails for all child schemas will an error be added to the
@@ -155,20 +155,20 @@ public:
// passed a reference to a constraint (_1), and a reference to the // passed a reference to a constraint (_1), and a reference to the
// visitor (*this). // visitor (*this).
Schema::ApplyFunction fn(boost::bind(validationCallback, _1, *this)); Schema::ApplyFunction fn(boost::bind(validationCallback, _1, *this));
BOOST_FOREACH( const Schema &schema, constraint.schemas ) { BOOST_FOREACH( const Schema &schema, constraint.schemas ) {
if (schema.apply(fn)) { if (schema.apply(fn)) {
return true; return true;
} }
} }
if (results) { if (results) {
results->pushError(context, "Failed to validate against any child schemas."); results->pushError(context, "Failed to validate against any child schemas.");
} }
return false; return false;
} }
/** /**
* @brief Validate against the dependencies constraint represented by a * @brief Validate against the dependencies constraint represented by a
* DependenciesConstraint object. * DependenciesConstraint object.
@@ -191,7 +191,7 @@ public:
// Typedef and reference for conciseness in nested loops // Typedef and reference for conciseness in nested loops
typedef DependenciesConstraint::PropertyDependenciesMap PDM; typedef DependenciesConstraint::PropertyDependenciesMap PDM;
const PDM &deps = constraint.dependencies; const PDM &deps = constraint.dependencies;
typedef DependenciesConstraint::PropertyDependentSchemasMap PDSM; typedef DependenciesConstraint::PropertyDependentSchemasMap PDSM;
const PDSM &depSchemas = constraint.dependentSchemas; const PDSM &depSchemas = constraint.dependentSchemas;
@@ -200,12 +200,12 @@ public:
// Flag used to track validation status if errors are non-fatal // Flag used to track validation status if errors are non-fatal
bool validated = true; bool validated = true;
// For each property in the object, check for a list of dependencies in // For each property in the object, check for a list of dependencies in
// the constraint object and verify that the dependencies have been // the constraint object and verify that the dependencies have been
// satisfied. // satisfied.
BOOST_FOREACH( const typename AdapterType::ObjectMember m, object ) { BOOST_FOREACH( const typename AdapterType::ObjectMember m, object ) {
// Check for this property in the dependency map. If it is not // Check for this property in the dependency map. If it is not
// present, we can move on to the next one... // present, we can move on to the next one...
PDM::const_iterator itr = deps.find(m.first); PDM::const_iterator itr = deps.find(m.first);
@@ -220,7 +220,7 @@ public:
} }
} }
} }
// Check for this property in the dependent schemas map. If it is // Check for this property in the dependent schemas map. If it is
// present then we need to validate the current target against the // present then we need to validate the current target against the
// dependent schema. // dependent schema.
@@ -237,7 +237,7 @@ public:
} }
} }
} }
return validated; return validated;
} }
@@ -260,16 +260,16 @@ public:
return true; return true;
} }
} }
if (results) { if (results) {
results->pushError(context, "Failed to match against any enum values."); results->pushError(context, "Failed to match against any enum values.");
} }
return false; return false;
} }
/** /**
* @brief Validate against the items and additionalItems constraints * @brief Validate against the items and additionalItems constraints
* represented by an ItemsConstraint object. * represented by an ItemsConstraint object.
* *
* An items constraint restricts the values in array to those that match a * An items constraint restricts the values in array to those that match a
@@ -279,7 +279,7 @@ public:
* validate all items. * validate all items.
* *
* If a list of child schemas is used, then the additionalItems constraint * If a list of child schemas is used, then the additionalItems constraint
* will also be considered. If present, the schema derived from the * will also be considered. If present, the schema derived from the
* additionalItems constraint will be used to validate items that do not * additionalItems constraint will be used to validate items that do not
* have a corresponding child schema in the items constraint. If the * have a corresponding child schema in the items constraint. If the
* items constraint was not provided, then the additionalItems schema will * items constraint was not provided, then the additionalItems schema will
@@ -295,11 +295,11 @@ public:
if (!target.isArray()) { if (!target.isArray()) {
return true; return true;
} }
bool validated = true; bool validated = true;
if (constraint.itemSchema) { if (constraint.itemSchema) {
// Validate all items against single schema // Validate all items against single schema
unsigned int index = 0; unsigned int index = 0;
BOOST_FOREACH( const AdapterType arrayItem, target.getArray() ) { BOOST_FOREACH( const AdapterType arrayItem, target.getArray() ) {
@@ -317,9 +317,9 @@ public:
} }
++index; ++index;
} }
} else if (constraint.itemSchemas) { } else if (constraint.itemSchemas) {
if (!constraint.additionalItemsSchema) { if (!constraint.additionalItemsSchema) {
// Check that the array length is <= length of the itemsSchema list // Check that the array length is <= length of the itemsSchema list
if (target.getArray().size() > constraint.itemSchemas->size()) { if (target.getArray().size() > constraint.itemSchemas->size()) {
@@ -331,7 +331,7 @@ public:
} }
} }
} }
// Validate items against the schema with the same index, or // Validate items against the schema with the same index, or
// additionalItems schema // additionalItems schema
unsigned int index = 0; unsigned int index = 0;
@@ -367,10 +367,10 @@ public:
} }
++index; ++index;
} }
} else if (constraint.additionalItemsSchema) { } else if (constraint.additionalItemsSchema) {
// Validate each item against additional items schema // Validate each item against additional items schema
BOOST_FOREACH( const AdapterType arrayItem, target.getArray() ) { BOOST_FOREACH( const AdapterType arrayItem, target.getArray() ) {
ValidationVisitor<AdapterType> v(arrayItem, ValidationVisitor<AdapterType> v(arrayItem,
@@ -387,14 +387,14 @@ public:
} }
} }
} }
} }
return validated; return validated;
} }
/** /**
* @brief Validate against the maximum and exclusiveMaximum constraints * @brief Validate against the maximum and exclusiveMaximum constraints
* represented by a MaximumConstraint object. * represented by a MaximumConstraint object.
* *
* @param constraint Constraint that the target must validate against. * @param constraint Constraint that the target must validate against.
@@ -426,10 +426,10 @@ public:
return false; return false;
} }
} }
return true; return true;
} }
/** /**
* @brief Validate against the maxItems constraint represented by a * @brief Validate against the maxItems constraint represented by a
* MaxItemsConstraint object. * MaxItemsConstraint object.
@@ -449,10 +449,10 @@ public:
} }
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Validate against the maxLength constraint represented by a * @brief Validate against the maxLength constraint represented by a
* MaxLengthConstraint object. * MaxLengthConstraint object.
@@ -472,10 +472,10 @@ public:
} }
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Validate against the maxProperties constraint represented by a * @brief Validate against the maxProperties constraint represented by a
* MaxPropertiesConstraint object. * MaxPropertiesConstraint object.
@@ -498,7 +498,7 @@ public:
return true; return true;
} }
/** /**
* @brief Validate against the minimum constraint represented by a * @brief Validate against the minimum constraint represented by a
* MinimumConstraint object. * MinimumConstraint object.
@@ -533,10 +533,10 @@ public:
return false; return false;
} }
} }
return true; return true;
} }
/** /**
* @brief Validate against the minItems constraint represented by a * @brief Validate against the minItems constraint represented by a
* MinItemsConstraint object. * MinItemsConstraint object.
@@ -556,10 +556,10 @@ public:
} }
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Validate against the minLength constraint represented by a * @brief Validate against the minLength constraint represented by a
* MinLengthConstraint object. * MinLengthConstraint object.
@@ -579,10 +579,10 @@ public:
} }
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Validate against the minProperties constraint represented by a * @brief Validate against the minProperties constraint represented by a
* MinPropertiesConstraint object. * MinPropertiesConstraint object.
@@ -605,9 +605,9 @@ public:
return true; return true;
} }
/** /**
* @brief Validate against the multipleOf or divisibleBy constraints * @brief Validate against the multipleOf or divisibleBy constraints
* represented by a MultipleOfConstraint object. * represented by a MultipleOfConstraint object.
* *
* @todo Not implemented. * @todo Not implemented.
@@ -620,15 +620,15 @@ public:
{ {
return true; return true;
} }
/** /**
* @brief Validate against the not constraint represented by a * @brief Validate against the not constraint represented by a
* NotConstraint object. * NotConstraint object.
* *
* @param constraint Constraint that the target must validate against. * @param constraint Constraint that the target must validate against.
* *
* @return true if the constraint is satisfied, false otherwise. * @return true if the constraint is satisfied, false otherwise.
*/ */
virtual bool visit(const NotConstraint &constraint) virtual bool visit(const NotConstraint &constraint)
{ {
ValidationVisitor<AdapterType> v(target, context, strictTypes, NULL); ValidationVisitor<AdapterType> v(target, context, strictTypes, NULL);
@@ -639,12 +639,12 @@ public:
} }
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Validate against the oneOf constraint represented by a * @brief Validate against the oneOf constraint represented by a
* OneOfConstraint object. * OneOfConstraint object.
* *
* @param constraint Constraint that the target must validate against. * @param constraint Constraint that the target must validate against.
@@ -654,13 +654,13 @@ public:
virtual bool visit(const OneOfConstraint &constraint) virtual bool visit(const OneOfConstraint &constraint)
{ {
unsigned int numValidated = 0; unsigned int numValidated = 0;
BOOST_FOREACH( const Schema &schema, constraint.schemas ) { BOOST_FOREACH( const Schema &schema, constraint.schemas ) {
if (validateSchema(schema)) { if (validateSchema(schema)) {
numValidated++; numValidated++;
} }
} }
if (numValidated != 1) { if (numValidated != 1) {
if (results) { if (results) {
results->pushError(context, "Failed to validate against exactly one child schema."); results->pushError(context, "Failed to validate against exactly one child schema.");
@@ -670,9 +670,9 @@ public:
return true; return true;
} }
/** /**
* @brief Validate against the pattern constraint represented by a * @brief Validate against the pattern constraint represented by a
* PatternConstraint object. * PatternConstraint object.
* *
* @param constraint Constraint that the target must validate against. * @param constraint Constraint that the target must validate against.
@@ -684,7 +684,7 @@ public:
if (!target.isString()) { if (!target.isString()) {
return true; return true;
} }
const boost::regex r(constraint.pattern, boost::regex::perl); const boost::regex r(constraint.pattern, boost::regex::perl);
if (!boost::regex_search(target.getString(), r)) { if (!boost::regex_search(target.getString(), r)) {
if (results) { if (results) {
@@ -692,10 +692,10 @@ public:
} }
return false; return false;
} }
return true; return true;
} }
/** /**
* @brief Validate against the properties, patternProperties, and * @brief Validate against the properties, patternProperties, and
* additionalProperties constraints represented by a * additionalProperties constraints represented by a
@@ -710,17 +710,17 @@ public:
if (!target.isObject()) { if (!target.isObject()) {
return true; return true;
} }
bool validated = true; bool validated = true;
// Validate each property in the target object // Validate each property in the target object
BOOST_FOREACH( const typename AdapterType::ObjectMember m, target.getObject() ) { BOOST_FOREACH( const typename AdapterType::ObjectMember m, target.getObject() ) {
const std::string propertyName = m.first; const std::string propertyName = m.first;
bool propertyNameMatched = false; bool propertyNameMatched = false;
ValidationVisitor<AdapterType> v(m.second, context + "." + m.first, strictTypes, results); ValidationVisitor<AdapterType> v(m.second, context + "." + m.first, strictTypes, results);
// Search for matching property name // Search for matching property name
PropertiesConstraint::PropertySchemaMap::const_iterator itr = PropertiesConstraint::PropertySchemaMap::const_iterator itr =
constraint.properties.find(propertyName); constraint.properties.find(propertyName);
@@ -737,7 +737,7 @@ public:
} }
} }
} }
// Search for a regex that matches the property name // Search for a regex that matches the property name
for (itr = constraint.patternProperties.begin(); itr != constraint.patternProperties.end(); ++itr) { for (itr = constraint.patternProperties.begin(); itr != constraint.patternProperties.end(); ++itr) {
const boost::regex r(itr->first, boost::regex::perl); const boost::regex r(itr->first, boost::regex::perl);
@@ -763,7 +763,7 @@ public:
if (propertyNameMatched) { if (propertyNameMatched) {
continue; continue;
} }
// If an additionalProperties schema has been provided, the values // If an additionalProperties schema has been provided, the values
// associated with unmatched property names should be validated // associated with unmatched property names should be validated
// against that schema. // against that schema.
@@ -784,10 +784,10 @@ public:
return false; return false;
} }
} }
return validated; return validated;
} }
/** /**
* @brief Validate against the required constraint represented by a * @brief Validate against the required constraint represented by a
* RequiredConstraint object. * RequiredConstraint object.
@@ -820,10 +820,10 @@ public:
} }
} }
} }
return validated; return validated;
} }
/** /**
* @brief Validate against the type constraint represented by a * @brief Validate against the type constraint represented by a
* TypeConstraint object. * TypeConstraint object.
@@ -878,25 +878,25 @@ public:
break; break;
} }
} }
BOOST_FOREACH( const Schema &schema, constraint.schemas ) { BOOST_FOREACH( const Schema &schema, constraint.schemas ) {
if (validateSchema(schema)) { if (validateSchema(schema)) {
return true; return true;
} }
} }
if (results) { if (results) {
results->pushError(context, "Value type not permitted by 'type' constraint."); results->pushError(context, "Value type not permitted by 'type' constraint.");
} }
return false; return false;
} }
/** /**
* @brief Validate the uniqueItems constraint represented by a * @brief Validate the uniqueItems constraint represented by a
* UniqueItems object. * UniqueItems object.
* *
* A uniqueItems constraint requires that each of the values in an array * A uniqueItems constraint requires that each of the values in an array
* are unique. Comparison is performed recursively. * are unique. Comparison is performed recursively.
* *
* @param constraint Constraint that the target must validate against * @param constraint Constraint that the target must validate against
@@ -908,9 +908,9 @@ public:
if (!target.isArray()) { if (!target.isArray()) {
return true; return true;
} }
bool validated = true; bool validated = true;
const typename AdapterType::Array targetArray = target.getArray(); const typename AdapterType::Array targetArray = target.getArray();
const typename AdapterType::Array::const_iterator end = targetArray.end(); const typename AdapterType::Array::const_iterator end = targetArray.end();
const typename AdapterType::Array::const_iterator secondLast = end - 1; const typename AdapterType::Array::const_iterator secondLast = end - 1;
@@ -932,10 +932,10 @@ public:
} }
++outerIndex; ++outerIndex;
} }
return validated; return validated;
} }
private: private:
/** /**
@@ -960,7 +960,7 @@ private:
/// Optional pointer to a ValidationResults object to be populated /// Optional pointer to a ValidationResults object to be populated
ValidationResults *results; ValidationResults *results;
/// Option to use strict type comparison /// Option to use strict type comparison
const bool strictTypes; const bool strictTypes;

View File

@@ -49,17 +49,17 @@ public:
/** /**
* @brief Validate a JSON document and optionally return the results. * @brief Validate a JSON document and optionally return the results.
* *
* When a ValidationResults object is provided via the \c results parameter, * When a ValidationResults object is provided via the \c results parameter,
* validation will be performed against each constraint defined by the * validation will be performed against each constraint defined by the
* schema, even if validation fails for some or all constraints. * schema, even if validation fails for some or all constraints.
* *
* If a pointer to a ValidationResults instance is not provided, validation * If a pointer to a ValidationResults instance is not provided, validation
* will only continue for as long as the constraints are validated * will only continue for as long as the constraints are validated
* successfully. * successfully.
* *
* @param target A rapidjson::Value to be validated. * @param target A rapidjson::Value to be validated.
* *
* @param results An optional pointer to a ValidationResults instance that * @param results An optional pointer to a ValidationResults instance that
* will be used to report validation errors. * will be used to report validation errors.
* *
* @returns true if validation succeeds, false otherwise. * @returns true if validation succeeds, false otherwise.
@@ -70,7 +70,7 @@ public:
// Construct a ValidationVisitor to perform validation at the root level // Construct a ValidationVisitor to perform validation at the root level
ValidationVisitor<AdapterType> v(target, std::string(), ValidationVisitor<AdapterType> v(target, std::string(),
strictTypes, results); strictTypes, results);
return v.validateSchema(*schema); return v.validateSchema(*schema);
} }
@@ -78,7 +78,7 @@ private:
/// Pointer to an internal copy of a schema to use for validation /// Pointer to an internal copy of a schema to use for validation
boost::scoped_ptr<const Schema> schema; boost::scoped_ptr<const Schema> schema;
/// Flag indicating that strict type comparisons should be used /// Flag indicating that strict type comparisons should be used
bool strictTypes; bool strictTypes;

View File

@@ -24,17 +24,17 @@ protected:
: path(path), : path(path),
strictGroup(strictGroup), strictGroup(strictGroup),
looseGroup(looseGroup) { } looseGroup(looseGroup) { }
const std::string path; const std::string path;
int strictGroup; int strictGroup;
int looseGroup; int looseGroup;
}; };
static void SetUpTestCase() { static void SetUpTestCase() {
const std::string testDataDir(TEST_DATA_DIR); const std::string testDataDir(TEST_DATA_DIR);
// //
// Each test is allocated to two groups. The first group is the strict // Each test is allocated to two groups. The first group is the strict
// comparison group. All test files that have been assigned to the same // comparison group. All test files that have been assigned to the same
@@ -50,11 +50,11 @@ protected:
jsonFiles.push_back(JsonFile(testDataDir + "array_doubles_1_2_3.json", 1, 1)); jsonFiles.push_back(JsonFile(testDataDir + "array_doubles_1_2_3.json", 1, 1));
jsonFiles.push_back(JsonFile(testDataDir + "array_integers_1_2_3.json", 1, 1)); jsonFiles.push_back(JsonFile(testDataDir + "array_integers_1_2_3.json", 1, 1));
jsonFiles.push_back(JsonFile(testDataDir + "array_strings_1_2_3.json", 2, 1)); jsonFiles.push_back(JsonFile(testDataDir + "array_strings_1_2_3.json", 2, 1));
jsonFiles.push_back(JsonFile(testDataDir + "array_doubles_1_2_3_4.json", 3, 2)); jsonFiles.push_back(JsonFile(testDataDir + "array_doubles_1_2_3_4.json", 3, 2));
jsonFiles.push_back(JsonFile(testDataDir + "array_integers_1_2_3_4.json", 3, 2)); jsonFiles.push_back(JsonFile(testDataDir + "array_integers_1_2_3_4.json", 3, 2));
jsonFiles.push_back(JsonFile(testDataDir + "array_strings_1_2_3_4.json", 4, 2)); jsonFiles.push_back(JsonFile(testDataDir + "array_strings_1_2_3_4.json", 4, 2));
jsonFiles.push_back(JsonFile(testDataDir + "array_doubles_10_20_30_40.json", 5, 3)); jsonFiles.push_back(JsonFile(testDataDir + "array_doubles_10_20_30_40.json", 5, 3));
jsonFiles.push_back(JsonFile(testDataDir + "array_integers_10_20_30_40.json", 5, 3)); jsonFiles.push_back(JsonFile(testDataDir + "array_integers_10_20_30_40.json", 5, 3));
jsonFiles.push_back(JsonFile(testDataDir + "array_strings_10_20_30_40.json", 6, 3)); jsonFiles.push_back(JsonFile(testDataDir + "array_strings_10_20_30_40.json", 6, 3));
@@ -64,13 +64,13 @@ protected:
static void testComparison() static void testComparison()
{ {
std::vector<JsonFile>::const_iterator outerItr, innerItr; std::vector<JsonFile>::const_iterator outerItr, innerItr;
for(outerItr = jsonFiles.begin(); outerItr != jsonFiles.end() - 1; ++outerItr) { for(outerItr = jsonFiles.begin(); outerItr != jsonFiles.end() - 1; ++outerItr) {
for(innerItr = outerItr; innerItr != jsonFiles.end(); ++innerItr) { for(innerItr = outerItr; innerItr != jsonFiles.end(); ++innerItr) {
const bool expectedStrict = (outerItr->strictGroup == innerItr->strictGroup); const bool expectedStrict = (outerItr->strictGroup == innerItr->strictGroup);
const bool expectedLoose = (outerItr->looseGroup == innerItr->looseGroup); const bool expectedLoose = (outerItr->looseGroup == innerItr->looseGroup);
typename AdapterTraits<Adapter1>::DocumentType document1; typename AdapterTraits<Adapter1>::DocumentType document1;
ASSERT_TRUE( valijson::utils::loadDocument(outerItr->path, document1) ); ASSERT_TRUE( valijson::utils::loadDocument(outerItr->path, document1) );
const Adapter1 adapter1(document1); const Adapter1 adapter1(document1);
@@ -96,7 +96,7 @@ protected:
<< outerItr->path << "' " << outerItr->path << "' "
<< "with strict comparison enabled"; << "with strict comparison enabled";
} }
EXPECT_EQ(expectedLoose, adapter1.equalTo(adapter2, false)) EXPECT_EQ(expectedLoose, adapter1.equalTo(adapter2, false))
<< "Comparing '" << outerItr->path << "' to '" << "Comparing '" << outerItr->path << "' to '"
<< innerItr->path << "' " << innerItr->path << "' "
@@ -108,7 +108,7 @@ protected:
} }
} }
} }
static std::vector<JsonFile> jsonFiles; static std::vector<JsonFile> jsonFiles;
}; };

View File

@@ -11,5 +11,5 @@ class TestDereferenceCallback : public ::testing::Test
TEST_F(TestDereferenceCallback, Basics) TEST_F(TestDereferenceCallback, Basics)
{ {
} }

View File

@@ -28,10 +28,10 @@ TEST_F(TestJsonCppAdapter, BasicArrayIteration)
ASSERT_ANY_THROW( adapter.getDouble() ); ASSERT_ANY_THROW( adapter.getDouble() );
ASSERT_ANY_THROW( adapter.getObject() ); ASSERT_ANY_THROW( adapter.getObject() );
ASSERT_ANY_THROW( adapter.getString() ); ASSERT_ANY_THROW( adapter.getString() );
// Ensure that the array contains the expected number of elements // Ensure that the array contains the expected number of elements
EXPECT_EQ( numElements, adapter.getArray().size() ); EXPECT_EQ( numElements, adapter.getArray().size() );
// Ensure that the elements are returned in the order they were inserted // Ensure that the elements are returned in the order they were inserted
unsigned int expectedValue = 0; unsigned int expectedValue = 0;
BOOST_FOREACH( const valijson::adapters::JsonCppAdapter value, adapter.getArray() ) { BOOST_FOREACH( const valijson::adapters::JsonCppAdapter value, adapter.getArray() ) {
@@ -39,7 +39,7 @@ TEST_F(TestJsonCppAdapter, BasicArrayIteration)
EXPECT_EQ( double(expectedValue), value.getNumber() ); EXPECT_EQ( double(expectedValue), value.getNumber() );
expectedValue++; expectedValue++;
} }
// Ensure that the correct number of elements were iterated over // Ensure that the correct number of elements were iterated over
EXPECT_EQ(numElements, expectedValue); EXPECT_EQ(numElements, expectedValue);
} }
@@ -64,10 +64,10 @@ TEST_F(TestJsonCppAdapter, BasicObjectIteration)
ASSERT_ANY_THROW( adapter.getBool() ); ASSERT_ANY_THROW( adapter.getBool() );
ASSERT_ANY_THROW( adapter.getDouble() ); ASSERT_ANY_THROW( adapter.getDouble() );
ASSERT_ANY_THROW( adapter.getString() ); ASSERT_ANY_THROW( adapter.getString() );
// Ensure that the object contains the expected number of members // Ensure that the object contains the expected number of members
EXPECT_EQ( numElements, adapter.getObject().size() ); EXPECT_EQ( numElements, adapter.getObject().size() );
// Ensure that the members are returned in the order they were inserted // Ensure that the members are returned in the order they were inserted
unsigned int expectedValue = 0; unsigned int expectedValue = 0;
BOOST_FOREACH( const valijson::adapters::JsonCppAdapter::ObjectMember member, adapter.getObject() ) { BOOST_FOREACH( const valijson::adapters::JsonCppAdapter::ObjectMember member, adapter.getObject() ) {
@@ -76,7 +76,7 @@ TEST_F(TestJsonCppAdapter, BasicObjectIteration)
EXPECT_EQ( double(expectedValue), member.second.getDouble() ); EXPECT_EQ( double(expectedValue), member.second.getDouble() );
expectedValue++; expectedValue++;
} }
// Ensure that the correct number of elements were iterated over // Ensure that the correct number of elements were iterated over
EXPECT_EQ( numElements, expectedValue ); EXPECT_EQ( numElements, expectedValue );
} }

View File

@@ -30,10 +30,10 @@ TEST_F(TestPropertyTreeAdapter, BasicArrayIteration)
ASSERT_ANY_THROW( adapter.getDouble() ); ASSERT_ANY_THROW( adapter.getDouble() );
ASSERT_ANY_THROW( adapter.getObject() ); ASSERT_ANY_THROW( adapter.getObject() );
ASSERT_ANY_THROW( adapter.getString() ); ASSERT_ANY_THROW( adapter.getString() );
// Ensure that the array contains the expected number of elements // Ensure that the array contains the expected number of elements
EXPECT_EQ( numElements, adapter.getArray().size() ); EXPECT_EQ( numElements, adapter.getArray().size() );
// Ensure that the elements are returned in the order they were inserted // Ensure that the elements are returned in the order they were inserted
unsigned int expectedValue = 0; unsigned int expectedValue = 0;
BOOST_FOREACH( const valijson::adapters::PropertyTreeAdapter value, adapter.getArray() ) { BOOST_FOREACH( const valijson::adapters::PropertyTreeAdapter value, adapter.getArray() ) {
@@ -43,7 +43,7 @@ TEST_F(TestPropertyTreeAdapter, BasicArrayIteration)
EXPECT_EQ( double(expectedValue), value.asDouble() ); EXPECT_EQ( double(expectedValue), value.asDouble() );
expectedValue++; expectedValue++;
} }
// Ensure that the correct number of elements were iterated over // Ensure that the correct number of elements were iterated over
EXPECT_EQ(numElements, expectedValue); EXPECT_EQ(numElements, expectedValue);
} }
@@ -69,10 +69,10 @@ TEST_F(TestPropertyTreeAdapter, BasicObjectIteration)
ASSERT_ANY_THROW( adapter.getBool() ); ASSERT_ANY_THROW( adapter.getBool() );
ASSERT_ANY_THROW( adapter.getDouble() ); ASSERT_ANY_THROW( adapter.getDouble() );
ASSERT_ANY_THROW( adapter.getString() ); ASSERT_ANY_THROW( adapter.getString() );
// Ensure that the object contains the expected number of members // Ensure that the object contains the expected number of members
EXPECT_EQ( numElements, adapter.getObject().size() ); EXPECT_EQ( numElements, adapter.getObject().size() );
// Ensure that the members are returned in the order they were inserted // Ensure that the members are returned in the order they were inserted
unsigned int expectedValue = 0; unsigned int expectedValue = 0;
BOOST_FOREACH( const valijson::adapters::PropertyTreeAdapter::ObjectMember member, adapter.getObject() ) { BOOST_FOREACH( const valijson::adapters::PropertyTreeAdapter::ObjectMember member, adapter.getObject() ) {
@@ -83,7 +83,7 @@ TEST_F(TestPropertyTreeAdapter, BasicObjectIteration)
EXPECT_EQ( double(expectedValue), member.second.asDouble() ); EXPECT_EQ( double(expectedValue), member.second.asDouble() );
expectedValue++; expectedValue++;
} }
// Ensure that the correct number of elements were iterated over // Ensure that the correct number of elements were iterated over
EXPECT_EQ( numElements, expectedValue ); EXPECT_EQ( numElements, expectedValue );
} }

View File

@@ -31,10 +31,10 @@ TEST_F(TestRapidJsonAdapter, BasicArrayIteration)
ASSERT_ANY_THROW( adapter.getDouble() ); ASSERT_ANY_THROW( adapter.getDouble() );
ASSERT_ANY_THROW( adapter.getObject() ); ASSERT_ANY_THROW( adapter.getObject() );
ASSERT_ANY_THROW( adapter.getString() ); ASSERT_ANY_THROW( adapter.getString() );
// Ensure that the array contains the expected number of elements // Ensure that the array contains the expected number of elements
EXPECT_EQ( numElements, adapter.getArray().size() ); EXPECT_EQ( numElements, adapter.getArray().size() );
// Ensure that the elements are returned in the order they were inserted // Ensure that the elements are returned in the order they were inserted
unsigned int expectedValue = 0; unsigned int expectedValue = 0;
BOOST_FOREACH( const valijson::adapters::RapidJsonAdapter value, adapter.getArray() ) { BOOST_FOREACH( const valijson::adapters::RapidJsonAdapter value, adapter.getArray() ) {
@@ -42,7 +42,7 @@ TEST_F(TestRapidJsonAdapter, BasicArrayIteration)
EXPECT_EQ( double(expectedValue), value.getDouble() ); EXPECT_EQ( double(expectedValue), value.getDouble() );
expectedValue++; expectedValue++;
} }
// Ensure that the correct number of elements were iterated over // Ensure that the correct number of elements were iterated over
EXPECT_EQ(numElements, expectedValue); EXPECT_EQ(numElements, expectedValue);
} }
@@ -70,10 +70,10 @@ TEST_F(TestRapidJsonAdapter, BasicObjectIteration)
ASSERT_ANY_THROW( adapter.getBool() ); ASSERT_ANY_THROW( adapter.getBool() );
ASSERT_ANY_THROW( adapter.getDouble() ); ASSERT_ANY_THROW( adapter.getDouble() );
ASSERT_ANY_THROW( adapter.getString() ); ASSERT_ANY_THROW( adapter.getString() );
// Ensure that the object contains the expected number of members // Ensure that the object contains the expected number of members
EXPECT_EQ( numElements, adapter.getObject().size() ); EXPECT_EQ( numElements, adapter.getObject().size() );
// Ensure that the members are returned in the order they were inserted // Ensure that the members are returned in the order they were inserted
unsigned int expectedValue = 0; unsigned int expectedValue = 0;
BOOST_FOREACH( const valijson::adapters::RapidJsonAdapter::ObjectMember member, adapter.getObject() ) { BOOST_FOREACH( const valijson::adapters::RapidJsonAdapter::ObjectMember member, adapter.getObject() ) {
@@ -82,7 +82,7 @@ TEST_F(TestRapidJsonAdapter, BasicObjectIteration)
EXPECT_EQ( double(expectedValue), member.second.getDouble() ); EXPECT_EQ( double(expectedValue), member.second.getDouble() );
expectedValue++; expectedValue++;
} }
// Ensure that the correct number of elements were iterated over // Ensure that the correct number of elements were iterated over
EXPECT_EQ( numElements, expectedValue ); EXPECT_EQ( numElements, expectedValue );
} }

View File

@@ -35,53 +35,53 @@ TEST_F(TestValidationErrors, AllOfConstraintFailure)
rapidjson::Document schemaDocument; rapidjson::Document schemaDocument;
ASSERT_TRUE( loadDocument(TEST_DATA_DIR "/schemas/allof_integers_and_numbers.schema.json", schemaDocument) ); ASSERT_TRUE( loadDocument(TEST_DATA_DIR "/schemas/allof_integers_and_numbers.schema.json", schemaDocument) );
RapidJsonAdapter schemaAdapter(schemaDocument); RapidJsonAdapter schemaAdapter(schemaDocument);
// Parse schema document // Parse schema document
Schema schema; Schema schema;
SchemaParser schemaParser; SchemaParser schemaParser;
ASSERT_NO_THROW( schemaParser.populateSchema(schemaAdapter, schema) ); ASSERT_NO_THROW( schemaParser.populateSchema(schemaAdapter, schema) );
// Load test document // Load test document
rapidjson::Document testDocument; rapidjson::Document testDocument;
ASSERT_TRUE( loadDocument(TEST_DATA_DIR "/documents/array_doubles_1_2_3.json", testDocument) ); ASSERT_TRUE( loadDocument(TEST_DATA_DIR "/documents/array_doubles_1_2_3.json", testDocument) );
RapidJsonAdapter testAdapter(testDocument); RapidJsonAdapter testAdapter(testDocument);
Validator validator(schema); Validator validator(schema);
ValidationResults results; ValidationResults results;
EXPECT_FALSE( validator.validate(testAdapter, &results) ); EXPECT_FALSE( validator.validate(testAdapter, &results) );
ValidationResults::Error error; ValidationResults::Error error;
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "[0]", error.context ); EXPECT_EQ( "[0]", error.context );
EXPECT_EQ( "Value type not permitted by 'type' constraint.", error.description ); EXPECT_EQ( "Value type not permitted by 'type' constraint.", error.description );
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "", error.context ); EXPECT_EQ( "", error.context );
EXPECT_EQ( "Failed to validate item #0 in array.", error.description ); EXPECT_EQ( "Failed to validate item #0 in array.", error.description );
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "[1]", error.context ); EXPECT_EQ( "[1]", error.context );
EXPECT_EQ( "Value type not permitted by 'type' constraint.", error.description ); EXPECT_EQ( "Value type not permitted by 'type' constraint.", error.description );
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "", error.context ); EXPECT_EQ( "", error.context );
EXPECT_EQ( "Failed to validate item #1 in array.", error.description ); EXPECT_EQ( "Failed to validate item #1 in array.", error.description );
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "[2]", error.context ); EXPECT_EQ( "[2]", error.context );
EXPECT_EQ( "Value type not permitted by 'type' constraint.", error.description ); EXPECT_EQ( "Value type not permitted by 'type' constraint.", error.description );
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "", error.context ); EXPECT_EQ( "", error.context );
EXPECT_EQ( "Failed to validate item #2 in array.", error.description ); EXPECT_EQ( "Failed to validate item #2 in array.", error.description );
EXPECT_TRUE( results.popError(error) ); EXPECT_TRUE( results.popError(error) );
EXPECT_EQ( "", error.context ); EXPECT_EQ( "", error.context );
EXPECT_EQ( "Failed to validate against child schema at index #0 of allOf constraint.", error.description ); EXPECT_EQ( "Failed to validate against child schema at index #0 of allOf constraint.", error.description );
EXPECT_FALSE( results.popError(error) ); EXPECT_FALSE( results.popError(error) );
while (results.popError(error)) { while (results.popError(error)) {
std::cerr << error.context << std::endl; std::cerr << error.context << std::endl;
std::cerr << error.description << std::endl; std::cerr << error.description << std::endl;

View File

@@ -32,21 +32,21 @@ protected:
{ {
std::string currentTestCase; std::string currentTestCase;
std::string currentTest; std::string currentTest;
try { try {
// Load test document // Load test document
typename AdapterTraits<AdapterType>::DocumentType document; typename AdapterTraits<AdapterType>::DocumentType document;
ASSERT_TRUE( valijson::utils::loadDocument(testFile, document) ); ASSERT_TRUE( valijson::utils::loadDocument(testFile, document) );
AdapterType testCases(document); AdapterType testCases(document);
ASSERT_TRUE( testCases.isArray() ); ASSERT_TRUE( testCases.isArray() );
// Process each test case in the file // Process each test case in the file
BOOST_FOREACH( const AdapterType testCase, testCases.getArray() ) { BOOST_FOREACH( const AdapterType testCase, testCases.getArray() ) {
currentTestCase.clear(); currentTestCase.clear();
currentTest.clear(); currentTest.clear();
// Ensure that testCase is an object // Ensure that testCase is an object
ASSERT_TRUE( testCase.isObject() ); ASSERT_TRUE( testCase.isObject() );
const typename AdapterType::Object object = testCase.getObject(); const typename AdapterType::Object object = testCase.getObject();
@@ -55,24 +55,24 @@ protected:
typename AdapterType::Object::const_iterator itr = object.find("description"); typename AdapterType::Object::const_iterator itr = object.find("description");
ASSERT_NE( object.end(), itr ); ASSERT_NE( object.end(), itr );
currentTestCase = itr->second.getString(); currentTestCase = itr->second.getString();
// Ensure that 'schema' property is present // Ensure that 'schema' property is present
itr = object.find("schema"); itr = object.find("schema");
ASSERT_NE( object.end(), itr ); ASSERT_NE( object.end(), itr );
// Parse schema // Parse schema
Schema schema; Schema schema;
SchemaParser parser(version); SchemaParser parser(version);
parser.populateSchema(itr->second, schema); parser.populateSchema(itr->second, schema);
// For each test in the 'tests' array // For each test in the 'tests' array
itr = object.find("tests"); itr = object.find("tests");
ASSERT_NE( object.end(), itr ); ASSERT_NE( object.end(), itr );
ASSERT_TRUE( itr->second.isArray() ); ASSERT_TRUE( itr->second.isArray() );
BOOST_FOREACH( const AdapterType test, itr->second.getArray() ) { BOOST_FOREACH( const AdapterType test, itr->second.getArray() ) {
const bool strict = itr->second.hasStrictTypes(); const bool strict = itr->second.hasStrictTypes();
ASSERT_TRUE( test.isObject() ); ASSERT_TRUE( test.isObject() );
const typename AdapterType::Object testObject = test.getObject(); const typename AdapterType::Object testObject = test.getObject();
@@ -84,12 +84,12 @@ protected:
testItr = testObject.find("description"); testItr = testObject.find("description");
ASSERT_NE( testObject.end(), testItr ); ASSERT_NE( testObject.end(), testItr );
currentTest = testItr->second.getString(); currentTest = testItr->second.getString();
testItr = testObject.find("data"); testItr = testObject.find("data");
ASSERT_NE( testObject.end(), testItr ); ASSERT_NE( testObject.end(), testItr );
Validator validator(schema); Validator validator(schema);
validator.setStrict(strict); validator.setStrict(strict);
EXPECT_EQ( shouldValidate, validator.validate(testItr->second, NULL) ) EXPECT_EQ( shouldValidate, validator.validate(testItr->second, NULL) )
<< "Failed while testing validate() function in '" << "Failed while testing validate() function in '"
<< currentTest << "' of test case '" << currentTest << "' of test case '"
@@ -97,7 +97,7 @@ protected:
<< AdapterTraits<AdapterType>::adapterName() << "'"; << AdapterTraits<AdapterType>::adapterName() << "'";
} }
} }
} catch (const std::exception &e) { } catch (const std::exception &e) {
FAIL() << "Exception thrown with message '" << e.what() FAIL() << "Exception thrown with message '" << e.what()
<< "' in '" << currentTest << "' of test case '" << "' in '" << currentTest << "' of test case '"
@@ -105,19 +105,19 @@ protected:
<< AdapterTraits<AdapterType>::adapterName() << "'"; << AdapterTraits<AdapterType>::adapterName() << "'";
} }
} }
void processTestFile(const std::string &testFile, void processTestFile(const std::string &testFile,
const SchemaParser::Version version) const SchemaParser::Version version)
{ {
processTestFile<valijson::adapters::JsonCppAdapter>(testFile, version); processTestFile<valijson::adapters::JsonCppAdapter>(testFile, version);
processTestFile<valijson::adapters::RapidJsonAdapter>(testFile, version); processTestFile<valijson::adapters::RapidJsonAdapter>(testFile, version);
} }
void processDraft3TestFile(const std::string &testFile) void processDraft3TestFile(const std::string &testFile)
{ {
return processTestFile(testFile, SchemaParser::kDraft3); return processTestFile(testFile, SchemaParser::kDraft3);
} }
void processDraft4TestFile(const std::string &testFile) void processDraft4TestFile(const std::string &testFile)
{ {
return processTestFile(testFile, SchemaParser::kDraft4); return processTestFile(testFile, SchemaParser::kDraft4);