Esempio n. 1
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Object)
            {
                return(results);
            }

            var missingProperties = new List <string>();
            var obj = context.Instance.Object;

            foreach (var propertyName in this)
            {
                if (!obj.ContainsKey(propertyName))
                {
                    missingProperties.Add(propertyName);
                }
            }

            if (missingProperties.Any())
            {
                results.IsValid = false;
                results.Keyword = Name;
                results.AdditionalInfo["missing"] = missingProperties.ToJson();
            }

            return(results);
        }
Esempio n. 2
0
        /// <summary>
        /// Provides the validation logic for this dependency.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(PropertyName, context)
            {
                Keyword = $"{context.Misc["dependencyParent"]}/{PropertyName}"
            };

            if (context.Instance.Type != JsonValueType.Object)
            {
                Log.Schema("Instance not an object; not applicable");
                return(results);
            }

            if (!context.Instance.Object.ContainsKey(PropertyName))
            {
                Log.Schema($"Property {PropertyName} not found; not applicable");
                return(results);
            }

            var missingProperties = _dependencies.Except(context.Instance.Object.Keys).ToList();

            if (missingProperties.Any())
            {
                Log.Schema($"Properties {missingProperties} not found but required by property {PropertyName}");
                results.IsValid = false;
                results.AdditionalInfo["required"]   = missingProperties.ToJson();
                results.AdditionalInfo["dependency"] = PropertyName;
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var nestedResults = this.Select((s, i) =>
            {
                var newContext = new SchemaValidationContext
                {
                    BaseUri              = context.BaseUri,
                    Instance             = context.Instance,
                    Root                 = context.Root,
                    BaseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name, i.ToString()),
                    RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name, i.ToString()),
                    InstanceLocation     = context.InstanceLocation
                };
                var result = s.Validate(newContext);
                context.EvaluatedPropertyNames.AddRange(newContext.EvaluatedPropertyNames);
                return(result);
            }).ToList();

            var results = new SchemaValidationResults(Name, context)
            {
                NestedResults = nestedResults
            };

            if (nestedResults.Any(r => !r.IsValid))
            {
                results.IsValid = false;
                results.Keyword = Name;
            }

            return(results);
        }
Esempio n. 4
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Object)
            {
                return(results);
            }

            var missingProperties = new List <string>();
            var obj = context.Instance.Object;

            foreach (var propertyName in this)
            {
                if (!obj.ContainsKey(propertyName))
                {
                    if (JsonSchemaOptions.OutputFormat == SchemaValidationOutputFormat.Flag)
                    {
                        results.IsValid = false;
                        return(results);
                    }
                    missingProperties.Add(propertyName);
                }
            }

            if (missingProperties.Any())
            {
                results.IsValid = false;
                results.AdditionalInfo["properties"] = missingProperties.ToJson();
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 5
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Number)
            {
                return(results);
            }

            var keyword = context.Local.Get <MinimumKeyword>();

            if (keyword == null)
            {
                return(results);
            }

            if (!Value)
            {
                return(results);
            }

            if (context.Instance.Number <= keyword.Value)
            {
                results.IsValid = false;
                results.AdditionalInfo["lowerBound"] = keyword.Value;
                results.AdditionalInfo["actual"]     = context.Instance;
            }

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Array)
            {
                Log.Schema(() => "Instance not an array; not applicable");
                return(results);
            }

            if (!context.Misc.TryGetValue("containsCount", out var value))
            {
                Log.Schema(() => "`contains` keyword not present; not applicable");
                return(results);
            }

            var containsCount = (int)value;

            if (containsCount > Value)
            {
                Log.Schema(() => $"Required no more than {Value} matching items, but {containsCount} found");
                results.IsValid = false;
                results.AdditionalInfo["actual"]     = containsCount;
                results.AdditionalInfo["upperBound"] = Value;
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 7
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            var newContext = new SchemaValidationContext(context)
            {
                BaseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name),
                RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name),
            };
            var nestedResults = Value.Validate(newContext);

            results.IsValid = !nestedResults.IsValid;

            if (!results.IsValid)
            {
                Log.Schema("Subschema succeeded; inverting result");
                results.ErrorMessage = ErrorTemplate;
            }

            if (JsonSchemaOptions.OutputFormat != SchemaValidationOutputFormat.Flag &&
                JsonSchemaOptions.ShouldReportChildErrors(this, context))
            {
                results.NestedResults = new List <SchemaValidationResults> {
                    nestedResults
                }
            }
            ;

            return(results);
        }
Esempio n. 8
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (Resolved == null)
            {
                _ResolveReference(context);
                if (Resolved == null)
                {
                    throw new SchemaReferenceNotFoundException(context.RelativeLocation);
                }
            }

            var results = new SchemaValidationResults(Name, context);

            var newContext = new SchemaValidationContext
            {
                BaseUri              = _resolvedRoot.DocumentPath,
                Instance             = context.Instance,
                Root                 = _resolvedRoot ?? context.Root,
                BaseRelativeLocation = _resolvedFragment,
                RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name),
                InstanceLocation     = context.InstanceLocation
            };
            var nestedResults = Resolved.Validate(newContext);

            if (!nestedResults.IsValid)
            {
                results.IsValid = false;
                results.Keyword = Name;
            }

            return(results);
        }
Esempio n. 9
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Number)
            {
                Log.Schema("Instance not a number; not applicable");
                return(results);
            }

            var keyword = context.Local.Get <MaximumKeyword>();

            if (keyword == null)
            {
                Log.Schema("`maximum` keyword not defined; not applicable");
                return(results);
            }

            if (!Value)
            {
                Log.Schema("Not exclusive; see `maximum` results");
                return(results);
            }

            if (context.Instance.Number >= keyword.Value)
            {
                Log.Schema($"Bounds check failed: {context.Instance.Number} >= {keyword.Value}");
                results.IsValid = false;
                results.AdditionalInfo["upperBound"] = keyword.Value;
                results.AdditionalInfo["actual"]     = context.Instance;
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 10
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context)
            {
                AnnotationValue = Value.Key
            };


            if (!JsonSchemaOptions.ValidateFormatKeyword)
            {
                return(results);
            }
            if (context.Instance.Type != JsonValueType.String)
            {
                return(results);
            }

            var format = Value;

            if (!format.Validate(context.Instance.String))
            {
                results.IsValid = false;
                results.AdditionalInfo["actual"]        = context.Instance;
                results.AdditionalInfo["format"]        = format.Key;
                results.AdditionalInfo["isKnownFormat"] = format.IsKnown;
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }
            ;

            return(results);
        }
Esempio n. 11
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var valid = new SchemaValidationResults(Name, context)
            {
                AnnotationValue = Value.Key
            };


            if (!JsonSchemaOptions.ValidateFormatKeyword)
            {
                return(valid);
            }
            if (context.Instance.Type != JsonValueType.String)
            {
                return(valid);
            }

            var format = Value;

            if (!format.Validate(context.Instance.String))
            {
                return new SchemaValidationResults(Name, context)
                       {
                           IsValid        = false,
                           AdditionalInfo =
                           {
                               ["format"]        = format.Key,
                               ["isKnownFormat"] = format.IsKnown
                           }
                       }
            }
            ;

            return(valid);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Array)
            {
                Log.Schema(() => "Instance not an array; not applicable");
                return(results);
            }

            if (!Value)
            {
                Log.Schema(() => "Keyword configured to not check for uniqueness");
                return(results);
            }

            if (context.Instance.Array.Distinct().Count() != context.Instance.Array.Count)
            {
                Log.Schema(() => "Instance contains duplicate items");
                results.IsValid = false;
                results.AdditionalInfo["value"] = context.Instance;
                results.ErrorMessage            = ErrorTemplate;
            }

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            var baseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name);
            var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);
            var nestedResults        = this.Select(d =>
            {
                var newContext = new SchemaValidationContext
                {
                    BaseUri              = context.BaseUri,
                    Instance             = context.Instance,
                    Root                 = context.Root,
                    BaseRelativeLocation = baseRelativeLocation,
                    RelativeLocation     = relativeLocation,
                    InstanceLocation     = context.InstanceLocation
                };
                return(d.Validate(newContext));
            }).ToList();

            if (nestedResults.Any(r => !r.IsValid))
            {
                results.IsValid       = false;
                results.Keyword       = Name;
                results.NestedResults = nestedResults;
            }

            return(results);
        }
Esempio n. 14
0
        /// <summary>
        /// Provides the validation logic for this dependency.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(PropertyName, context);

            if (context.Instance.Type != JsonValueType.Object)
            {
                return(results);
            }
            if (!context.Instance.Object.ContainsKey(PropertyName))
            {
                return(results);
            }

            var newContext = new SchemaValidationContext
            {
                Instance             = context.Instance,
                Root                 = context.Root,
                BaseUri              = context.BaseUri,
                BaseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(PropertyName),
                RelativeLocation     = context.RelativeLocation.CloneAndAppend(PropertyName),
                InstanceLocation     = context.InstanceLocation
            };

            var nestedResult = _schema.Validate(newContext);

            if (!nestedResult.IsValid)
            {
                results.IsValid = false;
                results.Keyword = $"dependencies.{PropertyName}";
                results.NestedResults.Add(nestedResult);
            }

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Number)
            {
                return(results);
            }

            var keyword = context.Local.Get <MaximumKeyword>();

            if (keyword == null)
            {
                return(results);
            }

            if (!Value)
            {
                return(results);
            }

            if (context.Instance.Number >= keyword.Value)
            {
                results.IsValid = false;
                results.Keyword = Name;
                results.AdditionalInfo["expected"]    = keyword.Value;
                results.AdditionalInfo["isExclusive"] = Value;
                results.AdditionalInfo["actual"]      = context.Instance;
            }

            return(results);
        }
Esempio n. 16
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            var newContext = new SchemaValidationContext
            {
                BaseUri              = context.BaseUri,
                Instance             = context.Instance,
                Root                 = context.Root,
                BaseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name),
                RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name),
                InstanceLocation     = context.InstanceLocation
            };
            var nestedResults = Value.Validate(newContext);

            context.EvaluatedPropertyNames.AddRange(newContext.EvaluatedPropertyNames);

            if (nestedResults.IsValid)
            {
                results.IsValid = false;
                results.Keyword = Name;
            }

            return(results);
        }
Esempio n. 17
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (Resolved == null)
            {
                _ResolveReference(context);
                if (Resolved == null)
                {
                    throw new SchemaReferenceNotFoundException(context.RelativeLocation);
                }

                Log.Schema("Reference found");
            }

            var results = new SchemaValidationResults(Name, context);

            var newContext = new SchemaValidationContext(context)
            {
                BaseUri              = _resolvedRoot?.DocumentPath,
                Instance             = context.Instance,
                Root                 = _resolvedRoot ?? context.Root,
                BaseRelativeLocation = _resolvedFragment?.WithHash(),
                RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name),
            };
            var nestedResults = Resolved.Validate(newContext);

            results.IsValid = nestedResults.IsValid;
            results.NestedResults.Add(nestedResults);

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Array)
            {
                return(results);
            }
            if (!context.Misc.TryGetValue("containsCount", out var value))
            {
                return(results);
            }

            var containsCount = (int)value;

            if (containsCount > Value)
            {
                results.IsValid = false;
                results.AdditionalInfo["actual"]     = containsCount;
                results.AdditionalInfo["upperBound"] = Value;
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 19
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (context.Instance.Type != JsonValueType.String)
            {
                Log.Schema(() => "Instance not a string; not applicable");
                return(new SchemaValidationResults(Name, context));
            }

            var baseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name);
            var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);
            var nestedResult         = Value.Validate(new SchemaValidationContext(context)
            {
                BaseRelativeLocation = baseRelativeLocation,
                RelativeLocation     = relativeLocation,
                InstanceLocation     = context.InstanceLocation.CloneAndAppend(Name),
            });

            var results = new SchemaValidationResults(Name, context)
            {
                IsValid = nestedResult.IsValid
            };

            if (context.Options.OutputFormat != SchemaValidationOutputFormat.Flag)
            {
                results.NestedResults = new List <SchemaValidationResults> {
                    nestedResult
                }
            }
            ;

            return(results);
        }
Esempio n. 20
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (context.Instance.Type != JsonValueType.Array)
            {
                return(new SchemaValidationResults(Name, context));
            }

            var nestedResults = new List <SchemaValidationResults>();
            var array         = context.Instance.Array;

            if (context.LastEvaluatedIndex < array.Count)
            {
                nestedResults.AddRange(array.Skip(context.LastEvaluatedIndex).Select((jv, i) =>
                {
                    var baseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name);
                    var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);
                    var newContext           = new SchemaValidationContext(context)
                    {
                        Instance             = jv,
                        BaseRelativeLocation = baseRelativeLocation,
                        RelativeLocation     = relativeLocation,
                        InstanceLocation     = context.InstanceLocation.CloneAndAppend(i.ToString()),
                    };
                    var localResults                    = Value.Validate(newContext);
                    context.LastEvaluatedIndex          = Math.Max(context.LastEvaluatedIndex, i);
                    context.LocalTierLastEvaluatedIndex = Math.Max(context.LastEvaluatedIndex, i);
                    return(localResults);
                }));
            }

            SchemaValidationResults results;

            if (JsonSchemaOptions.OutputFormat == SchemaValidationOutputFormat.Flag)
            {
                results = new SchemaValidationResults(Name, context)
                {
                    IsValid = nestedResults.All(r => r.IsValid)
                }
            }
            ;
            else
            {
                var resultsList = nestedResults.ToList();
                results = new SchemaValidationResults(Name, context)
                {
                    NestedResults = resultsList,
                    IsValid       = resultsList.All(r => r.IsValid)
                };
            }

            if (nestedResults.Any(r => !r.IsValid))
            {
                results.IsValid      = false;
                results.Keyword      = Name;
                results.ErrorMessage = ErrorTemplate;
            }

            return(results);
        }
Esempio n. 21
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (context.Instance.Type != JsonValueType.Array)
            {
                return(new SchemaValidationResults(Name, context));
            }

            var baseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name);
            var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);
            var nestedResults        = context.Instance.Array.Select((jv, i) =>
            {
                var newContext = new SchemaValidationContext(context)
                {
                    Instance             = jv,
                    BaseRelativeLocation = baseRelativeLocation,
                    RelativeLocation     = relativeLocation,
                    InstanceLocation     = context.InstanceLocation.CloneAndAppend(i.ToString()),
                };
                var result = Value.Validate(newContext);
                return(result);
            });

            SchemaValidationResults results;

            if (JsonSchemaOptions.OutputFormat == SchemaValidationOutputFormat.Flag &&
                context.Local.Get <MinContainsKeyword>() == null &&
                context.Local.Get <MaxContainsKeyword>() == null)
            {
                results = new SchemaValidationResults(Name, context)
                {
                    IsValid = nestedResults.Any(r => r.IsValid)
                }
            }
            ;
            else
            {
                var resultsList = nestedResults.ToList();
                results = new SchemaValidationResults(Name, context)
                {
                    NestedResults = resultsList
                };

                var matchedIndices = resultsList.IndexesWhere(r => r.IsValid).Select(i => (JsonValue)i).ToJson();
                context.Misc["containsCount"] = matchedIndices.Count;

                if (!matchedIndices.Any())
                {
                    results.IsValid      = false;
                    results.Keyword      = Name;
                    results.ErrorMessage = ErrorTemplate;
                }
                else
                {
                    results.AdditionalInfo["matchedIndices"] = matchedIndices;
                }
            }

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var results = new SchemaValidationResults(Name, context);

            if (context.Instance.Type != JsonValueType.Object)
            {
                Log.Schema(() => "Instance not an object; not applicable");
                return(results);
            }

            var baseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name);
            var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);
            var valid                = true;
            var reportChildErrors    = context.Options.ShouldReportChildErrors(this, context);
            var nestedResults        = new List <SchemaValidationResults>();
            var invalidPropertyNames = new JsonArray();

            foreach (var propertyName in context.Instance.Object.Keys)
            {
                var newContext = new SchemaValidationContext(context)
                {
                    Instance             = propertyName,
                    BaseRelativeLocation = baseRelativeLocation,
                    RelativeLocation     = relativeLocation,
                    InstanceLocation     = context.InstanceLocation.CloneAndAppend(propertyName),
                };
                var localResults = Value.Validate(newContext);
                valid &= localResults.IsValid;
                if (!valid)
                {
                    invalidPropertyNames.Add(propertyName);
                }

                if (context.Options.OutputFormat == SchemaValidationOutputFormat.Flag)
                {
                    if (!valid)
                    {
                        Log.Schema(() => "Subschema failed; halting validation early");
                        break;
                    }
                }
                else if (reportChildErrors)
                {
                    nestedResults.Add(localResults);
                }
            }

            results.IsValid       = valid;
            results.NestedResults = nestedResults;

            if (!results.IsValid)
            {
                Log.Schema(() => $"Property names {invalidPropertyNames.ToJson()} failed");
                results.AdditionalInfo["properties"] = invalidPropertyNames;
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 23
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var valid             = false;
            var reportChildErrors = context.Options.ShouldReportChildErrors(this, context);
            var i             = 0;
            var nestedResults = new List <SchemaValidationResults>();

            var baseContext = new SchemaValidationContext(context);

            baseContext.EvaluatedPropertyNames.Clear();
            baseContext.LocallyEvaluatedPropertyNames.Clear();
            baseContext.LastEvaluatedIndex          = -1;
            baseContext.LocalTierLastEvaluatedIndex = -1;
            foreach (var s in this)
            {
                var newContext = new SchemaValidationContext(baseContext)
                {
                    BaseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name, i.ToString()),
                    RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name, i.ToString()),
                };
                var localResults = s.Validate(newContext);
                valid |= localResults.IsValid;
                Log.Schema(() => $"`{Name}` {(valid ? "valid" : "invalid")} so far");
                if (localResults.IsValid)
                {
                    context.UpdateEvaluatedPropertiesAndItemsFromSubschemaValidation(newContext);
                }

                if (context.Options.OutputFormat == SchemaValidationOutputFormat.Flag)
                {
                    if (valid)
                    {
                        Log.Schema(() => "Subschema passed; halting validation early");
                        break;
                    }
                }
                else if (reportChildErrors)
                {
                    nestedResults.Add(localResults);
                }

                i++;
            }

            var resultsList = nestedResults.ToList();
            var results     = new SchemaValidationResults(Name, context)
            {
                NestedResults = resultsList,
                IsValid       = valid
            };

            if (!results.IsValid)
            {
                results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 24
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var valid             = true;
            var reportChildErrors = context.Options.ShouldReportChildErrors(this, context);
            var i             = 0;
            var nestedResults = new List <SchemaValidationResults>();
            var failedCount   = 0;

            foreach (var s in this)
            {
                var newContext = new SchemaValidationContext(context)
                {
                    BaseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name, i.ToString()),
                    RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name, i.ToString()),
                };
                var localResults = s.Validate(newContext);
                valid &= localResults.IsValid;
                Log.Schema(() => $"`{Name}` {(valid ? "valid" : "invalid")} so far");
                if (!localResults.IsValid)
                {
                    failedCount++;
                }
                else
                {
                    context.UpdateEvaluatedPropertiesAndItemsFromSubschemaValidation(newContext);
                }

                if (context.Options.OutputFormat == SchemaValidationOutputFormat.Flag)
                {
                    if (!valid)
                    {
                        Log.Schema(() => "Subschema failed; halting validation early");
                        break;
                    }
                }
                else if (reportChildErrors)
                {
                    nestedResults.Add(localResults);
                }

                i++;
            }

            var results = new SchemaValidationResults(Name, context)
            {
                NestedResults = nestedResults,
                IsValid       = valid
            };

            if (!results.IsValid)
            {
                results.AdditionalInfo["failed"] = failedCount;
                results.AdditionalInfo["total"]  = Count;
                results.ErrorMessage             = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 25
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (context.Instance.Type != JsonValueType.Array)
            {
                return(new SchemaValidationResults(Name, context));
            }

            var itemsKeyword = context.Local.Get <ItemsKeyword>();

            if (itemsKeyword == null || !itemsKeyword.IsArray)
            {
                return(new SchemaValidationResults(Name, context));
            }

            var nestedResults = new List <SchemaValidationResults>();
            var array         = context.Instance.Array;
            var results       = new SchemaValidationResults(Name, context);

            if (context.LocalTierLastEvaluatedIndex < array.Count)
            {
                if (Value == JsonSchema.False)
                {
                    results.IsValid      = false;
                    results.Keyword      = Name;
                    results.ErrorMessage = ErrorTemplate_False;
                    return(results);
                }

                nestedResults.AddRange(array.Skip(context.LocalTierLastEvaluatedIndex).Select((jv, i) =>
                {
                    var baseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name);
                    var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);
                    var newContext           = new SchemaValidationContext(context)
                    {
                        Instance             = jv,
                        BaseRelativeLocation = baseRelativeLocation,
                        RelativeLocation     = relativeLocation,
                        InstanceLocation     = context.InstanceLocation.CloneAndAppend(i.ToString()),
                    };
                    var localResults                    = Value.Validate(newContext);
                    context.LastEvaluatedIndex          = Math.Max(context.LastEvaluatedIndex, i);
                    context.LocalTierLastEvaluatedIndex = Math.Max(context.LastEvaluatedIndex, i);
                    return(localResults);
                }));
            }

            results.NestedResults = nestedResults;

            if (nestedResults.Any(r => !r.IsValid))
            {
                results.IsValid      = false;
                results.Keyword      = Name;
                results.ErrorMessage = ErrorTemplate;
            }

            return(results);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var baseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name);
            var relativeLocation     = context.RelativeLocation.CloneAndAppend(Name);

            var valid             = true;
            var reportChildErrors = context.Options.ShouldReportChildErrors(this, context);
            var nestedResults     = new List <SchemaValidationResults>();
            var failedCount       = 0;

            foreach (var d in this)
            {
                var newContext = new SchemaValidationContext(context)
                {
                    BaseRelativeLocation = baseRelativeLocation,
                    RelativeLocation     = relativeLocation,
                    Misc = { ["dependencyParent"] = Name }
                };
                var localResults = d.Validate(newContext);
                valid &= localResults.IsValid;
                if (!valid)
                {
                    failedCount++;
                }

                if (context.Options.OutputFormat == SchemaValidationOutputFormat.Flag)
                {
                    if (!valid)
                    {
                        Log.Schema(() => "Subschema failed; halting validation early");
                        break;
                    }
                }
                else if (reportChildErrors)
                {
                    nestedResults.Add(localResults);
                }
            }

            var results = new SchemaValidationResults(Name, context)
            {
                IsValid = valid
            };

            if (context.Options.OutputFormat == SchemaValidationOutputFormat.Flag)
            {
                results.NestedResults = nestedResults;
            }
            else if (!results.IsValid)
            {
                results.AdditionalInfo["failed"] = failedCount;
                results.AdditionalInfo["total"]  = Count;
                results.ErrorMessage             = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 27
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var reportChildErrors = context.Options.ShouldReportChildErrors(this, context);
            var i             = 0;
            var nestedResults = new List <SchemaValidationResults>();
            var validCount    = 0;

            var contextCopy = new SchemaValidationContext(context);

            foreach (var s in this)
            {
                var newContext = new SchemaValidationContext(context)
                {
                    BaseRelativeLocation = context.BaseRelativeLocation?.CloneAndAppend(Name, i.ToString()),
                    RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name, i.ToString()),
                };
                var localResults = s.Validate(newContext);
                if (localResults.IsValid)
                {
                    validCount++;
                    contextCopy.UpdateEvaluatedPropertiesAndItemsFromSubschemaValidation(newContext);
                }
                Log.Schema(() => $"`{Name}` {validCount} items valid so far");

                if (context.Options.OutputFormat == SchemaValidationOutputFormat.Flag)
                {
                    if (validCount > 1)
                    {
                        Log.Schema(() => "More than one subschema succeeded; halting validation early");
                        break;
                    }
                }
                else if (reportChildErrors)
                {
                    nestedResults.Add(localResults);
                }
            }

            var results = new SchemaValidationResults(Name, context)
            {
                IsValid       = validCount == 1,
                NestedResults = nestedResults
            };

            if (!results.IsValid)
            {
                Log.Schema(() => $"{validCount} subschemas passed validation; expected only one");
                results.AdditionalInfo["passed"] = validCount;
                results.ErrorMessage             = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }
            else
            {
                context.UpdateEvaluatedPropertiesAndItemsFromSubschemaValidation(contextCopy);
            }

            return(results);
        }
Esempio n. 28
0
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            var nestedResults = this.Select((s, i) =>
            {
                var newContext = new SchemaValidationContext(context)
                {
                    BaseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name, i.ToString()),
                    RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name, i.ToString()),
                };
                var result = s.Validate(newContext);
                context.EvaluatedPropertyNames.AddRange(newContext.EvaluatedPropertyNames);
                context.EvaluatedPropertyNames.AddRange(newContext.LocallyEvaluatedPropertyNames);
                return(result);
            });

            SchemaValidationResults results;
            var validCount = 0;

            if (JsonSchemaOptions.OutputFormat == SchemaValidationOutputFormat.Flag)
            {
                results = new SchemaValidationResults(Name, context);
                foreach (var result in nestedResults)
                {
                    if (result.IsValid)
                    {
                        if (validCount != 0)
                        {
                            results.IsValid = false;
                            return(results);
                        }

                        validCount++;
                    }
                }

                results.IsValid = validCount == 1;
            }
            else
            {
                var resultsList = nestedResults.ToList();
                validCount = resultsList.Count(r => r.IsValid);
                results    = new SchemaValidationResults(Name, context)
                {
                    NestedResults = resultsList,
                    IsValid       = validCount == 1
                };
            }

            if (!results.IsValid)
            {
                results.AdditionalInfo["passed"] = validCount;
                results.ErrorMessage             = ErrorTemplate.ResolveTokens(results.AdditionalInfo);
            }

            return(results);
        }
Esempio n. 29
0
        /// <summary>
        /// Downloads and registers a schema at the specified URI.
        /// </summary>
        public static IJsonSchema Get(string uri)
        {
            IJsonSchema schema;

            lock (_schemaLookup)
            {
                uri = uri.TrimEnd('#');
                if (!_schemaLookup.TryGetValue(uri, out schema))
                {
                    var schemaJson  = JsonSchemaOptions.Download(uri);
                    var schemaValue = JsonValue.Parse(schemaJson);
                    schema = JsonSchemaFactory.FromJson(schemaValue, new Uri(uri));

                    var metaSchemas = new IJsonSchema[]
                    {
                        JsonSchema07.MetaSchema,
                        JsonSchema06.MetaSchema,
                        JsonSchema04.MetaSchema
                    };

                    SchemaValidationResults validation = null;
                    if (schema.Schema != null)
                    {
                        var bySchema = metaSchemas.FirstOrDefault(s => s.Id == schema.Schema);
                        if (bySchema != null)
                        {
                            validation = bySchema.Validate(schemaValue);
                        }
                    }
                    else
                    {
                        foreach (var metaSchema in metaSchemas)
                        {
                            validation = metaSchema.Validate(schemaValue);
                            if (validation.Valid)
                            {
                                break;
                            }
                        }
                    }

                    if (validation != null && !validation.Valid)
                    {
                        var errors = string.Join(Environment.NewLine, validation.Errors.Select(e => e.Message));
                        throw new ArgumentException($"The given path does not contain a valid schema.  Errors: \n{errors}");
                    }

                    _schemaLookup[uri] = schema;
                }
            }

            return(schema);
        }
        /// <summary>
        /// Provides the validation logic for this keyword.
        /// </summary>
        /// <param name="context">The context object.</param>
        /// <returns>Results object containing a final result and any errors that may have been found.</returns>
        public SchemaValidationResults Validate(SchemaValidationContext context)
        {
            if (context.Instance.Type != JsonValueType.Object)
            {
                return(new SchemaValidationResults(Name, context));
            }

            var obj        = context.Instance.Object;
            var toEvaluate = obj.Where(kvp => !context.EvaluatedPropertyNames.Contains(kvp.Key));

            var nestedResults = new List <SchemaValidationResults>();

            foreach (var kvp in toEvaluate)
            {
                var newContext = new SchemaValidationContext(context)
                {
                    Instance             = kvp.Value,
                    BaseRelativeLocation = context.BaseRelativeLocation.CloneAndAppend(Name),
                    RelativeLocation     = context.RelativeLocation.CloneAndAppend(Name),
                    InstanceLocation     = context.InstanceLocation.CloneAndAppend(kvp.Key),
                };
                nestedResults.Add(Value.Validate(newContext));
            }

            SchemaValidationResults results;

            if (JsonSchemaOptions.OutputFormat == SchemaValidationOutputFormat.Flag)
            {
                results = new SchemaValidationResults(Name, context)
                {
                    IsValid = nestedResults.All(r => r.IsValid)
                }
            }
            ;
            else
            {
                var resultsList = nestedResults.ToList();
                results = new SchemaValidationResults(Name, context)
                {
                    NestedResults = resultsList,
                    IsValid       = resultsList.All(r => r.IsValid)
                };
            }

            if (nestedResults.Any(r => !r.IsValid))
            {
                results.IsValid      = false;
                results.Keyword      = Name;
                results.ErrorMessage = ErrorTemplate;
            }

            return(results);
        }