// Walker function to validate the json recursively against the subSchema
482949
func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *JsonContext) {

	if internalLogEnabled {
		internalLog("validateRecursive %s", context.String())
		internalLog(" %v", currentNode)
	}

	// Handle referenced schemas, returns directly when a $ref is found
	if currentSubSchema.refSchema != nil {
		v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context)
		return
	}

	// Check for null value
	if currentNode == nil {
		if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) {
			result.addInternalError(
				new(InvalidTypeError),
				context,
				currentNode,
				ErrorDetails{
					"expected": currentSubSchema.types.String(),
					"given":    TYPE_NULL,
				},
			)
			return
		}

		currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context)
		v.validateCommon(currentSubSchema, currentNode, result, context)

	} else { // Not a null value

		if isJSONNumber(currentNode) {

			value := currentNode.(json.Number)

			isInt := checkJSONInteger(value)

			validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isInt && currentSubSchema.types.Contains(TYPE_INTEGER))

			if currentSubSchema.types.IsTyped() && !validType {

				givenType := TYPE_INTEGER
				if !isInt {
					givenType = TYPE_NUMBER
				}

				result.addInternalError(
					new(InvalidTypeError),
					context,
					currentNode,
					ErrorDetails{
						"expected": currentSubSchema.types.String(),
						"given":    givenType,
					},
				)
				return
			}

			currentSubSchema.validateSchema(currentSubSchema, value, result, context)
			v.validateNumber(currentSubSchema, value, result, context)
			v.validateCommon(currentSubSchema, value, result, context)
			v.validateString(currentSubSchema, value, result, context)

		} else {

			rValue := reflect.ValueOf(currentNode)
			rKind := rValue.Kind()

			switch rKind {

			// Slice => JSON array

			case reflect.Slice:

				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) {
					result.addInternalError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_ARRAY,
						},
					)
					return
				}

				castCurrentNode := currentNode.([]interface{})

				currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)

				v.validateArray(currentSubSchema, castCurrentNode, result, context)
				v.validateCommon(currentSubSchema, castCurrentNode, result, context)

			// Map => JSON object

			case reflect.Map:
				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) {
					result.addInternalError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_OBJECT,
						},
					)
					return
				}

				castCurrentNode, ok := currentNode.(map[string]interface{})
				if !ok {
					castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{})
				}

				currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)

				v.validateObject(currentSubSchema, castCurrentNode, result, context)
				v.validateCommon(currentSubSchema, castCurrentNode, result, context)

				for _, pSchema := range currentSubSchema.propertiesChildren {
					nextNode, ok := castCurrentNode[pSchema.property]
					if ok {
						subContext := NewJsonContext(pSchema.property, context)
						v.validateRecursive(pSchema, nextNode, result, subContext)
					}
				}

			// Simple JSON values : string, number, boolean

			case reflect.Bool:

				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) {
					result.addInternalError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_BOOLEAN,
						},
					)
					return
				}

				value := currentNode.(bool)

				currentSubSchema.validateSchema(currentSubSchema, value, result, context)
				v.validateNumber(currentSubSchema, value, result, context)
				v.validateCommon(currentSubSchema, value, result, context)
				v.validateString(currentSubSchema, value, result, context)

			case reflect.String:

				if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) {
					result.addInternalError(
						new(InvalidTypeError),
						context,
						currentNode,
						ErrorDetails{
							"expected": currentSubSchema.types.String(),
							"given":    TYPE_STRING,
						},
					)
					return
				}

				value := currentNode.(string)

				currentSubSchema.validateSchema(currentSubSchema, value, result, context)
				v.validateNumber(currentSubSchema, value, result, context)
				v.validateCommon(currentSubSchema, value, result, context)
				v.validateString(currentSubSchema, value, result, context)

			}

		}

	}

	result.incrementScore()
}
910947
func NewJSONSchemaFromProps(t *Type, properties map[string]interface{}, typ, name string) JSONSchema {
	var required []string

	if isTypeArray(typ) {
		return newArraySchema(t, typ, name)
	}

	props := make(map[string]property, len(properties))
	for name := range properties {
		rp := t.GetProperty(name)
		if !isPropTypeSupported(rp) {
			continue
		}

		p := newProperty(rp)
		props[p.Name] = p
		if p.Required {
			required = append(required, p.Name)
		}
	}

	// we need it to be sorted for testing purpose
	sort.Strings(required)
	js := JSONSchema{
		Schema:     schemaVer,
		Name:       name,
		Type:       typ,
		T:          t,
		Properties: props,
		Required:   required,
	}
	if js.T == nil {
		js.T = &Type{
			Type:       typ,
			Properties: properties,
		}
	}
	return js
}
582475
func (n *ArgumentList) Walk(v walker.Visitor) {
	if v.EnterNode(n) == false {
		return
	}

	if n.Arguments != nil {
		v.EnterChildList("Arguments", n)
		for _, nn := range n.Arguments {
			if nn != nil {
				nn.Walk(v)
			}
		}
		v.LeaveChildList("Arguments", n)
	}

	v.LeaveNode(n)
}
295225
func (sl *SchemaLoader) AddSchemas(loaders ...JSONLoader) error {
	emptyRef, _ := gojsonreference.NewJsonReference("")

	for _, loader := range loaders {
		doc, err := loader.LoadJSON()

		if err != nil {
			return err
		}

		if sl.Validate {
			if err := sl.validateMetaschema(doc); err != nil {
				return err
			}
		}

		// Directly use the Recursive function, so that it get only added to the schema pool by $id
		// and not by the ref of the document as it's empty
		if err = sl.pool.parseReferences(doc, emptyRef, false); err != nil {
			return err
		}
	}

	return nil
}
16379
func (s *SchemaField) MarshalJSON() ([]byte, error) {
	if s.Type.Type() == Null || (s.Type.Type() == Union && s.Type.(*UnionSchema).Types[0].Type() == Null) {
		return json.Marshal(struct {
			Name    string      `json:"name,omitempty"`
			Doc     string      `json:"doc,omitempty"`
			Default interface{} `json:"default"`
			Type    Schema      `json:"type,omitempty"`
		}{
			Name:    s.Name,
			Doc:     s.Doc,
			Default: s.Default,
			Type:    s.Type,
		})
	}

	return json.Marshal(struct {
		Name    string      `json:"name,omitempty"`
		Doc     string      `json:"doc,omitempty"`
		Default interface{} `json:"default,omitempty"`
		Type    Schema      `json:"type,omitempty"`
	}{
		Name:    s.Name,
		Doc:     s.Doc,
		Default: s.Default,
		Type:    s.Type,
	})
}
729808
func (f *Facade) walkServices(ctx datastore.Context, serviceID string, traverse bool, visitFn service.Visit, callerLabel string) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start(fmt.Sprintf("Facade.walkServices_%s", callerLabel)))
	store := f.serviceStore
	getChildren := func(parentID string) ([]service.Service, error) {
		if !traverse {
			return []service.Service{}, nil
		}
		return store.GetChildServices(ctx, parentID)
	}
	getService := func(svcID string) (service.Service, error) {
		svc, err := store.Get(ctx, svcID)
		if err != nil {
			return service.Service{}, err
		}
		return *svc, nil
	}

	return service.Walk(serviceID, visitFn, getService, getChildren)
}
245820
func recursiveToJSON(v interface{}) (r interface{}) {
	switch v := v.(type) {
	case []interface{}:
		for i, e := range v {
			v[i] = recursiveToJSON(e)
		}
		r = jsonArray(v)
	case map[interface{}]interface{}:
		newMap := make(map[string]interface{}, len(v))
		for k, e := range v {
			newMap[k.(string)] = recursiveToJSON(e)
		}
		r = jsonMap(newMap)
	default:
		r = v
	}
	return
}
933568
func Validate(config map[string]interface{}, version string) error {
	schemaData, err := _escFSByte(false, fmt.Sprintf("/data/config_schema_v%s.json", version))
	if err != nil {
		return errors.Errorf("unsupported Compose file version: %s", version)
	}

	schemaLoader := gojsonschema.NewStringLoader(string(schemaData))
	dataLoader := gojsonschema.NewGoLoader(config)

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

	if !result.Valid() {
		return toError(result)
	}

	return nil
}
325174
func (rr *RoutingRule) MarshalJSON() ([]byte, error) {
	if rr.Error != nil {
		return json.Marshal(rr.Error.Error())
	}
	tables := make([]string, 0, len(rr.Tables))
	for _, t := range rr.Tables {
		tables = append(tables, t.Keyspace.Name+"."+t.Name.String())
	}
	return json.Marshal(tables)
}
305088
func ConvertJSONSchemaPropsToOpenAPIv2Schema(in *apiextensions.JSONSchemaProps) (*spec.Schema, error) {
	if in == nil {
		return nil, nil
	}

	// dirty hack to temporarily set the type at the root. See continuation at the func bottom.
	// TODO: remove for Kubernetes 1.15
	oldRootType := in.Type
	if len(in.Type) == 0 {
		in.Type = "object"
	}

	// Remove unsupported fields in OpenAPI v2 recursively
	out := new(spec.Schema)
	validation.ConvertJSONSchemaPropsWithPostProcess(in, out, func(p *spec.Schema) error {
		p.OneOf = nil
		// TODO(roycaihw): preserve cases where we only have one subtree in AnyOf, same for OneOf
		p.AnyOf = nil
		p.Not = nil

		// TODO: drop everything below in 1.15 when we have passed one version skew towards kube-openapi in <1.14, which rejects valid openapi schemata

		if p.Ref.String() != "" {
			// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R95
			p.Properties = nil

			// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R99
			p.Type = nil

			// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R104
			if !strings.HasPrefix(p.Ref.String(), "#/definitions/") {
				p.Ref = spec.Ref{}
			}
		}

		switch {
		case len(p.Type) == 2 && (p.Type[0] == "null" || p.Type[1] == "null"):
			// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-ce77fea74b9dd098045004410023e0c3R219
			p.Type = nil
		case len(p.Type) == 1:
			switch p.Type[0] {
			case "null":
				// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-ce77fea74b9dd098045004410023e0c3R219
				p.Type = nil
			case "array":
				// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R183
				// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R184
				if p.Items == nil || (p.Items.Schema == nil && len(p.Items.Schemas) != 1) {
					p.Type = nil
					p.Items = nil
				}
			}
		case len(p.Type) > 1:
			// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R272
			// We also set Properties to null to enforce parseArbitrary at https://github.com/kubernetes/kube-openapi/blob/814a8073653e40e0e324205d093770d4e7bb811f/pkg/util/proto/document.go#L247
			p.Type = nil
			p.Properties = nil
		default:
			// https://github.com/kubernetes/kube-openapi/pull/143/files#diff-62afddb578e9db18fb32ffb6b7802d92R248
			p.Properties = nil
		}

		// normalize items
		if p.Items != nil && len(p.Items.Schemas) == 1 {
			p.Items = &spec.SchemaOrArray{Schema: &p.Items.Schemas[0]}
		}

		// general fixups not supported by gnostic
		p.ID = ""
		p.Schema = ""
		p.Definitions = nil
		p.AdditionalItems = nil
		p.Dependencies = nil
		p.PatternProperties = nil
		if p.ExternalDocs != nil && len(p.ExternalDocs.URL) == 0 {
			p.ExternalDocs = nil
		}
		if p.Items != nil && p.Items.Schemas != nil {
			p.Items = nil
		}

		return nil
	})

	// restore root level type in input, and remove it in output if we had added it
	// TODO: remove with Kubernetes 1.15
	in.Type = oldRootType
	if len(oldRootType) == 0 {
		out.Type = nil
	}

	return out, nil
}
1067919
func (s *ArraySchema) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type  string `json:"type,omitempty"`
		Items Schema `json:"items,omitempty"`
	}{
		Type:  "array",
		Items: s.Items,
	})
}
1198349
func SubSpan(path, key string, i, j int) (string, error) {
	si, ok := segIndexByKey(path, key)
	if !ok {
		return "", ErrKeySegNotFound
	}

	if i >= 0 {
		i++
	}
	if j > 0 {
		j++
	}

	s, err := Span(path[si:], i, j)
	if err != nil {
		return "", err
	}

	return s, nil
}
582425
func validateFieldMap(jsonFragment map[string]interface{}) error {

	//iterate the fields to validate the sort criteria
	for jsonKey, jsonValue := range jsonFragment {

		switch jsonValue.(type) {

		case string:
			//Ensure the sort is either "asc" or "desc"
			if !(strings.ToLower(jsonValue.(string)) == "asc" || strings.ToLower(jsonValue.(string)) == "desc") {
				return fmt.Errorf("Sort must be either \"asc\" or \"desc\".  \"%s\" was found.", jsonValue)
			}
			logger.Debugf("Found index field name: \"%s\":\"%s\"", jsonKey, jsonValue)

		default:
			return fmt.Errorf("Invalid field definition, fields must be in the form \"fieldname\":\"sort\"")

		}
	}

	return nil

}
1216613
func walkFunc(ctx expr.EvalContext, node *expr.FuncNode, depth int) (value.Value, bool) {

	if node.F.CustomFunc == nil {
		return nil, false
	}
	if node.Eval == nil {
		u.LogThrottle(u.WARN, 10, "No Eval() for %s", node.Name)
		return nil, false
	}

	args := make([]value.Value, len(node.Args))

	for i, a := range node.Args {
		v, ok := Eval(ctx, a)
		if !ok {
			v = value.NewNilValue()
		}
		args[i] = v
	}
	return node.Eval(ctx, args)
}
318665
func (s *MapSchema) Validate(v reflect.Value) bool {
	v = dereference(v)

	return v.Kind() == reflect.Map && v.Type().Key().Kind() == reflect.String
}
908514
func (vl *Validator) Validate(v interface{}) error {
	if v == nil {
		return nil
	}
	rv := reflect.ValueOf(v)
	w := &walker{
		v: vl,
		report: &ErrorReport{
			Root: rv,
			Type: "https://github.com/favclip/golidator",
		},
		ParentFieldName: "",
		Root:            rv,
		Current:         rv,
	}
	if err := w.walkStruct(); err != nil {
		return err
	}

	if len(w.report.Details) != 0 {
		return w.report
	}

	return nil
}
617875
func (self *Schema) UnmarshalJSON(b []byte) error {
	var m rawSchema
	err := json.Unmarshal(b, &m)
	if err == nil {
		o := Schema(m)
		*self = o
		err = self.Validate()
	}
	return err
}