Commit 3ffef3ea authored by Noel's avatar Noel
Browse files

Adapta la librería a nuestras necesidades

Añade la  etiqueta JsonUrl para añadir este campo al esquema
Modifica el build para exportar a una dependencia de maven
Añade tests
parent ffdcc987
Loading
Loading
Loading
Loading
+4 −3
Original line number Diff line number Diff line

lazy val commonSettings = Seq(
  organization := "com.kjetland",
  organization := "es.redmic.kjetland",
  organizationName := "mbknor",
  version := "1.0.11-SNAPSHOT",
  scalaVersion := "2.12.0",
@@ -15,7 +15,7 @@ lazy val commonSettings = Seq(
//    else
//      Some("releases"  at nexus + "thirdparty/")
//  },
  publishTo := {
  /*publishTo := {
    val nexus = "https://oss.sonatype.org/"
    if (isSnapshot.value)
      Some("snapshots" at nexus + "content/repositories/snapshots")
@@ -25,7 +25,8 @@ lazy val commonSettings = Seq(
  credentials += Credentials(Path.userHome / ".ivy2" / ".credentials"),
  homepage := Some(url("https://github.com/mbknor/mbknor-jackson-jsonSchema")),
  licenses := Seq("MIT" -> url("https://github.com/mbknor/mbknor-jackson-jsonSchema/blob/master/LICENSE.txt")),
  startYear := Some(2016),
  startYear := Some(2016),*/
  publishTo := Some(Resolver.file("file",  new File(Path.userHome.absolutePath+"/.m2/repository"))),
  pomExtra := (
      <scm>
        <url>git@github.com:mbknor/mbknor-jackson-jsonSchema.git</url>
+13 −0
Original line number Diff line number Diff line
package com.kjetland.jackson.jsonSchema.annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ METHOD, FIELD, PARAMETER, TYPE })
@Retention(RUNTIME)
public @interface JsonSchemaUrl {
    String value();
}
+87 −48
Original line number Diff line number Diff line
@@ -5,7 +5,7 @@ import java.time.{LocalDate, LocalDateTime, LocalTime, OffsetDateTime}
import java.util
import java.util.Optional
import javax.validation.constraints.{Max, Min, NotNull, Pattern, Size}

import scala.collection.JavaConverters._
import com.fasterxml.jackson.annotation.{JsonPropertyDescription, JsonSubTypes, JsonTypeInfo}
import com.fasterxml.jackson.core.JsonParser.NumberType
import com.fasterxml.jackson.databind.jsonFormatVisitors._
@@ -14,7 +14,7 @@ import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.introspect.{AnnotatedClass, JacksonAnnotationIntrospector}
import com.fasterxml.jackson.databind.node.{ArrayNode, JsonNodeFactory, ObjectNode}
import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaDefault, JsonSchemaDescription, JsonSchemaFormat, JsonSchemaTitle}
import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaDefault, JsonSchemaDescription, JsonSchemaFormat, JsonSchemaTitle, JsonSchemaUrl}
import org.slf4j.LoggerFactory

object JsonSchemaGenerator {
@@ -40,7 +40,7 @@ object JsonSchemaConfig {
    *
    * autoGenerateTitleForProperties - If property is named "someName", we will add {"title": "Some Name"}
    * defaultArrayFormat - this will result in a better gui than te default one.

    *
    */
  val html5EnabledSchema = JsonSchemaConfig(
    autoGenerateTitleForProperties = true,
@@ -89,9 +89,7 @@ object JsonSchemaConfig {
      customType2FormatMapping.asScala.toMap
    )
  }

}

  case class JsonSchemaConfig
  (
    autoGenerateTitleForProperties:Boolean,
@@ -107,26 +105,55 @@ case class JsonSchemaConfig



  object JsonSchemaResources {

    val defaultResources = JsonSchemaResources(
      properties = Map()
    )

    def setResources(
                      properties: java.util.Map[String, Object]
                    ): JsonSchemaResources = {

      import scala.collection.JavaConverters._

      JsonSchemaResources(
        properties.asScala.mapValues(_.toString).toMap
      )
    }
  }

  case class JsonSchemaResources
  (
    properties:Map[String, String]
  )


/**
  * Json Schema Generator
  * @param rootObjectMapper pre-configured ObjectMapper
  * @param debug Default = false - set to true if generator should log some debug info while generating the schema
  * @param config default = vanillaJsonSchemaDraft4. Please use html5EnabledSchema if generating HTML5 GUI, e.g. using https://github.com/jdorn/json-editor
  * @param resources Set if use url label
  */
class JsonSchemaGenerator
(
  val rootObjectMapper: ObjectMapper,
  resources:JsonSchemaResources = JsonSchemaResources.defaultResources,
  debug:Boolean = false,
  config:JsonSchemaConfig = JsonSchemaConfig.vanillaJsonSchemaDraft4
) {

  // Java API
  def this(rootObjectMapper: ObjectMapper) = this(rootObjectMapper, false, JsonSchemaConfig.vanillaJsonSchemaDraft4)
  def this(rootObjectMapper: ObjectMapper) = this(rootObjectMapper, JsonSchemaResources.defaultResources, false, JsonSchemaConfig.vanillaJsonSchemaDraft4)

  // Java API
  def this(rootObjectMapper: ObjectMapper, config:JsonSchemaConfig) = this(rootObjectMapper, false, config)
  def this(rootObjectMapper: ObjectMapper, config:JsonSchemaConfig) = this(rootObjectMapper, JsonSchemaResources.defaultResources, false, config)

  // Java API
  def this(rootObjectMapper: ObjectMapper, resources: JsonSchemaResources) = this(rootObjectMapper, resources, false, JsonSchemaConfig.vanillaJsonSchemaDraft4)


  import scala.collection.JavaConverters._

  val log = LoggerFactory.getLogger(getClass)

@@ -173,6 +200,7 @@ class JsonSchemaGenerator

  // Class that manages creating new defenitions or getting $refs to existing definitions
  class DefinitionsHandler() {

    private var class2Ref = Map[Class[_], String]()
    private val definitionsNode = JsonNodeFactory.instance.objectNode()

@@ -245,6 +273,7 @@ class JsonSchemaGenerator
    currentProperty:Option[BeanProperty] // This property may represent the BeanProperty when we're directly processing beneath the property
  ) extends JsonFormatVisitorWrapper with MySerializerProvider {


    def l(s: => String): Unit = {
      if (!debug) return

@@ -540,14 +569,12 @@ class JsonSchemaGenerator
            val thisOneOfNode = JsonNodeFactory.instance.objectNode()
            thisOneOfNode.put("$ref", definitionInfo.ref.get)
            anyOfArrayNode.add(thisOneOfNode)

        }

        null // Returning null to stop jackson from visiting this object since we have done it manually

      } else {


        val objectBuilder:ObjectNode => Option[JsonObjectFormatVisitor] = {
          thisObjectNode:ObjectNode =>

@@ -735,6 +762,19 @@ class JsonSchemaGenerator
                      thisPropertyNode.meta.put("title", title)
                  }


                // Optionally add url
                prop.flatMap {
                  p: BeanProperty =>
                    Option(p.getAnnotation(classOf[JsonSchemaUrl])).map(_.value())
                }.map {
                  url =>
                    thisPropertyNode.meta.put("type", "integer")
                    thisPropertyNode.meta.put("url", resources.properties.get(url).getOrElse("none"))
                    thisPropertyNode.meta.remove("$ref")
                    definitionsHandler.getFinalDefinitionsNode().get.remove(propertyType.getRawClass.getSimpleName)
                }

              }

              override def optionalProperty(prop: BeanProperty): Unit = {
@@ -759,6 +799,7 @@ class JsonSchemaGenerator
            })
        }


        if ( level == 0 ) {
          // This is the first level - we must not use definitions
          objectBuilder(node).orNull
@@ -773,7 +814,6 @@ class JsonSchemaGenerator

            definitionInfo.jsonObjectFormatVisitor.orNull
        }

      }

    }
@@ -872,7 +912,6 @@ class JsonSchemaGenerator
        // If root class is annotated with @JsonSchemaDescription, it will later override this description
    }


    val definitionsHandler = new DefinitionsHandler
    val rootVisitor = new MyJsonFormatVisitorWrapper(rootObjectMapper, node = rootNode, definitionsHandler = definitionsHandler, currentProperty = None)
    rootObjectMapper.acceptJsonFormatVisitor(clazz, rootVisitor)
+34 −5
Original line number Diff line number Diff line
@@ -51,13 +51,27 @@ class JsonSchemaGeneratorTest extends FunSuite with Matchers {



  val jsonSchemaGenerator = new JsonSchemaGenerator(_objectMapper, debug = true)
  val jsonSchemaGeneratorHTML5 = new JsonSchemaGenerator(_objectMapper, debug = true, config = JsonSchemaConfig.html5EnabledSchema)
  val jsonSchemaGeneratorScala = new JsonSchemaGenerator(_objectMapperScala, debug = true)
  val jsonSchemaGeneratorScalaHTML5 = new JsonSchemaGenerator(_objectMapperScala, debug = true, config = JsonSchemaConfig.html5EnabledSchema)

  val jsonSchemaGenerator = new JsonSchemaGenerator(_objectMapper, null, debug = true)
  val jsonSchemaGeneratorHTML5 = new JsonSchemaGenerator(_objectMapper, null, debug = true, config = JsonSchemaConfig.html5EnabledSchema)
  val jsonSchemaGeneratorScala = new JsonSchemaGenerator(_objectMapperScala, null, debug = true)
  val jsonSchemaGeneratorScalaHTML5 = new JsonSchemaGenerator(_objectMapperScala, null, debug = true, config = JsonSchemaConfig.html5EnabledSchema)

  val vanillaJsonSchemaDraft4WithIds = JsonSchemaConfig.html5EnabledSchema.copy(useTypeIdForDefinitionName = true)
  val jsonSchemaGeneratorWithIds = new JsonSchemaGenerator(_objectMapperScala, debug = true, vanillaJsonSchemaDraft4WithIds)
  val jsonSchemaGeneratorWithIds = new JsonSchemaGenerator(_objectMapperScala, null, debug = true, vanillaJsonSchemaDraft4WithIds)

  val properties = new util.HashMap[String, Object]();
  properties.put("ACTIVITYBASE", "/operator/activities/");
  properties.put("ACCESSIBILITY", "/operator/accessibilities/");
  properties.put("SCOPE", "/operator/scopes/");
  properties.put("ACTIVITYTYPE", "/operator/activitytypes");
  properties.put("ACTIVITYDOCUMENT", "/operator/documents/");
  properties.put("ACTIVITYPLATFORMROLE", "/operator/contactroles/");
  properties.put("CONTACTORGANISATIONROLE", "/operator/contactroles/");
  properties.put("ORGANISATIONROLE", "/operator/organisationroles/");

  val jsonSchemaGeneratorWithResources = new JsonSchemaGenerator(_objectMapperScala, JsonSchemaResources.setResources(properties), debug = true, vanillaJsonSchemaDraft4WithIds)


  val testData = new TestData{}

@@ -161,6 +175,21 @@ class JsonSchemaGeneratorTest extends FunSuite with Matchers {
    root.at(fixedRef).asInstanceOf[ObjectNode]
  }



  test("Generate scheme for @JsonUrl") {

    {
      val schema = jsonSchemaGeneratorWithResources.generateJsonSchema(classOf[ClassWithRelation]);
      println("dentrooooooooooooooooooooo")
      println(schema)

    }
  }




  test("Generate scheme for plain class not using @JsonTypeInfo") {

    val enumList = MyEnum.values().toList.map(_.toString)
+41 −0
Original line number Diff line number Diff line
package com.kjetland.jackson.jsonSchema.testData;

import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaUrl;

/**
 * Created by noel on 5/12/16.
 */
public class ClassWithRelation {

    private Long id;

    private String name;

    @JsonSchemaUrl(value="ACCESSIBILITY")
    private Relation type;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Relation getType() {
        return type;
    }

    public void setType(Relation type) {
        this.type = type;
    }

    public Long getId() {

        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
Loading