io.circe.JsonObject Scala Examples

The following examples show how to use io.circe.JsonObject. 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: RepositoryNotPresent.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import cats.data.Ior
import com.mesosphere.cosmos.circe.Encoders._
import io.lemonlabs.uri.Uri
import io.circe.JsonObject
import io.circe.syntax._

final case class RepositoryNotPresent(nameOrUri: Ior[String, Uri]) extends CosmosError {
  override def data: Option[JsonObject] = {
    val jsonMap = nameOrUri match {
      case Ior.Both(n, u) => Map("name" -> n.asJson, "uri" -> u.asJson)
      case Ior.Left(n) => Map("name" -> n.asJson)
      case Ior.Right(u) => Map("uri" -> u.asJson)
    }
    Some(JsonObject.fromMap(jsonMap))
  }
  override def message: String = {
    nameOrUri match {
      case Ior.Both(n, u) => s"Neither repository name [$n] nor URI [$u] are present in the list"
      case Ior.Left(n) => s"Repository name [$n] is not present in the list"
      case Ior.Right(u) => s"Repository URI [$u] is not present in the list"
    }
  }
} 
Example 2
Source File: RepositoryUriSyntax.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.rpc
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class RepositoryUriSyntax(
  repository: rpc.v1.model.PackageRepository,
  cause: String
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"URI for repository [${repository.name}] has invalid syntax: ${repository.uri}"
  }
}

object RepositoryUriSyntax {
  implicit val encoder: Encoder[RepositoryUriSyntax] = deriveEncoder
} 
Example 3
Source File: Unauthorized.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import io.netty.handler.codec.http.HttpResponseStatus

final case class Unauthorized(
  serviceName: String,
  realm: Option[String],
  override val status: HttpResponseStatus = HttpResponseStatus.UNAUTHORIZED
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override val message: String = {
    s"Unable to complete request due to Unauthorized response from service [$serviceName]"
  }

  override def exception: CosmosException = {
    CosmosException(
      this,
      realm.map(r => Map("WWW-Authenticate" -> r)).getOrElse(Map.empty),
      None
    )
  }
}

object Unauthorized {
  implicit val encoder: Encoder[Unauthorized] = deriveEncoder
} 
Example 4
Source File: UnsupportedContentType.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.http.MediaType
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class UnsupportedContentType(
  supported: List[MediaType],
  actual: Option[String] = None
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    val acceptMsg = supported.map(_.show).mkString("[", ", ", "]")
    actual match {
      case Some(mt) =>
        s"Unsupported Content-Type: $mt Accept: $acceptMsg"
      case None =>
        s"Unspecified Content-Type Accept: $acceptMsg"
    }
  }
}

object UnsupportedContentType {
  def forMediaType(
    supported: List[MediaType],
    actual: Option[MediaType]
  ): UnsupportedContentType = {
    new UnsupportedContentType(supported, actual.map(_.show))
  }

  implicit val encoder: Encoder[UnsupportedContentType] = deriveEncoder
} 
Example 5
Source File: VersionNotFound.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.universe
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class VersionNotFound(
  packageName: String,
  packageVersion: universe.v3.model.Version
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Version [$packageVersion] of package [$packageName] not found"
  }
}

object VersionNotFound {
  implicit val encoder: Encoder[VersionNotFound] = deriveEncoder
} 
Example 6
Source File: JsonParsingError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class JsonParsingError(
  underlyingType : String,
  parsingErrorMessage: String,
  parsingInput: String
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = "Unable to parse the string as a JSON value"
}

object JsonParsingError {
  implicit val encoder: Encoder[JsonParsingError] = deriveEncoder
} 
Example 7
Source File: CosmosError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.netty.handler.codec.http.HttpResponseStatus

trait CosmosError{
  def message: String
  def data: Option[JsonObject]
  def status: HttpResponseStatus = HttpResponseStatus.BAD_REQUEST

  def exception: CosmosException = {
    CosmosException(this)
  }
}

object CosmosError {
  def deriveData[T <: CosmosError](
    error: T
  )(
    implicit encoder: Encoder[T]
  ): Option[JsonObject] = {
    encoder(error).asObject
  }
} 
Example 8
Source File: UninstallNonExistentAppForPackage.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class UninstallNonExistentAppForPackage(
  packageName: String,
  appId: AppId
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = s"Package [$packageName] with id [$appId] is not installed"
}

object UninstallNonExistentAppForPackage {
  implicit val encoder: Encoder[UninstallNonExistentAppForPackage] = deriveEncoder
} 
Example 9
Source File: JsonDecodingError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class JsonDecodingError(
  typeName : String,
  decodingErrorMessage: String,
  decodeInput : String
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = s"Unable to decode the JSON value as a ${typeName}"
}

object JsonDecodingError {
  implicit val encoder: Encoder[JsonDecodingError] = deriveEncoder
} 
Example 10
Source File: VersionUpgradeNotSupportedInOpen.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.universe
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class VersionUpgradeNotSupportedInOpen(
  requested: Option[universe.v3.model.Version],
  actual: universe.v3.model.Version
) extends CosmosError {
  override def message: String =
    s"Version Upgrades are an Enterprise DC/OS feature only"

  override def data: Option[JsonObject] = CosmosError.deriveData(this)
}

object VersionUpgradeNotSupportedInOpen {
  implicit val encoder: Encoder[VersionUpgradeNotSupportedInOpen] = deriveEncoder
} 
Example 11
Source File: MarathonBadGateway.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import io.netty.handler.codec.http.HttpResponseStatus

final case class MarathonBadGateway(
  marathonStatus: HttpResponseStatus,
  override val status: HttpResponseStatus = HttpResponseStatus.BAD_GATEWAY
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Received response status code ${marathonStatus.code} from Marathon"
  }
}

object MarathonBadGateway {
  implicit val encoder: Encoder[MarathonBadGateway] = deriveEncoder
} 
Example 12
Source File: MarathonGenericError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.netty.handler.codec.http.HttpResponseStatus
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder


final case class MarathonGenericError(
  marathonStatus: HttpResponseStatus,
  override val status: HttpResponseStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Received response status code ${marathonStatus.code} from Marathon"
  }

}

object MarathonGenericError {
  implicit val encoder: Encoder[MarathonGenericError] = deriveEncoder
} 
Example 13
Source File: Forbidden.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import io.netty.handler.codec.http.HttpResponseStatus

final case class Forbidden(
  serviceName: String,
  destination : Option[String] = None,
  override val status: HttpResponseStatus = HttpResponseStatus.FORBIDDEN
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Unable to complete request due to Forbidden response from service " +
      s"[$serviceName]$destinationMessage"
  }

  private def destinationMessage:String = {
    destination match {
      case Some(endpoint) => s" while accessing$endpoint"
      case None => ""
    }
  }
}

object Forbidden {
  implicit val encoder: Encoder[Forbidden] = deriveEncoder
} 
Example 14
Source File: EndpointUriConnection.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.lemonlabs.uri.Uri
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import io.netty.handler.codec.http.HttpResponseStatus

final case class EndpointUriConnection(
  destination: Uri,
  cause: String
) extends CosmosError {
  override val status: HttpResponseStatus = HttpResponseStatus.BAD_GATEWAY
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Could not access data at URI ${destination}"
  }
}

object EndpointUriConnection {
  implicit val encoder: Encoder[EndpointUriConnection] = deriveEncoder
} 
Example 15
Source File: IncompleteUninstall.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import io.netty.handler.codec.http.HttpResponseStatus

final case class IncompleteUninstall(
  packageName: String,
  override val status: HttpResponseStatus = HttpResponseStatus.SERVICE_UNAVAILABLE
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Incomplete uninstall of package [$packageName] due to Mesos unavailability"
  }

}

object IncompleteUninstall {
  implicit val encoder: Encoder[IncompleteUninstall] = deriveEncoder
} 
Example 16
Source File: UnsupportedContentEncoding.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class UnsupportedContentEncoding(
  supported: List[String],
  actual: Option[String] = None
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    val acceptMsg = supported.mkString("[", ", ", "]")
    actual match {
      case Some(mt) =>
        s"Unsupported Content-Encoding: $mt Accept-Encoding: $acceptMsg"
      case None =>
        s"Unspecified Content-Encoding Accept-Encoding: $acceptMsg"
    }
  }
}

object UnsupportedContentEncoding {
  implicit val encoder: Encoder[UnsupportedContentEncoding] = deriveEncoder
} 
Example 17
Source File: ServiceMarathonTemplateNotFound.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.universe
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class ServiceMarathonTemplateNotFound(
  packageName: String,
  packageVersion: universe.v3.model.Version
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Package: [$packageName] version: [$packageVersion] does not have a Marathon " +
    "template defined and can not be rendered"
  }
}

object ServiceMarathonTemplateNotFound {
  implicit val encoder: Encoder[ServiceMarathonTemplateNotFound] = deriveEncoder
} 
Example 18
Source File: EndpointUriSyntax.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.lemonlabs.uri.Uri
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class EndpointUriSyntax(
  destination: Uri,
  cause: String
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"URI for [${destination}] has invalid syntax"
  }
}

object EndpointUriSyntax {
  implicit val encoder: Encoder[EndpointUriSyntax] = deriveEncoder
} 
Example 19
Source File: testUtil.scala    From crjdt   with Apache License 2.0 5 votes vote down vote up
package eu.timepit.crjdt.circe

import eu.timepit.crjdt.core.{Cmd, Expr, Replica, Val}
import eu.timepit.crjdt.core.syntax._
import io.circe.{Json, JsonObject}
import org.scalacheck.Prop
import org.scalacheck.Prop._

import scala.util.Random

object testUtil {
  def converged(a: Replica, b: Replica): Prop =
    (a.processedOps ?= b.processedOps) && (a.document ?= b.document)

  def converged(a: Replica, b: Replica, c: Replica): Prop =
    converged(a, b) && converged(b, c)

  def diverged(a: Replica, b: Replica): Prop =
    (a.processedOps != b.processedOps) && (a.document != b.document)

  def merge(a: Replica, b: Replica): Replica =
    a.applyRemoteOps(b.generatedOps)

  def randomPermutation[A](xs: Vector[A]): Vector[A] = {
    val permutations = xs.permutations.toStream.take(12)
    val index = Random.nextInt(permutations.size)
    permutations.lift(index).getOrElse(Vector.empty)
  }

  def assignCmds(expr: Expr, value: Json): Vector[Cmd] = {
    val assign = expr := jsonToVal(value)
    val fillEmptyArrayOrMap = value.arrayOrObject(
      Vector.empty,
      array => insertToArrayCmds(expr, array),
      obj => assignObjectFieldsCmds(expr, obj)
    )
    assign +: fillEmptyArrayOrMap
  }

  def insertToArrayCmds(expr: Expr, array: Vector[Json]): Vector[Cmd] = {
    val (_, commands) = array.foldLeft((expr.iter.next, Vector.empty[Cmd])) {
      (acc, item) =>
        val (position, commands) = acc
        val insert = position.insert(jsonToVal(item))
        val fillEmptyArrayOrMap = item.arrayOrObject(
          Vector.empty,
          array => insertToArrayCmds(position, array),
          obj => assignObjectFieldsCmds(position, obj)
        )
        (position.next, commands ++ (insert +: fillEmptyArrayOrMap))
    }
    commands
  }

  def assignObjectFieldsCmds(expr: Expr, obj: JsonObject): Vector[Cmd] =
    obj.toMap.flatMap {
      case (key, value) =>
        val field = expr.downField(key)
        assignCmds(field, value)
    }.toVector

  def jsonToVal(value: Json): Val =
    value.fold(
      Val.Null,
      bool => if (bool) Val.True else Val.False,
      number => Val.Num(number.toBigDecimal.getOrElse(number.toDouble)),
      string => Val.Str(string),
      array => Val.EmptyList,
      obj => Val.EmptyMap
    )
} 
Example 20
Source File: package.scala    From patchless   with Apache License 2.0 5 votes vote down vote up
package patchless

import cats.syntax.either._
import io.circe.Decoder.Result
import io.circe.{Decoder, HCursor, Json, JsonObject}
import io.circe.generic.decoding.{DerivedDecoder, ReprDecoder}
import io.circe.generic.encoding.{DerivedObjectEncoder, ReprObjectEncoder}
import shapeless.{HList, LabelledGeneric}

package object circe {

  
  implicit def decodeOptionOption[T](
    implicit decodeOpt: Decoder[Option[T]]
  ) : Decoder[Option[Option[T]]] = {
    Decoder.instance {
      cursor => if(cursor.focus == Json.Null) {
        Right(Some(None))
      } else decodeOpt.apply(cursor).map(Some(_))
    }
  }

  implicit def decodePatch[T, U <: HList](implicit
    patchable: Patchable.Aux[T, U],
    decodeU: ReprDecoder[U]
  ): DerivedDecoder[Patch[T]] = new DerivedDecoder[Patch[T]] {
    def apply(c: HCursor): Result[Patch[T]] = decodeU(c).map {
      updates =>
        Patch.ofUpdates[T, U](updates)
    }
  }

  implicit def encodePatch[T, U <: HList](implicit
    patchable: Patchable.Aux[T, U],
    encodeU: ReprObjectEncoder[U]
  ): DerivedObjectEncoder[Patch[T]] = new DerivedObjectEncoder[Patch[T]] {
    def encodeObject(a: Patch[T]): JsonObject = encodeU.encodeObject(a.patchUpdates)
  }

} 
Example 21
Source File: package.scala    From patchless   with Apache License 2.0 5 votes vote down vote up
package patchless.circe

import cats.syntax.either._
import io.circe.{Decoder, HCursor, Json, JsonObject}
import io.circe.generic.decoding.DerivedDecoder
import io.circe.generic.extras.decoding.ReprDecoder
import io.circe.generic.encoding.DerivedObjectEncoder
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.encoding.ReprObjectEncoder
import io.circe.generic.extras.util.RecordToMap
import patchless.{Patch, Patchable}
import shapeless.{Default, HList, Lazy}

package object extras {

  
  implicit def decodeOptionOption[T](
    implicit decodeOpt: Decoder[Option[T]]
  ) : Decoder[Option[Option[T]]] =
    Decoder.withReattempt {
      c => if (c.succeeded) c.as[Option[T]].map(Some(_)) else Right(None)
    }

  implicit def decodePatch[T, U <: HList, D <: HList](implicit
    patchable: Patchable.Aux[T, U],
    decodeU: Lazy[ReprDecoder[U]],
    defaults: Default.AsRecord.Aux[T, D],
    defaultMapper: RecordToMap[D],
    config: Configuration
  ): DerivedDecoder[Patch[T]] = new DerivedDecoder[Patch[T]] {
    def apply(c: HCursor): Decoder.Result[Patch[T]] = decodeU.value.configuredDecode(c)(
      config.transformMemberNames,
      config.transformConstructorNames,
      if(config.useDefaults) defaultMapper(defaults()) else Map.empty,
      config.discriminator
    ).map {
      updates =>
        Patch.ofUpdates[T, U](updates)
    }
  }

  implicit def encodePatch[T, U <: HList](implicit
    patchable: Patchable.Aux[T, U],
    encodeU: Lazy[ReprObjectEncoder[U]],
    config: Configuration
  ): DerivedObjectEncoder[Patch[T]] = new DerivedObjectEncoder[Patch[T]] {
    def encodeObject(a: Patch[T]): JsonObject = encodeU.value.configuredEncodeObject(a.patchUpdates)(
      config.transformMemberNames,
      config.transformConstructorNames,
      config.discriminator
    )
  }

} 
Example 22
Source File: HeaderIdentityProvider.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.server.auth
import io.circe.{Decoder, Json, JsonObject, ObjectEncoder}
import io.circe.generic.extras.semiauto.{deriveDecoder, deriveEncoder}
import uzhttp.{HTTPError, Request, Response}, HTTPError.Forbidden
import polynote.kernel.{BaseEnv, environment}
import zio.{RIO, ZIO}
import polynote.config.circeConfig
import polynote.server.Server.Routes

case class HeaderIdentityProvider(
  header: String,
  permissions: Map[String, Set[PermissionType]] = Map("*" -> PermissionType.All),
  allowAnonymous: Boolean = false
) extends IdentityProvider.Service {
  override def authRoutes: Option[Routes] = None

  override def checkAuth(req: Request): ZIO[BaseEnv, Response, Option[Identity]] =
    req.headers.get(header) match {
      case Some(name)             => ZIO.succeed(Some(BasicIdentity(name)))
      case None if allowAnonymous => ZIO.succeed(None)
      case None                   => ZIO.fail(Response.plain("Anonymous access not allowed", status = Forbidden("Anonymous access not allowed")))
    }

  override def checkPermission(
    ident: Option[Identity],
    permission: Permission
  ): ZIO[BaseEnv, Permission.PermissionDenied, Unit] = {
    val matchedUser = ident.map(_.name).getOrElse("*")
    val anyPermissions = permissions.getOrElse("*", Set.empty)
    val resolvedPermissions = permissions.get(matchedUser).map(_ ++ anyPermissions).getOrElse(anyPermissions)
    if (resolvedPermissions contains permission.permissionType)
      ZIO.unit
    else
      ZIO.fail(Permission.PermissionDenied(permission, s"$matchedUser does not have ${permission.permissionType.encoded} access"))
  }
}

object HeaderIdentityProvider {
  implicit val encoder: ObjectEncoder[HeaderIdentityProvider] = deriveEncoder
  implicit val decoder: Decoder[HeaderIdentityProvider] = deriveDecoder

  class Loader extends ProviderLoader {
    override val providerKey: String = "header"
    override def provider(config: JsonObject): RIO[BaseEnv with environment.Config, HeaderIdentityProvider] =
      ZIO.fromEither(Json.fromJsonObject(config).as[HeaderIdentityProvider])
  }
} 
Example 23
Source File: Identity.scala    From polynote   with Apache License 2.0 5 votes vote down vote up
package polynote.server.auth

import io.circe.{Decoder, Encoder, JsonObject}
import polynote.kernel.environment.Config
import polynote.kernel.BaseEnv
import polynote.messages.CellID
import zio.RIO

trait Identity {
  def name: String
  def avatar: Option[String] = None
}

class BasicIdentity(val name: String) extends Identity with Serializable
object BasicIdentity {
  def apply(name: String): Identity = new BasicIdentity(name)
}

sealed abstract class PermissionType(val encoded: String)
object PermissionType {
  case object ReadNotebook extends PermissionType("read")
  case object ModifyNotebook extends PermissionType("modify")
  case object ExecuteCell extends PermissionType("execute")
  case object CreateNotebook extends PermissionType("create")
  case object DeleteNotebook extends PermissionType("delete")

  val All: Set[PermissionType] = Set(ReadNotebook, ModifyNotebook, ExecuteCell, CreateNotebook, DeleteNotebook)

  def fromString(string: String): Either[String, PermissionType] = All.find(_.encoded == string).map(Right(_))
    .getOrElse(Left(s"$string is not a valid permission type"))

  implicit val decoder: Decoder[PermissionType] = Decoder.decodeString.emap(fromString)
  implicit val encoder: Encoder[PermissionType] = Encoder.encodeString.contramap(_.encoded)

  private val setStringDecoder: Decoder[Set[PermissionType]] = Decoder.decodeString.flatMap {
    case "all" => Decoder.const(All)
    case str   => fromString(str).fold(Decoder.failedWithMessage, Decoder.const).map(Set(_))
  }

  implicit val setDecoder: Decoder[Set[PermissionType]] = setStringDecoder or Decoder.decodeSet(decoder)
}

sealed abstract class Permission(val permissionType: PermissionType)

object Permission {
  case class ReadNotebook(path: String) extends Permission(PermissionType.ReadNotebook)
  case class ModifyNotebook(path: String) extends Permission(PermissionType.ModifyNotebook)
  case class ExecuteCell(path: String, id: CellID) extends Permission(PermissionType.ExecuteCell)
  case class CreateNotebook(path: String) extends Permission(PermissionType.CreateNotebook)
  case class DeleteNotebook(path: String) extends Permission(PermissionType.DeleteNotebook)

  case class PermissionDenied(permission: Permission, reason: String) extends Throwable(s"Permission denied: $permission ($reason)")
}



trait ProviderLoader {
  def providerKey: String
  def provider(config: JsonObject): RIO[BaseEnv with Config, IdentityProvider.Service]
} 
Example 24
Source File: PackageFiles.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.universe.v2.model

import io.lemonlabs.uri.Uri
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder
import com.mesosphere.cosmos.circe.Encoders.encodeUri
import com.mesosphere.cosmos.circe.Decoders.decodeUri

case class PackageFiles(
  revision: String,
  sourceUri: Uri,
  packageJson: PackageDetails,
  marathonJsonMustache: String,
  commandJson: Option[Command] = None,
  configJson: Option[JsonObject] = None,
  resourceJson: Option[Resource] = None
)

object PackageFiles {
  implicit val encodeV2PackageFiles: Encoder[PackageFiles] = deriveEncoder[PackageFiles]
  implicit val decodeV2PackageFiles: Decoder[PackageFiles] = deriveDecoder[PackageFiles]
} 
Example 25
Source File: RepositoryUriConnection.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.rpc
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class RepositoryUriConnection(
  repository: rpc.v1.model.PackageRepository,
  cause: String
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Could not access data at URI for repository [${repository.name}]: ${repository.uri}"
  }
}

object RepositoryUriConnection {
  implicit val encoder: Encoder[RepositoryUriConnection] = deriveEncoder
} 
Example 26
Source File: CustomPackageManagerError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class CustomPackageManagerError(
  managerId: String,
  statusCode: Int,
  responseContent: String
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = s"Custom manager [$managerId] returned error code [$statusCode] and response [$responseContent]"
}

object CustomPackageManagerError {
  implicit val encoder: Encoder[CustomPackageManagerError] = deriveEncoder
} 
Example 27
Source File: UnsupportedRedirect.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class UnsupportedRedirect(
  supported: List[String],
  actual: Option[String] = None
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    val supportedMsg = supported.mkString("[", ", ", "]")
    actual match {
      case Some(act) =>
        s"Unsupported redirect scheme - supported: $supportedMsg actual: $act"
      case None =>
        s"Unsupported redirect scheme - supported: $supportedMsg"
    }
  }
}

object UnsupportedRedirect {
  implicit val encoder: Encoder[UnsupportedRedirect] = deriveEncoder
} 
Example 28
Source File: RepositoryAddIndexOutOfBounds.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class RepositoryAddIndexOutOfBounds(attempted: Int, max: Int) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    val suggestion = if (max == 0) "can be at most 0" else s"must be between 0 and $max inclusive."
    s"Index ($attempted) is out of range. Index value " + suggestion
  }
}

object RepositoryAddIndexOutOfBounds {
  implicit val encoder: Encoder[RepositoryAddIndexOutOfBounds] = deriveEncoder
} 
Example 29
Source File: ServiceUnavailable.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.netty.handler.codec.http.HttpResponseStatus
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class ServiceUnavailable(
  serviceName: String,
  override val status: HttpResponseStatus = HttpResponseStatus.SERVICE_UNAVAILABLE
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Unable to complete request due to service [$serviceName] unavailability"
  }

}

object ServiceUnavailable {
  implicit val encoder: Encoder[ServiceUnavailable] = deriveEncoder
} 
Example 30
Source File: MultipleFrameworkIds.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.universe
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder

final case class MultipleFrameworkIds(
  packageName: String,
  packageVersion: Option[universe.v2.model.PackageDetailsVersion],
  frameworkName: String,
  ids: List[String]
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    packageVersion match {
      case Some(ver) =>
        s"Uninstalled package [$packageName] version [$ver]\n" +
        s"Unable to shutdown [$packageName] service framework with name [$frameworkName] " +
        s"because there are multiple framework ids matching this name: [${ids.mkString(", ")}]"
      case None =>
        s"Uninstalled package [$packageName]\n" +
        s"Unable to shutdown [$packageName] service framework with name [$frameworkName] " +
        s"because there are multiple framework ids matching this name: [${ids.mkString(", ")}]"
    }
  }
}

object MultipleFrameworkIds {
  implicit val encoder: Encoder[MultipleFrameworkIds] = deriveEncoder
} 
Example 31
Source File: TimeoutError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error


import com.twitter.util.Duration
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import com.mesosphere.cosmos.circe.Encoders._

final case class TimeoutError(
  operation: String,
  destination: String,
  timeout: Duration
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = s"$operation timed out on $destination" +
    s" after ${timeout.inSeconds} seconds"
}

object TimeoutError {
  implicit val encoder: Encoder[TimeoutError] = deriveEncoder
} 
Example 32
Source File: UniverseClientHttpError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import com.mesosphere.cosmos.rpc
import io.netty.handler.codec.http.HttpResponseStatus
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import org.jboss.netty.handler.codec.http.HttpMethod

final case class UniverseClientHttpError(
  packageRepository: rpc.v1.model.PackageRepository,
  method: HttpMethod,
  clientStatus: HttpResponseStatus,
  override val status: HttpResponseStatus
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)

  override def message: String = {
    "Unexpected upstream http error " +
      s"while fetching repository '${packageRepository.name}'" +
      s" at ${packageRepository.uri.toString}: " +
      s"${method.getName} ${clientStatus.code}"
  }

}

object UniverseClientHttpError {
  implicit val encoder: Encoder[UniverseClientHttpError] = deriveEncoder
} 
Example 33
Source File: GenericHttpError.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import com.mesosphere.cosmos.circe.Encoders._
import io.lemonlabs.uri.Uri
import io.netty.handler.codec.http.HttpResponseStatus
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveEncoder
import org.jboss.netty.handler.codec.http.HttpMethod

final case class GenericHttpError(
  method: HttpMethod = HttpMethod.GET,
  uri: Uri,
  clientStatus: HttpResponseStatus,
  override val status: HttpResponseStatus = HttpResponseStatus.BAD_REQUEST
) extends CosmosError {
  override def data: Option[JsonObject] = CosmosError.deriveData(this)
  override def message: String = {
    s"Unexpected upstream http error: ${method.getName} ${uri.toString} ${clientStatus.code}"
  }

}

object GenericHttpError {
  implicit val encoder: Encoder[GenericHttpError] = deriveEncoder
} 
Example 34
Source File: RepositoryAlreadyPresent.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.error

import cats.data.Ior
import com.mesosphere.cosmos.circe.Encoders._
import io.lemonlabs.uri.Uri
import io.circe.JsonObject
import io.circe.syntax._

final case class RepositoryAlreadyPresent(nameOrUri: Ior[String, Uri]) extends CosmosError {
  override def data: Option[JsonObject] = {
    val jsonMap = nameOrUri match {
      case Ior.Both(n, u) => Map("name" -> n.asJson, "uri" -> u.asJson)
      case Ior.Left(n) => Map("name" -> n.asJson)
      case Ior.Right(u) => Map("uri" -> u.asJson)
    }
    Some(JsonObject.fromMap(jsonMap))
  }
  override def message: String = {
    nameOrUri match {
      case Ior.Both(n, u) =>
        s"Repository name [$n] and URI [$u] are both already present in the list"
      case Ior.Left(n) => s"Repository name [$n] is already present in the list"
      case Ior.Right(u) => s"Repository URI [$u] is already present in the list"
    }
  }
} 
Example 35
Source File: OpticsSuite.scala    From circe-optics   with Apache License 2.0 5 votes vote down vote up
package io.circe.optics

import cats.kernel.{ Hash, Order }
import io.circe.optics.all._
import io.circe.{ Json, JsonNumber, JsonObject }
import monocle.function.Plated.plate
import monocle.syntax.all._

class OpticsSuite extends CirceSuite {

  
  implicit override val catsKernelStdOrderForDouble: Order[Double] with Hash[Double] =
    new cats.kernel.instances.DoubleOrder {
      override def eqv(x: Double, y: Double): Boolean =
        (x.isNaN && y.isNaN) || x == y
    }

  checkAll("Json to Unit", LawsTests.prismTests(jsonNull))
  checkAll("Json to Boolean", LawsTests.prismTests(jsonBoolean))
  checkAll("Json to BigDecimal", LawsTests.prismTests(jsonBigDecimal))
  checkAll("Json to Double", LawsTests.prismTests(jsonDouble))
  checkAll("Json to BigInt", LawsTests.prismTests(jsonBigInt))
  checkAll("Json to Long", LawsTests.prismTests(jsonLong))
  checkAll("Json to Int", LawsTests.prismTests(jsonInt))
  checkAll("Json to Short", LawsTests.prismTests(jsonShort))
  checkAll("Json to Byte", LawsTests.prismTests(jsonByte))
  checkAll("Json to String", LawsTests.prismTests(jsonString))
  checkAll("Json to JsonNumber", LawsTests.prismTests(jsonNumber))
  checkAll("Json to JsonObject", LawsTests.prismTests(jsonObject))
  checkAll("Json to Vector[Json]", LawsTests.prismTests(jsonArray))

  checkAll("JsonNumber to BigDecimal", LawsTests.prismTests(jsonNumberBigDecimal))
  checkAll("JsonNumber to BigInt", LawsTests.prismTests(jsonNumberBigInt))
  checkAll("JsonNumber to Long", LawsTests.prismTests(jsonNumberLong))
  checkAll("JsonNumber to Int", LawsTests.prismTests(jsonNumberInt))
  checkAll("JsonNumber to Short", LawsTests.prismTests(jsonNumberShort))
  checkAll("JsonNumber to Byte", LawsTests.prismTests(jsonNumberByte))

  checkAll("plated Json", LawsTests.traversalTests(plate[Json]))

  checkAll("jsonObjectEach", LawsTests.eachTests[JsonObject, Json])
  checkAll("jsonObjectAt", LawsTests.atTests[JsonObject, String, Option[Json]])
  checkAll("jsonObjectIndex", LawsTests.indexTests[JsonObject, String, Json])
  checkAll("jsonObjectFilterIndex", LawsTests.filterIndexTests[JsonObject, String, Json])

  "jsonDouble" should "round-trip in reverse with Double.NaN" in {
    assert(jsonDouble.getOption(jsonDouble.reverseGet(Double.NaN)) === Some(Double.NaN))
  }

  it should "partial round-trip with numbers larger than Double.MaxValue" in {
    val json = Json.fromJsonNumber(JsonNumber.fromString((BigDecimal(Double.MaxValue) + 1).toString).get)

    assert(jsonDouble.getOrModify(json).fold(identity, jsonDouble.reverseGet) === json)
  }

  "jsonObjectFields" should "fold over all fields" in forAll { (obj: JsonObject) =>
    assert(obj.applyFold(JsonObjectOptics.jsonObjectFields).foldMap(List(_)) === obj.toList)
  }
} 
Example 36
Source File: JsonPathProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.json

import io.circe.{ Json, JsonObject }
import org.scalacheck.{ Properties, Test }
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim
import io.circe.testing.ArbitraryInstances

class JsonPathProperties extends Properties("JsonPath") with ArbitraryInstances {

  // avoid lists too long (default: 100)
  override def overrideParameters(p: Test.Parameters): Test.Parameters = super.overrideParameters(p.withMaxSize(10))

  property("select properly in any JsonObject") = {
    val targetValue = Json.fromString("target value")
    forAll { jos: List[JsonObject] =>
      val json = jos.foldRight(targetValue) { case (next, acc) => Json.fromJsonObject(next.add("stitch", acc)) }
      val path = List.fill(jos.size)(FieldSelection("stitch"))
      Claim {
        JsonPath(path).run(json).contains(targetValue)
      }
    }
  }
} 
Example 37
Source File: JsonStepsProperties.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.json

import cats.instances.string._
import com.github.agourlay.cornichon.core.{ Scenario, ScenarioRunner, Session, SessionKey }
import com.github.agourlay.cornichon.json.JsonSteps.JsonStepBuilder
import com.github.agourlay.cornichon.testHelpers.TaskSpec
import io.circe.{ Json, JsonObject }
import io.circe.testing.ArbitraryInstances
import org.scalacheck.Properties
import org.scalacheck.Prop._
import org.typelevel.claimant.Claim

class JsonStepsProperties extends Properties("JsonSteps") with ArbitraryInstances with TaskSpec {

  private val testKey = "test-key"
  private val jsonStepBuilder = JsonStepBuilder(SessionKey(testKey), Some("test body"))

  property("JsonStepBuild is value") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.is(input)
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuild is value fail") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.is(input + "42")
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(!t.isSuccess)
    }

  property("JsonStepBuild isNot value") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.isNot(input + "42")
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuild isNot value fail") =
    forAll { input: String =>
      val session = Session.newEmpty.addValuesUnsafe(testKey -> input)
      val step = jsonStepBuilder.isNot(input)
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(!t.isSuccess)
    }

  property("JsonStepBuilder is any Circe jsonObject") =
    forAll { jsonOb: JsonObject =>
      val json = Json.fromJsonObject(jsonOb)
      val session = Session.newEmpty.addValuesUnsafe(testKey -> json.spaces2)
      val step = jsonStepBuilder.is(json)
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuilder is any Circe jsonObject with placeholder") =
    forAll { jsonOb: JsonObject =>
      val fullJsonObj = jsonOb.add("myKeyOther", Json.fromString("myOtherValue"))
      val session = Session.newEmpty.addValuesUnsafe(
        testKey -> Json.fromJsonObject(fullJsonObj).spaces2,
        "a-placeholder" -> "myOtherValue"
      )
      val fullPlaceholderJsonObj = jsonOb.add("myKeyOther", Json.fromString("<a-placeholder>"))
      val step = jsonStepBuilder.is(Json.fromJsonObject(fullPlaceholderJsonObj))
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(t.isSuccess)
    }

  property("JsonStepBuilder is Circe jsonObject with absent placeholder") =
    forAll { jsonOb: JsonObject =>
      val fullJsonObj = jsonOb.add("myKeyOther", Json.fromString("myOtherValue"))
      val session = Session.newEmpty.addValuesUnsafe(testKey -> Json.fromJsonObject(fullJsonObj).spaces2)
      val fullPlaceholderJsonObj = jsonOb.add("myKeyOther", Json.fromString("<a-placeholder>"))
      val step = jsonStepBuilder.is(Json.fromJsonObject(fullPlaceholderJsonObj))
      val s = Scenario("scenario with JsonSteps", step :: Nil)
      val t = awaitTask(ScenarioRunner.runScenario(session)(s))
      Claim(!t.isSuccess)
    }
} 
Example 38
Source File: ReprAsObjectCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import cats.data.Validated
import io.circe.{ Decoder, DecodingFailure, HCursor, JsonObject }
import io.circe.generic.extras.ConfigurableDeriver
import io.circe.generic.extras.decoding.ReprDecoder
import io.circe.generic.extras.encoding.ReprAsObjectEncoder
import scala.annotation.implicitNotFound
import scala.collection.immutable.Map
import scala.language.experimental.macros
import shapeless.HNil


@implicitNotFound(
  """Could not find ReprAsObjectCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class ReprAsObjectCodec[A] extends ReprDecoder[A] with ReprAsObjectEncoder[A]

object ReprAsObjectCodec {
  implicit def deriveReprAsObjectCodec[R]: ReprAsObjectCodec[R] = macro ConfigurableDeriver.deriveConfiguredCodec[R]

  val hnilReprCodec: ReprAsObjectCodec[HNil] = new ReprAsObjectCodec[HNil] {
    def configuredDecode(c: HCursor)(
      transformMemberNames: String => String,
      transformConstructorNames: String => String,
      defaults: Map[String, Any],
      discriminator: Option[String]
    ): Decoder.Result[HNil] =
      if (c.value.isObject) Right(HNil) else Left(DecodingFailure("HNil", c.history))

    def configuredDecodeAccumulating(c: HCursor)(
      transformMemberNames: String => String,
      transformConstructorNames: String => String,
      defaults: Map[String, Any],
      discriminator: Option[String]
    ): Decoder.AccumulatingResult[HNil] =
      if (c.value.isObject) Validated.valid(HNil) else Validated.invalidNel(DecodingFailure("HNil", c.history))

    def configuredEncodeObject(a: HNil)(
      transformMemberNames: String => String,
      transformDiscriminator: String => String,
      discriminator: Option[String]
    ): JsonObject = JsonObject.empty
  }
} 
Example 39
Source File: ConfiguredAsObjectCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import io.circe.{ Decoder, Encoder, HCursor, JsonObject }
import io.circe.generic.codec.DerivedAsObjectCodec
import io.circe.generic.extras.{ Configuration, JsonKey }
import io.circe.generic.extras.decoding.ConfiguredDecoder
import io.circe.generic.extras.encoding.ConfiguredAsObjectEncoder
import io.circe.generic.extras.util.RecordToMap
import scala.annotation.implicitNotFound
import shapeless.{ Annotations, Coproduct, Default, HList, LabelledGeneric, Lazy }
import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.Keys

@implicitNotFound(
  """Could not find ConfiguredAsObjectCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class ConfiguredAsObjectCodec[A] extends DerivedAsObjectCodec[A]

object ConfiguredAsObjectCodec {
  implicit def codecForCaseClass[A, R <: HList, D <: HList, F <: HList, K <: HList](implicit
    gen: LabelledGeneric.Aux[A, R],
    codec: Lazy[ReprAsObjectCodec[R]],
    defaults: Default.AsRecord.Aux[A, D],
    defaultMapper: RecordToMap[D],
    config: Configuration,
    fields: Keys.Aux[R, F],
    fieldsToList: ToTraversable.Aux[F, List, Symbol],
    keys: Annotations.Aux[JsonKey, A, K],
    keysToList: ToTraversable.Aux[K, List, Option[JsonKey]]
  ): ConfiguredAsObjectCodec[A] = new ConfiguredAsObjectCodec[A] {
    private[this] val decodeA: Decoder[A] =
      ConfiguredDecoder.decodeCaseClass[A, R, D, F, K](
        gen,
        codec,
        defaults,
        defaultMapper,
        config,
        fields,
        fieldsToList,
        keys,
        keysToList
      )

    private[this] val encodeA: Encoder.AsObject[A] =
      ConfiguredAsObjectEncoder.encodeCaseClass[A, R, F, K](gen, codec, config, fields, fieldsToList, keys, keysToList)

    final def apply(c: HCursor): Decoder.Result[A] = decodeA.apply(c)
    final override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = decodeA.decodeAccumulating(c)

    final def encodeObject(a: A): JsonObject = encodeA.encodeObject(a)
  }

  implicit def codecForAdt[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    codec: Lazy[ReprAsObjectCodec[R]],
    config: Configuration
  ): ConfiguredAsObjectCodec[A] = new ConfiguredAsObjectCodec[A] {
    private[this] val decodeA: Decoder[A] =
      ConfiguredDecoder.decodeAdt[A, R](gen, codec, config)

    private[this] val encodeA: Encoder.AsObject[A] =
      ConfiguredAsObjectEncoder.encodeAdt[A, R](gen, codec, config)

    final def apply(c: HCursor): Decoder.Result[A] = decodeA.apply(c)
    final override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = decodeA.decodeAccumulating(c)

    final def encodeObject(a: A): JsonObject = encodeA.encodeObject(a)
  }
} 
Example 40
Source File: ConfiguredAsObjectEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding

import io.circe.JsonObject
import io.circe.generic.encoding.DerivedAsObjectEncoder
import io.circe.generic.extras.{ Configuration, JsonKey }
import java.util.concurrent.ConcurrentHashMap
import scala.annotation.implicitNotFound
import scala.collection.immutable.Map
import shapeless.{ Annotations, Coproduct, HList, LabelledGeneric, Lazy }
import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.Keys

@implicitNotFound(
  """Could not find ConfiguredAsObjectEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class ConfiguredAsObjectEncoder[A](config: Configuration) extends DerivedAsObjectEncoder[A] {
  private[this] val constructorNameCache: ConcurrentHashMap[String, String] =
    new ConcurrentHashMap[String, String]()

  protected[this] def constructorNameTransformer(value: String): String = {
    val current = constructorNameCache.get(value)

    if (current eq null) {
      val transformed = config.transformConstructorNames(value)
      constructorNameCache.put(value, transformed)
      transformed
    } else {
      current
    }
  }
}

object ConfiguredAsObjectEncoder {
  implicit def encodeCaseClass[A, R <: HList, F <: HList, K <: HList](implicit
    gen: LabelledGeneric.Aux[A, R],
    encode: Lazy[ReprAsObjectEncoder[R]],
    config: Configuration,
    fields: Keys.Aux[R, F],
    fieldsToList: ToTraversable.Aux[F, List, Symbol],
    keys: Annotations.Aux[JsonKey, A, K],
    keysToList: ToTraversable.Aux[K, List, Option[JsonKey]]
  ): ConfiguredAsObjectEncoder[A] = new ConfiguredAsObjectEncoder[A](config) {
    private[this] val keyAnnotations: List[Option[JsonKey]] = keysToList(keys())
    private[this] val hasKeyAnnotations: Boolean = keyAnnotations.exists(_.nonEmpty)

    private[this] val keyAnnotationMap: Map[String, String] =
      fieldsToList(fields())
        .map(_.name)
        .zip(keyAnnotations)
        .collect {
          case (field, Some(keyAnnotation)) => (field, keyAnnotation.value)
        }
        .toMap

    private[this] def memberNameTransformer(value: String): String =
      if (hasKeyAnnotations)
        keyAnnotationMap.getOrElse(value, config.transformMemberNames(value))
      else
        config.transformMemberNames(value)

    private[this] val transformedMemberCache: Map[String, String] = {
      fieldsToList(fields()).map(f => (f.name, memberNameTransformer(f.name))).toMap
    }

    private[this] def transformMemberName(value: String) =
      transformedMemberCache.getOrElse(value, value)

    final def encodeObject(a: A): JsonObject =
      encode.value.configuredEncodeObject(gen.to(a))(
        transformMemberName,
        constructorNameTransformer,
        None
      )
  }

  implicit def encodeAdt[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    encode: Lazy[ReprAsObjectEncoder[R]],
    config: Configuration
  ): ConfiguredAsObjectEncoder[A] = new ConfiguredAsObjectEncoder[A](config) {
    final def encodeObject(a: A): JsonObject =
      encode.value.configuredEncodeObject(gen.to(a))(
        Predef.identity,
        constructorNameTransformer,
        config.discriminator
      )
  }
} 
Example 41
Source File: ReprAsObjectEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding
import io.circe.{ Encoder, Json, JsonObject }
import io.circe.generic.extras.ConfigurableDeriver
import scala.annotation.implicitNotFound
import scala.language.experimental.macros


@implicitNotFound(
  """Could not find ReprAsObjectEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
trait ReprAsObjectEncoder[A] extends Encoder.AsObject[A] {
  def configuredEncodeObject(a: A)(
    transformMemberNames: String => String,
    transformDiscriminator: String => String,
    discriminator: Option[String]
  ): JsonObject

  final protected[this] def addDiscriminator[B](
    encode: Encoder[B],
    value: B,
    name: String,
    discriminator: Option[String]
  ): JsonObject = discriminator match {
    case None => JsonObject.singleton(name, encode(value))
    case Some(disc) =>
      encode match {
        case oe: Encoder.AsObject[B] @unchecked => oe.encodeObject(value).add(disc, Json.fromString(name))
        case _                                  => JsonObject.singleton(name, encode(value))
      }
  }

  final def encodeObject(a: A): JsonObject = configuredEncodeObject(a)(Predef.identity, Predef.identity, None)
}

object ReprAsObjectEncoder {
  implicit def deriveReprAsObjectEncoder[R]: ReprAsObjectEncoder[R] =
    macro ConfigurableDeriver.deriveConfiguredEncoder[R]
} 
Example 42
Source File: JsonLdCirceSupport.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.storage

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.model.{ContentTypeRange, HttpEntity}
import ch.epfl.bluebrain.nexus.commons.http.RdfMediaTypes
import ch.epfl.bluebrain.nexus.storage.JsonLdCirceSupport.{sortKeys, OrderedKeys}
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport
import io.circe.syntax._
import io.circe.{Encoder, Json, JsonObject, Printer}

import scala.collection.immutable.Seq


  def sortKeys(json: Json)(implicit keys: OrderedKeys): Json = {

    implicit val customStringOrdering: Ordering[String] = new Ordering[String] {
      private val middlePos = keys.withPosition("")

      private def position(key: String): Int = keys.withPosition.getOrElse(key, middlePos)

      override def compare(x: String, y: String): Int = {
        val posX = position(x)
        val posY = position(y)
        if (posX == middlePos && posY == middlePos) x compareTo y
        else posX compareTo posY
      }
    }

    def canonicalJson(json: Json): Json =
      json.arrayOrObject[Json](json, arr => Json.fromValues(arr.map(canonicalJson)), obj => sorted(obj).asJson)

    def sorted(jObj: JsonObject): JsonObject =
      JsonObject.fromIterable(jObj.toVector.sortBy(_._1).map { case (k, v) => k -> canonicalJson(v) })

    canonicalJson(json)
  }
} 
Example 43
Source File: CirceJsonInputOutput.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package ser

import com.avsystem.commons.serialization.GenCodec.ReadFailure
import com.avsystem.commons.serialization._
import io.circe.{Json, JsonObject}

import scala.collection.mutable.ArrayBuffer

object CirceJsonOutput {
  def write[T: GenCodec](value: T): Json = {
    var result: Json = null
    GenCodec.write(new CirceJsonOutput(result = _), value)
    result
  }
}

class CirceJsonOutput(consumer: Json => Any) extends OutputAndSimpleOutput {
  def writeNull(): Unit = consumer(Json.Null)
  def writeString(str: String): Unit = consumer(Json.fromString(str))
  def writeBoolean(boolean: Boolean): Unit = consumer(Json.fromBoolean(boolean))
  def writeInt(int: Int): Unit = consumer(Json.fromInt(int))
  def writeLong(long: Long): Unit = consumer(Json.fromLong(long))
  def writeDouble(double: Double): Unit = consumer(Json.fromDoubleOrString(double))
  def writeBigInt(bigInt: BigInt): Unit = consumer(Json.fromBigInt(bigInt))
  def writeBigDecimal(bigDecimal: BigDecimal): Unit = consumer(Json.fromBigDecimal(bigDecimal))
  def writeBinary(binary: Array[Byte]): Unit = consumer(Json.fromValues(binary.map(Json.fromInt(_))))
  def writeList(): ListOutput = new CirceJsonListOutput(consumer)
  def writeObject(): ObjectOutput = new CirceJsonObjectOutput(consumer)
  override def writeFloat(float: Float): Unit = consumer(Json.fromFloatOrString(float))
}

class CirceJsonListOutput(consumer: Json => Any) extends ListOutput {
  private[this] val elems = Vector.newBuilder[Json]

  def writeElement(): Output = new CirceJsonOutput(elems += _)
  def finish(): Unit = consumer(Json.fromValues(elems.result()))
}

class CirceJsonObjectOutput(consumer: Json => Any) extends ObjectOutput {
  private[this] val elems = new ArrayBuffer[(String, Json)]

  def writeField(key: String): Output = new CirceJsonOutput(json => elems += ((key, json)))
  def finish(): Unit = consumer(Json.fromFields(elems))
}

object CirceJsonInput {
  def read[T: GenCodec](json: Json): T =
    GenCodec.read[T](new CirceJsonInput(json))
}

class CirceJsonInput(json: Json) extends InputAndSimpleInput {
  private def failNot(what: String) =
    throw new ReadFailure(s"not $what")

  private def asNumber = json.asNumber.getOrElse(failNot("number"))

  def readNull(): Boolean = json.isNull
  def readString(): String = json.asString.getOrElse(failNot("string"))
  def readBoolean(): Boolean = json.asBoolean.getOrElse(failNot("boolean"))
  override def readByte(): Byte = asNumber.toByte.getOrElse(failNot("byte"))
  override def readShort(): Short = asNumber.toShort.getOrElse(failNot("short"))
  def readInt(): Int = asNumber.toInt.getOrElse(failNot("int"))
  def readLong(): Long = asNumber.toLong.getOrElse(failNot("long"))
  def readDouble(): Double = asNumber.toDouble
  def readBigInt(): BigInt = asNumber.toBigInt.getOrElse(failNot("bigInteger"))
  def readBigDecimal(): BigDecimal = asNumber.toBigDecimal.getOrElse(failNot("bigDecimal"))
  def readBinary(): Array[Byte] = json.asArray.getOrElse(failNot("array")).iterator
    .map(_.asNumber.flatMap(_.toByte).getOrElse(failNot("byte"))).toArray
  def readList(): ListInput = new CirceJsonListInput(json.asArray.getOrElse(failNot("array")))
  def readObject(): ObjectInput = new CirceJsonObjectInput(json.asObject.getOrElse(failNot("object")))
  def skip(): Unit = ()
}

class CirceJsonFieldInput(val fieldName: String, json: Json) extends CirceJsonInput(json) with FieldInput

class CirceJsonListInput(jsonArray: Vector[Json]) extends ListInput {
  private[this] val it = jsonArray.iterator

  def hasNext: Boolean = it.hasNext
  def nextElement(): Input = new CirceJsonInput(it.next())
}

class CirceJsonObjectInput(jsonObject: JsonObject) extends ObjectInput {
  private[this] val fieldIt = jsonObject.keys.iterator

  def hasNext: Boolean = fieldIt.hasNext
  def nextField(): FieldInput = {
    val field = fieldIt.next()
    new CirceJsonFieldInput(field, jsonObject(field).get)
  }
} 
Example 44
Source File: ZLogsSuite.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.logging.zlogs

import ch.qos.logback.classic.Logger
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.read.ListAppender
import derevo.derive
import io.circe.JsonObject
import io.circe.syntax._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.slf4j.LoggerFactory
import tofu.logging.LogTree
import tofu.logging.derivation.loggable
import tofu.logging.impl.ContextMarker
import tofu.syntax.logging._
import zio.blocking.Blocking
import zio.clock.Clock
import zio.console.Console
import zio.{Has, Runtime, URIO, URLayer, ZLayer}

import scala.jdk.CollectionConverters._

class ZLogsSuite extends AnyFlatSpec with Matchers {
  import ZLogsSuite.MyLogging

  val expr = debug"hello" *> info"world"

  "ZLogs" should "log the context" in {
    val appender = ZLogsSuite.attachList()
    Runtime.default.unsafeRun(expr.provideLayer(ZLogsSuite.fullLayer))
    val items    = appender.list.asScala

    val expected = JsonObject("foo" -> "kojima".asJson, "bar" -> 2.asJson).asJson

    items.map(_.getMarker).collect {
      case ContextMarker(ctx, _) => LogTree(ctx)
    } should ===(List.fill(2)(expected))
  }
}

object ZLogsSuite {
  val Name = "zio logs suite"

  @derive(loggable)
  case class FooService(foo: String)

  val fooLayer = ZLayer.succeed(FooService("kojima"))

  @derive(loggable)
  case class BarService(bar: Int)

  val barLayer = ZLayer.succeed(BarService(2))

  type Foo = Has[FooService]
  type Bar = Has[BarService]

  type LogEnv    = Foo with Bar
  type SystemEnv = Blocking with Clock with Console
  type MyEnv     = SystemEnv with LogEnv with ZLog[LogEnv]
  type TIO[+A]   = URIO[MyEnv, A]

  val logs: ZLogs[Foo with Bar] = ZLogs.build.of[Foo].of[Bar].make

  implicit val MyLogging: ZLogging[MyEnv] = ZLogs.access[MyEnv, LogEnv]

  implicitly[ZioHasBuilder.UnHas[Foo]](ZioHasBuilder.UnHas.unHas[FooService])
  val fullLayer: URLayer[Blocking with Console with Clock, MyEnv] =
    ZLayer.identity[SystemEnv] ++ fooLayer ++ barLayer ++ ZLogs.named(logs, Name)

  def attachList() = {
    val logger   = LoggerFactory.getLogger(Name).asInstanceOf[Logger]
    val appender = new ListAppender[ILoggingEvent]
    appender.start()
    logger.addAppender(appender)
    appender
  }
} 
Example 45
Source File: JsonOptics.scala    From circe-optics   with Apache License 2.0 5 votes vote down vote up
package io.circe.optics

import cats.Applicative
import cats.instances.vector._
import cats.syntax.functor._
import cats.syntax.traverse._
import io.circe.{ Json, JsonNumber, JsonObject }
import io.circe.optics.JsonNumberOptics._
import io.circe.optics.JsonObjectOptics.jsonObjectEach
import monocle.{ Prism, Traversal }
import monocle.function.{ Each, Plated }


  final lazy val jsonDescendants: Traversal[Json, Json] = new Traversal[Json, Json] {
    override def modifyF[F[_]](f: Json => F[Json])(s: Json)(implicit F: Applicative[F]): F[Json] =
      s.fold(
        F.pure(s),
        _ => F.pure(s),
        _ => F.pure(s),
        _ => F.pure(s),
        arr => F.map(Each.each[Vector[Json], Json].modifyF(f)(arr))(Json.arr(_: _*)),
        obj => F.map(Each.each[JsonObject, Json].modifyF(f)(obj))(Json.fromJsonObject)
      )
  }

  implicit final lazy val jsonPlated: Plated[Json] = new Plated[Json] {
    val plate: Traversal[Json, Json] = new Traversal[Json, Json] {
      def modifyF[F[_]](f: Json => F[Json])(a: Json)(
        implicit
        F: Applicative[F]
      ): F[Json] =
        a.fold(
          F.pure(a),
          b => F.pure(Json.fromBoolean(b)),
          n => F.pure(Json.fromJsonNumber(n)),
          s => F.pure(Json.fromString(s)),
          _.traverse(f).map(Json.fromValues),
          _.traverse(f).map(Json.fromJsonObject)
        )
    }
  }
}

final object JsonOptics extends JsonOptics 
Example 46
Source File: JsonObjectOptics.scala    From circe-optics   with Apache License 2.0 5 votes vote down vote up
package io.circe.optics

import cats.{ Applicative, Foldable, Monoid, Traverse }
import cats.instances.ListInstances
import io.circe.{ Json, JsonObject }
import monocle.{ Fold, Lens, Traversal }
import monocle.function.{ At, Each, FilterIndex, Index }


trait JsonObjectOptics extends ListInstances {
  final lazy val jsonObjectFields: Fold[JsonObject, (String, Json)] = new Fold[JsonObject, (String, Json)] {
    def foldMap[M: Monoid](f: ((String, Json)) => M)(obj: JsonObject): M = Foldable[List].foldMap(obj.toList)(f)
  }

  implicit final lazy val jsonObjectEach: Each[JsonObject, Json] = new Each[JsonObject, Json] {
    final def each: Traversal[JsonObject, Json] = new Traversal[JsonObject, Json] {
      final def modifyF[F[_]](f: Json => F[Json])(from: JsonObject)(
        implicit
        F: Applicative[F]
      ): F[JsonObject] = from.traverse(f)
    }
  }

  implicit final lazy val jsonObjectAt: At[JsonObject, String, Option[Json]] =
    new At[JsonObject, String, Option[Json]] {
      final def at(field: String): Lens[JsonObject, Option[Json]] =
        Lens[JsonObject, Option[Json]](_.apply(field))(optVal =>
          obj => optVal.fold(obj.remove(field))(value => obj.add(field, value))
        )
    }

  implicit final lazy val jsonObjectFilterIndex: FilterIndex[JsonObject, String, Json] =
    new FilterIndex[JsonObject, String, Json] {
      final def filterIndex(p: String => Boolean) = new Traversal[JsonObject, Json] {
        final def modifyF[F[_]](f: Json => F[Json])(from: JsonObject)(
          implicit
          F: Applicative[F]
        ): F[JsonObject] =
          F.map(
            Traverse[List].traverse(from.toList) {
              case (field, json) =>
                F.map(if (p(field)) f(json) else F.point(json))((field, _))
            }
          )(JsonObject.fromFoldable(_))
      }
    }

  implicit final lazy val jsonObjectIndex: Index[JsonObject, String, Json] = Index.fromAt
}

final object JsonObjectOptics extends JsonObjectOptics 
Example 47
Source File: FeatureExtractor.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.crawler

import com.azavea.stac4s.StacLink
import com.azavea.stac4s.TwoDimBbox
import com.azavea.stac4s._
import geotrellis.vector.methods.Implicits._
import geotrellis.vector.{Feature, Geometry}
import io.circe.JsonObject

import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.util.UUID

object FeatureExtractor {

  def toItem(
      feature: Feature[Geometry, JsonObject],
      forItem: StacItem,
      forItemCollection: String,
      inCollection: StacCollection
  ): StacItem = {
    val collectionHref =
      s"/collections/${URLEncoder.encode(inCollection.id, StandardCharsets.UTF_8.toString)}"
    val encodedSourceItemCollectionId =
      URLEncoder.encode(forItemCollection, StandardCharsets.UTF_8.toString)
    val sourceItemHref =
      s"/collections/$encodedSourceItemCollectionId/items/${URLEncoder.encode(forItem.id, StandardCharsets.UTF_8.toString)}"

    val collectionLink = StacLink(
      collectionHref,
      StacLinkType.Collection,
      Some(`application/json`),
      title = Some("Source item's original collection")
    )

    val sourceItemLink = StacLink(
      sourceItemHref,
      StacLinkType.VendorLinkType("derived_from"),
      Some(`application/json`),
      None
    )

    val featureExtent = feature.geom.extent

    StacItem(
      s"${UUID.randomUUID}",
      "0.9.0",
      Nil,
      "Feature",
      feature.geom,
      TwoDimBbox(featureExtent.xmin, featureExtent.ymin, featureExtent.xmax, featureExtent.ymax),
      links = List(collectionLink, sourceItemLink),
      assets = Map.empty,
      collection = Some(inCollection.id),
      properties = feature.data
    )
  }

} 
Example 48
Source File: package.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.marshalling

import cats.free.Trampoline
import cats.instances.function._
import cats.instances.list._
import cats.syntax.traverse._
import io.circe.parser.parse
import io.circe.syntax._
import io.circe.{Json, JsonObject, _}

object `package` extends CirceEncoders with CirceDecoders with CaseConversions {

  private def transformKeys(json: Json, f: String => String): Trampoline[Json] = {
    def transformObjectKeys(obj: JsonObject, f: String => String): JsonObject =
      JsonObject.fromIterable(
        obj.toList.map {
          case (k, v) => f(k) -> v
        }
      )

    json.arrayOrObject(
      Trampoline.done(json),
      _.toList.traverse(j => Trampoline.defer(transformKeys(j, f))).map(Json.fromValues(_)),
      transformObjectKeys(_, f).traverse(obj => Trampoline.defer(transformKeys(obj, f))).map(Json.fromJsonObject)
    )
  }

  private def camelKeys(json: io.circe.Json): Json = transformKeys(json, camelize).run

  private def snakeKeys(json: io.circe.Json): Json = transformKeys(json, snakenize).run

  val printer = Printer.noSpaces.copy(dropNullValues = true)

  def toJson[T: Encoder](t: T): String = printer.pretty(t.asJson)

  def fromJson[T: Decoder](s: String): T = {
    parse(s).fold(throw _,
      json =>
        camelKeys(json).as[T].fold(throw _, identity))
  }
} 
Example 49
Source File: HealthCheckRoutes.scala    From healthchecks   with MIT License 5 votes vote down vote up

package com.github.everpeace.healthchecks.route

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.PathDirectives
import akka.http.scaladsl.server.{PathMatchers, Route}
import cats.data.Validated.{Invalid, Valid}
import com.github.everpeace.healthchecks.{HealthCheck, HealthCheckResult}
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import io.circe.JsonObject
import io.circe.generic.JsonCodec
import io.circe.generic.auto._

import scala.collection.convert.DecorateAsScala
import scala.concurrent.{ExecutionContext, Future}

object HealthCheckRoutes extends DecorateAsScala {

  @JsonCodec case class HealthCheckResultJson(
      name: String,
      severity: String,
      status: String,
      messages: List[String])

  @JsonCodec case class ResponseJson(status: String, check_results: List[HealthCheckResultJson])

  private def status(s: Boolean) = if (s) "healthy" else "unhealthy"

  private def statusCode(s: Boolean) = if (s) OK else ServiceUnavailable

  private def toResultJson(check: HealthCheck, result: HealthCheckResult) =
    HealthCheckResultJson(
      check.name,
      check.severity.toString,
      status(result.isValid),
      result match {
        case Valid(_)        => List()
        case Invalid(errors) => errors.toList
      }
    )

  def health(
      checks: HealthCheck*
    )(implicit
      ec: ExecutionContext
    ): Route = health("health", checks.toList)

  def health(
      path: String,
      checks: List[HealthCheck]
    )(implicit
      ec: ExecutionContext
    ): Route = {
    require(checks.nonEmpty, "checks must not empty.")
    require(
      checks.map(_.name).toSet.size == checks.length,
      s"HealthCheck name should be unique (given HealthCheck names = [${checks.map(_.name).mkString(",")}])."
    )
    val rootSlashRemoved =
      if (path.startsWith("/")) path.substring(1) else path
    PathDirectives.path(PathMatchers.separateOnSlashes(rootSlashRemoved)) {
      parameter("full" ? false) { full =>
        get {
          def isHealthy(checkAndResults: List[(HealthCheck, HealthCheckResult)]) =
            checkAndResults.forall(cr => cr._2.isValid || (!cr._1.severity.isFatal))
          val checkAndResultsFuture = Future.traverse(checks) { c =>
            c.run().map(c -> _)
          }
          if (full) {
            complete {
              checkAndResultsFuture.map { checkAndResults =>
                val healthy = isHealthy(checkAndResults)
                statusCode(healthy) -> ResponseJson(
                  status(healthy),
                  checkAndResults.map {
                    case (check, result) => toResultJson(check, result)
                  }
                )
              }
            }
          } else {
            complete {
              checkAndResultsFuture.map { checkAndResults =>
                statusCode(isHealthy(checkAndResults)) -> JsonObject.empty
              }
            }
          }
        }
      }
    }
  }
} 
Example 50
Source File: Message.scala    From lsp4s   with Apache License 2.0 5 votes vote down vote up
package scala.meta.jsonrpc

import monix.eval.Task
import io.circe.Json
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.derivation.annotations.JsonCodec
import io.circe.syntax._

import cats.syntax.either._

sealed trait Message
object Message {
  implicit val encoder: Encoder[Message] = new Encoder[Message] {
    override def apply(a: Message): Json = {
      val json = a match {
        case r: Request => r.asJson
        case r: Notification => r.asJson
        case r: Response => r.asJson
      }
      json.mapObject(_.add("jsonrpc", "2.0".asJson))
    }
  }
  implicit val decoder: Decoder[Message] =
    Decoder.decodeJsonObject.emap { obj =>
      val json = Json.fromJsonObject(obj)
      val result =
        if (obj.contains("id"))
          if (obj.contains("error")) json.as[Response.Error]
          else if (obj.contains("result")) json.as[Response.Success]
          else json.as[Request]
        else json.as[Notification]
      result.leftMap(_.toString)
    }
}

@JsonCodec case class Request(
    method: String,
    params: Option[Json],
    id: RequestId
) extends Message {
  def toError(code: ErrorCode, message: String): Response =
    Response.error(ErrorObject(code, message, None), id)
}

@JsonCodec case class Notification(method: String, params: Option[Json])
    extends Message

sealed trait Response extends Message {
  def isSuccess: Boolean = this.isInstanceOf[Response.Success]
}
object Response {
  implicit val encoderResponse: Encoder[Response] = new Encoder[Response] {
    override def apply(a: Response): Json = a match {
      case r: Response.Success => r.asJson
      case r: Response.Error => r.asJson
      case Response.Empty => JsonObject.empty.asJson
    }
  }
  @JsonCodec case class Success(result: Json, id: RequestId) extends Response
  @JsonCodec case class Error(error: ErrorObject, id: RequestId)
      extends Response
  case object Empty extends Response
  def empty: Response = Empty
  def ok(result: Json, id: RequestId): Response =
    success(result, id)
  def okAsync[T](value: T): Task[Either[Response.Error, T]] =
    Task(Right(value))
  def success(result: Json, id: RequestId): Response =
    Success(result, id)
  def error(error: ErrorObject, id: RequestId): Response.Error =
    Error(error, id)
  def internalError(message: String): Response.Error =
    internalError(message, RequestId.Null)
  def internalError(message: String, id: RequestId): Response.Error =
    Error(ErrorObject(ErrorCode.InternalError, message, None), id)
  def invalidParams(message: String): Response.Error =
    invalidParams(message, RequestId.Null)
  def invalidParams(message: String, id: RequestId): Response.Error =
    Error(ErrorObject(ErrorCode.InvalidParams, message, None), id)
  def invalidRequest(message: String): Response.Error =
    Error(
      ErrorObject(ErrorCode.InvalidRequest, message, None),
      RequestId.Null
    )
  def cancelled(id: Json): Response.Error =
    Error(
      ErrorObject(ErrorCode.RequestCancelled, "", None),
      id.as[RequestId].getOrElse(RequestId.Null)
    )
  def parseError(message: String): Response.Error =
    Error(ErrorObject(ErrorCode.ParseError, message, None), RequestId.Null)
  def methodNotFound(message: String, id: RequestId): Response.Error =
    Error(ErrorObject(ErrorCode.MethodNotFound, message, None), id)
} 
Example 51
Source File: Schema.scala    From circe-json-schema   with Apache License 2.0 5 votes vote down vote up
package io.circe.schema

import cats.data.{ Validated, ValidatedNel }
import io.circe.{ Json, JsonNumber, JsonObject }
import java.util.HashMap
import org.everit.json.schema.{ Schema => EveritSchema, ValidationException }
import org.everit.json.schema.loader.SchemaLoader
import org.json.{ JSONArray, JSONObject, JSONTokener }
import scala.util.Try

trait Schema {
  def validate(value: Json): ValidatedNel[ValidationError, Unit]
}

object Schema {
  def load(value: Json): Schema = new EveritSchemaImpl(
    SchemaLoader.builder().schemaJson(fromCirce(value)).draftV7Support().build().load().build()
  )

  def loadFromString(value: String): Try[Schema] = Try(
    new EveritSchemaImpl(
      SchemaLoader.builder().schemaJson(new JSONTokener(value).nextValue).draftV7Support().build().load().build()
    )
  )

  private[this] class EveritSchemaImpl(schema: EveritSchema) extends Schema {
    def validate(value: Json): ValidatedNel[ValidationError, Unit] =
      try {
        schema.validate(fromCirce(value))
        Validated.valid(())
      } catch {
        case e: ValidationException => Validated.invalid(ValidationError.fromEverit(e))
      }
  }

  private[this] val fromCirceVisitor: Json.Folder[Object] = new Json.Folder[Object] {
    def onNull: Object = JSONObject.NULL
    def onBoolean(value: Boolean): Object = Predef.boolean2Boolean(value)
    def onString(value: String): Object = value
    def onNumber(value: JsonNumber): Object =
      value.toInt match {
        case Some(asInt) => Predef.int2Integer(asInt)
        case None        => new JSONTokener(value.toString).nextValue
      }
    def onArray(value: Vector[Json]): Object = new JSONArray(value.map(_.foldWith(this)).toArray)
    def onObject(value: JsonObject): Object = {
      val map = new HashMap[String, Object](value.size)
      val iter = value.toIterable.iterator

      while (iter.hasNext) {
        val (k, v) = iter.next
        map.put(k, v.foldWith(this))
      }
      new JSONObject(map)
    }
  }

  private[this] def fromCirce(value: Json): Object = value.foldWith(fromCirceVisitor)
} 
Example 52
Source File: StructFormat.scala    From scalapb-circe   with MIT License 5 votes vote down vote up
package scalapb_circe

import com.google.protobuf.struct.Value.Kind
import com.google.protobuf.struct
import io.circe.{Json, JsonObject}
import scalapb_json._

object StructFormat {
  def structValueWriter(v: struct.Value): Json = v.kind match {
    case Kind.Empty => Json.Null
    case Kind.NullValue(_) => Json.Null
    case Kind.NumberValue(value) => Json.fromDoubleOrString(value)
    case Kind.StringValue(value) => Json.fromString(value)
    case Kind.BoolValue(value) => Json.fromBoolean(value)
    case Kind.StructValue(value) => structWriter(value)
    case Kind.ListValue(value) => listValueWriter(value)
  }

  def structValueParser(v: Json): struct.Value = {
    val kind: struct.Value.Kind = v.fold(
      jsonNull = Kind.NullValue(struct.NullValue.NULL_VALUE),
      jsonBoolean = value => Kind.BoolValue(value = value),
      jsonNumber = x => Kind.NumberValue(value = x.toDouble),
      jsonString = x => Kind.StringValue(value = x),
      jsonArray = x => Kind.ListValue(listValueParser(x)),
      jsonObject = x => Kind.StructValue(value = structParser(x))
    )
    struct.Value(kind = kind)
  }

  def structParser(v: JsonObject): struct.Struct = {
    struct.Struct(fields = v.toMap.map(kv => (kv._1, structValueParser(kv._2))))
  }

  def structParser(v: Json): struct.Struct = v.asObject match {
    case Some(x) => structParser(x)
    case None => throw new JsonFormatException("Expected an object")
  }

  def structWriter(v: struct.Struct): Json =
    Json.obj(v.fields.iterator.map {
      case (x, y) => x -> structValueWriter(y)
    }.toList: _*)

  def listValueParser(json: Seq[Json]): struct.ListValue =
    com.google.protobuf.struct.ListValue(json.map(structValueParser))

  def listValueParser(json: Json): struct.ListValue = json.asArray match {
    case Some(v) =>
      listValueParser(v)
    case None =>
      throw new JsonFormatException("Expected an array")
  }

  def listValueWriter(v: struct.ListValue): Json =
    Json.fromValues(v.values.map(structValueWriter))

  def nullValueParser(v: Json): struct.NullValue = {
    if (v.isNull)
      com.google.protobuf.struct.NullValue.NULL_VALUE
    else
      throw new JsonFormatException("Expected a null")
  }

} 
Example 53
Source File: CirceUtilsSuite.scala    From elastiknn   with Apache License 2.0 5 votes vote down vote up
package com.klibisz.elastiknn.utils

import java.util

import io.circe.{Json, JsonObject}
import org.scalatest.{FunSuite, Matchers}
import scala.collection.JavaConverters._

class CirceUtilsSuite extends FunSuite with Matchers with CirceUtils {

  val map = new java.util.HashMap[String, Object] {
    put("foo", Integer.valueOf(1))
    put(
      "bar",
      new util.HashMap[String, Object] {
        put("nums", List(1, 2, 3).asJava)
        put("strings", List("one", "two", "three").asJava)
        put("anys", List("string", 42).asJava)
      }
    )
  }

  test("encode scala map to json") {
    val encoded = javaMapEncoder(map)
    encoded shouldBe Json.fromJsonObject(
      JsonObject(
        "foo" -> Json.fromInt(1),
        "bar" -> Json.fromJsonObject(JsonObject(
          "nums" -> Json.fromValues(
            Seq(
              Json.fromInt(1),
              Json.fromInt(2),
              Json.fromInt(3)
            )),
          "strings" -> Json.fromValues(
            Seq(
              Json.fromString("one"),
              Json.fromString("two"),
              Json.fromString("three")
            )),
          "anys" -> Json.fromValues(Seq(
            Json.fromString("string"),
            Json.fromInt(42)
          ))
        ))
      ))

  }

} 
Example 54
Source File: CirceUtils.scala    From elastiknn   with Apache License 2.0 5 votes vote down vote up
package com.klibisz.elastiknn.utils

import java.{lang, util}

import io.circe.{Encoder, Json, JsonObject}

import scala.collection.JavaConverters._

trait CirceUtils {

  // Most of the Elasticsearch Json inputs are available as Maps.
  // This encoder converts the map to a Json so it can then be parsed into case classes.
  implicit def javaMapEncoder: Encoder[util.Map[String, Object]] = new Encoder[util.Map[String, Object]] {
    private def encodeAny(a: Any): Json = a match {
      case s: lang.String  => Json.fromString(s)
      case l: lang.Long    => Json.fromLong(l)
      case i: lang.Integer => Json.fromInt(i)
      case d: lang.Double  => Json.fromDoubleOrNull(d)
      case f: lang.Float   => Json.fromFloatOrNull(f)
      case b: lang.Boolean => Json.fromBoolean(b)
      case l: util.List[_] => Json.fromValues(l.asScala.map(encodeAny))
      case m: util.Map[_, _] =>
        val iterable = m.asScala.map(x => x._1.toString -> encodeAny(x._2))
        Json.fromJsonObject(JsonObject.fromIterable(iterable))
      case null  => null
      case other => throw new RuntimeException(s"Couldn't encode object $other to Json")
    }
    override def apply(a: util.Map[String, Object]): Json = encodeAny(a)
  }

}

object CirceUtils extends CirceUtils 
Example 55
Source File: ServiceDescribeHandler.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.handler

import com.mesosphere.cosmos.AdminRouter
import com.mesosphere.cosmos.http.RequestSession
import com.mesosphere.cosmos.render.PackageDefinitionRenderer
import com.mesosphere.cosmos.repository.PackageCollection
import com.mesosphere.cosmos.repository.rewriteUrlWithProxyInfo
import com.mesosphere.cosmos.rpc
import com.mesosphere.cosmos.service.CustomPackageManagerRouter
import com.mesosphere.cosmos.thirdparty.marathon.model.MarathonApp
import com.mesosphere.universe
import com.mesosphere.universe.v4.model.PackageDefinition
import com.twitter.util.Future
import io.circe.JsonObject

private[cosmos] final class ServiceDescribeHandler(
  adminRouter: AdminRouter,
  packageCollection: PackageCollection,
  customPackageManagerRouter: CustomPackageManagerRouter
) extends CustomEndpointHandler[rpc.v1.model.ServiceDescribeRequest, rpc.v1.model.ServiceDescribeResponse] {

  private[this] lazy val logger = org.slf4j.LoggerFactory.getLogger(getClass)

  override def apply(
    request: rpc.v1.model.ServiceDescribeRequest
  )(
    implicit session: RequestSession
  ): Future[rpc.v1.model.ServiceDescribeResponse] = {
    orElseGet(tryCustomPackageManager(request)) {
      for {
        marathonAppResponse <- adminRouter.getApp(request.appId)
        packageDefinition <- getPackageDefinition(marathonAppResponse.app)
        upgradesTo <- packageCollection.upgradesTo(packageDefinition.name, packageDefinition.version)
        downgradesTo <- packageCollection.downgradesTo(packageDefinition)
      } yield {
        val userProvidedOptions = marathonAppResponse.app.serviceOptions
        rpc.v1.model.ServiceDescribeResponse(
          `package` = packageDefinition,
          upgradesTo = upgradesTo,
          downgradesTo = downgradesTo,
          resolvedOptions = getResolvedOptions(packageDefinition, userProvidedOptions),
          userProvidedOptions = userProvidedOptions
        )
      }
    }
  }

  private def getPackageDefinition(
    app: MarathonApp)(implicit
    session: RequestSession
  ): Future[universe.v4.model.PackageDefinition] = {
    app.packageDefinition
      .map(pkg => Future.value(pkg.rewrite(rewriteUrlWithProxyInfo(session.originInfo), identity)))
      .getOrElse {
        val (name, version) =
          app.packageName.flatMap(name => app.packageVersion.map(name -> _))
            .getOrElse(throw new IllegalStateException(
              "The name and version of the service were not found in the labels"))
        packageCollection
          .getPackageByPackageVersion(name, Some(version))
          .map(_._1)
      }
  }

  private def getResolvedOptions(
    packageDefinition: PackageDefinition,
    serviceOptions: Option[JsonObject]
  ): Option[JsonObject] = {
    serviceOptions.map { userSuppliedOptions =>
      PackageDefinitionRenderer.mergeDefaultAndUserOptions(packageDefinition, Some(userSuppliedOptions))
    }
  }

  override def tryCustomPackageManager(
    request: rpc.v1.model.ServiceDescribeRequest
  )(
    implicit session: RequestSession
  ): Future[Option[rpc.v1.model.ServiceDescribeResponse]] = {
    customPackageManagerRouter.getCustomPackageManagerId(
      request.managerId,
      request.packageName,
      request.packageVersion,
      Some(request.appId)
    ).flatMap {
      case Some((Some(managerId), Some(pkgName), Some(pkgVersion))) if !managerId.isEmpty =>
        logger.debug(s"Request [$request] requires a custom manager: [$managerId]")
        customPackageManagerRouter.callCustomServiceDescribe(
          request,
          managerId,
          pkgName,
          pkgVersion
        ).map(Some(_))
      case _ => Future(None)
    }
  }
} 
Example 56
Source File: JsonSchemaSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.jsonschema

import com.github.fge.jsonschema.main.JsonSchemaFactory
import io.circe.Json
import io.circe.JsonObject
import io.circe.jawn.parse
import io.circe.syntax._
import org.scalatest.FreeSpec
import org.scalatest.Tag
import scala.io.Source
import scala.util.Right

class JsonSchemaSpec extends FreeSpec {

  private[this] implicit val jsf = JsonSchemaFactory.byDefault()

  "JsonSchema should" - {
    "be able to validate a document against a schema" - {
      // the draft v4 json schema itself should be able to validate itself
      val jsonSchemaDraftV4String = classpathJsonString("/draftv4/schema")

      "as io.circe.JsonObject" in {
        val Right(parsedJson: Json) = parse(jsonSchemaDraftV4String)
        val xor = JsonSchema.jsonMatchesSchema(parsedJson, parsedJson)
        assert(xor.isRight)
      }

      "as io.circe.Json" in {
        val Right(parsedJson: Json) = parse(jsonSchemaDraftV4String)
        val jObject: JsonObject = parsedJson.asObject.get
        val xor = JsonSchema.jsonObjectMatchesSchema(jObject, jObject)
        assert(xor.isRight)
      }
    }

    "be able to extract default property values from a schema" - {
      val expected = JsonObject.fromMap(Map(
        "prop1" -> 57.asJson,
        "prop2" -> Json.obj(
          "sub1" -> "ta-da".asJson
        )
      ))

      "when schema does not use definition refs" in {
        val s = classpathJsonString("/com/mesosphere/cosmos/jsonschema/no-definition-ref-used.json")
        val Right(schema) = parse(s)
        val defaults = JsonSchema.extractDefaultsFromSchema(schema.asObject.get)
        assertResult(expected)(defaults)
      }

      "when schema does use definition refs" taggedAs Tag("https://mesosphere.atlassian.net/browse/DCOS-10455") ignore {
        val s = classpathJsonString("/com/mesosphere/cosmos/jsonschema/definition-ref-used.json")
        val Right(schema) = parse(s)
        val defaults = JsonSchema.extractDefaultsFromSchema(schema.asObject.get)
        assertResult(expected)(defaults)
      }

    }
  }

  private[this] def classpathJsonString(resourceName: String): String = {
    Option(this.getClass.getResourceAsStream(resourceName)) match {
      case Some(is) => Source.fromInputStream(is).mkString
      case _ => throw new IllegalStateException(s"Unable to load classpath resource: $resourceName")
    }
  }

} 
Example 57
Source File: JsonUtilSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.universe.common

import io.circe.Encoder
import io.circe.Json
import io.circe.JsonObject
import io.circe.generic.semiauto._
import io.circe.syntax._
import org.scalatest.FreeSpec
import org.scalatest.prop.TableDrivenPropertyChecks

class JsonUtilSpec extends FreeSpec with TableDrivenPropertyChecks {

  case class Foo(bar: Option[Int],far: Option[Int])

  implicit val encodeFoo: Encoder[Foo] = {
    deriveEncoder[Foo]
  }

  "dropNullKeys" in {
    val ls = Foo(None,None)
    val string = JsonUtil.dropNullKeysPrinter.pretty(ls.asJson)
    assertResult("{}")(string)
  }

  "Merging JSON objects" - {

    "should pass on all examples" in {
      forAll (Examples) { (defaultsJson, optionsJson, mergedJson) =>
        assertResult(mergedJson)(JsonUtil.merge(defaultsJson, optionsJson))
      }
    }
  }

  private[this] val Examples = Table(
    ("defaults JSON", "options JSON", "merged JSON"),
    (JsonObject.empty, JsonObject.empty, JsonObject.empty),

    (
      JsonObject.empty,
      JsonObject.singleton("a", Json.False),
      JsonObject.singleton("a", Json.False)
    ),
    (
      JsonObject.singleton("a", Json.False),
      JsonObject.empty,
      JsonObject.singleton("a", Json.False)
    ),
    (
      JsonObject.singleton("a", Json.False),
      JsonObject.singleton("a", Json.True),
      JsonObject.singleton("a", Json.True)
    ),
    (
      JsonObject.singleton("a", Json.obj("a" -> Json.False)),
      JsonObject.singleton("a", Json.obj()),
      JsonObject.singleton("a", Json.obj("a" -> Json.False))
    ),
    (
      JsonObject.singleton("a", Json.obj("a" -> Json.False)),
      JsonObject.singleton("a", Json.obj("a" -> Json.True)),
      JsonObject.singleton("a", Json.obj("a" -> Json.True))
    ),
    (
      JsonObject.singleton("a", Json.obj("a" -> Json.False)),
      JsonObject.singleton("a", Json.obj("b" -> Json.False)),
      JsonObject.singleton("a", Json.obj("a" -> Json.False, "b" -> Json.False))
    ),
    (
      JsonObject.singleton("a", Json.obj("a" -> Json.False)),
      JsonObject.singleton("a", Json.True),
      JsonObject.singleton("a", Json.True)
    )
  )

} 
Example 58
Source File: RoundTrips.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos

import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import com.mesosphere.universe
import com.mesosphere.util.RoundTrip
import io.lemonlabs.uri.Uri
import io.circe.JsonObject

object RoundTrips {

  def withInstallV1(
    name: String,
    version: Option[universe.v2.model.PackageDetailsVersion] = None,
    options: Option[JsonObject] = None,
    appId: Option[AppId] = None
  ): RoundTrip[rpc.v1.model.InstallResponse] = {
    RoundTrip(
      Requests.installV1(name, version, options, appId)
    ) { ir =>
      Requests.uninstall(ir.packageName, Some(ir.appId))
      Requests.waitForDeployments()
    }
  }

  def withInstallV2(
   name: String,
   version: Option[universe.v2.model.PackageDetailsVersion] = None,
   options: Option[JsonObject] = None,
   appId: Option[AppId] = None,
   managerId: Option[String] = None
 ): RoundTrip[rpc.v2.model.InstallResponse] = {
    RoundTrip(
      Requests.installV2(name, version, options, appId, managerId)
    ) { ir =>
      Requests.uninstall(ir.packageName, ir.appId, None, managerId)
      Requests.waitForDeployments()
    }
  }

  def withDeletedRepository(
    name: Option[String] = None,
    uri: Option[Uri] = None
  ): RoundTrip[rpc.v1.model.PackageRepositoryDeleteResponse] = {
    RoundTrip.lift {
      val repos = Requests.listRepositories()
      val repo = repos.find { repo =>
        name.contains(repo.name) || uri.contains(repo.uri)
      }
      (repo, repo.map(repos.indexOf(_)))
    }.flatMap { case (repo, index) =>
      withDeletedRepository(name, uri, repo, index)
    }
  }

  def withRepository(
    name: String,
    uri: Uri,
    index: Option[Int] = None
  ): RoundTrip[rpc.v1.model.PackageRepositoryAddResponse] = {
    RoundTrip(
      Requests.addRepository(name, uri, index))(_ =>
      Requests.deleteRepository(Some(name))
    )
  }

  private[this] def withDeletedRepository(
    name: Option[String],
    uri: Option[Uri],
    oldRepo: Option[rpc.v1.model.PackageRepository],
    oldIndex: Option[Int]
  ): RoundTrip[rpc.v1.model.PackageRepositoryDeleteResponse] = {
    RoundTrip(
      Requests.deleteRepository(name, uri)
    ) { _ =>
      val repo = oldRepo.getOrElse {
        throw new RuntimeException("Unable to restore repository")
      }
      val index = oldIndex.getOrElse(
        throw new RuntimeException("Unable to restore repository index")
      )
      Requests.addRepository(repo.name, repo.uri, Some(index))
    }
  }

} 
Example 59
Source File: NonSharedServiceUpdateSpec.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.handler

import com.mesosphere.cosmos.HttpErrorResponse
import com.mesosphere.cosmos.IntegrationBeforeAndAfterAll
import com.mesosphere.cosmos.ItObjects
import com.mesosphere.cosmos.ItOps._
import com.mesosphere.cosmos.RoundTrips
import com.mesosphere.cosmos.error.VersionUpgradeNotSupportedInOpen
import com.mesosphere.cosmos.http.TestContext
import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import com.twitter.finagle.http.Status
import io.circe.JsonObject
import io.circe.syntax._
import java.util.UUID
import org.scalatest.FeatureSpec
import org.scalatest.Matchers

class NonSharedServiceUpdateSpec extends FeatureSpec with Matchers with IntegrationBeforeAndAfterAll {
  private[this] implicit val testContext = TestContext.fromSystemProperties()

  import ServiceUpdateSpec._

  val helloworld = "helloworld"

  feature("The service/update endpoint") {
    scenario("The user must get an error when attempting to upgrade a service") {
      val name = helloworld
      val version = "0.4.0"
      val appId = AppId(UUID.randomUUID().toString)
      val expectedOptions = JsonObject.fromIterable(
        List("port" -> 8888.asJson, "name" -> appId.asJson)
      )
      val expectedPackage = ItObjects.helloWorldPackage4

      val expectedError = cosmosErrorToErrorResponse(
        VersionUpgradeNotSupportedInOpen(
          requested = Some(expectedPackage.version),
          actual = version.version
        )
      )

      RoundTrips.withInstallV1(name, Some(version.detailsVersion), Some(expectedOptions)).runWith { _ =>
        waitForDeployment()
        val error = intercept[HttpErrorResponse] {
          serviceUpdate(appId, Some(expectedPackage.version), None, false)
        }
        error.status shouldBe Status.BadRequest
        error.errorResponse shouldBe expectedError
      }
    }
  }
} 
Example 60
Source File: MarathonApp.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.thirdparty.marathon.model

import com.mesosphere.cosmos.circe.Decoders.decode64
import com.mesosphere.cosmos.circe.Decoders.parse64
import com.mesosphere.cosmos.model.PackageOrigin
import com.mesosphere.cosmos.model.StorageEnvelope
import com.mesosphere.error.ResultOps
import com.mesosphere.universe
import io.lemonlabs.uri.Uri
import io.circe.Decoder
import io.circe.Json
import io.circe.JsonObject
import io.circe.generic.semiauto._
import scala.util.Try


case class MarathonApp(
  id: AppId,
  env: Option[Map[String, Json]],
  labels: Option[Map[String, String]]
)

object MarathonApp {
  val frameworkNameLabel = "DCOS_PACKAGE_FRAMEWORK_NAME"
  val nameLabel = "DCOS_PACKAGE_NAME"
  val repositoryLabel = "DCOS_PACKAGE_SOURCE"
  val versionLabel = "DCOS_PACKAGE_VERSION"
  val optionsLabel = "DCOS_PACKAGE_OPTIONS"
  val packageLabel = "DCOS_PACKAGE_DEFINITION"

  implicit val decodeMarathonApp: Decoder[MarathonApp] = deriveDecoder[MarathonApp]

  implicit final class Ops(val app: MarathonApp) extends AnyVal {

    def getLabel(key: String):Option[String] = app.labels.flatMap(_.get(key))

    def getEnv(key: String):Option[String] = app.env.flatMap(_.get(key)).flatMap(_.asString)

    def packageName: Option[String] = getLabel(MarathonApp.nameLabel)

    def packageVersion: Option[universe.v3.model.Version] = {
      getLabel(MarathonApp.versionLabel).map(universe.v3.model.Version(_))
    }

    def packageRepository: Option[PackageOrigin] = for {
      repoValue <- getLabel(MarathonApp.repositoryLabel)
      originUri <- Try(Uri.parse(repoValue)).toOption
    } yield PackageOrigin(originUri)

    def packageDefinition: Option[universe.v4.model.PackageDefinition] = {
      getLabel(MarathonApp.packageLabel).map { string =>
        decode64[StorageEnvelope](
          string
        ).decodeData[universe.v4.model.PackageDefinition].getOrThrow
      }
    }

    def serviceOptions: Option[JsonObject] = {
      getLabel(MarathonApp.optionsLabel).flatMap { string =>
        parse64(string).asObject
      }
    }

  }
} 
Example 61
Source File: ServiceDescribeResponse.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v1.model

import com.mesosphere.cosmos.finch.DispatchingMediaTypedEncoder
import com.mesosphere.cosmos.finch.MediaTypedEncoder
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.universe
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class ServiceDescribeResponse(
  `package`: universe.v4.model.PackageDefinition,
  upgradesTo: List[universe.v3.model.Version],
  downgradesTo: List[universe.v3.model.Version],
  resolvedOptions: Option[JsonObject],
  userProvidedOptions: Option[JsonObject]
)

object ServiceDescribeResponse {

  implicit val encode: Encoder[ServiceDescribeResponse] = deriveEncoder

  implicit val decode: Decoder[ServiceDescribeResponse] = deriveDecoder

  implicit val mediaTypedEncoder: MediaTypedEncoder[ServiceDescribeResponse] =
    MediaTypedEncoder(MediaTypes.ServiceDescribeResponse)

  implicit val dispatchingMediaTypedEncoder: DispatchingMediaTypedEncoder[ServiceDescribeResponse] =
    DispatchingMediaTypedEncoder(MediaTypes.ServiceDescribeResponse)

} 
Example 62
Source File: RenderRequest.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v1.model

import com.mesosphere.cosmos.finch.MediaTypedDecoder
import com.mesosphere.cosmos.finch.MediaTypedRequestDecoder
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import com.mesosphere.universe.v2.model.PackageDetailsVersion
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class RenderRequest(
  packageName: String,
  packageVersion: Option[PackageDetailsVersion] = None,
  options: Option[JsonObject] = None,
  appId: Option[AppId] = None
)

object RenderRequest{
  implicit val encodeRenderRequest: Encoder[RenderRequest] = deriveEncoder[RenderRequest]
  implicit val decodeRenderRequest: Decoder[RenderRequest] = deriveDecoder[RenderRequest]
  implicit val packageRenderDecoder: MediaTypedRequestDecoder[RenderRequest] =
    MediaTypedRequestDecoder(MediaTypedDecoder(MediaTypes.RenderRequest))
} 
Example 63
Source File: InstallRequest.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v1.model

import com.mesosphere.cosmos.finch.MediaTypedDecoder
import com.mesosphere.cosmos.finch.MediaTypedRequestDecoder
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import com.mesosphere.universe.v2.model.PackageDetailsVersion
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class InstallRequest(
  packageName: String,
  packageVersion: Option[PackageDetailsVersion],
  options: Option[JsonObject],
  appId: Option[AppId],
  managerId: Option[String]
)

object InstallRequest {
  implicit val encodeInstallRequest: Encoder[InstallRequest] = deriveEncoder[InstallRequest]
  implicit val decodeInstallRequest: Decoder[InstallRequest] = deriveDecoder[InstallRequest]
  implicit val packageInstallDecoder: MediaTypedRequestDecoder[InstallRequest] =
    MediaTypedRequestDecoder(MediaTypedDecoder(MediaTypes.InstallRequest))
} 
Example 64
Source File: ServiceUpdateResponse.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v1.model

import com.mesosphere.cosmos.finch.DispatchingMediaTypedEncoder
import com.mesosphere.cosmos.finch.MediaTypedEncoder
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.universe
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class ServiceUpdateResponse(
  `package`: universe.v4.model.PackageDefinition,
  resolvedOptions: JsonObject,
  marathonDeploymentId: String
)

object ServiceUpdateResponse {
  implicit val encode: Encoder[ServiceUpdateResponse] = deriveEncoder
  implicit val decode: Decoder[ServiceUpdateResponse] = deriveDecoder
  implicit val mediaTypedEncoder: MediaTypedEncoder[ServiceUpdateResponse] =
    MediaTypedEncoder(MediaTypes.ServiceUpdateResponse)
  implicit val dispatchingMediaTypedEncoder: DispatchingMediaTypedEncoder[ServiceUpdateResponse] =
    DispatchingMediaTypedEncoder(MediaTypes.ServiceUpdateResponse)
} 
Example 65
Source File: ErrorResponse.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v1.model

import com.mesosphere.cosmos.error.CosmosError
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class ErrorResponse(
  `type`: String,
  message: String,
  data: Option[JsonObject] = None
)

object ErrorResponse {
  implicit val encode: Encoder[ErrorResponse] = deriveEncoder
  implicit val decode: Decoder[ErrorResponse] = deriveDecoder

  def apply(error: CosmosError) : ErrorResponse = {
    ErrorResponse(
      error.getClass.getSimpleName,
      error.message,
      error.data
    )
  }
} 
Example 66
Source File: ServiceUpdateRequest.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v1.model

import com.mesosphere.cosmos.finch.MediaTypedDecoder
import com.mesosphere.cosmos.finch.MediaTypedEncoder
import com.mesosphere.cosmos.finch.MediaTypedRequestDecoder
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.cosmos.thirdparty.marathon.model.AppId
import com.mesosphere.universe
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class ServiceUpdateRequest(
  appId: AppId,
  packageVersion: Option[universe.v3.model.Version],
  options: Option[JsonObject],
  replace: Boolean,
  managerId: Option[String],
  packageName: Option[String],
  currentPackageVersion: Option[universe.v3.model.Version]
)

object ServiceUpdateRequest {
  implicit val encode: Encoder[ServiceUpdateRequest] = deriveEncoder
  implicit val decode: Decoder[ServiceUpdateRequest] = deriveDecoder
  implicit val mediaTypedEncoder: MediaTypedEncoder[ServiceUpdateRequest] =
    MediaTypedEncoder(MediaTypes.ServiceUpdateRequest)
  implicit val mediaTypedRequestDecoder: MediaTypedRequestDecoder[ServiceUpdateRequest] =
    MediaTypedRequestDecoder(MediaTypedDecoder(MediaTypes.ServiceUpdateRequest))
} 
Example 67
Source File: DescribeResponse.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.rpc.v2.model

import com.mesosphere.universe
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder

case class DescribeResponse(
  packagingVersion: universe.v3.model.PackagingVersion,
  name: String,
  version: universe.v3.model.Version,
  maintainer: String,
  description: String,
  tags: List[universe.v3.model.Tag] = Nil,
  selected: Boolean = false,
  scm: Option[String] = None,
  website: Option[String] = None,
  framework: Boolean = false,
  preInstallNotes: Option[String] = None,
  postInstallNotes: Option[String] = None,
  postUninstallNotes: Option[String] = None,
  licenses: Option[List[universe.v3.model.License]] = None,
  minDcosReleaseVersion: Option[universe.v3.model.DcosReleaseVersion] = None,
  marathon: Option[universe.v3.model.Marathon] = None,
  resource: Option[universe.v3.model.V3Resource] = None,
  config: Option[JsonObject] = None,
  command: Option[universe.v3.model.Command] = None
)

object DescribeResponse {
  implicit val encodeV2DescribeResponse: Encoder[DescribeResponse] = {
    deriveEncoder[DescribeResponse]
  }
  implicit val decodeV2DescribeResponse: Decoder[DescribeResponse] = {
    deriveDecoder[DescribeResponse]
  }
}