예제 #1
0
//Validate will validate a file with a Nulecule Specification
func Validate(schemaVersion string, location *url.URL) (bool, error) {
	var rc error

	// check if schemaVersion equals nulecule.NuleculeReleasedVersions
	if schemaVersion != nulecule.NuleculeReleasedVersions {
		return false, fmt.Errorf("The specified version (%s) of the Nulecule Specification is invalid", schemaVersion)
	}

	schemaLoader := gojsonschema.NewReferenceLoader(schemaLocation[schemaVersion])
	documentLoader := gojsonschema.NewReferenceLoader(location.String())

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		return false, err
	}

	if result.Valid() {
		return true, nil
	}

	fmt.Printf("The document is not valid. see errors :\n")
	for _, desc := range result.Errors() {
		rc = multierror.Append(rc, fmt.Errorf("%s\n", desc.Description()))
		fmt.Printf("- %s\n", desc)
	}

	rc = multierror.Append(fmt.Errorf("The document is not valid with Nulecule Specification version %s", schemaVersion))

	return false, rc
}
예제 #2
0
func TestValidRegistry(t *testing.T) {
	schemaLoader := gojsonschema.NewReferenceLoader("file://./just-install-schema.json")
	documentLoader := gojsonschema.NewReferenceLoader("file://./just-install.json")

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)

	assert.Nil(t, err)
	assert.Empty(t, result.Errors())
	assert.True(t, result.Valid())
}
예제 #3
0
func validateJson(schemaUrl, docUrl string) {
	schemaLoader := gojsonschema.NewReferenceLoader(schemaUrl)
	docLoader := gojsonschema.NewReferenceLoader(docUrl)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	utils.ExitOnFail(err)
	if result.Valid() {
		fmt.Printf("Document '%v' is valid against '%v'.\n", docUrl, schemaUrl)
	} else {
		fmt.Printf("Document '%v' is INVALID against '%v'.\n", docUrl, schemaUrl)
		for _, desc := range result.Errors() {
			fmt.Println("")
			fmt.Printf("- %s\n", desc)
		}
		// os.Exit(70)
	}
}
예제 #4
0
//ValidateSchema validates json schema
func (manager *Manager) ValidateSchema(schemaPath, filePath string) error {
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
	documentLoader := gojsonschema.NewReferenceLoader("file://" + filePath)
	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}
	if result.Valid() {
		return nil
	}
	var errMessage string
	for _, err := range result.Errors() {
		errMessage += fmt.Sprintf("%v   ", err)
	}
	return fmt.Errorf("Invalid json: %s", errMessage)
}
예제 #5
0
func NewSchemaValidator(t *testing.T, schemaName string, got interface{}) *SchemaValidator {
	dir, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	// Platform compatibility: use "/" separators always for file://
	dir = filepath.ToSlash(dir)

	schema := gojsonschema.NewReferenceLoader(fmt.Sprintf(
		"file:///%s/schema/%s", dir, schemaName),
	)

	marshalled, err := json.Marshal(got)
	if err != nil {
		t.Fatal(err)
	}

	subject := gojsonschema.NewStringLoader(string(marshalled))

	return &SchemaValidator{
		Schema:  schema,
		Subject: subject,
	}
}
예제 #6
0
func main() {
	nargs := len(os.Args[1:])
	if nargs == 0 || nargs > 2 {
		fmt.Printf("ERROR: usage is: %s <schema.json> [<document.json>]\n", os.Args[0])
		os.Exit(1)
	}

	schemaPath, err := filepath.Abs(os.Args[1])
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
	var documentLoader gojsonschema.JSONLoader

	if nargs > 1 {
		documentPath, err := filepath.Abs(os.Args[2])
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		documentLoader = gojsonschema.NewReferenceLoader("file://" + documentPath)
	} else {
		documentBytes, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		documentString := string(documentBytes)
		documentLoader = gojsonschema.NewStringLoader(documentString)
	}

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
	} else {
		fmt.Printf("The document is not valid. see errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
		os.Exit(1)
	}
}
예제 #7
0
//middleware for json schema validation
func JsonSchemaValidator() gin.HandlerFunc {

	return func(c *gin.Context) {

		contextCopy := c.Copy()
		var schema string
		validateSchema := true

		switch c.Request.RequestURI {
		case "/signup":
			schema = "signup.json"
		case "/login":
			schema = "login.json"
		default:
			validateSchema = false
		}

		if validateSchema {

			schemaLoader := gojsonschema.NewReferenceLoader("file://" + myConstants.JsonSchemasFilesLocation + "/" +
				schema)

			body, _ := ioutil.ReadAll(contextCopy.Request.Body)
			//fmt.Printf("%s", body)

			documentLoader := gojsonschema.NewStringLoader(string(body))

			result, err := gojsonschema.Validate(schemaLoader, documentLoader)

			if err != nil {
				log.Fatalln(myMessages.JsonSchemaValidationError + err.Error())
			}

			if !result.Valid() {
				//fmt.Printf("The document is not valid. see errors :\n")
				type errorsList []string
				type JsonErrorOutput struct {
					Error   bool
					Message string
					Faults  errorsList
				}
				var el errorsList
				for _, desc := range result.Errors() {
					//fmt.Printf("- %s\n", desc)
					el = append(el, fmt.Sprintf("%s", desc))
				}
				var jeo JsonErrorOutput
				jeo.Error = true
				jeo.Message = myMessages.JsonSchemaValidationFailed
				jeo.Faults = el
				c.JSON(http.StatusBadRequest, jeo)
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
예제 #8
0
func main() {

	schemaLoader := gojsonschema.NewReferenceLoader("file:///code/schema.json")
	documentLoader := gojsonschema.NewReferenceLoader("file:///code/sample.json")

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
	} else {
		fmt.Printf("The document is not valid. see errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
	}

}
예제 #9
0
func (c *InterfaceController) Update(w http.ResponseWriter, r *http.Request) {
	// Get ID
	id := mux.Vars(r)["id"]

	// Validate ObjectId
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Get object id
	oid := bson.ObjectIdHex(id)

	// Initialize empty struct
	s := models.Interface{}

	// Decode JSON into struct
	err := json.NewDecoder(r.Body).Decode(&s)
	if err != nil {
		jsonError(w, r, "Failed to deconde JSON: "+err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Validate input using JSON Schema
	docLoader := gojsonschema.NewGoLoader(s)
	schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI)

	res, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		jsonError(w, r, "Failed to load schema: "+err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	if !res.Valid() {
		var errors []string
		for _, e := range res.Errors() {
			errors = append(errors, fmt.Sprintf("%s: %s", e.Context().String(), e.Description()))
		}
		jsonError(w, r, errors, http.StatusInternalServerError, c.envelope)
		return
	}

	// Update entry
	if err := c.session.DB(c.database).C("interfaces").UpdateId(oid, s); err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Write content-type, header and payload
	jsonWriter(w, r, s, http.StatusOK, c.envelope)
}
예제 #10
0
파일: schema.go 프로젝트: chop-dbhi/scds
func (s *Schema) Load() error {
	p, err := filepath.Abs(s.File)
	if err != nil {
		return err
	}

	if _, err := os.Stat(p); err != nil {
		return err
	}

	p = fmt.Sprintf("file://%s", p)
	s.loader = gojsonschema.NewReferenceLoader(p)
	return nil
}
예제 #11
0
func validateSchema(schemaPathString string, docPathString string) {
	schemaPath, _ := filepath.Abs(schemaPathString)
	schemaUri := "file://" + schemaPath
	schemaLoader := gojsonschema.NewReferenceLoader(schemaUri)

	docPath, _ := filepath.Abs(docPathString)
	docUri := "file://" + docPath
	docLoader := gojsonschema.NewReferenceLoader(docUri)

	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		panic(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document %s is valid\n", docPathString)
	} else {
		fmt.Printf("The document %s is not valid. see errors :\n", docPathString)
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
		os.Exit(1)
	}
}
예제 #12
0
// validateRequestData takes in a schema path and the request
// and will do the legwork of determining if the post data is valid
func validateRequestData(schemaPath string, r *web.Request) (
	document map[string]interface{},
	result *gojsonschema.Result,
	err error,
) {
	err = json.NewDecoder(r.Body).Decode(&document)
	if err == nil && schemaPath != "" {
		schemaLoader := gojsonschema.NewReferenceLoader(schemaPath)
		documentLoader := gojsonschema.NewGoLoader(document)

		result, err = gojsonschema.Validate(schemaLoader, documentLoader)
	}

	return document, result, err
}
예제 #13
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)
		}
	}
}
예제 #14
0
func validateFunc(e Etcdtool, dir string, d interface{}) {
	// Map directory to routes.
	var schema string
	for _, r := range e.Routes {
		match, err := regexp.MatchString(r.Regexp, dir)
		if err != nil {
			fatal(err.Error())
		}
		if match {
			schema = r.Schema
		}
	}

	if schema == "" {
		fatal("Couldn't determine which JSON schema to use for validation")
	}

	/*
	   if schema == "" && len(c.Args()) == 1 {
	       fatal("You need to specify JSON schema URI")
	   }

	   if len(c.Args()) > 1 {
	       schema = c.Args()[1]
	   }
	*/

	// Validate directory.
	infof("Using JSON schema: %s", schema)
	schemaLoader := gojsonschema.NewReferenceLoader(schema)
	docLoader := gojsonschema.NewGoLoader(d)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		fatal(err.Error())
	}

	// Print results.
	if !result.Valid() {
		for _, err := range result.Errors() {
			fmt.Printf("%s: %s\n", strings.Replace(err.Context().String("/"), "(root)", dir, 1), err.Description())
		}
		fatal("Data validation failed aborting")
	}
}
예제 #15
0
func (c *TenantController) Create(w http.ResponseWriter, r *http.Request) {
	// Initialize empty struct
	s := models.Tenant{}

	// Decode JSON into struct
	err := json.NewDecoder(r.Body).Decode(&s)
	if err != nil {
		jsonError(w, r, "Failed to deconde JSON: "+err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Set ID
	s.ID = bson.NewObjectId()

	// Validate input using JSON Schema
	log.Printf("Using schema: %s", c.schemaURI)
	docLoader := gojsonschema.NewGoLoader(s)
	schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI)

	res, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	if !res.Valid() {
		var errors []string
		for _, e := range res.Errors() {
			errors = append(errors, fmt.Sprintf("%s: %s", e.Context().String(), e.Description()))
		}
		jsonError(w, r, errors, http.StatusInternalServerError, c.envelope)
		return
	}

	// Insert entry
	if err := c.session.DB(c.database).C("tenants").Insert(s); err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Write content-type, header and payload
	jsonWriter(w, r, s, http.StatusCreated, c.envelope)
}
예제 #16
0
func checkSchema(chain *chain, value, schema interface{}) {
	if chain.failed() {
		return
	}

	valueLoader := gojsonschema.NewGoLoader(value)

	var schemaLoader gojsonschema.JSONLoader

	if str, ok := toString(schema); ok {
		if ok, _ := regexp.MatchString(`^\w+://`, str); ok {
			schemaLoader = gojsonschema.NewReferenceLoader(str)
		} else {
			schemaLoader = gojsonschema.NewStringLoader(str)
		}
	} else {
		schemaLoader = gojsonschema.NewGoLoader(schema)
	}

	result, err := gojsonschema.Validate(schemaLoader, valueLoader)
	if err != nil {
		chain.fail("\n%s\n\nschema:\n%s\n\nvalue:\n%s",
			err.Error(),
			dumpSchema(schema),
			dumpValue(value))
		return
	}

	if !result.Valid() {
		errors := ""
		for _, err := range result.Errors() {
			errors += fmt.Sprintf(" %s\n", err)
		}

		chain.fail(
			"\njson schema validation failed, schema:\n%s\n\nvalue:%s\n\nerrors:\n%s",
			dumpSchema(schema),
			dumpValue(value),
			errors)

		return
	}
}
예제 #17
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
}
예제 #18
0
/**
 * Function validates JSON schema for `device` od `channel` models
 * By convention, Schema files must be kept as:
 * - ./models/deviceSchema.json
 * - ./models/channelSchema.json
 */
func validateJsonSchema(model string, body map[string]interface{}) bool {
	pwd, _ := os.Getwd()
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + pwd +
		"/schema/" + model + "Schema.json")
	bodyLoader := gojsonschema.NewGoLoader(body)
	result, err := gojsonschema.Validate(schemaLoader, bodyLoader)
	if err != nil {
		log.Print(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
		return true
	} else {
		fmt.Printf("The document is not valid. See errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
		return false
	}
}
예제 #19
0
func NewSchemaValidator(t *testing.T, schemaName string, got interface{}) *SchemaValidator {
	dir, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	schema := gojsonschema.NewReferenceLoader(fmt.Sprintf(
		"file:///%s",
		filepath.Join(dir, "schema/", schemaName),
	))

	marshalled, err := json.Marshal(got)
	if err != nil {
		t.Fatal(err)
	}

	subject := gojsonschema.NewStringLoader(string(marshalled))

	return &SchemaValidator{
		Schema:  schema,
		Subject: subject,
	}
}
예제 #20
0
파일: server.go 프로젝트: mickep76/etcdrest
func (c *config) validateDoc(doc []byte, path string, schema string) (int, []error) {
	// Prepare document and JSON schema.
	docLoader := gojsonschema.NewStringLoader(string(doc))
	log.Infof("Using schema URI: %s/%s", c.schemaURI, schema)
	schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI + "/" + schema)

	// Validate document using JSON schema.
	res, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		return http.StatusInternalServerError, []error{err}
	}

	if !res.Valid() {
		var errors []error
		for _, e := range res.Errors() {
			errors = append(errors, fmt.Errorf("%s: %s", strings.Replace(e.Context().String("/"), "(root)", path, 1), e.Description()))
		}

		return http.StatusBadRequest, errors
	}

	return http.StatusOK, nil
}
예제 #21
0
// validateCommandFunc validate data using JSON Schema.
func validateCommandFunc(c *cli.Context) {
	if len(c.Args()) == 0 {
		fatal("You need to specify directory")
	}
	dir := c.Args()[0]

	// Remove trailing slash.
	if dir != "/" {
		dir = strings.TrimRight(dir, "/")
	}
	infof("Using dir: %s", dir)

	// Load configuration file.
	e := loadConfig(c)

	// New dir API.
	ki := newKeyAPI(e)

	// Map directory to routes.
	var schema string
	for _, r := range e.Routes {
		match, err := regexp.MatchString(r.Regexp, dir)
		if err != nil {
			fatal(err.Error())
		}
		if match {
			schema = r.Schema
		}
	}

	if schema == "" && len(c.Args()) == 1 {
		fatal("You need to specify JSON schema URI")
	}

	if len(c.Args()) > 1 {
		schema = c.Args()[1]
	}

	// Get directory.
	ctx, cancel := contextWithCommandTimeout(c)
	resp, err := ki.Get(ctx, dir, &client.GetOptions{Recursive: true})
	cancel()
	if err != nil {
		fatal(err.Error())
	}
	m := etcdmap.Map(resp.Node)

	// Validate directory.
	infof("Using JSON schema: %s", schema)
	schemaLoader := gojsonschema.NewReferenceLoader(schema)
	docLoader := gojsonschema.NewGoLoader(m)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		fatal(err.Error())
	}

	// Print results.
	if !result.Valid() {
		for _, err := range result.Errors() {
			fmt.Printf("%s: %s\n", strings.Replace(err.Context().String("/"), "(root)", dir, 1), err.Description())
		}
	}
}