schemaPool.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. // Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // author xeipuuv
  15. // author-github https://github.com/xeipuuv
  16. // author-mail xeipuuv@gmail.com
  17. //
  18. // repository-name gojsonschema
  19. // repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
  20. //
  21. // description Defines resources pooling.
  22. // Eases referencing and avoids downloading the same resource twice.
  23. //
  24. // created 26-02-2013
  25. package gojsonschema
  26. import (
  27. "errors"
  28. "fmt"
  29. "reflect"
  30. "github.com/xeipuuv/gojsonreference"
  31. )
  32. type schemaPoolDocument struct {
  33. Document interface{}
  34. Draft *Draft
  35. }
  36. type schemaPool struct {
  37. schemaPoolDocuments map[string]*schemaPoolDocument
  38. jsonLoaderFactory JSONLoaderFactory
  39. autoDetect *bool
  40. }
  41. func (p *schemaPool) parseReferences(document interface{}, ref gojsonreference.JsonReference, pooled bool) error {
  42. var (
  43. draft *Draft
  44. err error
  45. reference = ref.String()
  46. )
  47. // Only the root document should be added to the schema pool if pooled is true
  48. if _, ok := p.schemaPoolDocuments[reference]; pooled && ok {
  49. return fmt.Errorf("Reference already exists: \"%s\"", reference)
  50. }
  51. if *p.autoDetect {
  52. _, draft, err = parseSchemaURL(document)
  53. if err != nil {
  54. return err
  55. }
  56. }
  57. err = p.parseReferencesRecursive(document, ref, draft)
  58. if pooled {
  59. p.schemaPoolDocuments[reference] = &schemaPoolDocument{Document: document, Draft: draft}
  60. }
  61. return err
  62. }
  63. func (p *schemaPool) parseReferencesRecursive(document interface{}, ref gojsonreference.JsonReference, draft *Draft) error {
  64. // parseReferencesRecursive parses a JSON document and resolves all $id and $ref references.
  65. // For $ref references it takes into account the $id scope it is in and replaces
  66. // the reference by the absolute resolved reference
  67. // When encountering errors it fails silently. Error handling is done when the schema
  68. // is syntactically parsed and any error encountered here should also come up there.
  69. switch m := document.(type) {
  70. case []interface{}:
  71. for _, v := range m {
  72. p.parseReferencesRecursive(v, ref, draft)
  73. }
  74. case map[string]interface{}:
  75. localRef := &ref
  76. keyID := KEY_ID_NEW
  77. if existsMapKey(m, KEY_ID) {
  78. keyID = KEY_ID
  79. }
  80. if existsMapKey(m, keyID) && isKind(m[keyID], reflect.String) {
  81. jsonReference, err := gojsonreference.NewJsonReference(m[keyID].(string))
  82. if err == nil {
  83. localRef, err = ref.Inherits(jsonReference)
  84. if err == nil {
  85. if _, ok := p.schemaPoolDocuments[localRef.String()]; ok {
  86. return fmt.Errorf("Reference already exists: \"%s\"", localRef.String())
  87. }
  88. p.schemaPoolDocuments[localRef.String()] = &schemaPoolDocument{Document: document, Draft: draft}
  89. }
  90. }
  91. }
  92. if existsMapKey(m, KEY_REF) && isKind(m[KEY_REF], reflect.String) {
  93. jsonReference, err := gojsonreference.NewJsonReference(m[KEY_REF].(string))
  94. if err == nil {
  95. absoluteRef, err := localRef.Inherits(jsonReference)
  96. if err == nil {
  97. m[KEY_REF] = absoluteRef.String()
  98. }
  99. }
  100. }
  101. for k, v := range m {
  102. // const and enums should be interpreted literally, so ignore them
  103. if k == KEY_CONST || k == KEY_ENUM {
  104. continue
  105. }
  106. // Something like a property or a dependency is not a valid schema, as it might describe properties named "$ref", "$id" or "const", etc
  107. // Therefore don't treat it like a schema.
  108. if k == KEY_PROPERTIES || k == KEY_DEPENDENCIES || k == KEY_PATTERN_PROPERTIES {
  109. if child, ok := v.(map[string]interface{}); ok {
  110. for _, v := range child {
  111. p.parseReferencesRecursive(v, *localRef, draft)
  112. }
  113. }
  114. } else {
  115. p.parseReferencesRecursive(v, *localRef, draft)
  116. }
  117. }
  118. }
  119. return nil
  120. }
  121. func (p *schemaPool) GetDocument(reference gojsonreference.JsonReference) (*schemaPoolDocument, error) {
  122. var (
  123. spd *schemaPoolDocument
  124. draft *Draft
  125. ok bool
  126. err error
  127. )
  128. if internalLogEnabled {
  129. internalLog("Get Document ( %s )", reference.String())
  130. }
  131. // Create a deep copy, so we can remove the fragment part later on without altering the original
  132. refToURL, _ := gojsonreference.NewJsonReference(reference.String())
  133. // First check if the given fragment is a location independent identifier
  134. // http://json-schema.org/latest/json-schema-core.html#rfc.section.8.2.3
  135. if spd, ok = p.schemaPoolDocuments[refToURL.String()]; ok {
  136. if internalLogEnabled {
  137. internalLog(" From pool")
  138. }
  139. return spd, nil
  140. }
  141. // If the given reference is not a location independent identifier,
  142. // strip the fragment and look for a document with it's base URI
  143. refToURL.GetUrl().Fragment = ""
  144. if cachedSpd, ok := p.schemaPoolDocuments[refToURL.String()]; ok {
  145. document, _, err := reference.GetPointer().Get(cachedSpd.Document)
  146. if err != nil {
  147. return nil, err
  148. }
  149. if internalLogEnabled {
  150. internalLog(" From pool")
  151. }
  152. spd = &schemaPoolDocument{Document: document, Draft: cachedSpd.Draft}
  153. p.schemaPoolDocuments[reference.String()] = spd
  154. return spd, nil
  155. }
  156. // It is not possible to load anything remotely that is not canonical...
  157. if !reference.IsCanonical() {
  158. return nil, errors.New(formatErrorDescription(
  159. Locale.ReferenceMustBeCanonical(),
  160. ErrorDetails{"reference": reference.String()},
  161. ))
  162. }
  163. jsonReferenceLoader := p.jsonLoaderFactory.New(reference.String())
  164. document, err := jsonReferenceLoader.LoadJSON()
  165. if err != nil {
  166. return nil, err
  167. }
  168. // add the whole document to the pool for potential re-use
  169. p.parseReferences(document, refToURL, true)
  170. _, draft, _ = parseSchemaURL(document)
  171. // resolve the potential fragment and also cache it
  172. document, _, err = reference.GetPointer().Get(document)
  173. if err != nil {
  174. return nil, err
  175. }
  176. return &schemaPoolDocument{Document: document, Draft: draft}, nil
  177. }