Validate a JSON string against the schema
- Converts the string into a JSON object then uses the JsonSchema Validator to validate
174941
public function validate($value)
    {
        $validator = new Validator();
        $jsonSchema = $this->json;

        $validator->check($value, $jsonSchema);

        if (!$validator->isValid()) {
            foreach ($validator->getErrors() as $error) {
                $this->errors[] = new TypeValidationError($error['property'], $error['constraint']);
            }
        }
    }
893610
def validate(style):
    
    try:
        import jsonschema
    except ImportError:
        return

    try:
        jsonschema.validate(style, schema)
    except jsonschema.ValidationError as exc:
        new_exc = StyleValidationError(exc)
        # Don't dump the original jsonschema exception because it is already
        # included in the StyleValidationError's message.
        new_exc.__cause__ = None
        raise new_exc
1181610
def _validate_keyschema(self, schema, field, value):
        
        if isinstance(value, Mapping):
            validator = self._get_child_validator(
                document_crumb=field,
                schema_crumb=(field, 'keyschema'),
                schema=dict(((k, schema) for k in value.keys())))
            if not validator(dict(((k, k) for k in value.keys())),
                             normalize=False):
                self._drop_nodes_from_errorpaths(validator._errors,
                                                 [], [2, 4])
                self._error(field, errors.KEYSCHEMA, validator._errors)
1066033
def validate(text, file, schema_type):
    """"""
    content = None

    if text:
        print('Validating text input...')
        content = text

    if file:
        print('Validating file input...')
        content = file.read()

    if content is None:
        click.secho('Please give either text input or a file path. See help for more details.', fg='red')
        exit(1)

    try:
        if schema_type == 'dependencies':
            validator = DependenciesSchemaValidator()
        elif schema_type == 'actions':
            validator = ActionsSchemaValidator()
        else:
            raise Exception('Unknown type')

        validator.validate_json(content)
        click.secho('Valid JSON schema!', fg='green')
    except Exception as e:
        click.secho('Invalid JSON schema!', fg='red')
        raise e
342752
def parse_schema(schema):
    """"""

    if isinstance(schema, BaseSchema):
        return schema.validate

    if type(schema) is type:
        return _build_type_validator(schema)

    if isinstance(schema, dict):
        return _build_dict_validator(schema)

    if type(schema) in (list, tuple, set):
        return _build_iterable_validator(schema)

    if callable(schema):
        return _build_callable_validator(schema)

    return _build_static_validator(schema)
685270
def _validate_example(rh, method, example_type):
    
    example = getattr(method, example_type + "_example")
    schema = getattr(method, example_type + "_schema")

    if example is None:
        return None

    try:
        validate(example, schema)
    except ValidationError as e:
        raise ValidationError(
            "{}_example for {}.{} could not be validated.\n{}".format(
                example_type, rh.__name__, method.__name__, str(e)
            )
        )

    return json.dumps(example, indent=4, sort_keys=True)
474698
def validation_error_try_to_accept(err, data, schema):
    
    if not isinstance(err, ValidationError):
        abort(Response(err, status=HTTPStatus.BAD_REQUEST))

    alernative_schema = dict(schema)
    alernative_schema['properties']['running_time'].update({
        'description': "Films's running time",
        'type': 'integer',
        'example': 169
    })

    try:
        jsonschema.validate(data, alernative_schema)
    except ValidationError as err:
        abort(Response(str(err), status=400))
49235
def validate_json(data, validator):
    
    errors = []
    for err in sorted(validator.iter_errors(data), key=lambda e: e.path):
        if err.path:
            err_path = "[{}]".format(" -> ".join([str(p) for p in err.path]))
        else:
            err_path = ""
        msg = err.message + " " + err_path
        if err.context:  # Error has suberrors, e.g. if schema uses anyOf
            suberrs = ["  - {}".format(suberr.message) for suberr in err.context]
            msg += ":\n{}".format("".join(suberrs))
        errors.append(msg)
    return errors
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
451192
function checkSchemaErrors(schemaJSON)
    {

      //check against the proper schema definition
      // var vck = self.validator.validateMultiple(schemaJSON, schemaSpec, true);
       var valCheck = self.validateFunction.apply(self.validator, [schemaJSON, schemaSpec, true]);
       
       //grab all possible errors
       var checkErrors = {length: 0};
       var checkWarnings = {length: 0};

       //if we're valid -- which we almost certainly are -- just keep going
       if(!valCheck.valid)
       {
          //let it be known -- this is a weird error
          self.log("Invalid from v4 JSON schema perspective: ", valCheck[errorKey]);

          checkErrors["root"] = valCheck[errorKey];
          checkErrors.length++;

          //not valid, throw it back
          return checkErrors;
       }


       //make sure we have some properties -- otherwise there is literally no validation/
       //during the move process, this is overridden, but it's a good check nonetheless
       if(!schemaJSON.properties && !schemaJSON.items)
       {
          checkErrors["root"] = "No properties/items defined at root. Schema has no validation without properties!";
          checkErrors.length++;
       }

       //going to need to traverse our schema object
       var tJSON = traverse(schemaJSON);

       tJSON.forEach(function(node)
       {
        //skip the root please
        if(this.isRoot || this.path.join(pathDelim).indexOf('required') != -1)
          return;

        //this should be a warning
        if(!self.requireByDefault && !this.isLeaf && !this.node.required)
        {
            //if you don't have a required object, then you're gonna have a bad time
            //this is a warning
            checkWarnings[this.path.join(pathDelim)] = "warning: if you disable requireByDefault and don't put require arrays, validation will ignore those properties.";
            checkWarnings.length++;

        }
        if(this.key == "properties" && this.node.properties)
        {
           checkErrors[this.path.join(pathDelim)] = "Properties inside properties is meaningless.";
           checkErrors.length++;
        }
        if(this.key == "type" && typeof this.node != "string")
        {
            //for whatever reason, there is a type defined, but not a string in it's place? Waa?
            checkErrors[this.path.join(pathDelim)] = "Types must be string";
            checkErrors.length++;
        }
        if(this.key == "type" && !self.typeRegExp.test(this.node.toLowerCase()))
        {
           checkErrors[this.path.join(pathDelim)] = "Types must be one of " + self.validTypes + " not " + this.node;
           checkErrors.length++;
        }
        if(this.isLeaf)
        {
          //if you don't have a type, and there is no ref object
          if(!this.parent.node.properties && (this.key != "type" && this.key != "$ref") && !this.parent.node.type && !this.parent.node["$ref"])
          {
              checkErrors[this.path.join(pathDelim)] = "Object doesn't have any properties, a valid type, or a reference, therefore it is invalid in the WIN spec.";
              checkErrors.length++;
          }
        }
        //not a leaf, you don't have a reference
        if(!self.allowAnyObjects && !this.isLeaf && !this.node["$ref"] )
        {
          //special case for items -- doesn't apply
          if(this.node.type == "object" && this.key != "items")
          {
            //we're going to check if the list of keys to follow have any non keywords
            //for instance if {type: "object", otherThing: "string"} keys = type, otherThing
            //if instead it's just {type : "object", required : []}, keys = type, required 
            //notice that the top has non-keyword keys, and the bottom example does not 
            //we're looking for the bottom example and rejecting it
            var bHasNonKeywords = hasNonKeywords(this.keys);
            
            //if you ONLY have keywords -- you don't have any other object types
            //you are a violation of win spec and you allow any object or array to be passed in
            if(!bHasNonKeywords){
              // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
              checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'object' type with no inner properties";
              checkErrors.length++;
            }
          }
          else if(this.node.type == "array")
          {
            //if you are an array and you have no items -- not allowed!
            if(!this.node.items){
              // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
              checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'array' type with no inner items";
              checkErrors.length++;
            }
            else
            {
              //if you have a ref -- you're okay for us!
              var bIemsHaveNonKey = this.node.items["$ref"] || this.node.items["type"] || hasNonKeywords(this.node.items.properties || {});
               if(!bIemsHaveNonKey){
                // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
                checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'array' type with no non-keyword inner items";
                checkErrors.length++;
              }
            }
          }
        
        }
        //if you're an array
        if(this.node.type == "array")
        {
          //grab your items
          var items = this.node.items;
          if(!items && !self.allowAnyObjects)
          {
             checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off for arrays, therefore you cannot simple have an 'array' type with no inner items";
              checkErrors.length++;
          }
          else
          {
            items = items || {};
            //we have items -- we shouldn't have a reference type && other items
            if(items.properties && items["$ref"])
            {
              checkErrors[this.path.join(pathDelim)] = "Array items in WIN cannot have properties AND a reference type. One or the other.";
              checkErrors.length++;
            }
          }
        }


       });

       if(checkErrors.length || checkWarnings.length)
        return {errors: checkErrors, warnings: checkWarnings};
      else
        return null;

    }
131607
async function validateJSON(someJson, jsonschema) {
          utilsLogger.debug("called validateJSON someJson, jsonschema");
          return studyUtils.jsonschema.validate(someJson, jsonschema);
          // return { valid: true, errors: [] };
        }
1214725
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    this.logger.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema, schema);
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') this.logger.error(message);
    else throw new Error(message);
  }
  return valid;
}
974351
private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) {
        log.debug("Starting Json schema validation ...");

        ProcessingReport report = jsonSchemaValidation.validate(receivedMessage,
                                                                schemaRepositories,
                                                                validationContext,
                                                                applicationContext);
        if (!report.isSuccess()) {
            log.error("Failed to validate Json schema for message:\n" + receivedMessage.getPayload(String.class));

            throw new ValidationException(constructErrorMessage(report));
        }

        log.info("Json schema validation successful: All values OK");
    }
156221
private void understandSchema(String schema) throws JSONException {

    JSONObject j1 = new JSONObject(schema);
    JSONArray fields = j1.getJSONArray(FIELDS);

    String fieldName;
    String fieldTypeValue;
    Object recName;

    for (int k = 0; k < fields.length(); k++) {
      if (fields.get(k) == null) {
        continue;
      }
      JSONObject allEvents = new JSONObject(fields.get(k).toString());
      Object name = allEvents.get(NAME);
      if (name != null) {
        if (name.toString().equalsIgnoreCase(EVENT)) {
          JSONArray allTypeDetails = allEvents.getJSONArray(TYPE);
          for (int i = 0; i < allTypeDetails.length(); i++) {
            JSONObject actual = (JSONObject) allTypeDetails.get(i);
            JSONArray types = actual.getJSONArray(FIELDS);
            Map<String, String> typeDetails = new HashMap<String, String>();
            for (int j = 0; j < types.length(); j++) {
              if (types.getJSONObject(j) == null ) {
                continue;
              }
              fieldName = types.getJSONObject(j).getString(NAME);
              fieldTypeValue = types.getJSONObject(j).getString(TYPE);
              if ((fieldName != null) && (fieldTypeValue != null)) {
                typeDetails.put(fieldName, fieldTypeValue);
              }
            }

            recName = actual.get(NAME);
            if (recName != null) {
              /* the next statement may throw an IllegalArgumentException if
               * it finds a new string that's not part of the Hadoop2RecordType enum
               * that way we know what types of events we are parsing
               */
              fieldTypes.put(Hadoop2RecordType.valueOf(recName.toString()), typeDetails);
            }
          }
        }
      }
    }
  }
1065372
def load_schema(name):
    

    data = pkgutil.get_data('jsonschema', "schemas/{0}.json".format(name))
    return json.loads(data.decode("utf-8"))
1029138
def validate(self, data):
        """"""
        try:
            schema_path = os.path.normpath(SCHEMA_ROOT)
            location = u'file://%s' % (schema_path)
            fs_resolver = resolver.LocalRefResolver(location, self.schema)
            jsonschema.Draft3Validator(self.schema, resolver=fs_resolver).validate(data)

        except jsonschema.ValidationError as exc:
            # print "data %s" % (data)
            raise jsonschema.exceptions.ValidationError(str(exc))
427185
def timestamping_validate(data, schema):
    
    jsonschema.validate(data, schema)
    data['timestamp'] = str(time.time())