public void Initialize(ContextBase context, SchemaScope parent, int initialDepth, ScopeType type)
        {
            base.Initialize(context, parent, initialDepth, type);

            ParentSchemaScope = parent;
            ConditionalContext = ConditionalContext.Create(context);
        }
        public void ValidateCurrentToken(JsonToken token, object?value, int depth)
        {
            if (depth == 0)
            {
                // Handle validating multiple content
                RemoveCompletedScopes();
            }

            if (_scopes.Count == 0)
            {
                if (Schema == null)
                {
                    throw new JSchemaException("No schema has been set for the validator.");
                }

                if (!_hasValidatedLicense)
                {
                    LicenseHelpers.IncrementAndCheckValidationCount();
                    _hasValidatedLicense = true;
                }

                SchemaScope.CreateTokenScope(token, Schema, _context, null, depth);
            }

            if (TokenWriter != null)
            {
                // JTokenReader can return JsonToken.String with a null value which WriteToken doesn't like.
                // Hacky - change token to JsonToken.Null. Can be removed when fixed Newtonsoft.Json is public.
                JsonToken fixedToken = (token == JsonToken.String && value == null) ? JsonToken.Null : token;

                TokenWriter.WriteToken(fixedToken, value);
            }

            for (int i = _scopes.Count - 1; i >= 0; i--)
            {
                Scope scope = _scopes[i];

                if (scope.Complete != CompleteState.Completed)
                {
                    scope.EvaluateToken(token, value, depth);
                }
                else
                {
                    _scopes.RemoveAt(i);
                    _scopesCache.Add(scope);
                }
            }

            if (TokenWriter != null && (TokenWriter.WriteState == WriteState.Start || TokenWriter.WriteState == WriteState.Closed))
            {
                TokenWriter = null;
            }
        }
Beispiel #3
0
        internal static void EnsureValid(SchemaScope scope, JSchema schema, object value)
        {
            if (schema.Reference != null)
            {
                throw new JSchemaException("Schema has unresolved reference '{0}'. All references must be resolved before a schema can be validated.".FormatWith(CultureInfo.InvariantCulture, schema.Reference.OriginalString));
            }

            if (schema.Valid != null && !schema.Valid.Value)
            {
                scope.RaiseError($"Schema always fails validation.", ErrorType.Valid, schema, value, null);
            }
        }
        public virtual void Initialize(ContextBase context, SchemaScope parent, int initialDepth, ScopeType type)
        {
            Context      = context;
            Parent       = parent;
            InitialDepth = initialDepth;
            Type         = type;
            Complete     = false;

#if DEBUG
            Interlocked.Increment(ref LastDebugId);
            DebugId = LastDebugId;
#endif
        }
        protected SchemaScope GetSchemaScopeBySchema(JSchema schema)
        {
            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];

                if (schemaScope.Schema == schema)
                {
                    return(schemaScope);
                }
            }

            return(null);
        }
Beispiel #6
0
        protected bool GetChildrenAllValid()
        {
            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];

                if (!schemaScope.IsValid)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #7
0
 public void InitializeScopes(JsonToken token)
 {
     if (!Schema._dependencies.IsNullOrEmpty())
     {
         foreach (KeyValuePair <string, object> dependency in Schema._dependencies.GetInnerDictionary())
         {
             if (dependency.Value is JSchema dependencySchema)
             {
                 SchemaScope scope = CreateTokenScope(token, dependencySchema, ConditionalContext.Create(Context), null, InitialDepth);
                 _dependencyScopes.Add(dependency.Key, scope);
             }
         }
     }
 }
Beispiel #8
0
 protected IEnumerable <SchemaScope> GetChildren()
 {
     foreach (Scope scope in Context.Scopes)
     {
         SchemaScope schemaScope = scope as SchemaScope;
         if (schemaScope != null)
         {
             if (schemaScope.Parent == this)
             {
                 yield return(schemaScope);
             }
         }
     }
 }
        public void Initialize(ContextBase context, SchemaScope parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Object);
            InitializeSchema(schema);

            _propertyCount       = 0;
            _currentPropertyName = null;

            if (!schema._required.IsNullOrEmpty())
            {
                if (_requiredProperties != null)
                {
                    _requiredProperties.Clear();
                }
                else
                {
                    _requiredProperties = new List <string>(schema._required.Count);
                }

                foreach (string required in schema._required)
                {
                    _requiredProperties.Add(required);
                }
            }

            if (!schema._dependencies.IsNullOrEmpty())
            {
                if (_readProperties != null)
                {
                    _readProperties.Clear();
                }
                else
                {
                    _readProperties = new List <string>();
                }

                if (schema._dependencies.HasSchemas)
                {
                    if (_dependencyScopes != null)
                    {
                        _dependencyScopes.Clear();
                    }
                    else
                    {
                        _dependencyScopes = new Dictionary <string, SchemaScope>(StringComparer.Ordinal);
                    }
                }
            }
        }
Beispiel #10
0
 public void InitializeScopes(JsonToken token)
 {
     if (_dependencyScopes != null)
     {
         foreach (KeyValuePair <string, object> dependency in Schema._dependencies)
         {
             JSchema dependencySchema = dependency.Value as JSchema;
             if (dependencySchema != null)
             {
                 SchemaScope scope = CreateTokenScope(token, dependencySchema, ConditionalContext.Create(Context), null, InitialDepth);
                 _dependencyScopes.Add(dependency.Key, scope);
             }
         }
     }
 }
Beispiel #11
0
        public void InitializeScopes(JsonToken token, List <JSchema> schemas)
        {
            foreach (JSchema schema in schemas)
            {
                // check to see whether a scope with the same schema exists
                SchemaScope childScope = GetExistingSchemaScope(schema);

                if (childScope == null)
                {
                    childScope = SchemaScope.CreateTokenScope(token, schema, ConditionalContext, null, InitialDepth);
                }

                ChildScopes.Add(childScope);
            }
        }
Beispiel #12
0
        protected bool GetChildrenAllValid(JsonToken token, object value, int depth)
        {
            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];
                AssertScopeComplete(schemaScope, token, value, depth);

                if (!schemaScope.IsValid)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #13
0
        protected SchemaScope GetSchemaScopeBySchema(JSchema schema, JsonToken token, object value, int depth)
        {
            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];

                if (schemaScope.Schema == schema)
                {
                    AssertScopeComplete(schemaScope, token, value, depth);
                    return(schemaScope);
                }
            }

            return(null);
        }
Beispiel #14
0
        protected int GetChildrenValidCount()
        {
            int count = 0;

            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];

                if (schemaScope.IsValid)
                {
                    count++;
                }
            }

            return(count);
        }
Beispiel #15
0
        private void AssertScopeComplete(SchemaScope schemaScope, JsonToken token, object value, int depth)
        {
            // the schema scope that the conditional scope depends on may not be complete because it has be re-ordered
            // schema scope will be at the same depth at the conditional so evaluate it immediately
            if (!schemaScope.Complete)
            {
                schemaScope.EvaluateToken(token, value, depth);

#if DEBUG
                if (!schemaScope.Complete)
                {
                    throw new Exception("Schema scope {0} is not complete.".FormatWith(CultureInfo.InvariantCulture, schemaScope.DebugId));
                }
#endif
            }
        }
Beispiel #16
0
        private static bool DependentSchemaAlreadyCreated(SchemaScope scope, string dependencyKey)
        {
            if (scope.ConditionalChildren != null)
            {
                for (int i = 0; i < scope.ConditionalChildren.Count; i++)
                {
                    if (scope.ConditionalChildren[i] is DependentSchemaScope dependentSchemaScope &&
                        dependentSchemaScope.PropertyName == dependencyKey)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Beispiel #17
0
        public void ValidateCurrentToken(JsonToken token, object value, int depth)
        {
            if (depth == 0)
            {
                // Handle validating multiple content
                RemoveCompletedScopes();
            }

            if (_scopes.Count == 0)
            {
                if (Schema == null)
                {
                    throw new JSchemaException("No schema has been set for the validator.");
                }

                if (!_hasValidatedLicense)
                {
                    LicenseHelpers.IncrementAndCheckValidationCount();
                    _hasValidatedLicense = true;
                }

                SchemaScope.CreateTokenScope(token, Schema, _context, null, depth);
            }

            TokenWriter?.WriteToken(token, value);

            for (int i = _scopes.Count - 1; i >= 0; i--)
            {
                Scope scope = _scopes[i];

                if (!scope.Complete)
                {
                    scope.EvaluateToken(token, value, depth);
                }
                else
                {
                    _scopes.RemoveAt(i);
                    _scopesCache.Add(scope);
                }
            }

            if (TokenWriter != null && TokenWriter.Top == 0)
            {
                TokenWriter = null;
            }
        }
Beispiel #18
0
        protected int GetChildrenValidCount(JsonToken token, object value, int depth)
        {
            int count = 0;

            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];
                AssertScopeComplete(schemaScope, token, value, depth);

                if (schemaScope.IsValid)
                {
                    count++;
                }
            }

            return(count);
        }
        protected SchemaScope CreateScopesAndEvaluateToken(JsonToken token, object?value, int depth, JSchema schema, SchemaScope?parent, ContextBase context)
        {
            int startCount = Context.Scopes.Count;

            SchemaScope createdScope = CreateTokenScope(token, schema, context, parent, depth);

            int start = Context.Scopes.Count - 1;
            int end   = startCount;

            for (int i = start; i >= end; i--)
            {
                Scope newScope = Context.Scopes[i];
                newScope.EvaluateToken(token, value, depth);
            }

            return(createdScope);
        }
        public void InitializeScopes(JsonToken token, List <JSchema> schemas, int scopeIndex)
        {
            foreach (JSchema schema in schemas)
            {
                // cache this for performance
                int scopeCurrentIndex = scopeIndex;

                // check to see whether a scope with the same schema exists
                SchemaScope childScope = GetExistingSchemaScope(schema, ref scopeCurrentIndex);

                if (childScope == null)
                {
                    childScope = SchemaScope.CreateTokenScope(token, schema, ConditionalContext, null, InitialDepth);
                }

                ChildScopes.Add(childScope);
            }
        }
        public void Initialize(ContextBase context, SchemaScope parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Array);
            InitializeSchema(schema);

            _index      = -1;
            _matchCount = 0;

            if (schema.Contains != null)
            {
                if (_containsContexts != null)
                {
                    _containsContexts.Clear();
                }
                else
                {
                    _containsContexts = new List <ConditionalContext>();
                }
            }

            if (schema.UniqueItems)
            {
                if (_uniqueArrayItems != null)
                {
                    _uniqueArrayItems.Clear();
                }
                else
                {
                    _uniqueArrayItems = new List <JToken>();
                }
            }

            if (ShouldValidateUnevaluated())
            {
                if (_unevaluatedScopes != null)
                {
                    _unevaluatedScopes.Clear();
                }
                else
                {
                    _unevaluatedScopes = new Dictionary <int, UnevaluatedContext>();
                }
            }
        }
Beispiel #22
0
        internal static bool ValidateString(SchemaScope scope, JSchema schema, string value)
        {
            if (!TestType(scope, schema, JSchemaType.String, value))
            {
                return(false);
            }

            if (schema.MaximumLength != null || schema.MinimumLength != null)
            {
                // want to test the character length and ignore unicode surrogates
                StringInfo stringInfo = new StringInfo(value);
                int        textLength = stringInfo.LengthInTextElements;

                if (schema.MaximumLength != null && textLength > schema.MaximumLength)
                {
                    scope.RaiseError($"String '{value}' exceeds maximum length of {schema.MaximumLength}.", ErrorType.MaximumLength, schema, value, null);
                }

                if (schema.MinimumLength != null && textLength < schema.MinimumLength)
                {
                    scope.RaiseError($"String '{value}' is less than minimum length of {schema.MinimumLength}.", ErrorType.MinimumLength, schema, value, null);
                }
            }

            if (schema.Pattern != null)
            {
                if (schema.TryGetPatternRegex(
#if !(NET35 || NET40)
                        scope.Context.Validator.RegexMatchTimeout,
#endif
                        out Regex regex,
                        out string errorMessage))
                {
                    if (!RegexHelpers.IsMatch(regex, schema.Pattern, value))
                    {
                        scope.RaiseError($"String '{value}' does not match regex pattern '{schema.Pattern}'.", ErrorType.Pattern, schema, value, null);
                    }
                }
                else
                {
                    scope.RaiseError($"Could not validate string with regex pattern '{schema.Pattern}'. There was an error parsing the regex: {errorMessage}", ErrorType.Pattern, schema, value, null);
                }
            }
Beispiel #23
0
        public void InitializeScope(JsonToken token, int scopeIndex, JSchema schema, ContextBase context)
        {
            // cache this for performance
            int scopeCurrentIndex = scopeIndex;

            // check to see whether a scope with the same schema exists
            SchemaScope?childScope = GetExistingSchemaScope(schema, ref scopeCurrentIndex);

            if (childScope == null)
            {
                childScope = SchemaScope.CreateTokenScope(token, schema, context, null, InitialDepth);
            }
            else
            {
                if (childScope.Context != context)
                {
                    // The schema scope needs to be part of a different conditional contexts.
                    // We need to create a composite so that errors are raised to both.
                    CompositeContext?compositeContext = childScope.Context as CompositeContext;
                    if (compositeContext == null)
                    {
                        compositeContext = new CompositeContext(context.Validator);
                        compositeContext.Contexts.Add(childScope.Context);
                        compositeContext.Contexts.Add(context);

                        childScope.Context = compositeContext;
                    }
                    else
                    {
                        if (!compositeContext.Contexts.Contains(context))
                        {
                            compositeContext.Contexts.Add(context);
                        }
                    }
                }
            }

#if DEBUG
            childScope.ConditionalParents.Add(this);
#endif

            ChildScopes.Add(childScope);
        }
        public void Initialize(ContextBase context, SchemaScope parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Array);
            InitializeSchema(schema);

            _index = -1;

            if (schema.UniqueItems)
            {
                if (_uniqueArrayItems != null)
                {
                    _uniqueArrayItems.Clear();
                }
                else
                {
                    _uniqueArrayItems = new List <JToken>();
                }
            }
        }
Beispiel #25
0
        protected override bool EvaluateTokenCore(JsonToken token, object value, int depth)
        {
            SchemaScope ifScope = GetSchemaScopeBySchema(If, token, value, depth);

            if (ifScope.IsValid)
            {
                ConditionalContext.TrackEvaluatedSchema(ifScope.Schema);

                if (Then != null)
                {
                    SchemaScope thenScope = GetSchemaScopeBySchema(Then, token, value, depth);

                    if (!thenScope.IsValid)
                    {
                        ConditionalContext context = (ConditionalContext)thenScope.Context;
                        RaiseError($"JSON does not match schema from 'then'.", ErrorType.Then, Then, null, context.Errors);
                    }
                    else
                    {
                        ConditionalContext.TrackEvaluatedSchema(thenScope.Schema);
                    }
                }
            }
            else
            {
                if (Else != null)
                {
                    SchemaScope elseScope = GetSchemaScopeBySchema(Else, token, value, depth);

                    if (!elseScope.IsValid)
                    {
                        ConditionalContext context = (ConditionalContext)elseScope.Context;
                        RaiseError($"JSON does not match schema from 'else'.", ErrorType.Else, Else, null, context.Errors);
                    }
                    else
                    {
                        ConditionalContext.TrackEvaluatedSchema(elseScope.Schema);
                    }
                }
            }

            return(true);
        }
Beispiel #26
0
        protected bool TryGetChildrenValidCount(JsonToken token, object?value, int depth, out int validCount)
        {
            validCount = 0;
            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];
                if (!AssertScopeComplete(schemaScope, token, value, depth))
                {
                    return(false);
                }

                if (schemaScope.IsValid)
                {
                    validCount++;
                }
            }

            return(true);
        }
        private void InitializeScope(JsonToken token, int scopeIndex, JSchema schema, ConditionalContext context)
        {
            // cache this for performance
            int scopeCurrentIndex = scopeIndex;

            // check to see whether a scope with the same schema exists
            SchemaScope childScope = GetExistingSchemaScope(schema, ref scopeCurrentIndex);

            if (childScope == null)
            {
                childScope = SchemaScope.CreateTokenScope(token, schema, context, null, InitialDepth);
            }

#if DEBUG
            childScope.ConditionalParents.Add(this);
#endif

            ChildScopes.Add(childScope);
        }
Beispiel #28
0
        protected bool TryGetChildrenAllValid(JsonToken token, object?value, int depth, out bool allValid)
        {
            for (int i = 0; i < ChildScopes.Count; i++)
            {
                SchemaScope schemaScope = ChildScopes[i];
                if (!AssertScopeComplete(schemaScope, token, value, depth))
                {
                    allValid = default;
                    return(false);
                }

                if (!schemaScope.IsValid)
                {
                    allValid = false;
                    return(true);
                }
            }

            allValid = true;
            return(true);
        }
Beispiel #29
0
        private void ValidateDependantSchema(string readProperty)
        {
            SchemaScope dependencyScope = _dependencyScopes[readProperty];

            if (dependencyScope.Context.HasErrors)
            {
                IFormattable message = $"Dependencies for property '{readProperty}' failed.";
                RaiseError(message, ErrorType.Dependencies, Schema, readProperty, dependencyScope.GetValidationErrors());
            }
            else
            {
                if (!_unevaluatedScopes.IsNullOrEmpty())
                {
                    foreach (KeyValuePair <string, UnevaluatedContext> item in _unevaluatedScopes)
                    {
                        if (!item.Value.Evaluated && IsPropertyDefined(dependencyScope.Schema, item.Key))
                        {
                            item.Value.Evaluated = true;
                        }
                    }
                }
            }
        }
        public void ValidateCurrentToken(JsonToken token, object value, int depth)
        {
            if (_scopes.Count == 0)
            {
                if (Schema == null)
                {
                    throw new JsonException("No schema has been set for the validator.");
                }

                LicenseHelpers.IncrementAndCheckValidationCount();
                SchemaScope.CreateTokenScope(token, Schema, _context, null, depth);
            }

            if (TokenWriter != null)
            {
                TokenWriter.WriteToken(token, value);
            }

            for (int i = _scopes.Count - 1; i >= 0; i--)
            {
                Scope scope = _scopes[i];

                if (!scope.Complete)
                {
                    scope.EvaluateToken(token, value, depth);
                }
                else
                {
                    _scopes.RemoveAt(i);
                }
            }

            if (TokenWriter != null && TokenWriter.Top == 0)
            {
                TokenWriter = null;
            }
        }
        private SchemaScope GetExistingSchemaScope(JSchema schema)
        {
            for (int i = Context.Scopes.Count - 1; i >= 0; i--)
            {
                SchemaScope scope = Context.Scopes[i] as SchemaScope;

                if (scope != null)
                {
                    if (scope.InitialDepth == InitialDepth)
                    {
                        if (!scope.Complete && scope.Schema == schema)
                        {
                            return(scope);
                        }
                    }
                    else if (scope.InitialDepth < InitialDepth)
                    {
                        break;
                    }
                }
            }

            return(null);
        }
 public OneOfScope(SchemaScope parent, ContextBase context, int depth)
     : base(context, parent, depth)
 {
 }
 protected ConditionalScope(ContextBase context, SchemaScope parent, int initialDepth)
     : base(context, parent, initialDepth)
 {
     ParentSchemaScope = parent;
     ConditionalContext = ConditionalContext.Create(context);
 }
 protected static bool IsValidPredicateInternal(SchemaScope s)
 {
     return s.IsValid;
 }