示例#1
0
// LoadSchema loads the schema from a string.
func LoadSchema(schema string) error {
	var err error
	schemaLoader := gojsonschema.NewStringLoader(schema)

	movenSchemaValidator, err = gojsonschema.NewSchema(schemaLoader)
	return err
}
示例#2
0
func BenchmarkGojsonschemaParse(b *testing.B) {
	l := gojsonschema.NewStringLoader(schemaJSON)
	for i := 0; i < b.N; i++ {
		s, _ := gojsonschema.NewSchema(l)
		_ = s
	}
}
示例#3
0
文件: schema.go 项目: snikch/api
func MustSchema(schemaString string) *schema.Schema {
	s, err := schema.NewSchema(schema.NewStringLoader(schemaString))
	if err != nil {
		panic(err)
	}
	return s
}
示例#4
0
func TestGenJsonSchema(t *testing.T) {
	str := `
		{
		"k1":"a",
		"k2":1,
		"k3":[],
		"k4":["a"],
		"k5":[1],
		"k6":[1.1],
		"k7":{},
		"k8":{"a":1},
		"k9":{"a":1,"b":[]},
		"k10":{"a":1,"b":[],"c":{"d":1.1}},
		"k11":{"a":1,"b":[],"c":{"d":1.1,"f":["a"]}},
		"k12":{"a":1,"b":[{"a":1,"b":[1]}]}
		}
	`
	var obj interface{}
	err := json.Unmarshal([]byte(str), &obj)
	assert.Equal(t, err, nil)

	schema, err := GenJsonSchema(obj)
	assert.Equal(t, err, nil)

	_, err = json.MarshalIndent(schema, "", "  ")
	assert.Equal(t, err, nil)
	//	fmt.Println(string(bs))

	goSchema, err := gojsonschema.NewSchema(gojsonschema.NewGoLoader(schema))
	assert.Equal(t, err, nil)
	documentLoader := gojsonschema.NewStringLoader(str)
	ret, err := goSchema.Validate(documentLoader)
	assert.Equal(t, err, nil)
	assert.Equal(t, ret.Valid(), true)
}
//NewJSONEventTrackingValidator returns a new JSONEventTrackingValidator with the parsed Schema
func NewJSONEventTrackingValidator() (*JSONEventTrackingValidator, error) {
	schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(schema))
	if err != nil {
		return nil, err
	}
	return &JSONEventTrackingValidator{schema}, err
}
示例#6
0
文件: fix.go 项目: DirkZhao/pproxy
func FixDataWithSchema(data interface{}, schema interface{}) (dataFix interface{}, err error) {
	_, err = gojsonschema.NewSchema(gojsonschema.NewGoLoader(schema))
	if err != nil {
		return nil, err
	}

	return fixDataWithSchemaInterface(data, schema)
}
示例#7
0
func ParseSchema(path string, route *Route) error {
	content, err := ioutil.ReadFile(path + "/schemas/" + route.Name + ".schema")
	if err != nil {
		return nil
	}
	schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(string(content)))
	if err != nil {
		return err
	}
	route.Schema = schema
	return nil
}
示例#8
0
// Test that the burned in payload schema is a valid json schema
func TestPayloadSchemaValid(t *testing.T) {
	payloadSchema := taskPayloadSchema()
	schemaLoader := gojsonschema.NewStringLoader(payloadSchema)
	_, err := gojsonschema.NewSchema(schemaLoader)
	if err != nil {
		t.Logf("Generic Worker payload schema is not a valid json schema for platform %v.", runtime.GOOS)
		t.Log("Payload schema:")
		t.Log(payloadSchema)
		t.Log("Error:")
		t.Fatalf("%s", err)
	}
}
示例#9
0
func (s *JSONSchema) getSchema() (schema *gojsonschema.Schema, err error) {
	if s.schema != nil && !s.enumLoader.IsDirty() {
		return s.schema, nil
	}

	loader := gojsonschema.NewGoLoader(s.GetPreprocessed())
	s.schema, err = gojsonschema.NewSchema(loader)
	if err != nil {
		return
	}

	return s.schema, nil
}
示例#10
0
// New returns JSON schema created from JSON byte string
// returns a valid schema or error if schema is invalid
func New(data []byte) (*JSONSchema, error) {
	j := JSONSchema{}
	err := json.Unmarshal(data, &j.rawSchema)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	loader := gojsonschema.NewGoLoader(j.rawSchema)
	j.schema, err = gojsonschema.NewSchema(loader)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &j, nil
}
示例#11
0
func ParseSchemaVersion(route *Route, path string, version int) error {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(string(content)))
	if err != nil {
		return err
	}
	if route.Versions[version] == nil {
		route.Versions[version] = &RouteVersion{Version: version}
	}
	route.Versions[version].Schema = schema
	return nil
}
示例#12
0
文件: main.go 项目: dolmen/jsonchk
func main() {
	result := make(chan string)
	running := make(chan bool)
	ctx := Context{
		result:  result,
		running: running,
	}

	schemaFile, err := filepath.Abs(os.Args[1])
	u := url.URL{
		Scheme: "file",
		Path:   schemaFile,
	}
	ctx.schema, err = gojsonschema.NewSchema(gojsonschema.NewReferenceLoader(u.String()))
	if err != nil {
		panic(err)
	}

	if len(os.Args) == 2 {
		fmt.Println("missing files/dir to process")
		return
	}

	for _, arg := range os.Args[2:] {
		validateAny(ctx, arg)
	}
	count := 0
	for {
		select {
		case r := <-running:
			if r {
				count++
			} else {
				count--
				if count == 0 {
					//fmt.Println("Done.")
					return
				}
			}
			//fmt.Println("Running: ", count)
		case r := <-result:
			fmt.Print(r)
		}
	}
}
示例#13
0
func NewValidator(plans, providers, drugs string) (Validator, error) {
	v := make(Validator)
	var err error
	for _, x := range []struct {
		name     string
		filename string
	}{
		{"plans", plans},
		{"providers", providers},
		{"drugs", drugs},
	} {
		v[x.name], err = js.NewSchema(js.NewReferenceLoader("file://" + abs(x.filename)))
		if err != nil {
			log.Printf(x.name)
			return nil, err
		}
	}
	return v, nil
}
示例#14
0
func TestRouteSql(t *testing.T) {
	schemaContent := `
{
  "title": "Get user",
  "description": "Get user",
  "type": "object",
  "properties": {
    "id": {
      "description": "User id",
      "type": "integer"
    }
  },
  "required": ["id"]
}
`
	schema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(string(schemaContent)))
	if err != nil {
		t.Errorf("Expected not to get error, but got: %v", err)
	}
	tmpl, err := makeTemplate(`select * from users where id={{.id}}`)
	if err != nil {
		t.Errorf("Expected not to get error, but got: %v", err)
	}
	route := &Route{
		Versions: map[int]*RouteVersion{
			0: {
				Version:     0,
				SqlTemplate: tmpl,
				Schema:      schema,
			},
		},
	}
	params := make(map[string]interface{})
	params["id"] = 23
	sql, err := route.Sql(params, 0)
	if err != nil {
		t.Errorf("Expected not to get error, but got: %v", err)
	}
	expected := "with response_table as (select * from users where id=23) select row_to_json(t) as value from (select * from response_table) t"
	if sql != expected {
		t.Errorf("Expected sql:\n%v, but got:\n%v\n", expected, sql)
	}
}
示例#15
0
func (a *App) LoadConfig(file string) error {
	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()

	if err := json.NewDecoder(f).Decode(&a.Conf); err != nil {
		return err
	}

	a.DB, err = bolt.Open(a.DBFile, 0600, nil)
	if err != nil {
		return err
	}

	a.DB.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte(PublicBucketName))
		return err
	})

	a.Router = mux.NewRouter()

	a.Log = logrus.New()
	a.Log.Out = os.Stderr
	a.Log.Formatter = &logrus.TextFormatter{ForceColors: true}
	a.Log.Level = logrus.ErrorLevel
	if ll, err := logrus.ParseLevel(a.LogLevel); err == nil {
		a.Log.Level = ll
	}

	for _, pp := range a.PublicParams {
		loader := gojsonschema.NewStringLoader(string(pp.RawSchema))
		schema, err := gojsonschema.NewSchema(loader)
		if err != nil {
			return err
		}
		pp.Schema = schema
	}

	return nil
}
示例#16
0
func (self *JSONSchemaMiddleware) LoadFromPath(base_path string) error {
	return filepath.Walk(base_path, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.Mode().IsRegular() {
			return nil
		}
		if !strings.HasSuffix(path, ".json") {
			return nil
		}

		bytes, err := ioutil.ReadFile(path)
		if err != nil {
			return fmt.Errorf("Error reading schema from %s: %s", path, err)
		}

		json_string := string(bytes)

		loader := gojsonschema.NewStringLoader(json_string)
		schema, err := gojsonschema.NewSchema(loader)
		if err != nil {
			return fmt.Errorf("Error loading schema from %s: %s", path, err)
		}

		name := filepath.Base(path)
		name = name[0 : len(name)-5]

		self.jsonSchemas[name] = &JSONSchema{
			schema:     schema,
			jsonString: json_string,
		}

		if self.logger != nil {
			self.logger.Debugf("Loaded schema %s", name)
		}

		return nil
	})
}
示例#17
0
// NewSchema creates a Schema that wraps a jsonschema.
// The jsonschema can be specified as a JSON string or a hierarchy of
//   * map[string]interface{}
//   * []interface{}
//   * string
//   * float64
//   * bool
//   * nil
func NewSchema(jsonschema interface{}) (Schema, error) {
	var loader gojsonschema.JSONLoader
	if s, ok := jsonschema.(string); ok {
		var target interface{}
		if err := json.Unmarshal([]byte(s), &target); err != nil {
			return nil, fmt.Errorf("Failed to parse JSON string, error: %s", err)
		}
		jsonschema = target
	}
	obj, ok := jsonschema.(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("Expected map[string]interface{} got: %T", jsonschema)
	}
	loader = gojsonschema.NewGoLoader(jsonschema)

	s, err := gojsonschema.NewSchema(loader)
	if err != nil {
		return nil, err
	}

	return schema{schema: s, raw: obj}, nil
}
示例#18
0
					"controller"
				]
			}]
		}
	},
	"additionalProperties":				false,
	"required": [
		"uuid",
		"network",
		"keyboard"
	]
}`

var machineSchema = func() *gojsonschema.Schema {
	schema, err := gojsonschema.NewSchema(
		gojsonschema.NewStringLoader(machineSchemaString),
	)
	if err != nil {
		panic(err)
	}
	return schema
}()

// LoadMachine will load machine definition from file
func LoadMachine(machineFile string) (*Machine, error) {
	// Load the machine configuration
	machineData, err := ioext.BoundedReadFile(machineFile, 1024*1024)
	if err == ioext.ErrFileTooBig {
		return nil, engines.NewMalformedPayloadError(
			"The file 'machine.json' larger than 1MiB. JSON files must be small.")
	}