com.fasterxml.jackson.annotation.JsonProperty Scala Examples

The following examples show how to use com.fasterxml.jackson.annotation.JsonProperty. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SidechainCommitmentEntryProof.scala    From Sidechains-SDK   with MIT License 5 votes vote down vote up
package com.horizen.block

import com.fasterxml.jackson.annotation.{JsonProperty, JsonView}
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.horizen.serialization.{JsonMerklePathSerializer, Views}
import com.horizen.utils.MerklePath
import scorex.core.serialization.{BytesSerializable, ScorexSerializer}
import scorex.util.serialization.{Reader, Writer}

@JsonView(Array(classOf[Views.Default]))
case class SidechainCommitmentEntryProof(sidechainId: Array[Byte],
                                         txsHash: Array[Byte],
                                         wcertHash: Array[Byte],
                                         @JsonProperty("merklePath")
                                         @JsonSerialize(using = classOf[JsonMerklePathSerializer])
                                         merklePath: MerklePath
                                        )
  extends BytesSerializable
{
  override type M = SidechainCommitmentEntryProof

  override def serializer: ScorexSerializer[SidechainCommitmentEntryProof] = SidechainCommitmentEntryProofSerializer
}

object SidechainCommitmentEntryProofSerializer extends ScorexSerializer[SidechainCommitmentEntryProof]
{
  override def serialize(proof: SidechainCommitmentEntryProof, w: Writer): Unit = {
    w.putBytes(proof.sidechainId)
    w.putBytes(proof.txsHash)
    w.putBytes(proof.wcertHash)
    w.putInt(proof.merklePath.bytes().length)
    w.putBytes(proof.merklePath.bytes())
  }

  override def parse(r: Reader): SidechainCommitmentEntryProof = {
    val sidechainId = r.getBytes(32)
    val txsHash = r.getBytes(32)
    val wcertHash = r.getBytes(32)
    val merklePathSize = r.getInt()
    val merklePath = MerklePath.parseBytes(r.getBytes(merklePathSize))

    SidechainCommitmentEntryProof(sidechainId, txsHash, wcertHash, merklePath)
  }
} 
Example 2
Source File: YamlProjectOperationInfoParser.scala    From rug   with GNU General Public License v3.0 5 votes vote down vote up
package com.atomist.project.common.yaml

import java.util.regex.{Pattern, PatternSyntaxException}

import com.atomist.param._
import com.atomist.project.common.template.{InvalidTemplateException, TemplateBasedProjectOperationInfo}
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import org.apache.commons.lang3.builder.ReflectionToStringBuilder

import scala.util.{Failure, Success, Try}


object YamlProjectOperationInfoParser {

  private val mapper = new ObjectMapper(new YAMLFactory()) with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)

  @throws[InvalidYamlDescriptorException]
  def parse(yaml: String): TemplateBasedProjectOperationInfo = {
    if (yaml == null || "".equals(yaml))
      throw new InvalidYamlDescriptorException("YAML content required in template metadata file")

    Try(mapper.readValue(yaml, classOf[BoundProjectOperationInfo])) match {
      case s: Success[BoundProjectOperationInfo] =>
        val badPatterns = s.value.parameters.flatMap(p => patternError(p))
        if (badPatterns.nonEmpty)
          throw new InvalidYamlDescriptorException(s"Bad regexp patterns: ${badPatterns.mkString(",")}")
        s.value
      case f: Failure[BoundProjectOperationInfo] =>
        throw new InvalidYamlDescriptorException(s"Failed to parse YAML [$yaml]: ${f.exception.getMessage}", f.exception)
    }
  }

  private def patternError(p: Parameter): Option[String] = {
    try {
      Pattern.compile(p.getPattern)
      None
    } catch {
      case pse: PatternSyntaxException => Some(s"${p.getName}: Bad regular expression pattern: ${pse.getMessage}")
    }
  }
}

private class BoundProjectOperationInfo extends TemplateBasedProjectOperationInfo {

  @JsonProperty("name")
  var name: String = _

  @JsonProperty("description")
  var description: String = _

  @JsonProperty("template_name")
  var templateName: String = _

  @JsonProperty("type")
  var _templateType: String = _

  override def templateType: Option[String] =
    if (_templateType == null || "".equals(_templateType)) None
    else Some(_templateType)

  @JsonProperty("parameters")
  private var _params: Seq[Parameter] = Nil

  @JsonProperty("tags")
  private var _tags: Seq[TagHolder] = Nil

  override def parameters: Seq[Parameter] = _params

  override def tags: Seq[Tag] = _tags.map(tw => tw.toTag)

  override def toString = ReflectionToStringBuilder.toString(this)
}

private class TagHolder {

  @JsonProperty
  var name: String = _

  @JsonProperty
  var description: String = _

  def toTag = Tag(name, description)
}

class InvalidYamlDescriptorException(msg: String, ex: Throwable = null) extends InvalidTemplateException(msg, ex) 
Example 3
Source File: TestStrategy.scala    From regressr   with Apache License 2.0 5 votes vote down vote up
package org.ebayopensource.regression.internal.reader

import java.net.URI
import java.util
import java.util.{UUID, List => JList, Map => JMap}

import org.ebayopensource.regression.internal.components.comparator.common.Comparator
import org.ebayopensource.regression.internal.components.continuation.Continuation
import org.ebayopensource.regression.internal.components.printer.ProgressPrinter
import org.ebayopensource.regression.internal.components.recorder.common.Recorder
import org.ebayopensource.regression.internal.components.requestBuilder.RequestPayloadBuilder
import com.fasterxml.jackson.annotation.JsonProperty

import scala.collection.JavaConversions._


class TestStrategy(@JsonProperty("service") _service: Service,
               @JsonProperty(value = "commonHeaders", required = false) _headers: JMap[String, String],
               @JsonProperty("requests") _requests: JList[RequestEntry]) {
  val service = _service
  val headers: Map[String, String] = setSpecialHeaders(Option(_headers).getOrElse(new util.HashMap).toMap)
  val requests = _requests.toList

  def setSpecialHeaders(headers: Map[String, String]): Map[String, String] = {
    headers map { case (k,v) => if (v.equals("<new-guid>")) (k, UUID.randomUUID().toString) else (k, v) }
  }
}

class Service(@JsonProperty(value = "baseURL", required = true) _baseURL: String) {
  val baseURL = new URI(_baseURL)
}

class RequestEntry(@JsonProperty(value = "requestName", required = true) _reqName: String,
                   @JsonProperty(value = "path", required = true) _path: String,
                   @JsonProperty(value = "method", required = true) _method: String,
                   @JsonProperty(value = "extraHeaders", required = false) _headers: JMap[String, String],
                   @JsonProperty(value = "requestBuilder", required = false) _bodyBuilder: String,
                   @JsonProperty(value = "recorder", required = true) _recorder: String,
                   @JsonProperty(value = "continuation", required = false) _continuation: String,
                   @JsonProperty(value = "comparator", required = true) _comparator: String,
                   @JsonProperty(value = "dataInput", required = false) _dataInput: JMap[String, String],
                   @JsonProperty(value = "progressPrinter", required = false) _progressPrinter: String)
{
  val requestName = _reqName.replaceAll(" ", "_")
  val path = _path
  val method : HttpMethods.Value = HttpMethods.withName(_method)
  val extraHeaders = Option(_headers).getOrElse(new util.HashMap[String, String]()).toMap
  val requestBuilder = if (Option(_bodyBuilder).isDefined) Some(Class.forName(_bodyBuilder).newInstance().asInstanceOf[RequestPayloadBuilder]) else None
  val recorder = Class.forName(_recorder).newInstance().asInstanceOf[Recorder]
  val comparator = Class.forName(_comparator).newInstance().asInstanceOf[Comparator]
  val continuation = if (Option(_continuation).isDefined) Some(Class.forName(_continuation).newInstance().asInstanceOf[Continuation]) else None
  val dataInput = Option(_dataInput).getOrElse(new util.HashMap[String, String]()).toMap
  val progressPrinter = if (Option(_progressPrinter).isDefined) Some(Class.forName(_progressPrinter).newInstance().asInstanceOf[ProgressPrinter]) else None
}

object HttpMethods extends Enumeration {
  val GET, POST, PUT, DELETE = Value
} 
Example 4
Source File: OperationResponse.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import de.leanovate.swaggercheck.SwaggerChecks
import de.leanovate.swaggercheck.schema.model.{Definition, JsonPath, ValidationResult}
import de.leanovate.swaggercheck.shrinkable.{CheckJsString, CheckJsValue}

@JsonDeserialize(builder = classOf[OperationResponseBuilder])
case class OperationResponse(
                              schema: Option[Definition],
                              headers: Seq[(String, Definition)]
                              ) {
  def verify(context: SwaggerChecks, requestHeader: Map[String, String], requestBody: String): ValidationResult = {
    val bodyVerify = schema.map {
      expected =>
        expected.validate(context, JsonPath(), CheckJsValue.parse(requestBody))
    }.getOrElse(ValidationResult.success)

    headers.foldLeft(bodyVerify) {
      case (result, (name, schema)) =>
        result.combine(
          requestHeader.get(name.toLowerCase)
            .map(value => schema.validate[CheckJsValue](context, JsonPath(), CheckJsString.formatted(value)))
            .getOrElse(ValidationResult.success))
    }
  }
}

class OperationResponseBuilder @JsonCreator()(
                                               @JsonProperty("schema") schema: Option[Definition],
                                               @JsonProperty("headers") headers: Option[Map[String, Definition]]
                                               ) {
  def build(): OperationResponse = OperationResponse(schema, headers.map(_.toSeq).getOrElse(Seq.empty))
} 
Example 5
Source File: SwaggerAPI.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema

import java.io.InputStream

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, MappingJsonFactory, ObjectMapper}
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import de.leanovate.swaggercheck.schema.jackson.JsonSchemaModule
import de.leanovate.swaggercheck.schema.model.{Definition, Parameter}

import scala.collection.JavaConverters._
import scala.io.Source

@JsonDeserialize(builder = classOf[SwaggerAPIBuilder])
case class SwaggerAPI(
                       basePath: Option[String],
                       paths: Map[String, Map[String, Operation]],
                       definitions: Map[String, Definition]
                     )

object SwaggerAPI {
  val jsonMapper = objectMapper(new MappingJsonFactory())
  val yamlMapper = objectMapper(new YAMLFactory())

  def parse(jsonOrYaml: String): SwaggerAPI = {
    val mapper = if (jsonOrYaml.trim().startsWith("{")) jsonMapper else yamlMapper
    mapper.readValue(jsonOrYaml, classOf[SwaggerAPI])
  }

  def parse(swaggerInput: InputStream): SwaggerAPI = {
    parse(Source.fromInputStream(swaggerInput).mkString)
  }

  def objectMapper(jsonFactory: JsonFactory): ObjectMapper = {
    val mapper = new ObjectMapper(jsonFactory)
    mapper.registerModule(DefaultScalaModule)
    mapper.registerModule(JsonSchemaModule)
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    mapper
  }
}

class SwaggerAPIBuilder @JsonCreator()(
                                        @JsonProperty("basePath") basePath: Option[String],
                                        @JsonProperty("consumes") consumes: Option[Seq[String]],
                                        @JsonProperty("produces") produces: Option[Seq[String]],
                                        @JsonProperty("paths") paths: Option[Map[String, JsonNode]],
                                        @JsonProperty("definitions") definitions: Option[Map[String, Definition]],
                                        @JsonProperty("parameters") globalParameters: Option[Map[String, Parameter]]
                                      ) {
  def build(): SwaggerAPI = {
    val defaultConsumes = consumes.map(_.toSet).getOrElse(Set.empty)
    val defaultProduces = produces.map(_.toSet).getOrElse(Set.empty)
    SwaggerAPI(basePath,
      paths.getOrElse(Map.empty).map {
        case (path, pathDefinition) =>
          val defaultParameters = Option(pathDefinition.get("parameters")).map {
             node =>
               node.iterator().asScala.map {
                 element => SwaggerAPI.jsonMapper.treeToValue(element, classOf[OperationParameter])
               }.toSeq
          }.getOrElse(Seq.empty)

          basePath.map(_ + path).getOrElse(path) -> pathDefinition.fields().asScala.filter(_.getKey != "parameters").map {
            entry =>
              val operation = SwaggerAPI.jsonMapper.treeToValue(entry.getValue, classOf[Operation])
              entry.getKey.toUpperCase -> operation.withDefaults(defaultParameters, defaultConsumes, defaultProduces).resolveGlobalParameters(globalParameters.getOrElse(Map()))
          }.toMap
      },
      definitions.getOrElse(Map.empty))
  }
} 
Example 6
Source File: OperationParameter.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import de.leanovate.swaggercheck.SwaggerChecks
import de.leanovate.swaggercheck.schema.Operation.RequestBuilder
import de.leanovate.swaggercheck.schema.gen.GeneratableDefinition._
import de.leanovate.swaggercheck.schema.jackson.DefinitionBuilder
import de.leanovate.swaggercheck.schema.model.Definition
import org.scalacheck.Gen

@JsonDeserialize(builder = classOf[OperationParameterBuilder])
case class OperationParameter(
                               name: Option[String],
                               in: String,
                               required: Boolean,
                               schema: Definition
                             ) {
  def applyTo(context: SwaggerChecks, builder: RequestBuilder): RequestBuilder = (name, in) match {
    case (Some(paramName), "path") =>
      builder.withPathParam(schema.generate(context)
        .map(value => Some(paramName -> value.asText("")))
        .suchThat(_.get._2.length > 0))
    case (Some(paramName), "query") if required =>
      builder.withQueryParam(schema.generate(context).map(value => Some(paramName -> value.asText(""))))
    case (Some(paramName), "query") =>
      builder.withQueryParam(Gen.option(schema.generate(context).map(value => paramName -> value.asText(""))))
    case (Some(headerName), "header") if required =>
      builder.withHeader(schema.generate(context).map(value => Some(headerName -> value.asText(""))))
    case (Some(headerName), "header") =>
      builder.withHeader(Gen.option(schema.generate(context).map(value => headerName -> value.asText(""))))
    case (_, "body") => builder.withBody(schema.generate(context))
    case _ => builder
  }
}

class ReferenceOperationParameter(globalRef: String) extends OperationParameter(None, "", false, null) {
  require(globalRef.startsWith("#/parameters/"), "Global parameters references need to start with #/parameters/")
  val ref = globalRef.substring(13)

  override def applyTo(context: SwaggerChecks, builder: RequestBuilder): RequestBuilder = throw new IllegalStateException("Not resolved ReferenceParameter")
}

object ReferenceOperationParameter {
  def unapply(parameter: ReferenceOperationParameter): Option[String] = Some(parameter.ref)
}

class OperationParameterBuilder @JsonCreator()(
                                                @JsonProperty("name") name: Option[String],
                                                @JsonProperty("$ref") ref: Option[String],
                                                @JsonProperty("in") in: String,
                                                @JsonProperty("required") required: Option[Boolean],
                                                @JsonProperty("type") schemaType: Option[String],
                                                @JsonProperty("format") format: Option[String],
                                                @JsonProperty("schema") schema: Option[Definition],
                                                @JsonProperty("enum") enum: Option[List[String]]
                                              ) {
  def build(): OperationParameter =
    ref match {
      case Some(reference) => new ReferenceOperationParameter(reference)
      case None => OperationParameter(
      name,
      in,
      required.getOrElse(false),
      schema.getOrElse(new DefinitionBuilder(schemaType = schemaType, format = format, enum = enum).build()))

  }
} 
Example 7
Source File: DefinitionBuilder.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.jackson

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import de.leanovate.swaggercheck.schema.model._

@JsonDeserialize(builder = classOf[DefinitionBuilder])
trait DefinitionMixin {

}

class DefinitionBuilder @JsonCreator()(
                                        @JsonProperty("type") schemaType: Option[String] = None,
                                        @JsonProperty("allOf") allOf: Option[Seq[Definition]] = None,
                                        @JsonProperty("enum") enum: Option[List[String]] = None,
                                        @JsonProperty("exclusiveMinimum") exclusiveMinimum: Option[Boolean] = None,
                                        @JsonProperty("exclusiveMaximum") exclusiveMaximum: Option[Boolean] = None,
                                        @JsonProperty("format") format: Option[String] = None,
                                        @JsonProperty("items") items: Option[Definition] = None,
                                        @JsonProperty("minItems") minItems: Option[Int] = None,
                                        @JsonProperty("maxItems") maxItems: Option[Int] = None,
                                        @JsonProperty("minimum") minimum: Option[BigDecimal] = None,
                                        @JsonProperty("maximum") maximum: Option[BigDecimal] = None,
                                        @JsonProperty("minLength") minLength: Option[Int] = None,
                                        @JsonProperty("maxLength") maxLength: Option[Int] = None,
                                        @JsonProperty("oneOf") oneOf: Option[Seq[Definition]] = None,
                                        @JsonProperty("pattern") pattern: Option[String] = None,
                                        @JsonProperty("properties") properties: Option[Map[String, Definition]] = None,
                                        @JsonProperty("additionalProperties") additionalPropertiesNode: Option[JsonNode] = None,
                                        @JsonProperty("required") required: Option[Set[String]] = None,
                                        @JsonProperty("$ref") ref: Option[String] = None,
                                        @JsonProperty("uniqueItems") uniqueItems: Option[Boolean] = None) {
  val additionalProperties = additionalPropertiesNode.map {
    case node if node.isBoolean => Left(node.isBinary)
    case node => Right(DefinitionBuilder.mapper.treeToValue(node, classOf[Definition]))
  }

  def build(): Definition = {
    Definition.build(
      schemaType,
      allOf,
      enum,
      exclusiveMinimum,
      exclusiveMaximum,
      format,
      items,
      minItems,
      maxItems,
      minimum,
      maximum,
      minLength,
      maxLength,
      oneOf,
      pattern,
      properties,
      additionalProperties,
      required,
      ref,
      uniqueItems
    )
  }
}

object DefinitionBuilder {
  val mapper = new ObjectMapper().registerModule(DefaultScalaModule).registerModule(JsonSchemaModule)
} 
Example 8
Source File: ParameterMixin.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.schema.jackson

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import de.leanovate.swaggercheck.schema.model._

@JsonDeserialize(builder = classOf[ParameterBuilder])
trait ParameterMixin {

}

class ParameterBuilder @JsonCreator()(
                                       @JsonProperty("name") name: String,
                                       @JsonProperty("in") in: String,
                                       @JsonProperty("required") required: Option[Boolean] = None,
                                       @JsonProperty("type") schemaType: Option[String] = None,
                                       @JsonProperty("schema") schema: Option[Definition] = None,
                                       @JsonProperty("format") format: Option[String] = None,
                                       @JsonProperty("allowEmptyValue") allowEmptyValue: Option[Boolean] = None,
                                       @JsonProperty("items") items: Option[Definition] = None,
                                       @JsonProperty("maximum") maximum: Option[BigDecimal] = None,
                                       @JsonProperty("exclusiveMaximum") exclusiveMaximum: Option[Boolean] = None,
                                       @JsonProperty("minimum") minimum: Option[BigDecimal] = None,
                                       @JsonProperty("exclusiveMinimum") exclusiveMinimum: Option[Boolean] = None,
                                       @JsonProperty("maxLength") maxLength: Option[Int] = None,
                                       @JsonProperty("minLength") minLength: Option[Int] = None,
                                       @JsonProperty("pattern") pattern: Option[String] = None,
                                       @JsonProperty("maxItems") maxItems: Option[Int] = None,
                                       @JsonProperty("minItems") minItems: Option[Int] = None,
                                       @JsonProperty("uniqueItems") uniqueItems: Option[Boolean] = None,
                                       @JsonProperty("enum") enum: Option[List[String]] = None) {


  def build(): Parameter = {
    Parameter.build(
      name,
      in,
      required,
      schema,
      schemaType,
      format,
      allowEmptyValue,
      items,
      maximum,
      exclusiveMaximum,
      minimum,
      exclusiveMinimum,
      maxLength,
      minLength,
      pattern,
      maxItems,
      minItems,
      uniqueItems,
      enum
    )
  }
} 
Example 9
Source File: Point.scala    From magellan   with Apache License 2.0 5 votes vote down vote up
package magellan

import com.fasterxml.jackson.annotation.{JsonIgnore, JsonProperty}
import org.apache.spark.sql.types._
import org.json4s.JsonAST.JValue
import org.json4s.JsonDSL._


  override def transform(fn: (Point) => Point): Point = fn(this)

  def withinCircle(origin: Point, radius: Double): Boolean = {
    val sqrdL2Norm = Math.pow((origin.getX() - getX()), 2) + Math.pow((origin.getY() - getY()), 2)
    sqrdL2Norm <= Math.pow(radius, 2)
  }

  @JsonProperty
  override def getType(): Int = 1

  override def jsonValue: JValue =
    ("type" -> "udt") ~
      ("class" -> this.getClass.getName) ~
      ("pyClass" -> "magellan.types.PointUDT") ~
      ("x" -> x) ~
      ("y" -> y)

  @JsonProperty
  override def boundingBox = BoundingBox(x, y, x, y)

  @JsonIgnore
  override def isEmpty(): Boolean = true

}

object Point {

  def apply(x: Double, y: Double) = {
    val p = new Point()
    p.setX(x)
    p.setY(y)
    p
  }
} 
Example 10
Source File: BoundingBox.scala    From magellan   with Apache License 2.0 5 votes vote down vote up
package magellan

import magellan.Relate._

import com.fasterxml.jackson.annotation.JsonProperty


  def withinCircle(origin: Point, radius: Double): Boolean = {
    val vertices = Array(
      Point(xmin, ymin),
      Point(xmax, ymin),
      Point(xmax, ymax),
      Point(xmin, ymax)
    )
    !(vertices exists  (vertex => !(vertex withinCircle(origin, radius))))
  }

  private [magellan] def disjoint(other: BoundingBox): Boolean = {
    val BoundingBox(otherxmin, otherymin, otherxmax, otherymax) = other
    (otherxmin > xmax || otherxmax < xmin || otherymin > ymax || otherymax < ymin)
  }

  def contains(point: Point): Boolean = {
    val (x, y) = (point.getX(), point.getY())
    (xmin <= x && ymin <= y && xmax >= x && ymax >= y)
  }

  private [magellan] def intersects(point: Point): Boolean = {
    val lines = Array(
      Line(Point(xmin, ymin), Point(xmax, ymin)),
      Line(Point(xmin, ymin), Point(xmin, ymax)),
      Line(Point(xmax, ymin), Point(xmax, ymax)),
      Line(Point(xmin, ymax), Point(xmax, ymax)))

    lines exists (_ contains point)
  }

  private [magellan] def disjoint(shape: Shape): Boolean = {
    relate(shape) == Disjoint
  }

  private [magellan] def relate(shape: Shape): Relate = {
    val vertices = Array(Point(xmin, ymin),
      Point(xmax, ymin),
      Point(xmax, ymax),
      Point(xmin, ymax)
    )

    // include both edges and diagonals
    // diagonals catch corner cases of bounding box in annulus
    val lines = Array(
      Line(Point(xmin, ymin), Point(xmax, ymin)),
      Line(Point(xmin, ymin), Point(xmin, ymax)),
      Line(Point(xmax, ymin), Point(xmax, ymax)),
      Line(Point(xmin, ymax), Point(xmax, ymax)),
      Line(Point(xmin, ymin), Point(xmax, ymax)),
      Line(Point(xmin, ymax), Point(xmax, ymin))
    )

    // look for strict intersections between the edges of the bounding box and the shape
    val lineIntersections = lines count (shape intersects (_, true))
    val vertexContained = vertices count (shape contains _)

    if (contains(shape.boundingBox)) {
      Contains
    } else if (lineIntersections == 0 && vertexContained == 4) {
      Within
    } else if (lineIntersections > 0 || vertexContained > 0) {
      Intersects
    } else {
      Disjoint
    }
  }

} 
Example 11
Source File: DefaultAndExamples.scala    From mbknor-jackson-jsonSchema   with MIT License 5 votes vote down vote up
package com.kjetland.jackson.jsonSchema.testDataScala

import com.fasterxml.jackson.annotation.JsonProperty
import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaDefault
import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaExamples;

case class DefaultAndExamples
(
  @JsonSchemaExamples(Array("[email protected]"))
  emailValue:String,
  @JsonSchemaDefault("12")
  @JsonSchemaExamples(Array("10", "14", "18"))
  fontSize:Int,

  @JsonProperty( defaultValue = "ds")
  defaultStringViaJsonValue:String,
  @JsonProperty( defaultValue = "1")
  defaultIntViaJsonValue:Int,
  @JsonProperty( defaultValue = "true")
  defaultBoolViaJsonValue:Boolean
) 
Example 12
Source File: AppConfig.scala    From spark-summit-2018   with GNU General Public License v3.0 5 votes vote down vote up
package com.twilio.open.streaming.trend.discovery.config

import java.io.File

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.scala.DefaultScalaModule

sealed trait Configuration extends Product with Serializable

@SerialVersionUID(101L)
case class AppConfiguration(
  @JsonProperty appName: String,
  @JsonProperty triggerInterval: String, // "30 seconds", "1 minute"
  @JsonProperty outputMode: String,
  @JsonProperty checkpointPath: String,
  @JsonProperty("windowInterval") windowIntervalMinutes: Long,
  @JsonProperty("watermarkInterval") watermarkIntervalMinutes: Long,
  @JsonProperty("core") sparkCoreConfig: Map[String, String],
  @JsonProperty callEventsTopic: KafkaReaderOrWriterConfig)
  extends Configuration with Serializable

trait KafkaConfig {
  val topic: String
  val subscriptionType: String
  val conf: Map[String, String]
}

case class KafkaReaderOrWriterConfig(
  override val topic: String,
  override val subscriptionType: String,
  override val conf: Map[String, String]) extends KafkaConfig with Serializable

object AppConfig {

  private val mapper = new ObjectMapper(new YAMLFactory)
  mapper.registerModule(DefaultScalaModule)

  @volatile
  private var config: AppConfiguration = _

  def apply(resourcePath: String): AppConfiguration = {
    if (config == null)
      synchronized {
        if (config == null)
          config = parse(resourcePath)
      }
    config
  }

  private def parse(resourcePath: String): AppConfiguration = {
    mapper.readValue(new File(resourcePath), classOf[AppConfiguration])
  }

} 
Example 13
Source File: TableCluster.scala    From carbondata   with Apache License 2.0 5 votes vote down vote up
package org.apache.carbondata.mv.plans.util

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty, JsonRawValue}
import com.google.common.base.Objects

class TableCluster @JsonCreator()(@JsonProperty("fact") @JsonRawValue fact: Set[String],
    @JsonProperty("dimension") @JsonRawValue dimension: Set[String]) {

  //  @JsonProperty
  def getFact(): Set[String] = {
    fact
  }

  //
  //  @JsonProperty
  def getDimension(): Set[String] = {
    dimension
  }

  @Override
  override def toString: String = {
    Objects.toStringHelper(this)
      .add("fact", fact)
      .add("dimension", dimension)
      .toString
  }

  
} 
Example 14
Source File: ConfigFile.scala    From pizza-auth-3   with MIT License 5 votes vote down vote up
package moe.pizza.auth.config

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.JsonNode
import moe.pizza.auth.adapters.GraderChain
import moe.pizza.auth.adapters.PilotGraderLike.PilotGraderFactory
import moe.pizza.auth.interfaces.PilotGrader
import moe.pizza.auth.webapp.oauth.OAuthApplication

import scala.concurrent.ExecutionContext
import org.http4s.client.Client


object ConfigFile {
  case class PingBotConfig(
      host: String,
      password: String
  )
  case class EmbeddedLdapConfig(
      instancePath: String = "./ldap",
      port: Int = 389,
      basedn: String = "ou=pizza",
      host: String = "localhost",
      password: Option[String] = None
  )
  case class AuthGroupConfig(closed: List[String],
                             open: List[String],
                             public: List[String])

  case class AuthConfig(
      domain: String,
      corporation: String,
      alliance: String,
      groupName: String,
      groupShortName: String,
      groups: AuthGroupConfig,
      graders: List[JsonNode],
      pingbot: Option[PingBotConfig],
      restkeys: List[String],
      applications: List[OAuthApplication] = List()
  ) {
    def constructGraders(c: ConfigFile)(
        implicit client: Client): PilotGrader =
      new GraderChain(
        graders.map(g => PilotGraderFactory.fromYaml(g, c)).flatten.toList)

  }
  case class CrestConfig(
      @JsonProperty("login_url") loginUrl: String,
      @JsonProperty("crest_url") crestUrl: String,
      clientID: String,
      secretKey: String,
      redirectUrl: String
  )
  case class ConfigFile(
      crest: CrestConfig,
      auth: AuthConfig,
      embeddedldap: EmbeddedLdapConfig
  )

} 
Example 15
Source File: JavaInvalidCharacterEscapingTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Dropwizard

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import invalidCharacters.client.dropwizard.invalidCharacters.InvalidCharactersClient
import invalidCharacters.server.dropwizard.definitions.{InvalidCharacters, InvalidCharactersEnum}
import io.netty.buffer.Unpooled
import java.net.{SocketAddress, URI, URLDecoder}
import java.util.concurrent.{CompletableFuture, CompletionStage}
import java.util.function
import org.asynchttpclient.Response.ResponseBuilder
import org.asynchttpclient.netty.EagerResponseBodyPart
import org.asynchttpclient.uri.Uri
import org.asynchttpclient.{HttpResponseStatus, Request, Response}
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import scala.collection.JavaConverters._

object JavaInvalidCharacterEscapingTest {
  private implicit class RichString(private val s: String) extends AnyVal {
    def dec: String = URLDecoder.decode(s, "UTF-8")
  }

  private object OkStatus extends HttpResponseStatus(Uri.create("http://localhost:1234/foo?foo^bar=query-param")) {
    override def getStatusCode = 200
    override def getStatusText = "OK"
    override def getProtocolName = "HTTP"
    override def getProtocolMajorVersion = 1
    override def getProtocolMinorVersion = 1
    override def getProtocolText = "HTTP/1.1"
    override def getRemoteAddress: SocketAddress = ???
    override def getLocalAddress: SocketAddress = ???
  }
}

class JavaInvalidCharacterEscapingTest extends AnyFreeSpec with Matchers {
  import JavaInvalidCharacterEscapingTest._

  "Invalid characters in Java enums should be escaped" in {
    InvalidCharactersEnum.NORMAL.getName mustBe "normal"
    InvalidCharactersEnum.BANG_MOO_COLON_COW_SEMICOLON.getName mustBe "!moo:cow;"
    InvalidCharactersEnum.POUND_YEAH.getName mustBe "#yeah"
    InvalidCharactersEnum.WEIRD_AT.getName mustBe "weird@"
  }

  "Invalid characters in Java POJO properties should be escaped" in {
    val invChar = new InvalidCharacters.Builder("stuff", InvalidCharactersEnum.POUND_YEAH).build()
    invChar.getCloseSquareBraceMoo mustBe "stuff"
    invChar.getSomeEnumAsteriskCaret mustBe InvalidCharactersEnum.POUND_YEAH

    classOf[InvalidCharacters].getDeclaredField("closeSquareBraceMoo").getAnnotation(classOf[JsonProperty]).value mustBe "]moo"
    classOf[InvalidCharacters].getDeclaredField("someEnumAsteriskCaret").getAnnotation(classOf[JsonProperty]).value mustBe "some-enum*^"
  }

  "Invalid characters in Java operation param names should be escaped" in {
    val httpClient = new function.Function[Request, CompletionStage[Response]] {
      override def apply(request: Request): CompletionStage[Response] = {
        println(request.getUri)
        println(request.getQueryParams.asScala.map(_.getName))
        val qps = request.getQueryParams.asScala.map(p => (p.getName.dec, p.getValue.dec))
        val fps = request.getFormParams.asScala.map(p => (p.getName.dec, p.getValue.dec))
        qps.find(_._1 == "foo^bar").map(_._2) mustBe Some("firstarg")
        fps.find(_._1 == "a*b").map(_._2) mustBe Some("secondarg")
        fps.find(_._1 == "bc?").map(_._2) mustBe Some("thirdarg")
        fps.find(_._1 == "d/c").map(_._2) mustBe Some("fourtharg")
        val response = new ResponseBuilder()
        response.accumulate(OkStatus)
        response.accumulate(new EagerResponseBodyPart(
          Unpooled.copiedBuffer(new ObjectMapper().writeValueAsBytes(new InvalidCharacters.Builder("foo", InvalidCharactersEnum.WEIRD_AT).build())),
          true
        ))
        CompletableFuture.completedFuture(response.build())
      }
    }

    val client = new InvalidCharactersClient.Builder(new URI("http://localhost:1234")).withHttpClient(httpClient).build()
    val response = client.getFoo("firstarg", "secondarg", "thirdarg", "fourtharg").call().toCompletableFuture.get()
    response.fold(
      { invChar =>
        invChar.getCloseSquareBraceMoo mustBe "foo"
        invChar.getSomeEnumAsteriskCaret mustBe invalidCharacters.client.dropwizard.definitions.InvalidCharactersEnum.WEIRD_AT
      }
    )
  }
} 
Example 16
Source File: AppConfig.scala    From odsc-west-streaming-trends   with GNU General Public License v3.0 5 votes vote down vote up
package com.twilio.open.streaming.trend.discovery.config

import java.io.File

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.scala.DefaultScalaModule

sealed trait Configuration extends Product with Serializable

@SerialVersionUID(101L)
case class AppConfiguration(
  @JsonProperty appName: String,
  @JsonProperty triggerInterval: String, // "30 seconds", "1 minute"
  @JsonProperty outputMode: String,
  @JsonProperty checkpointPath: String,
  @JsonProperty("windowInterval") windowIntervalMinutes: Long,
  @JsonProperty("watermarkInterval") watermarkIntervalMinutes: Long,
  @JsonProperty("core") sparkCoreConfig: Map[String, String],
  @JsonProperty callEventsTopic: KafkaReaderOrWriterConfig)
  extends Configuration with Serializable

trait KafkaConfig {
  val topic: String
  val subscriptionType: String
  val conf: Map[String, String]
}

case class KafkaReaderOrWriterConfig(
  override val topic: String,
  override val subscriptionType: String,
  override val conf: Map[String, String]) extends KafkaConfig with Serializable

object AppConfig {

  private val mapper = new ObjectMapper(new YAMLFactory)
  mapper.registerModule(DefaultScalaModule)

  @volatile
  private var config: AppConfiguration = _

  def apply(resourcePath: String): AppConfiguration = {
    if (config == null)
      synchronized {
        if (config == null)
          config = parse(resourcePath)
      }
    config
  }

  private def parse(resourcePath: String): AppConfiguration = {
    mapper.readValue(new File(resourcePath), classOf[AppConfiguration])
  }

}