Get a schema that can validate BSE JSON files

       The schema_type represents the type of BSE JSON file to be validated,
       and can be 'component', 'element', 'table', 'metadata', or 'references'.
324231
def get_schema(schema_type):
    '''
    '''

    schema_file = "{}-schema.json".format(schema_type)
    file_path = os.path.join(_default_schema_dir, schema_file)

    if not os.path.isfile(file_path):
        raise RuntimeError('Schema file \'{}\' does not exist, is not readable, or is not a file'.format(file_path))

    return fileio.read_schema(file_path)
761262
function JsonSchema (schema) {
  if (!schema) {
    throw ono({ status: 500 }, "Missing JSON schema");
  }
  if (schema.type !== undefined && dataTypes.indexOf(schema.type) === -1) {
    throw ono({ status: 500 }, "Invalid JSON schema type: %s", schema.type);
  }

  this.schema = schema;
}
871141
def validate(obj, schema):
        
        if isinstance(obj, str):
            obj = json.loads(obj)
        return JsonValidator(schema)._validate(obj)
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);
            }
          }
        }
      }
    }
  }
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)
971237
def _build_schema(self, s):
        
        w = self._whatis(s)
        if w == self.IS_LIST:
            w0 = self._whatis(s[0])
            js = {"type": "array",
                  "items": {"type": self._jstype(w0, s[0])}}
        elif w == self.IS_DICT:
            js = {"type": "object",
                  "properties": {key: self._build_schema(val) for key, val in s.items()}}
            req = [key for key, val in s.items() if not val.is_optional]
            if req:
                js["required"] = req
        else:
            js = {"type": self._jstype(w, s)}
        for k, v in self._json_schema_keys.items():
            if k not in js:
                js[k] = v
        return js
930292
static TypeInformation schemaToTypeInfo(TypeDescription schema) {
		switch (schema.getCategory()) {
			case BOOLEAN:
				return BasicTypeInfo.BOOLEAN_TYPE_INFO;
			case BYTE:
				return BasicTypeInfo.BYTE_TYPE_INFO;
			case SHORT:
				return BasicTypeInfo.SHORT_TYPE_INFO;
			case INT:
				return BasicTypeInfo.INT_TYPE_INFO;
			case LONG:
				return BasicTypeInfo.LONG_TYPE_INFO;
			case FLOAT:
				return BasicTypeInfo.FLOAT_TYPE_INFO;
			case DOUBLE:
				return BasicTypeInfo.DOUBLE_TYPE_INFO;
			case DECIMAL:
				return BasicTypeInfo.BIG_DEC_TYPE_INFO;
			case STRING:
			case CHAR:
			case VARCHAR:
				return BasicTypeInfo.STRING_TYPE_INFO;
			case DATE:
				return SqlTimeTypeInfo.DATE;
			case TIMESTAMP:
				return SqlTimeTypeInfo.TIMESTAMP;
			case BINARY:
				return PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO;
			case STRUCT:
				List<TypeDescription> fieldSchemas = schema.getChildren();
				TypeInformation[] fieldTypes = new TypeInformation[fieldSchemas.size()];
				for (int i = 0; i < fieldSchemas.size(); i++) {
					fieldTypes[i] = schemaToTypeInfo(fieldSchemas.get(i));
				}
				String[] fieldNames = schema.getFieldNames().toArray(new String[]{});
				return new RowTypeInfo(fieldTypes, fieldNames);
			case LIST:
				TypeDescription elementSchema = schema.getChildren().get(0);
				TypeInformation<?> elementType = schemaToTypeInfo(elementSchema);
				// arrays of primitive types are handled as object arrays to support null values
				return ObjectArrayTypeInfo.getInfoFor(elementType);
			case MAP:
				TypeDescription keySchema = schema.getChildren().get(0);
				TypeDescription valSchema = schema.getChildren().get(1);
				TypeInformation<?> keyType = schemaToTypeInfo(keySchema);
				TypeInformation<?> valType = schemaToTypeInfo(valSchema);
				return new MapTypeInfo<>(keyType, valType);
			case UNION:
				throw new UnsupportedOperationException("UNION type is not supported yet.");
			default:
				throw new IllegalArgumentException("Unknown type " + schema);
		}
	}
375974
def _verify_type(self, spec, path):
        """"""
        field_type = spec['type']

        if isinstance(field_type, Schema):
            # Nested documents cannot have validation
            if not set(spec.keys()).issubset(set(['type', 'required', 'nullable', 'default'])):
                raise SchemaFormatException("Unsupported field spec item at {}. Items: "+repr(spec.keys()), path)
            return

        elif isinstance(field_type, Array):
            if not isinstance(field_type.contained_type, (type, Schema, Array, types.FunctionType)):
                raise SchemaFormatException("Unsupported field type contained by Array at {}.", path)

        elif not isinstance(field_type, type) and not isinstance(field_type, types.FunctionType):
            raise SchemaFormatException("Unsupported field type at {}. Type must be a type, a function, an Array or another Schema", path)
1003966
def schema(self):
        
        if self.key_type is None:
            return "%s %s" % (self.name, self.data_type)
        else:
            return "%s %s %s KEY" % (self.name, self.data_type, self.key_type)
436759
def validate_yaml_file(schema: dict, yaml_file: Path):
    

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

    jsonschema.validate(data, schema)
716790
def get_validator(self, schema=None):
        
        schema = schema if schema is not None else self.schema
        return jsonschema.Draft4Validator(
            schema, resolver=self.resolver,
            format_checker=jsonschema.draft4_format_checker)
476431
public boolean matchJsonToSchema(JSONObject schema, JSONObject json) throws Exception {
        SchemaLoader.builder()
                 .useDefaults(true)
                 .schemaJson(schema)
                 .build()
                 .load()
                 .build()
                 .validate(json);
        return true;
    }
1321610
def load_schema(schema_path):
    
    with open(schema_path, 'r') as schema_file:
        schema = simplejson.load(schema_file)
    resolver = RefResolver('', '', schema.get('models', {}))
    return build_request_to_validator_map(schema, resolver)
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
1247181
def dict2schema(dct, schema_class=ma.Schema):
    
    attrs = dct.copy()

    class Meta(object):
        if MARSHMALLOW_VERSION_INFO[0] < 3:
            strict = True
        else:
            register = False

    attrs["Meta"] = Meta
    return type(str(""), (schema_class,), attrs)
940403
def _validate_json_format(self, filter_value, schema_validation_type):
        
        ok = False
        try:
            validators.json_schema_validation_format(filter_value, schema_validation_type)
            ok = True
        except ValueError as e:
            pass
        return ok
457549
def special_validate(data, schema):
    
    jsonschema.validate(data, schema)
    data['special'] = str(data['name'] == 'Garfield').lower()