Load the JSON Schema Draft 4 validator with the given name from the
    local schema directory.
321887
def load_validator(name):
    
    with open(os.path.join(SCHEMA_PATH, name)) as fh:
        schema = json.load(fh)
    Draft4Validator.check_schema(schema)
    return Draft4Validator(schema, format_checker=checker)
871141
def validate(obj, schema):
        
        if isinstance(obj, str):
            obj = json.loads(obj)
        return JsonValidator(schema)._validate(obj)
1345346
def validate_mapping(mapping):
    
    file_path = os.path.join(os.path.dirname(__file__),
                             'schemas', 'mapping.json')
    with open(file_path, 'r') as fh:
        validator = Draft4Validator(json.load(fh))
        validator.validate(mapping)
    return mapping
413082
def loadSchema(uri, base_uri=None):
    

    # uri to use for reporting errors - include base uri if any
    if uri in _loaded_schemas:
        return _loaded_schemas[uri]

    error_uri = uri
    if base_uri is not None:
        error_uri += ' (base URI %s)' % base_uri


    try:
        logger.debug('Loading schema %s' % uri)
        _loaded_schemas[uri] = etree.XMLSchema(etree.parse(uri,
                                                           parser=_get_xmlparser(),
                                                           base_url=base_uri))
        return _loaded_schemas[uri]
    except IOError as io_err:
        # add a little more detail to the error message - but should still be an IO error
        raise IOError('Failed to load schema %s : %s' % (error_uri, io_err))
    except etree.XMLSchemaParseError as parse_err:
        # re-raise as a schema parse error, but ensure includes details about schema being loaded
        raise etree.XMLSchemaParseError('Failed to parse schema %s -- %s' % (error_uri, parse_err))
685894
def validate(payload, schema):
    
    v = jsonschema.Draft4Validator(
        schema, format_checker=jsonschema.FormatChecker())
    error_list = []
    for error in v.iter_errors(payload):
        message = error.message
        location = '/' + '/'.join([str(c) for c in error.absolute_path])
        error_list.append(message + ' at ' + location)
    return error_list
1083502
def jsonresolver_loader(url_map):
    
    from flask import current_app
    from . import current_jsonschemas
    url_map.add(Rule(
        "{0}/<path:path>".format(current_app.config['JSONSCHEMAS_ENDPOINT']),
        endpoint=current_jsonschemas.get_schema,
        host=current_app.config['JSONSCHEMAS_HOST']))
766938
def main(source):
    
    if source is None:
        click.echo(
            "You need to supply a file or url to a schema to a swagger schema, for"
            "the validator to work."
        )
        return 1
    try:
        load(source)
        click.echo("Validation passed")
        return 0
    except ValidationError as e:
        raise click.ClickException(str(e))
758348
def load_schema(schema):
    
    with repo.Repo.db:
        repo.Repo.db.executescript(schema)
436759
def validate_yaml_file(schema: dict, yaml_file: Path):
    

    with yaml_file.open() as f:
        data = yaml.load(f)

    jsonschema.validate(data, schema)
736122
def _schema_from_json_file_object(self, file_obj):
        
        json_data = json.load(file_obj)
        return [SchemaField.from_api_repr(field) for field in json_data]
588797
def import_schema_to_json(name, store_it=False):
    

    schema_file = u"%s.json" % name
    file_path = os.path.join(SCHEMA_ROOT, schema_file)
    log.debug(u"trying to load %s " % file_path)
    schema = None
    try:
        schema_file = open(file_path, "r").read()
    except IOError, e:
        log.error(u"file not found %s" % e)
        msg = "Could not find schema file. %s" % file_path
        raise SalesKingException("SCHEMA_NOT_FOUND", msg)
    schema = json.loads(schema_file)

    if schema is None:
        msg = "loading failed foo %s" % name
        raise SalesKingException("SCHEMA_NOT_FOUND", msg)
    return schema
397398
def _validate_schema(schema, body):
    """"""

    # Note
    #
    # Schema validation is currently the major CPU bottleneck of
    # BigchainDB. the `jsonschema` library validates python data structures
    # directly and produces nice error messages, but validation takes 4+ ms
    # per transaction which is pretty slow. The rapidjson library validates
    # much faster at 1.5ms, however it produces _very_ poor error messages.
    # For this reason we use both, rapidjson as an optimistic pathway and
    # jsonschema as a fallback in case there is a failure, so we can produce
    # a helpful error message.

    try:
        schema[1](rapidjson.dumps(body))
    except ValueError as exc:
        try:
            jsonschema.validate(body, schema[0])
        except jsonschema.ValidationError as exc2:
            raise SchemaValidationError(str(exc2)) from exc2
        logger.warning('code problem: jsonschema did not raise an exception, wheras rapidjson raised %s', exc)
        raise SchemaValidationError(str(exc)) from exc
1230856
def register_schemas_dir(self, directory):
        
        for root, dirs, files in os.walk(directory):
            dir_path = os.path.relpath(root, directory)
            if dir_path == '.':
                dir_path = ''
            for file_ in files:
                if file_.lower().endswith(('.json')):
                    schema_name = os.path.join(dir_path, file_)
                    if schema_name in self.schemas:
                        raise JSONSchemaDuplicate(
                            schema_name,
                            self.schemas[schema_name],
                            directory
                        )
                    self.schemas[schema_name] = os.path.abspath(directory)
885365
def _validate_json(self, checked_json, schema):
        
        try:
            jsonschema.validate(checked_json, schema)
        except jsonschema.ValidationError as e:
            print("""Failed validating '{0}'
in schema {1}:
{2}
On instance {3}:
{4}""".format(e.validator,
              list(e.relative_schema_path)[:-1], pprint.pformat(e.schema),
              "[%s]" % "][".join(repr(index) for index in e.absolute_path),
              pprint.pformat(e.instance).encode('utf-8')))
            raise JsonValidatorError("Failed validating json by schema")
        except jsonschema.SchemaError as e:
            raise JsonValidatorError('Json-schema error')
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
224498
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None:
        
        self.pfx = None
        if shex is not None:
            if isinstance(shex, ShExJ.Schema):
                self._schema = shex
            else:
                shext = shex.strip()
                loader = SchemaLoader()
                if ('\n' in shex or '\r' in shex) or shext[0] in '#<_: ':
                    self._schema = loader.loads(shex)
                else:
                    self._schema = loader.load(shex) if isinstance(shex, str) else shex
                if self._schema is None:
                    raise ValueError("Unable to parse shex file")
                self.pfx = PrefixLibrary(loader.schema_text)
1301529
function load(schema) {
  var obj;
  if (typeof schema == 'string' && schema !== 'null') {
    // This last predicate is to allow `avro.parse('null')` to work similarly
    // to `avro.parse('int')` and other primitives (null needs to be handled
    // separately since it is also a valid JSON identifier).
    try {
      obj = JSON.parse(schema);
    } catch (err) {
      if (~schema.indexOf('/')) {
        // This can't be a valid name, so we interpret is as a filepath. This
        // makes is always feasible to read a file, independent of its name
        // (i.e. even if its name is valid JSON), by prefixing it with `./`.
        obj = JSON.parse(fs.readFileSync(schema));
      }
    }
  }
  if (obj === undefined) {
    obj = schema;
  }
  return obj;
}