Create a JSON schema validator for the given schema.

    Args:
        schema_path: The filename of the JSON schema.
        schema: A Python object representation of the same schema.

    Returns:
        An instance of Draft4Validator.
1064
def load_validator(schema_path, schema):
    
    # Get correct prefix based on OS
    if os.name == 'nt':
        file_prefix = 'file:///'
    else:
        file_prefix = 'file:'

    resolver = RefResolver(file_prefix + schema_path.replace("\\", "/"), schema)
    validator = Draft4Validator(schema, resolver=resolver)

    return validator
487193
def validate_manifest_against_schema(manifest: Dict[str, Any]) -> None:
    
    schema_data = _load_schema_data()
    try:
        validate(manifest, schema_data)
    except jsonValidationError as e:
        raise ValidationError(
            f"Manifest invalid for schema version {schema_data['version']}. "
            f"Reason: {e.message}"
        )
48859
def _validate_dict(self, input_dict, schema_dict, path_to_root, object_title=''):

        ''' 
        '''

    # reconstruct key path to current dictionary in model
        rules_top_level_key = re.sub('\[\d+\]', '[0]', path_to_root)
        map_rules = self.keyMap[rules_top_level_key]

    # construct list error report template
        map_error = {
            'object_title': object_title,
            'model_schema': self.schema,
            'input_criteria': map_rules,
            'failed_test': 'value_datatype',
            'input_path': path_to_root,
            'error_value': 0,
            'error_code': 4001
        }

    # validate map size
        if 'min_size' in map_rules.keys():
            input_size = sys.getsizeof(json.dumps(str(input_dict)).replace(' ','')) - 51
            if input_size < map_rules['min_size']:
                map_error['failed_test'] = 'min_size'
                map_error['error_value'] = input_size
                map_error['error_code'] = 4031
                raise InputValidationError(map_error)
        if 'max_size' in map_rules.keys():
            input_size = sys.getsizeof(json.dumps(str(input_dict)).replace(' ','')) - 51
            if input_size > map_rules['max_size']:
                map_error['failed_test'] = 'max_size'
                map_error['error_value'] = input_size
                map_error['error_code'] = 4032
                raise InputValidationError(map_error)

    # construct lists of keys in input dictionary
        input_keys = []
        input_key_list = []
        for key in input_dict.keys():
            error_dict = {
                'object_title': object_title,
                'model_schema': self.schema,
                'input_criteria': self.keyMap[rules_top_level_key],
                'failed_test': 'key_datatype',
                'input_path': path_to_root,
                'error_value': key,
                'error_code': 4004
            }
            error_dict['input_criteria']['key_datatype'] = 'string'
            if path_to_root == '.':
                if not isinstance(key, str):
                    input_key_name = path_to_root + str(key)
                    error_dict['input_path'] = input_key_name
                    raise InputValidationError(error_dict)
                input_key_name = path_to_root + key
            else:
                if not isinstance(key, str):
                    input_key_name = path_to_root + '.' + str(key)
                    error_dict['input_path'] = input_key_name
                    raise InputValidationError(error_dict)
                input_key_name = path_to_root + '.' + key
            input_keys.append(input_key_name)
            input_key_list.append(key)

    # TODO: validate top-level key and values against identical to reference

    # TODO: run lambda function and call validation

    # construct lists of keys in schema dictionary
        max_keys = []
        max_key_list = []
        req_keys = []
        req_key_list = []
        for key in schema_dict.keys():
            if path_to_root == '.':
                schema_key_name = path_to_root + key
            else:
                schema_key_name = path_to_root + '.' + key
            max_keys.append(schema_key_name)
            max_key_list.append(key)
            rules_schema_key_name = re.sub('\[\d+\]', '[0]', schema_key_name)
            if self.keyMap[rules_schema_key_name]['required_field']:
                req_keys.append(schema_key_name)
                req_key_list.append(key)

    # validate existence of required fields
        missing_keys = set(req_keys) - set(input_keys)
        if missing_keys:
            error_dict = {
                'object_title': object_title,
                'model_schema': self.schema,
                'input_criteria': self.keyMap[rules_top_level_key],
                'failed_test': 'required_field',
                'input_path': path_to_root,
                'error_value': list(missing_keys),
                'error_code': 4002
            }
            error_dict['input_criteria']['required_keys'] = req_keys
            raise InputValidationError(error_dict)

    # validate existence of extra fields
        extra_keys = set(input_keys) - set(max_keys)
        if extra_keys and not self.keyMap[rules_top_level_key]['extra_fields']:
            extra_key_list = []
            for key in extra_keys:
                pathless_key = re.sub(rules_top_level_key, '', key, count=1)
                extra_key_list.append(pathless_key)
            error_dict = {
                'object_title': object_title,
                'model_schema': self.schema,
                'input_criteria': self.keyMap[rules_top_level_key],
                'failed_test': 'extra_fields',
                'input_path': path_to_root,
                'error_value': extra_key_list,
                'error_code': 4003
            }
            error_dict['input_criteria']['maximum_scope'] = max_key_list
            raise InputValidationError(error_dict)

    # validate datatype of value
        for key, value in input_dict.items():
            if path_to_root == '.':
                input_key_name = path_to_root + key
            else:
                input_key_name = path_to_root + '.' + key
            rules_input_key_name = re.sub('\[\d+\]', '[0]', input_key_name)
            if input_key_name in max_keys:
                input_criteria = self.keyMap[rules_input_key_name]
                error_dict = {
                    'object_title': object_title,
                    'model_schema': self.schema,
                    'input_criteria': input_criteria,
                    'failed_test': 'value_datatype',
                    'input_path': input_key_name,
                    'error_value': value,
                    'error_code': 4001
                }
                try:
                    value_index = self._datatype_classes.index(value.__class__)
                except:
                    error_dict['error_value'] = value.__class__.__name__
                    raise InputValidationError(error_dict)
                value_type = self._datatype_names[value_index]
                if input_criteria['value_datatype'] == 'null':
                    pass
                else:
                    if value_type != input_criteria['value_datatype']:
                        raise InputValidationError(error_dict)

    # call appropriate validation sub-routine for datatype of value
                    if value_type == 'boolean':
                        input_dict[key] = self._validate_boolean(value, input_key_name, object_title)
                    elif value_type == 'number':
                        input_dict[key] = self._validate_number(value, input_key_name, object_title)
                    elif value_type == 'string':
                        input_dict[key] = self._validate_string(value, input_key_name, object_title)
                    elif value_type == 'map':
                        input_dict[key] = self._validate_dict(value, schema_dict[key], input_key_name, object_title)
                    elif value_type == 'list':
                        input_dict[key] = self._validate_list(value, schema_dict[key], input_key_name, object_title)

    # set default values for empty optional fields
        for key in max_key_list:
            if key not in input_key_list:
                indexed_key = max_keys[max_key_list.index(key)]
                if indexed_key in self.components.keys():
                    if 'default_value' in self.components[indexed_key]:
                        input_dict[key] = self.components[indexed_key]['default_value']

        return input_dict
1339828
def _validate(self, schema):
        
        if isinstance(schema, _str_type):
            schema = self.validator.schema_registry.get(schema, schema)

        if schema is None:
            raise SchemaError(errors.SCHEMA_ERROR_MISSING)

        schema = copy(schema)
        for field in schema:
            if isinstance(schema[field], _str_type):
                schema[field] = rules_set_registry.get(schema[field],
                                                       schema[field])

        if not self.schema_validator(schema, normalize=False):
            raise SchemaError(self.schema_validator.errors)
576768
def do_schema(self, line):
        
        args = self.getargs(line)

        if not args:
            for k in sorted(self.schema):
                print "%s\t%s" % (k, self.schema[k])
        elif args[0] == "--clear":
            self.schema.clear()
        else:
            fname = args[0]
            ftype = args[1]

            if not ftype in VALID_TYPES:
                print "invalid type: use %s" % list(VALID_TYPES)
            else:
                self.schema[fname] = ftype
844767
def validate(self, schema):
        
        try:
            validate(instance=self.to_dict(), schema=schema, cls=Draft4Validator)
        except ValidationError as e:
            raise ValidationError(_validate_err_template.format(VDOM_SCHEMA, e))
1065372
def load_schema(name):
    

    data = pkgutil.get_data('jsonschema', "schemas/{0}.json".format(name))
    return json.loads(data.decode("utf-8"))
334712
def _validate(data, schema, ac_schema_safe=True, **options):
    
    try:
        jsonschema.validate(data, schema, **options)

    except (jsonschema.ValidationError, jsonschema.SchemaError,
            Exception) as exc:
        if ac_schema_safe:
            return (False, str(exc))  # Validation was failed.
        raise

    return (True, '')
1193932
def ensure_schema(self):
        """"""
        self._ensure_filename()
        if not os.path.isfile(self.filename):
            self.create_schema()
476431
public boolean matchJsonToSchema(JSONObject schema, JSONObject json) throws Exception {
        SchemaLoader.builder()
                 .useDefaults(true)
                 .schemaJson(schema)
                 .build()
                 .load()
                 .build()
                 .validate(json);
        return true;
    }
970028
def _validate_valueschema(self, schema, field, value):
        
        schema_crumb = (field, 'valueschema')
        if isinstance(value, Mapping):
            validator = self._get_child_validator(
                document_crumb=field, schema_crumb=schema_crumb,
                schema=dict((k, schema) for k in value))
            validator(value, update=self.update, normalize=False)
            if validator._errors:
                self._drop_nodes_from_errorpaths(validator._errors, [], [2])
                self._error(field, errors.VALUESCHEMA, validator._errors)
461387
def validate_schema(schema_name):
    """"""
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            instance = args[0]
            try:
                instance.validator(instance.schemas[schema_name]).validate(request.get_json())
            except ValidationError, e:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.BAD_SCHEMA,
                                                       e.message)
                instance.logger.error("Invalid Schema", ret_dict)
                return jsonify(ret_dict), 400
            instance.logger.debug("Schema is valid")
            return f(*args, **kw)
        return wrapper
    return decorator
871141
def validate(obj, schema):
        
        if isinstance(obj, str):
            obj = json.loads(obj)
        return JsonValidator(schema)._validate(obj)
156242
def schemaValidateDoc(self, doc):
        
        if doc is None: doc__o = None
        else: doc__o = doc._o
        ret = libxml2mod.xmlSchemaValidateDoc(self._o, doc__o)
        return ret
166763
def from_schemafile(cls, schemafile):
        
        with open(schemafile) as f:
            return cls(json.load(f))
860783
private function validateSchema(Schema $schema)
    {
        $this->jsonValidator->check(
            json_decode(json_encode($schema->jsonSerialize())),
            json_decode(file_get_contents($schema->getSchema()))
        );

        return $this->jsonValidator->isValid();
    }
275570
def schema_digest(self) -> str:
        
        res = self.schema._node_digest()
        res["config"] = True
        return json.dumps(res)