Skip to content

Instantly share code, notes, and snippets.

@afranzi
Created March 13, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afranzi/527674af16d9f51556f4f401934e31a7 to your computer and use it in GitHub Desktop.
Save afranzi/527674af16d9f51556f4f401934e31a7 to your computer and use it in GitHub Desktop.
Schema Validation Listener for JSON Schemas
import SchemaValidationListener._
import org.everit.json.schema.Schema
import org.everit.json.schema.event.{CombinedSchemaMatchEvent, SchemaReferencedEvent, ValidationListener}
import scala.collection.mutable.ListBuffer
import scala.util.matching.Regex
import scala.collection.JavaConverters._
object SchemaValidationListener {
case class SchemaReferenced(location: String, schemaId: String)
val SchemaId = "schemaId"
val schemaRefRe: Regex = "^\\{\"\\$ref\":\"([\\w\\/._-]+)\"\\}$".r(SchemaId)
def extractSchemaReferenced(schema: String): Option[String] = {
schemaRefRe
.findFirstMatchIn(schema)
.map(_.group(SchemaId))
}
}
case class SchemaValidationListener() extends ValidationListener {
val schemasReferencedMatching: ListBuffer[SchemaReferenced] = ListBuffer.empty
override def schemaReferenced(event: SchemaReferencedEvent): Unit = {
val subSchema: Schema = event.getReferredSchema
val schemaReferenced = Option(subSchema.getId).getOrElse(subSchema.getSchemaLocation)
val path = event.getPath.asScala.mkString("/")
val reference = SchemaReferenced(path, schemaReferenced)
schemasReferencedMatching.append(reference)
}
override def combinedSchemaMatch(event: CombinedSchemaMatchEvent): Unit = {
val subSchema: Schema = event.getSubSchema
val path = event.getPath.asScala.mkString("/")
extractSchemaReferenced(subSchema.toString)
.foreach { schemaId =>
val reference = SchemaReferenced(path, schemaId)
schemasReferencedMatching.append(reference)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment