io.circe.Json Scala Examples
The following examples show how to use io.circe.Json.
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: Analyzer.scala From scarango with MIT License | 8 votes |
package com.outr.arango import io.circe.Decoder.Result import io.circe.{Decoder, DecodingFailure, Encoder, HCursor, Json} sealed abstract class Analyzer(val name: String) object Analyzer { case object Identity extends Analyzer("identity") case object TextGerman extends Analyzer("text_de") case object TextEnglish extends Analyzer("text_en") case object TextSpanish extends Analyzer("text_es") case object TextFinnish extends Analyzer("text_fi") case object TextFrench extends Analyzer("text_fr") case object TextItalian extends Analyzer("text_it") case object TextDutch extends Analyzer("text_nl") case object TextNorwegian extends Analyzer("text_no") case object TextPortuguese extends Analyzer("text_pt") case object TextRussian extends Analyzer("text_ru") case object TextSwedish extends Analyzer("text_sv") case object TextChinese extends Analyzer("text_zh") private val map = List(Identity, TextGerman, TextEnglish, TextSpanish, TextFinnish, TextFrench, TextItalian, TextDutch, TextNorwegian, TextPortuguese, TextRussian, TextSwedish, TextChinese).map(a => a.name -> a).toMap def apply(name: String): Analyzer = map.getOrElse(name, throw new RuntimeException(s"Unable to find analyzer by name: $name")) implicit val decoder: Decoder[Analyzer] = new Decoder[Analyzer] { override def apply(c: HCursor): Result[Analyzer] = c.value.asString match { case Some(s) => Right(Analyzer(s)) case None => Left(DecodingFailure(s"Expected String to decode Analyzer, but got: ${c.value}", Nil)) } } implicit val encoder: Encoder[Analyzer] = new Encoder[Analyzer] { override def apply(a: Analyzer): Json = Json.fromString(a.name) } }
Example 2
Source File: TopicConfigurationParser.scala From kafka-configurator with BSD 3-Clause "New" or "Revised" License | 6 votes |
package com.sky.kafka.configurator import java.io.{Reader => JReader} import cats.instances.either._ import cats.instances.list._ import cats.syntax.either._ import cats.syntax.traverse._ import io.circe import io.circe.generic.AutoDerivation import io.circe.yaml.parser._ import io.circe.{Decoder, DecodingFailure, Json} import scala.collection.immutable.ListMap object TopicConfigurationParser extends AutoDerivation { def apply(topicConfigReader: JReader): Either[circe.Error, List[Topic]] = for { ymlAsJson <- parse(topicConfigReader) topicConfigs <- if (ymlAsJson.isBoolean) List.empty[Topic].asRight else ymlAsJson.as[List[Topic]] } yield topicConfigs case class TopicConfig(partitions: Int, replication: Int, config: Map[String, String]) implicit val topicsDecoder: Decoder[List[Topic]] = Decoder.instance { cursor => for { configMap <- cursor.as[ListMap[String, TopicConfig]] topics = configMap.map { case (name, conf) => Topic(name, conf.partitions, conf.replication, conf.config) } } yield topics.toList } implicit val stringMapDecoder: Decoder[Map[String, String]] = Decoder.instance { cursor => def stringify(json: Json): Json = json.asNumber.fold(json)(num => Json.fromString(num.toLong.fold(num.toDouble.toString)(_.toString))) def failWithMsg(msg: String) = DecodingFailure(msg, List.empty) for { jsonObj <- cursor.value.asObject.toRight(failWithMsg(s"${cursor.value} is not an object")) valuesAsJsonStrings = jsonObj.mapValues(stringify) stringMap <- valuesAsJsonStrings.toList.traverse[Decoder.Result, (String, String)] { case (key, json) => json.asString.toRight(failWithMsg(s"$json is not a string")).map(key -> _) } } yield stringMap.toMap } }
Example 3
Source File: Http4sRpcServer.scala From iotchain with MIT License | 5 votes |
package jbok.network.rpc.http import cats.effect.{ConcurrentEffect, Resource, Sync, Timer} import cats.implicits._ import io.circe.Json import io.circe.syntax._ import jbok.network.rpc.{RpcRequest, RpcService} import org.http4s.HttpRoutes import org.http4s.circe.CirceEntityCodec._ import org.http4s.dsl.Http4sDsl import org.http4s.implicits._ import org.http4s.server.Server import org.http4s.server.blaze.BlazeServerBuilder object Http4sRpcServer { def routes[F[_]](service: RpcService[F, Json])(implicit F: Sync[F]): HttpRoutes[F] = { val dsl = Http4sDsl[F] import dsl._ HttpRoutes.of[F] { case req @ POST -> path => for { json <- req.as[Json] result <- service.handle(RpcRequest(path.toList, json)) resp <- Ok(result.asJson) } yield resp } } def server[F[_]](service: RpcService[F, Json])(implicit F: ConcurrentEffect[F], T: Timer[F]): Resource[F, Server[F]] = BlazeServerBuilder[F] .bindLocal(0) .withHttpApp(routes[F](service).orNotFound) .withWebSockets(true) .resource }
Example 4
Source File: Http4sRpcSpec.scala From iotchain with MIT License | 5 votes |
package jbok.network.rpc import cats.effect.IO import io.circe.Json import jbok.common.CommonSpec import jbok.network.rpc.http.{Http4sRpcServer, Http4sRpcTransport} import org.http4s.Uri import cats.implicits._ import org.http4s.circe.CirceEntityCodec._ import org.scalatest.Assertion import jbok.codec.impl.circe._ import io.circe.generic.auto._ class Http4sRpcSpec extends CommonSpec { val impl = new TestApiImpl val service = RpcService[IO, Json].mount[TestAPI[IO]](impl) val server = Http4sRpcServer.server[IO](service) def transport(uri: Uri) = new Http4sRpcTransport[IO, Json](uri) def client(uri: Uri) = RpcClient[IO, Json](transport(uri)).use[TestAPI[IO]] def assertIO[A](io1: IO[A], io2: IO[A]): IO[Assertion] = (io1, io2).mapN(_ shouldBe _) "Http4sRpcService" should { "impl service and client" in { val p = server.use { s => val c = client(s.baseUri) assertIO(c.foo, impl.foo) >> assertIO(c.bar, impl.bar) >> assertIO(c.qux("oho", 42), impl.qux("oho", 42)) } p.unsafeRunSync() } } }
Example 5
Source File: HttpTransport.scala From iotchain with MIT License | 5 votes |
package jbok.network.http import cats.effect.Async import cats.implicits._ import io.circe.Json import jbok.network.rpc._ import io.circe.parser._ object HttpTransport { def apply[F[_]](baseUri: String)(implicit F: Async[F]): RpcTransport[F, Json] = new RpcTransport[F, Json] { override def fetch(request: RpcRequest[Json]): F[RpcResponse[Json]] = { val uri = (baseUri :: request.path).mkString("/") for { response <- HttpClient.post[F](uri, request.payload.noSpaces) resp <- F.fromEither(decode[RpcResponse[Json]](response.data)) } yield resp } } }
Example 6
Source File: HttpService.scala From iotchain with MIT License | 5 votes |
package jbok.app.service import cats.effect.{ConcurrentEffect, Resource, Timer} import io.circe.Json import cats.implicits._ import fs2._ import javax.net.ssl.SSLContext import jbok.network.http.server.middleware.{CORSMiddleware, GzipMiddleware, LoggerMiddleware, MetricsMiddleware} import jbok.core.config.ServiceConfig import jbok.core.api._ import jbok.crypto.ssl.SSLConfig import jbok.network.rpc.RpcService import jbok.network.rpc.http.Http4sRpcServer import org.http4s.HttpRoutes import org.http4s.implicits._ import org.http4s.server.{SSLClientAuthMode, Server} import org.http4s.server.blaze.BlazeServerBuilder final class HttpService[F[_]]( config: ServiceConfig, sslConfig: SSLConfig, account: AccountAPI[F], admin: AdminAPI[F], block: BlockAPI[F], contract: ContractAPI[F], miner: MinerAPI[F], personal: PersonalAPI[F], transaction: TransactionAPI[F], sslOpt: Option[SSLContext] )(implicit F: ConcurrentEffect[F], T: Timer[F]) { import jbok.codec.impl.circe._ import _root_.io.circe.generic.auto._ import jbok.codec.json.implicits._ val rpcService: RpcService[F, Json] = { var service = RpcService[F, Json] if (config.apis.contains("account")) service = service.mount(account) else () if (config.apis.contains("admin")) service = service.mount(admin) else () if (config.apis.contains("block")) service = service.mount(block) else () if (config.apis.contains("contract")) service = service.mount(contract) else () if (config.apis.contains("miner")) service = service.mount(miner) else () if (config.apis.contains("personal")) service = service.mount(personal) else () if (config.apis.contains("transaction")) service = service.mount(transaction) else () service } val routes: HttpRoutes[F] = Http4sRpcServer.routes(rpcService) private val builder: F[BlazeServerBuilder[F]] = { val httpApp = for { exportRoute <- MetricsMiddleware.exportService[F] withMetrics <- MetricsMiddleware[F](routes, config.enableMetrics) withLogger = LoggerMiddleware[F](config.logHeaders, config.logBody)((withMetrics <+> exportRoute).orNotFound) withCORS = CORSMiddleware[F](withLogger, config.allowedOrigins) app = GzipMiddleware[F](withCORS) } yield app val builder = httpApp.map { app => BlazeServerBuilder[F] .withHttpApp(app) .withNio2(true) .enableHttp2(config.enableHttp2) .withWebSockets(config.enableWebsockets) .bindHttp(config.port, config.local) } val sslLClientAuthMode = sslConfig.clientAuth match { case "NotRequested" => SSLClientAuthMode.NotRequested case "Requested" => SSLClientAuthMode.Requested case "Required" => SSLClientAuthMode.Requested case x => throw new IllegalArgumentException(s"SSLClientAuthMode ${x} is not supported") } sslOpt match { case Some(ssl) => builder.map(_.withSSLContext(ssl, sslLClientAuthMode)) case None => builder.map(_.enableHttp2(false)) } } val resource: Resource[F, Server[F]] = Resource.liftF(builder).flatMap(_.resource) val stream: Stream[F, Unit] = if (config.enable) { Stream.eval(builder).flatMap(_.serve).drain } else { Stream.empty } }
Example 7
Source File: JbokClientPlatform.scala From iotchain with MIT License | 5 votes |
package jbok.app import java.net.URI import cats.effect.ConcurrentEffect import io.circe.Json import jbok.network.http.HttpTransport import jbok.network.rpc.RpcClient import jbok.core.api._ object JbokClientPlatform { import jbok.codec.impl.circe._ import io.circe.generic.auto._ import jbok.codec.json.implicits._ def apply[F[_]](url: String)(implicit F: ConcurrentEffect[F]): JbokClient[F] = { val transport = HttpTransport[F](url) val rpc = RpcClient[F, Json](transport) new JbokClient[F] { override def uri: URI = new URI(url) override def client: RpcClient[F, Json] = rpc override def account: AccountAPI[F] = rpc.use[AccountAPI[F]] override def admin: AdminAPI[F] = rpc.use[AdminAPI[F]] override def block: BlockAPI[F] = rpc.use[BlockAPI[F]] override def contract: ContractAPI[F] = rpc.use[ContractAPI[F]] override def miner: MinerAPI[F] = rpc.use[MinerAPI[F]] override def personal: PersonalAPI[F] = rpc.use[PersonalAPI[F]] override def transaction: TransactionAPI[F] = rpc.use[TransactionAPI[F]] } } }
Example 8
Source File: SdkClient.scala From iotchain with MIT License | 5 votes |
package jbok.sdk import java.net.URI import cats.effect.{Clock, IO} import io.circe.Json import io.circe.syntax._ import io.circe.parser._ import jbok.network.http.HttpTransport import jbok.network.rpc.{RpcClient, RpcRequest} import scala.concurrent.ExecutionContext.Implicits.global import scala.scalajs.js import scala.scalajs.js.JSConverters._ import scala.scalajs.js.Promise import scala.scalajs.js.annotation.{JSExportAll, JSExportTopLevel} import scala.scalajs.js.JSON @JSExportAll final class SdkClient(val uri: URI, val client: RpcClient[IO, Json]) { def fetch(api: String, method: String, params: js.UndefOr[js.Any]): Promise[String] = { val json = params.toOption match { case Some(a) => parse(JSON.stringify(a)).getOrElse(Json.Null) case None => Json.Null } val request = RpcRequest(List(api, method), json) client.transport.fetch(request).map(_.asJson.spaces2).unsafeToFuture().toJSPromise } } @JSExportTopLevel("SdkClient") @JSExportAll object SdkClient { implicit val clock: Clock[IO] = Clock.create[IO] def http(url: String): SdkClient = { val transport = HttpTransport[IO](url) val client = RpcClient(transport) new SdkClient(new URI(url), client) } }
Example 9
Source File: JbokClientPlatform.scala From iotchain with MIT License | 5 votes |
package jbok.core.api import java.net.URI import cats.effect._ import io.circe.Json import javax.net.ssl.SSLContext import jbok.network.http.HttpTransport import jbok.network.http.client.HttpClients import jbok.network.http.client.HttpClients.withMiddlewares import jbok.network.rpc.RpcClient object JbokClientPlatform { import jbok.codec.impl.circe._ import io.circe.generic.auto._ import jbok.codec.json.implicits._ def resource[F[_]](url: String, ssl: Option[SSLContext] = None)(implicit F: ConcurrentEffect[F], cs: ContextShift[F], T: Timer[F]): Resource[F, JbokClient[F]] = HttpClients.okHttp[F](ssl).evalMap(withMiddlewares[F]).map { client => val transport = new HttpTransport[F](url, client) val rpc = RpcClient(transport) new JbokClient[F] { override def uri: URI = new URI(url) override def client: RpcClient[F, Json] = rpc override def account: AccountAPI[F] = rpc.use[AccountAPI[F]] override def admin: AdminAPI[F] = rpc.use[AdminAPI[F]] override def block: BlockAPI[F] = rpc.use[BlockAPI[F]] override def contract: ContractAPI[F] = rpc.use[ContractAPI[F]] override def miner: MinerAPI[F] = rpc.use[MinerAPI[F]] override def personal: PersonalAPI[F] = rpc.use[PersonalAPI[F]] override def transaction: TransactionAPI[F] = rpc.use[TransactionAPI[F]] } } }
Example 10
Source File: JbokClient.scala From iotchain with MIT License | 5 votes |
package jbok.core.api import java.net.URI import io.circe.Json import jbok.network.rpc.RpcClient trait JbokClient[F[_]] { def uri: URI def client: RpcClient[F, Json] def account: AccountAPI[F] def admin: AdminAPI[F] def block: BlockAPI[F] def contract: ContractAPI[F] def miner: MinerAPI[F] def personal: PersonalAPI[F] def transaction: TransactionAPI[F] }
Example 11
Source File: APIGharialGraphEdgeCollectionEdge.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraphEdgeCollectionEdge { def delete(client: HttpClient, graph: String, collection: String, edge: String, waitForSync: Option[Boolean] = None, returnOld: Option[Boolean] = None, ifMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[GeneralGraphEdgeDeleteHttpExamplesRc200] = client .method(HttpMethod.Delete) .path(path"/_api/gharial/{graph}/edge/{collection}/{edge}".withArguments(Map("graph" -> graph, "collection" -> collection, "edge" -> edge)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("returnOld", returnOld, None) .call[GeneralGraphEdgeDeleteHttpExamplesRc200] def get(client: HttpClient, graph: String, collection: String, edge: String, rev: Option[String] = None, ifMatch: Option[String] = None, ifNoneMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[GeneralGraphEdgeGetHttpExamplesRc200] = client .method(HttpMethod.Get) .path(path"/_api/gharial/{graph}/edge/{collection}/{edge}".withArguments(Map("graph" -> graph, "collection" -> collection, "edge" -> edge)), append = true) .param[Option[String]]("rev", rev, None) .call[GeneralGraphEdgeGetHttpExamplesRc200] def patch(client: HttpClient, graph: String, collection: String, edge: String, waitForSync: Option[Boolean] = None, keepNull: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None, ifMatch: Option[String] = None, body: Json)(implicit ec: ExecutionContext): Future[GeneralGraphEdgeModifyHttpExamplesRc200] = client .method(HttpMethod.Patch) .path(path"/_api/gharial/{graph}/edge/{collection}/{edge}".withArguments(Map("graph" -> graph, "collection" -> collection, "edge" -> edge)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("keepNull", keepNull, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[Json, GeneralGraphEdgeModifyHttpExamplesRc200](body) def put(client: HttpClient, graph: String, collection: String, edge: String, waitForSync: Option[Boolean] = None, keepNull: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None, ifMatch: Option[String] = None, body: GeneralGraphEdgeReplaceHttpExamples)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/gharial/{graph}/edge/{collection}/{edge}".withArguments(Map("graph" -> graph, "collection" -> collection, "edge" -> edge)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("keepNull", keepNull, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[GeneralGraphEdgeReplaceHttpExamples, Json](body) }
Example 12
Source File: AdminLog.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object AdminLog { def get(client: HttpClient, upto: Option[String] = None, level: Option[String] = None, start: Option[Double] = None, size: Option[Double] = None, offset: Option[Double] = None, search: Option[String] = None, sort: Option[String] = None)(implicit ec: ExecutionContext): Future[GetAdminLogRc200] = client .method(HttpMethod.Get) .path(path"/_admin/log", append = true) .param[Option[String]]("upto", upto, None) .param[Option[String]]("level", level, None) .param[Option[Double]]("start", start, None) .param[Option[Double]]("size", size, None) .param[Option[Double]]("offset", offset, None) .param[Option[String]]("search", search, None) .param[Option[String]]("sort", sort, None) .call[GetAdminLogRc200] }
Example 13
Source File: WALOperation.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import io.circe.Json case class WALOperation(tick: Long, `type`: OperationType, db: String, data: Json = Json.obj(), cuid: Option[String], tid: Option[String]) sealed abstract class OperationType(val value: Int) object OperationType { case object CreatedDatabase extends OperationType(1100) case object DropDatabase extends OperationType(1101) case object CreateCollection extends OperationType(2000) case object DropCollection extends OperationType(2001) case object RenameCollection extends OperationType(2002) case object ChangeCollection extends OperationType(2003) case object TruncateCollection extends OperationType(2004) case object CreateIndex extends OperationType(2100) case object DropIndex extends OperationType(2101) case object CreateView extends OperationType(2110) case object DropView extends OperationType(2111) case object ChangeView extends OperationType(2112) case object StartTransaction extends OperationType(2200) case object AbortTransaction extends OperationType(2201) case object InsertReplaceDocument extends OperationType(2300) case object RemoveDocument extends OperationType(2302) lazy val all: List[OperationType] = List( CreatedDatabase, DropDatabase, CreateCollection, DropCollection, RenameCollection, ChangeCollection, TruncateCollection, CreateIndex, DropIndex, CreateView, DropView, ChangeView, StartTransaction, AbortTransaction, InsertReplaceDocument, RemoveDocument ) lazy val map: Map[Int, OperationType] = all.map(ot => ot.value -> ot).toMap def apply(value: Int): OperationType = map(value) }
Example 14
Source File: APIFoxxDependencies.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIFoxxDependencies { def get(client: HttpClient, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/foxx/dependencies", append = true) .params("mount" -> mount.toString) .call[Json] def patch(client: HttpClient, body: Json, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/foxx/dependencies", append = true) .params("mount" -> mount.toString) .restful[Json, Json](body) def put(client: HttpClient, body: Json, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/foxx/dependencies", append = true) .params("mount" -> mount.toString) .restful[Json, Json](body) }
Example 15
Source File: APIFoxx.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIFoxx { def get(client: HttpClient, excludeSystem: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/foxx", append = true) .param[Option[Boolean]]("excludeSystem", excludeSystem, None) .call[Json] def post(client: HttpClient, mount: String, development: Option[Boolean] = None, setup: Option[Boolean] = None, legacy: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/foxx", append = true) .params("mount" -> mount.toString) .param[Option[Boolean]]("development", development, None) .param[Option[Boolean]]("setup", setup, None) .param[Option[Boolean]]("legacy", legacy, None) .call[Json] }
Example 16
Source File: APIAqlfunction.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIAqlfunction { def get(client: HttpClient, namespace: Option[String] = None)(implicit ec: ExecutionContext): Future[GetAPIAqlfunctionRc200] = client .method(HttpMethod.Get) .path(path"/_api/aqlfunction", append = true) .param[Option[String]]("namespace", namespace, None) .call[GetAPIAqlfunctionRc200] def post(client: HttpClient, body: PostAPIAqlfunction)(implicit ec: ExecutionContext): Future[PostAPIAqlfunctionRc200] = client .method(HttpMethod.Post) .path(path"/_api/aqlfunction", append = true) .restful[PostAPIAqlfunction, PostAPIAqlfunctionRc200](body) }
Example 17
Source File: AdminServerMode.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object AdminServerMode { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_admin/server/mode", append = true) .call[Json] def put(client: HttpClient, body: PutAdminServerMode)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_admin/server/mode", append = true) .restful[PutAdminServerMode, Json](body) }
Example 18
Source File: APIFoxxTests.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIFoxxTests { def post(client: HttpClient, mount: String, reporter: Option[String] = None, idiomatic: Option[Boolean] = None, filter: Option[String] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/foxx/tests", append = true) .params("mount" -> mount.toString) .param[Option[String]]("reporter", reporter, None) .param[Option[Boolean]]("idiomatic", idiomatic, None) .param[Option[String]]("filter", filter, None) .call[Json] }
Example 19
Source File: APIViewViewNamePropertiesArangoSearch.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.{HttpMethod, HttpRequest, HttpResponse} import io.youi.net._ import io.circe.Json import io.youi.client.intercept.Interceptor import scala.concurrent.{ExecutionContext, Future} object APIViewViewNamePropertiesArangoSearch { def patch(client: HttpClient, viewName: String, body: PatchAPIViewPropertiesIresearch)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/view/{view-name}/properties".withArguments(Map("view-name" -> viewName)), append = true) .restful[PatchAPIViewPropertiesIresearch, Json](body) def put(client: HttpClient, viewName: String, body: PostAPIViewProps)(implicit ec: ExecutionContext): Future[Json] = { client .method(HttpMethod.Put) .path(path"/_api/view/{view-name}/properties".withArguments(Map("view-name" -> viewName)), append = true) .restful[PostAPIViewProps, Json](body) } }
Example 20
Source File: APICollectionCollectionName.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APICollectionCollectionName { def delete(client: HttpClient, collectionName: String, isSystem: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/collection/{collection-name}".withArguments(Map("collection-name" -> collectionName)), append = true) .param[Option[Boolean]]("isSystem", isSystem, None) .call[Json] def get(client: HttpClient, collectionName: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/collection/{collection-name}".withArguments(Map("collection-name" -> collectionName)), append = true) .call[Json] }
Example 21
Source File: APIDocumentCollection.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIDocumentCollection { def delete(client: HttpClient, body: Json, collection: String, waitForSync: Option[Boolean] = None, returnOld: Option[Boolean] = None, ignoreRevs: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/document/{collection}".withArguments(Map("collection" -> collection)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("ignoreRevs", ignoreRevs, None) .restful[Json, Json](body) def patch(client: HttpClient, body: Json, collection: String, keepNull: Option[Boolean] = None, mergeObjects: Option[Boolean] = None, waitForSync: Option[Boolean] = None, ignoreRevs: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/document/{collection}".withArguments(Map("collection" -> collection)), append = true) .param[Option[Boolean]]("keepNull", keepNull, None) .param[Option[Boolean]]("mergeObjects", mergeObjects, None) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("ignoreRevs", ignoreRevs, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[Json, Json](body) def post(client: HttpClient, collection: String, body: Json, waitForSync: Option[Boolean] = None, returnNew: Option[Boolean] = None, returnOld: Option[Boolean] = None, silent: Option[Boolean] = None, overwrite: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/document/{collection}".withArguments(Map("collection" -> collection)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("returnNew", returnNew, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("silent", silent, None) .param[Option[Boolean]]("overwrite", overwrite, None) .restful[Json, Json](body) def put(client: HttpClient, body: Json, collection: String, waitForSync: Option[Boolean] = None, ignoreRevs: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/document/{collection}".withArguments(Map("collection" -> collection)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("ignoreRevs", ignoreRevs, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[Json, Json](body) }
Example 22
Source File: APIViewViewName.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIViewViewName { def delete(client: HttpClient, viewName: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/view/{view-name}".withArguments(Map("view-name" -> viewName)), append = true) .call[Json] def get(client: HttpClient, viewName: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/view/{view-name}".withArguments(Map("view-name" -> viewName)), append = true) .call[Json] }
Example 23
Source File: APIQueryCacheProperties.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIQueryCacheProperties { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/query-cache/properties", append = true) .call[Json] def put(client: HttpClient, body: PutApiQueryCacheProperties)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/query-cache/properties", append = true) .restful[PutApiQueryCacheProperties, Json](body) }
Example 24
Source File: APIReplicationBatchId.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIReplicationBatchId { def delete(client: HttpClient, id: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/replication/batch/{id}".withArguments(Map("id" -> id)), append = true) .call[Json] def put(client: HttpClient, body: PutBatchReplication, id: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/replication/batch/{id}".withArguments(Map("id" -> id)), append = true) .restful[PutBatchReplication, Json](body) }
Example 25
Source File: APIReplicationDump.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIReplicationDump { def get(client: HttpClient, collection: String, chunkSize: Option[Double] = None, batchId: Double, from: Option[Double] = None, to: Option[Double] = None, includeSystem: Option[Boolean] = None, ticks: Option[Boolean] = None, flush: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/replication/dump", append = true) .params("collection" -> collection.toString) .param[Option[Double]]("chunkSize", chunkSize, None) .params("batchId" -> batchId.toString) .param[Option[Double]]("from", from, None) .param[Option[Double]]("to", to, None) .param[Option[Boolean]]("includeSystem", includeSystem, None) .param[Option[Boolean]]("ticks", ticks, None) .param[Option[Boolean]]("flush", flush, None) .call[Json] }
Example 26
Source File: APIImportjson.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIImportjson { def post(client: HttpClient, body: Json, `type`: String, collection: String, fromPrefix: Option[String] = None, toPrefix: Option[String] = None, overwrite: Option[Boolean] = None, waitForSync: Option[Boolean] = None, onDuplicate: Option[String] = None, complete: Option[Boolean] = None, details: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/import#json", append = true) .params("type" -> `type`.toString) .params("collection" -> collection.toString) .param[Option[String]]("fromPrefix", fromPrefix, None) .param[Option[String]]("toPrefix", toPrefix, None) .param[Option[Boolean]]("overwrite", overwrite, None) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[String]]("onDuplicate", onDuplicate, None) .param[Option[Boolean]]("complete", complete, None) .param[Option[Boolean]]("details", details, None) .restful[Json, Json](body) }
Example 27
Source File: APIImportdocument.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIImportdocument { def post(client: HttpClient, body: Json, collection: String, fromPrefix: Option[String] = None, toPrefix: Option[String] = None, overwrite: Option[Boolean] = None, waitForSync: Option[Boolean] = None, onDuplicate: Option[String] = None, complete: Option[Boolean] = None, details: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/import#document", append = true) .params("collection" -> collection.toString) .param[Option[String]]("fromPrefix", fromPrefix, None) .param[Option[String]]("toPrefix", toPrefix, None) .param[Option[Boolean]]("overwrite", overwrite, None) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[String]]("onDuplicate", onDuplicate, None) .param[Option[Boolean]]("complete", complete, None) .param[Option[Boolean]]("details", details, None) .restful[Json, Json](body) }
Example 28
Source File: APIQuerySlow.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIQuerySlow { def delete(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/query/slow", append = true) .call[Json] def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/query/slow", append = true) .call[Json] }
Example 29
Source File: VersionDetailsStruct.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class VersionDetailsStruct(architecture: Option[String] = None, arm: Option[String] = None, asan: Option[String] = None, asmCrc32: Option[String] = None, assertions: Option[String] = None, boostVersion: Option[String] = None, buildDate: Option[String] = None, buildRepository: Option[String] = None, compiler: Option[String] = None, cplusplus: Option[String] = None, debug: Option[String] = None, endianness: Option[String] = None, failureTests: Option[String] = None, fdClientEventHandler: Option[String] = None, fdSetsize: Option[String] = None, fullVersionString: Option[String] = None, host: Option[String] = None, icuVersion: Option[String] = None, jemalloc: Option[String] = None, maintainerMode: Option[String] = None, mode: Option[String] = None, opensslVersion: Option[String] = None, platform: Option[String] = None, reactorType: Option[String] = None, rocksdbVersion: Option[String] = None, serverVersion: Option[String] = None, sizeofInt: Option[String] = None, sizeofVoid: Option[String] = None, sse42: Option[String] = None, unalignedAccess: Option[String] = None, v8Version: Option[String] = None, vpackVersion: Option[String] = None, zlibVersion: Option[String] = None)
Example 30
Source File: PutAPIReplicationApplierAdjust.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class PutAPIReplicationApplierAdjust(endpoint: String, adaptivePolling: Option[Boolean] = None, autoResync: Option[Boolean] = None, autoResyncRetries: Option[Long] = None, autoStart: Option[Boolean] = None, chunkSize: Option[Long] = None, connectTimeout: Option[Long] = None, connectionRetryWaitTime: Option[Long] = None, database: Option[String] = None, idleMaxWaitTime: Option[Long] = None, idleMinWaitTime: Option[Long] = None, includeSystem: Option[Boolean] = None, initialSyncMaxWaitTime: Option[Long] = None, maxConnectRetries: Option[Long] = None, password: Option[String] = None, requestTimeout: Option[Long] = None, requireFromPresent: Option[Boolean] = None, restrictCollections: Option[List[String]] = None, restrictType: Option[String] = None, username: Option[String] = None, verbose: Option[Boolean] = None)
Example 31
Source File: HttpStatisticsStruct.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class HttpStatisticsStruct(requestsAsync: Option[Int] = None, requestsDelete: Option[Int] = None, requestsGet: Option[Int] = None, requestsHead: Option[Int] = None, requestsOptions: Option[Int] = None, requestsOther: Option[Int] = None, requestsPatch: Option[Int] = None, requestsPost: Option[Int] = None, requestsPut: Option[Int] = None, requestsTotal: Option[Int] = None)
Example 32
Source File: CollectionFigures.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class CollectionFigures(alive: Option[CollectionFiguresAlive] = None, compactionStatus: Option[CompactionStatusAttributes] = None, compactors: Option[CollectionFiguresCompactors] = None, datafiles: Option[CollectionFiguresDatafiles] = None, dead: Option[CollectionFiguresDead] = None, documentReferences: Option[Long] = None, indexes: Option[CollectionFiguresIndexes] = None, journals: Option[CollectionFiguresJournals] = None, lastTick: Option[Long] = None, readcache: Option[CollectionFiguresReadcache] = None, revisions: Option[CollectionFiguresRevisions] = None, uncollectedLogfileEntries: Option[Long] = None, waitingFor: Option[String] = None)
Example 33
Source File: PutAPIReplicationMakeSlave.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class PutAPIReplicationMakeSlave(endpoint: String, adaptivePolling: Option[Boolean] = None, autoResync: Option[Boolean] = None, autoResyncRetries: Option[Long] = None, chunkSize: Option[Long] = None, connectTimeout: Option[Long] = None, connectionRetryWaitTime: Option[Long] = None, database: Option[String] = None, idleMaxWaitTime: Option[Long] = None, idleMinWaitTime: Option[Long] = None, includeSystem: Option[Boolean] = None, initialSyncMaxWaitTime: Option[Long] = None, maxConnectRetries: Option[Long] = None, password: Option[String] = None, requestTimeout: Option[Long] = None, requireFromPresent: Option[Boolean] = None, restrictCollections: Option[List[String]] = None, restrictType: Option[String] = None, username: Option[String] = None, verbose: Option[Boolean] = None)
Example 34
Source File: PostAdminEchoRc200.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class PostAdminEchoRc200(authorized: Boolean, client: Option[AdminEchoClientStruct] = None, cookies: Option[Json] = None, database: Option[String] = None, headers: Option[Json] = None, internals: Option[Json] = None, parameters: Option[Json] = None, path: Option[String] = None, prefix: Option[Json] = None, protocol: Option[String] = None, rawRequestBody: Option[List[String]] = None, rawSuffix: Option[List[String]] = None, requestBody: Option[String] = None, requestType: Option[String] = None, server: Option[AdminEchoServerStruct] = None, suffix: Option[List[String]] = None, url: Option[String] = None, user: Option[String] = None)
Example 35
Source File: PostAPICollection.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class PostAPICollection(name: String, distributeShardsLike: Option[String] = None, doCompact: Option[Boolean] = None, indexBuckets: Option[Long] = None, isSystem: Option[Boolean] = None, isVolatile: Option[Boolean] = None, journalSize: Option[Long] = None, keyOptions: Option[PostAPICollectionOpts] = None, numberOfShards: Long = 1L, replicationFactor: Long = 1L, shardKeys: List[String] = List("_key"), shardingStrategy: Option[String] = None, smartJoinAttribute: Option[String] = None, `type`: Option[Long] = None, waitForSync: Option[Boolean] = None)
Example 36
Source File: PutAdminLoglevel.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class PutAdminLoglevel(agency: Option[String] = None, agencycomm: Option[String] = None, auditAuthentication: Option[String] = None, auditAuthorization: Option[String] = None, auditCollection: Option[String] = None, auditDatabase: Option[String] = None, auditDocument: Option[String] = None, auditService: Option[String] = None, auditView: Option[String] = None, authentication: Option[String] = None, authorization: Option[String] = None, cache: Option[String] = None, cluster: Option[String] = None, collector: Option[String] = None, communication: Option[String] = None, compactor: Option[String] = None, config: Option[String] = None, datafiles: Option[String] = None, development: Option[String] = None, engines: Option[String] = None, general: Option[String] = None, graphs: Option[String] = None, heartbeat: Option[String] = None, ldap: Option[String] = None, memory: Option[String] = None, mmap: Option[String] = None, performance: Option[String] = None, pregel: Option[String] = None, queries: Option[String] = None, replication: Option[String] = None, requests: Option[String] = None, rocksdb: Option[String] = None, ssl: Option[String] = None, startup: Option[String] = None, supervision: Option[String] = None, syscall: Option[String] = None, threads: Option[String] = None, trx: Option[String] = None, v8: Option[String] = None, views: Option[String] = None)
Example 37
Source File: HTTPAPITRAVERSAL.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class HTTPAPITRAVERSAL(startVertex: String, direction: Option[String] = None, edgeCollection: Option[String] = None, expander: Option[String] = None, filter: Option[String] = None, graphName: Option[String] = None, init: Option[String] = None, itemOrder: Option[String] = None, maxDepth: Option[String] = None, maxIterations: Option[String] = None, minDepth: Option[String] = None, order: Option[String] = None, sort: Option[String] = None, strategy: Option[String] = None, uniqueness: Option[String] = None, visitor: Option[String] = None)
Example 38
Source File: CollectionInfo.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api.model import io.circe.Json case class CollectionInfo(keyOptions: KeyGeneratorType, doCompact: Option[Boolean] = None, globallyUniqueId: Option[String] = None, id: Option[String] = None, indexBuckets: Option[Int] = None, isSystem: Option[Boolean] = None, isVolatile: Option[Boolean] = None, journalSize: Option[Int] = None, name: Option[String] = None, numberOfShards: Option[Int] = None, replicationFactor: Option[Int] = None, shardKeys: Option[List[String]] = None, shardingStrategy: Option[String] = None, smartGraphAttribute: Option[String] = None, status: Option[Int] = None, statusString: Option[String] = None, `type`: Option[Int] = None, waitForSync: Option[Boolean] = None)
Example 39
Source File: APITasks.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APITasks { def post(client: HttpClient, body: PostAPINewTasks)(implicit ec: ExecutionContext): Future[PostAPINewTasksRc200] = client .method(HttpMethod.Post) .path(path"/_api/tasks", append = true) .restful[PostAPINewTasks, PostAPINewTasksRc200](body) def get(client: HttpClient)(implicit ec: ExecutionContext): Future[GetAPITasksAllRc200] = client .method(HttpMethod.Get) .path(path"/_api/tasks/", append = true) .call[GetAPITasksAllRc200] }
Example 40
Source File: APIUserUserDatabaseDbname.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIUserUserDatabaseDbname { def delete(client: HttpClient, user: String, dbname: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/user/{user}/database/{dbname}".withArguments(Map("user" -> user, "dbname" -> dbname)), append = true) .call[Json] def put(client: HttpClient, body: UserHandlingGrantDatabase, user: String, dbname: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/user/{user}/database/{dbname}".withArguments(Map("user" -> user, "dbname" -> dbname)), append = true) .restful[UserHandlingGrantDatabase, Json](body) }
Example 41
Source File: APIDatabase.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIDatabase { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/database", append = true) .call[Json] def post(client: HttpClient, body: GetAPIDatabaseNew)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/database", append = true) .restful[GetAPIDatabaseNew, Json](body) }
Example 42
Source File: APIFoxxConfiguration.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIFoxxConfiguration { def get(client: HttpClient, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/foxx/configuration", append = true) .params("mount" -> mount.toString) .call[Json] def patch(client: HttpClient, body: Json, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/foxx/configuration", append = true) .params("mount" -> mount.toString) .restful[Json, Json](body) def put(client: HttpClient, body: Json, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/foxx/configuration", append = true) .params("mount" -> mount.toString) .restful[Json, Json](body) }
Example 43
Source File: APIUserUser.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIUserUser { def delete(client: HttpClient, user: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/user/{user}".withArguments(Map("user" -> user)), append = true) .call[Json] def get(client: HttpClient, user: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/user/{user}".withArguments(Map("user" -> user)), append = true) .call[Json] def patch(client: HttpClient, user: String, body: UserHandlingModify)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/user/{user}".withArguments(Map("user" -> user)), append = true) .restful[UserHandlingModify, Json](body) def put(client: HttpClient, user: String, body: UserHandlingReplace)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/user/{user}".withArguments(Map("user" -> user)), append = true) .restful[UserHandlingReplace, Json](body) }
Example 44
Source File: APIGharialGraphVertexCollection.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraphVertexCollection { def delete(client: HttpClient, graph: String, collection: String, dropCollection: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[GeneralGraphVertexCollectionRemoveHttpExamplesRc200] = client .method(HttpMethod.Delete) .path(path"/_api/gharial/{graph}/vertex/{collection}".withArguments(Map("graph" -> graph, "collection" -> collection)), append = true) .param[Option[Boolean]]("dropCollection", dropCollection, None) .call[GeneralGraphVertexCollectionRemoveHttpExamplesRc200] def post(client: HttpClient, graph: String, collection: String, waitForSync: Option[Boolean] = None, returnNew: Option[Boolean] = None, body: Json)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/gharial/{graph}/vertex/{collection}".withArguments(Map("graph" -> graph, "collection" -> collection)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[Json, Json](body) }
Example 45
Source File: APIReplicationLoggerFollow.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIReplicationLoggerFollow { def get(client: HttpClient, from: Option[Double] = None, to: Option[Double] = None, chunkSize: Option[Double] = None, includeSystem: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/replication/logger-follow", append = true) .param[Option[Double]]("from", from, None) .param[Option[Double]]("to", to, None) .param[Option[Double]]("chunkSize", chunkSize, None) .param[Option[Boolean]]("includeSystem", includeSystem, None) .call[Json] }
Example 46
Source File: APIGharialGraphEdge.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraphEdge { def get(client: HttpClient, graph: String)(implicit ec: ExecutionContext): Future[GeneralGraphListEdgeHttpExamplesRc200] = client .method(HttpMethod.Get) .path(path"/_api/gharial/{graph}/edge".withArguments(Map("graph" -> graph)), append = true) .call[GeneralGraphListEdgeHttpExamplesRc200] def post(client: HttpClient, graph: String, body: GeneralGraphEdgeDefinitionAddHttpExamples)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/gharial/{graph}/edge".withArguments(Map("graph" -> graph)), append = true) .restful[GeneralGraphEdgeDefinitionAddHttpExamples, Json](body) }
Example 47
Source File: APIFoxxService.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIFoxxService { def delete(client: HttpClient, mount: String, teardown: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/foxx/service", append = true) .params("mount" -> mount.toString) .param[Option[Boolean]]("teardown", teardown, None) .call[Json] def get(client: HttpClient, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/foxx/service", append = true) .params("mount" -> mount.toString) .call[Json] def patch(client: HttpClient, mount: String, teardown: Option[Boolean] = None, setup: Option[Boolean] = None, legacy: Option[Boolean] = None, force: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/foxx/service", append = true) .params("mount" -> mount.toString) .param[Option[Boolean]]("teardown", teardown, None) .param[Option[Boolean]]("setup", setup, None) .param[Option[Boolean]]("legacy", legacy, None) .param[Option[Boolean]]("force", force, None) .call[Json] def put(client: HttpClient, mount: String, teardown: Option[Boolean] = None, setup: Option[Boolean] = None, legacy: Option[Boolean] = None, force: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/foxx/service", append = true) .params("mount" -> mount.toString) .param[Option[Boolean]]("teardown", teardown, None) .param[Option[Boolean]]("setup", setup, None) .param[Option[Boolean]]("legacy", legacy, None) .param[Option[Boolean]]("force", force, None) .call[Json] }
Example 48
Source File: APICollection.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APICollection { def get(client: HttpClient, excludeSystem: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/collection", append = true) .param[Option[Boolean]]("excludeSystem", excludeSystem, None) .call[Json] def post(client: HttpClient, body: PostAPICollection, waitForSyncReplication: Option[Int] = None, enforceReplicationFactor: Option[Int] = None)(implicit ec: ExecutionContext): Future[CollectionInfo] = client .method(HttpMethod.Post) .path(path"/_api/collection", append = true) .param[Option[Int]]("waitForSyncReplication", waitForSyncReplication, None) .param[Option[Int]]("enforceReplicationFactor", enforceReplicationFactor, None) .restful[PostAPICollection, CollectionInfo](body) }
Example 49
Source File: APIAnalyzerAnalyzerName.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIAnalyzerAnalyzerName { def delete(client: HttpClient, analyzerName: String, force: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/analyzer/{analyzer-name}".withArguments(Map("analyzer-name" -> analyzerName)), append = true) .param[Option[Boolean]]("force", force, None) .call[Json] def get(client: HttpClient, analyzerName: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/analyzer/{analyzer-name}".withArguments(Map("analyzer-name" -> analyzerName)), append = true) .call[Json] }
Example 50
Source File: APIJobJobId.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIJobJobId { def get(client: HttpClient, jobId: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/job/{job-id}".withArguments(Map("job-id" -> jobId)), append = true) .call[Json] def put(client: HttpClient, jobId: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/job/{job-id}".withArguments(Map("job-id" -> jobId)), append = true) .call[Json] }
Example 51
Source File: APIJobType.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIJobType { def delete(client: HttpClient, `type`: String, stamp: Option[Double] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/job/{type}".withArguments(Map("type" -> `type`)), append = true) .param[Option[Double]]("stamp", stamp, None) .call[Json] def get(client: HttpClient, `type`: String, count: Option[Double] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/job/{type}".withArguments(Map("type" -> `type`)), append = true) .param[Option[Double]]("count", count, None) .call[Json] }
Example 52
Source File: APICursorCursorIdentifier.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APICursorCursorIdentifier { def delete(client: HttpClient, cursorIdentifier: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/cursor/{cursor-identifier}".withArguments(Map("cursor-identifier" -> cursorIdentifier)), append = true) .call[Json] def put(client: HttpClient, cursorIdentifier: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/cursor/{cursor-identifier}".withArguments(Map("cursor-identifier" -> cursorIdentifier)), append = true) .call[Json] }
Example 53
Source File: APIGharialGraphVertexCollectionVertex.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraphVertexCollectionVertex { def delete(client: HttpClient, graph: String, collection: String, vertex: String, waitForSync: Option[Boolean] = None, returnOld: Option[Boolean] = None, ifMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[GeneralGraphVertexDeleteHttpExamplesRc200] = client .method(HttpMethod.Delete) .path(path"/_api/gharial/{graph}/vertex/{collection}/{vertex}".withArguments(Map("graph" -> graph, "collection" -> collection, "vertex" -> vertex)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("returnOld", returnOld, None) .call[GeneralGraphVertexDeleteHttpExamplesRc200] def get(client: HttpClient, graph: String, collection: String, vertex: String, rev: Option[String] = None, ifMatch: Option[String] = None, ifNoneMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[GeneralGraphVertexGetHttpExamplesRc200] = client .method(HttpMethod.Get) .path(path"/_api/gharial/{graph}/vertex/{collection}/{vertex}".withArguments(Map("graph" -> graph, "collection" -> collection, "vertex" -> vertex)), append = true) .param[Option[String]]("rev", rev, None) .call[GeneralGraphVertexGetHttpExamplesRc200] def patch(client: HttpClient, graph: String, collection: String, vertex: String, waitForSync: Option[Boolean] = None, keepNull: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None, ifMatch: Option[String] = None, body: Json)(implicit ec: ExecutionContext): Future[GeneralGraphVertexModifyHttpExamplesRc200] = client .method(HttpMethod.Patch) .path(path"/_api/gharial/{graph}/vertex/{collection}/{vertex}".withArguments(Map("graph" -> graph, "collection" -> collection, "vertex" -> vertex)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("keepNull", keepNull, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[Json, GeneralGraphVertexModifyHttpExamplesRc200](body) def put(client: HttpClient, graph: String, collection: String, vertex: String, waitForSync: Option[Boolean] = None, keepNull: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None, ifMatch: Option[String] = None, body: Json)(implicit ec: ExecutionContext): Future[GeneralGraphVertexReplaceHttpExamplesRc200] = client .method(HttpMethod.Put) .path(path"/_api/gharial/{graph}/vertex/{collection}/{vertex}".withArguments(Map("graph" -> graph, "collection" -> collection, "vertex" -> vertex)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("keepNull", keepNull, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .restful[Json, GeneralGraphVertexReplaceHttpExamplesRc200](body) }
Example 54
Source File: APIReplicationApplierConfig.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIReplicationApplierConfig { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/replication/applier-config", append = true) .call[Json] def put(client: HttpClient, body: PutAPIReplicationApplierAdjust)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/replication/applier-config", append = true) .restful[PutAPIReplicationApplierAdjust, Json](body) }
Example 55
Source File: APIAnalyzer.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIAnalyzer { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/analyzer", append = true) .call[Json] def post(client: HttpClient, body: PostAPIAnalyzer)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/analyzer", append = true) .restful[PostAPIAnalyzer, Json](body) }
Example 56
Source File: AdminLogLevel.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object AdminLogLevel { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_admin/log/level", append = true) .call[Json] def put(client: HttpClient, body: PutAdminLoglevel)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_admin/log/level", append = true) .restful[PutAdminLoglevel, Json](body) }
Example 57
Source File: APIGharial.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharial { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[GeneralGraphListHttpExamplesRc200] = client .method(HttpMethod.Get) .path(path"/_api/gharial", append = true) .call[GeneralGraphListHttpExamplesRc200] def post(client: HttpClient, waitForSync: Option[Boolean] = None, body: GeneralGraphCreateHttpExamples)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/gharial", append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .restful[GeneralGraphCreateHttpExamples, Json](body) }
Example 58
Source File: APITasksId.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APITasksId { def delete(client: HttpClient, id: String)(implicit ec: ExecutionContext): Future[DeleteAPITasksRc200] = client .method(HttpMethod.Delete) .path(path"/_api/tasks/{id}".withArguments(Map("id" -> id)), append = true) .call[DeleteAPITasksRc200] def get(client: HttpClient, id: String)(implicit ec: ExecutionContext): Future[APITaskStruct] = client .method(HttpMethod.Get) .path(path"/_api/tasks/{id}".withArguments(Map("id" -> id)), append = true) .call[APITaskStruct] def put(client: HttpClient, id: String, body: PutAPINewTasks)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/tasks/{id}".withArguments(Map("id" -> id)), append = true) .restful[PutAPINewTasks, Json](body) }
Example 59
Source File: APIUser.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIUser { def post(client: HttpClient, body: UserHandlingCreate)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/user", append = true) .restful[UserHandlingCreate, Json](body) def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/user/", append = true) .call[Json] }
Example 60
Source File: APIQueryProperties.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIQueryProperties { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/query/properties", append = true) .call[Json] def put(client: HttpClient, body: PutApiQueryProperties)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/query/properties", append = true) .restful[PutApiQueryProperties, Json](body) }
Example 61
Source File: APIIndexIndexHandle.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIIndexIndexHandle { def delete(client: HttpClient, collection: String, indexHandle: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/index/{collection}/{index-handle}".withArguments(Map("collection" -> collection, "index-handle" -> indexHandle)), append = true) .call[Json] def get(client: HttpClient, indexHandle: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/index/{index-handle}".withArguments(Map("index-handle" -> indexHandle)), append = true) .call[Json] }
Example 62
Source File: APIGharialGraphVertex.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraphVertex { def get(client: HttpClient, graph: String)(implicit ec: ExecutionContext): Future[GeneralGraphListVertexHttpExamplesRc200] = client .method(HttpMethod.Get) .path(path"/_api/gharial/{graph}/vertex".withArguments(Map("graph" -> graph)), append = true) .call[GeneralGraphListVertexHttpExamplesRc200] def post(client: HttpClient, graph: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/gharial/{graph}/vertex".withArguments(Map("graph" -> graph)), append = true) .call[Json] }
Example 63
Source File: AdminWalProperties.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object AdminWalProperties { def get(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_admin/wal/properties", append = true) .call[Json] def put(client: HttpClient)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_admin/wal/properties", append = true) .call[Json] }
Example 64
Source File: APICollectionCollectionNameProperties.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APICollectionCollectionNameProperties { def get(client: HttpClient, collectionName: String)(implicit ec: ExecutionContext): Future[CollectionInfo] = client .method(HttpMethod.Get) .path(path"/_api/collection/{collection-name}/properties".withArguments(Map("collection-name" -> collectionName)), append = true) .call[CollectionInfo] def put(client: HttpClient, collectionName: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/collection/{collection-name}/properties".withArguments(Map("collection-name" -> collectionName)), append = true) .call[Json] }
Example 65
Source File: APIUserUserDatabaseDbnameCollection.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIUserUserDatabaseDbnameCollection { def delete(client: HttpClient, user: String, dbname: String, collection: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/user/{user}/database/{dbname}/{collection}".withArguments(Map("user" -> user, "dbname" -> dbname, "collection" -> collection)), append = true) .call[Json] def put(client: HttpClient, body: UserHandlingGrantCollection, user: String, dbname: String, collection: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/user/{user}/database/{dbname}/{collection}".withArguments(Map("user" -> user, "dbname" -> dbname, "collection" -> collection)), append = true) .restful[UserHandlingGrantCollection, Json](body) }
Example 66
Source File: APIGharialGraph.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraph { def delete(client: HttpClient, graph: String, dropCollections: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/gharial/{graph}".withArguments(Map("graph" -> graph)), append = true) .param[Option[Boolean]]("dropCollections", dropCollections, None) .call[Json] def get(client: HttpClient, graph: String)(implicit ec: ExecutionContext): Future[GeneralGraphGetHttpExamplesRc200] = client .method(HttpMethod.Get) .path(path"/_api/gharial/{graph}".withArguments(Map("graph" -> graph)), append = true) .call[GeneralGraphGetHttpExamplesRc200] }
Example 67
Source File: APIFoxxDevelopment.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIFoxxDevelopment { def delete(client: HttpClient, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/foxx/development", append = true) .params("mount" -> mount.toString) .call[Json] def post(client: HttpClient, mount: String)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Post) .path(path"/_api/foxx/development", append = true) .params("mount" -> mount.toString) .call[Json] }
Example 68
Source File: APIDocumentDocumentHandle.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIDocumentDocumentHandle { def put(client: HttpClient, body: Json, documentHandle: String, waitForSync: Option[Boolean] = None, ignoreRevs: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None, silent: Option[Boolean] = None, IfMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/document/{document-handle}".withArguments(Map("document-handle" -> documentHandle)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("ignoreRevs", ignoreRevs, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .param[Option[Boolean]]("silent", silent, None) .restful[Json, Json](body) def patch(client: HttpClient, body: Json, documentHandle: String, keepNull: Option[Boolean] = None, mergeObjects: Option[Boolean] = None, waitForSync: Option[Boolean] = None, ignoreRevs: Option[Boolean] = None, returnOld: Option[Boolean] = None, returnNew: Option[Boolean] = None, silent: Option[Boolean] = None, IfMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Patch) .path(path"/_api/document/{document-handle}".withArguments(Map("document-handle" -> documentHandle)), append = true) .param[Option[Boolean]]("keepNull", keepNull, None) .param[Option[Boolean]]("mergeObjects", mergeObjects, None) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("ignoreRevs", ignoreRevs, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("returnNew", returnNew, None) .param[Option[Boolean]]("silent", silent, None) .restful[Json, Json](body) def delete(client: HttpClient, collectionName: String, documentHandle: String, waitForSync: Option[Boolean] = None, returnOld: Option[Boolean] = None, silent: Option[Boolean] = None, IfMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/document/{collection}/{document-handle}".withArguments(Map("collection" -> collectionName, "document-handle" -> documentHandle)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("returnOld", returnOld, None) .param[Option[Boolean]]("silent", silent, None) .call[Json] def get(client: HttpClient, collection: String, documentHandle: String, IfNoneMatch: Option[String] = None, IfMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/document/{collection}/{document-handle}".withArguments(Map("collection" -> collection, "document-handle" -> documentHandle)), append = true) .call[Json] def head(client: HttpClient, documentHandle: String, IfNoneMatch: Option[String] = None, IfMatch: Option[String] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Head) .path(path"/_api/document/{document-handle}".withArguments(Map("document-handle" -> documentHandle)), append = true) .call[Json] }
Example 69
Source File: APIGharialGraphEdgeDefinition.scala From scarango with MIT License | 5 votes |
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIGharialGraphEdgeDefinition { def delete(client: HttpClient, graph: String, definition: String, waitForSync: Option[Boolean] = None, dropCollections: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Delete) .path(path"/_api/gharial/{graph}/edge/{definition}".withArguments(Map("graph" -> graph, "definition" -> definition)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("dropCollections", dropCollections, None) .call[Json] def put(client: HttpClient, graph: String, definition: String, waitForSync: Option[Boolean] = None, dropCollections: Option[Boolean] = None, body: GeneralGraphEdgeDefinitionModifyHttpExamples)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Put) .path(path"/_api/gharial/{graph}/edge/{definition}".withArguments(Map("graph" -> graph, "definition" -> definition)), append = true) .param[Option[Boolean]]("waitForSync", waitForSync, None) .param[Option[Boolean]]("dropCollections", dropCollections, None) .restful[GeneralGraphEdgeDefinitionModifyHttpExamples, Json](body) }
Example 70
Source File: ArangoView.scala From scarango with MIT License | 5 votes |
package com.outr.arango import com.outr.arango.api.model.{ArangoLinkFieldProperties, ArangoLinkProperties, PostAPIViewFields, PostAPIViewIresearch, PostAPIViewLinkProps, PostAPIViewProps, PostAPIViewPropsConsolidation, PutAPIViewPropertiesIresearch} import com.outr.arango.api.{APIViewArangoSearch, APIViewViewNamePropertiesArangoSearch} import io.circe.Json import io.youi.client.HttpClient import profig.JsonUtil import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} class ArangoView(client: HttpClient, dbName: String, viewName: String, `type`: String) { def create(cleanupIntervalStep: Int = 10, commitInterval: FiniteDuration = 1.second, consolidationInterval: FiniteDuration = 60.seconds, consolidationPolicy: Option[PostAPIViewPropsConsolidation] = None) (implicit ec: ExecutionContext): Future[ViewInfo] = APIViewArangoSearch.post( client = client, body = PostAPIViewIresearch( name = viewName, properties = Some(PostAPIViewProps( cleanupIntervalStep = Some(cleanupIntervalStep), commitIntervalMsec = Some(commitInterval.toMillis), consolidationIntervalMsec = Some(consolidationInterval.toMillis), consolidationPolicy = consolidationPolicy, links = None )), `type` = Some(`type`) ) ).map(json => JsonUtil.fromJson[ViewInfo](json)) def update(includeAllFields: Boolean, links: Option[List[ViewLink]] = None, cleanupIntervalStep: Option[Int] = None, commitInterval: Option[FiniteDuration] = None, consolidationInterval: Option[FiniteDuration] = None, consolidationPolicy: Option[PostAPIViewPropsConsolidation] = None) (implicit ec: ExecutionContext): Future[ViewInfo] = { val map = links.map(_.map { l => l.collectionName -> ArangoLinkProperties( analyzers = l.analyzers, fields = l.fields, includeAllFields = includeAllFields, storeValues = if (l.allowExists) "id" else "none", trackListPositions = l.trackListPositions ) }.toMap) APIViewViewNamePropertiesArangoSearch.put( client = client, viewName = viewName, body = PostAPIViewProps( cleanupIntervalStep = cleanupIntervalStep.map(_.toLong), commitIntervalMsec = commitInterval.map(_.toMillis), consolidationIntervalMsec = consolidationInterval.map(_.toMillis), consolidationPolicy = consolidationPolicy, links = map ) ).map(json => JsonUtil.fromJson[ViewInfo](json)) } }
Example 71
Source File: Value.scala From scarango with MIT License | 5 votes |
package com.outr.arango import io.circe.Json import scala.language.implicitConversions case class Value(json: Json) object Value { implicit def string(value: String): Value = if (value != null) Value(Json.fromString(value)) else Value(Json.Null) implicit def string(value: Option[String]): Value = Value(value.map(Json.fromString).getOrElse(Json.Null)) implicit def boolean(value: Boolean): Value = Value(Json.fromBoolean(value)) implicit def boolean(value: Option[Boolean]): Value = Value(value.map(Json.fromBoolean).getOrElse(Json.Null)) implicit def int(value: Int): Value = Value(Json.fromInt(value)) implicit def int(value: Option[Int]): Value = Value(value.map(Json.fromInt).getOrElse(Json.Null)) implicit def long(value: Long): Value = Value(Json.fromLong(value)) implicit def long(value: Option[Long]): Value = Value(value.map(Json.fromLong).getOrElse(Json.Null)) implicit def double(value: Double): Value = Value(Json.fromDouble(value).get) implicit def double(value: Option[Double]): Value = Value(value.map(Json.fromDouble(_).get).getOrElse(Json.Null)) implicit def bigDecimal(value: BigDecimal): Value = Value(Json.fromBigDecimal(value)) implicit def bigDecimal(value: Option[BigDecimal]): Value = Value(value.map(Json.fromBigDecimal).getOrElse(Json.Null)) implicit def values(values: Seq[Value]): Value = Value(Json.arr(values.map(_.json): _*)) implicit def strings(value: Seq[String]): Value = conv[String](value, string) implicit def booleans(value: Seq[Boolean]): Value = conv[Boolean](value, boolean) implicit def ints(value: Seq[Int]): Value = conv[Int](value, int) implicit def longs(value: Seq[Long]): Value = conv[Long](value, long) implicit def doubles(value: Seq[Double]): Value = conv[Double](value, double) implicit def bigDecimals(value: Seq[BigDecimal]): Value = conv[BigDecimal](value, bigDecimal) implicit def id[T](value: Id[T]): Value = string(value._id) implicit def json(value: Json): Value = Value(value) private def conv[T](seq: Seq[T], converter: T => Value): Value = { val values = seq.toList.map(converter).map(_.json) Value(Json.arr(values: _*)) } }
Example 72
Source File: Serialization.scala From scarango with MIT License | 5 votes |
package com.outr.arango import io.circe.Decoder.Result import io.circe.{Decoder, Encoder, HCursor, Json} import scala.language.experimental.macros case class Serialization[D](private val doc2Json: D => Json, private val json2Doc: Json => D) { final def toJson(document: D): Json = Id.update(doc2Json(document)) final def fromJson(json: Json): D = json2Doc(Id.update(json)) lazy val decoder: Decoder[D] = new Decoder[D] { override def apply(c: HCursor): Result[D] = Right(fromJson(c.value)) } } object Serialization { def auto[D]: Serialization[D] = macro Macros.serializationAuto[D] def create[D](encoder: Encoder[D], decoder: Decoder[D]): Serialization[D] = { val doc2Json = (d: D) => encoder(d) val json2Doc = (json: Json) => decoder.decodeJson(json) match { case Left(df) => throw df case Right(d) => d } Serialization[D](doc2Json, json2Doc) } }
Example 73
Source File: Query.scala From scarango with MIT License | 5 votes |
package com.outr.arango import io.circe.Json case class Query(value: String, args: Map[String, Value]) { def fixed(): Query = if (args.valuesIterator.map(_.json).contains(Json.Null)) { var updated = value val filteredArgs = args.filter { case (k, v) => if (v.json == Json.Null) { updated = updated.replaceAllLiterally(s"@$k", "null") false } else { true } } copy(updated, filteredArgs) } else { this } def +(that: Query): Query = Query.merge(List(this, that)) def bindVars: Json = Json.obj(args.toList.map { case (key, v) => { val argValue: Json = v.json key -> argValue } }: _*) override def toString: String = s"[$value] (${args.map(t => s"${t._1}: ${t._2}").mkString(", ")})" } object Query { private val ExtractNumeric = """(.+)(\d+)""".r def merge(queries: List[Query], separator: String = "\n"): Query = { var usedKeys = Set.empty[String] val updatedQueries: List[Query] = queries.map { q => var query = q val localKeys = query.args.keys.toSet def nextKey(key: String): String = key match { case ExtractNumeric(prefix, n) => { val newKey = s"$prefix${n.toInt + 1}" if (!usedKeys.contains(newKey) && !localKeys.contains(newKey)) { newKey } else { nextKey(newKey) } } case _ => nextKey(s"${key}1") } query.args.keys.foreach { case key if usedKeys.contains(key) => { val newKey = nextKey(key) usedKeys += newKey query = query.copy( value = query.value.replaceAllLiterally(s"@$key", s"@$newKey"), args = query.args.map { case (k, v) if k == key => newKey -> v case (k, v) => k -> v } ) } case key => usedKeys += key } query } val value = updatedQueries.map(_.value).mkString(separator) val args = updatedQueries.flatMap(_.args).toMap Query(value, args) } }
Example 74
package com.outr.arango import io.circe.Decoder.Result import io.circe.{Decoder, Encoder, HCursor, Json} import com.outr.arango.JsonImplicits._ lazy val _id: String = s"$collection/$value" override def compare(that: Id[D]): Int = this._id.compare(that._id) override def toString: String = _id } object Id { private val ExtractorRegex = """(.+)/(.+)""".r implicit def encoder[D]: Encoder[Id[D]] = new Encoder[Id[D]] { override def apply(id: Id[D]): Json = Json.fromString(id._id) } implicit def decoder[D]: Decoder[Id[D]] = new Decoder[Id[D]] { override def apply(c: HCursor): Result[Id[D]] = c.value.asString.get match { case ExtractorRegex(collection, value) => Right(Id[D](value, collection)) } } def parse[D](id: String): Id[D] = id match { case ExtractorRegex(collection, value) => Id[D](value, collection) } def extract[D](json: Json): Id[D] = { val updated = update(json) decoder[D].decodeJson((updated \ "_id").get) match { case Left(df) => throw df case Right(id) => id } } def update(json: Json): Json = { val _key = (json \ "_key").flatMap(_.asString) val _id = (json \ "_id").flatMap(_.asString) val _identity = _id.map(parse[Any]) if (_id.nonEmpty && _key.isEmpty) { json.deepMerge(Json.obj("_key" -> Json.fromString(_identity.get.value))) } else { json } } }
Example 75
Source File: GoldenCodecLaws.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden import cats.instances.list._, cats.instances.try_._ import cats.syntax.traverse._ import cats.laws._ import io.circe.{ Json, Printer } import io.circe.testing.CodecLaws import scala.util.{ Failure, Success, Try } trait GoldenCodecLaws[A] extends CodecLaws[A] { protected def goldenExamples: Try[List[(A, String)]] final def goldenDecoding: Try[List[IsEq[A]]] = goldenExamples.flatMap { _.traverse { case (value, encoded) => io.circe.parser.decode[A](encoded)(decode) match { case Left(error) => Failure(error) case Right(decoded) => Success(decoded <-> value) } } } final def goldenEncoding: Try[List[IsEq[String]]] = goldenExamples.map { _.map { case (value, encoded) => printJson(encode(value)) <-> encoded } } }
Example 76
Source File: GoldenCodecTests.scala From circe-golden with Apache License 2.0 | 5 votes |
package io.circe.testing.golden import cats.instances.string._ import cats.kernel.Eq import cats.laws.IsEq import cats.laws.discipline.catsLawsIsEqToProp import io.circe.{ Decoder, Encoder, Json, Printer } import io.circe.testing.CodecTests import org.scalacheck.{ Arbitrary, Prop, Shrink } import scala.reflect.runtime.universe.TypeTag import scala.util.{ Failure, Success, Try } trait GoldenCodecTests[A] extends CodecTests[A] { def laws: GoldenCodecLaws[A] private[this] def tryListToProp[A: Eq](result: Try[List[IsEq[A]]]): Prop = result match { case Failure(error) => Prop.exception(error) case Success(equalities) => Prop.all(equalities.map(catsLawsIsEqToProp(_)): _*) } def goldenCodec( implicit arbitraryA: Arbitrary[A], shrinkA: Shrink[A], eqA: Eq[A], arbitraryJson: Arbitrary[Json], shrinkJson: Shrink[Json] ): RuleSet = new DefaultRuleSet( name = "goldenCodec", parent = Some(codec), "decoding golden files" -> tryListToProp(laws.goldenDecoding), "encoding golden files" -> tryListToProp(laws.goldenEncoding) ) def unserializableGoldenCodec( implicit arbitraryA: Arbitrary[A], shrinkA: Shrink[A], eqA: Eq[A], arbitraryJson: Arbitrary[Json], shrinkJson: Shrink[Json] ): RuleSet = new DefaultRuleSet( name = "goldenCodec", parent = Some(unserializableCodec), "decoding golden files" -> tryListToProp(laws.goldenDecoding), "encoding golden files" -> tryListToProp(laws.goldenEncoding) ) } object GoldenCodecTests { def apply[A: Decoder: Encoder: Arbitrary: TypeTag]: GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A]()) def apply[A: Decoder: Encoder: Arbitrary: TypeTag](printer: Printer): GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A](printer = printer)) def apply[A: Decoder: Encoder: Arbitrary: TypeTag](count: Int): GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A](count = count)) def apply[A: Decoder: Encoder: Arbitrary: TypeTag](count: Int, printer: Printer): GoldenCodecTests[A] = apply[A](ResourceFileGoldenCodecLaws[A](count = count, printer = printer)) def apply[A: Decoder: Encoder: Arbitrary](laws0: GoldenCodecLaws[A]): GoldenCodecTests[A] = new GoldenCodecTests[A] { val laws: GoldenCodecLaws[A] = laws0 } }
Example 77
Source File: OAuthFailedSpec.scala From kanadi with MIT License | 5 votes |
package org.zalando.kanadi import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.stream.ActorMaterializer import com.typesafe.config.ConfigFactory import io.circe.Json import org.mdedetrich.webmodels.{FlowId, OAuth2Token, OAuth2TokenProvider} import org.specs2.Specification import org.specs2.concurrent.ExecutionEnv import org.specs2.execute.Skipped import org.specs2.matcher.FutureMatchers import org.specs2.specification.core.SpecStructure import org.zalando.kanadi.api.{Events, Subscriptions} import org.zalando.kanadi.models._ import scala.concurrent.Future import scala.concurrent.duration._ class OAuthFailedSpec(implicit ec: ExecutionEnv) extends Specification with FutureMatchers with Config { val config = ConfigFactory.load() implicit val system = ActorSystem() implicit val http = Http() implicit val materializer = ActorMaterializer() val failingOauth2TokenProvider = Some( OAuth2TokenProvider(() => Future.successful(OAuth2Token("Failing token"))) ) val subscriptionsClient = Subscriptions(nakadiUri, failingOauth2TokenProvider) val eventsClient = Events(nakadiUri, failingOauth2TokenProvider) override def is: SpecStructure = s2""" Call to subscriptions list should fail with invalid token $oAuthCallSubscriptions Call to publishEvents should fail with invalid token $oAuthPublishEvents """ def oAuthCallSubscriptions = Skipped("No way for current Nakadi docker image to detect \"wrong\" tokens") def oAuthPublishEvents = Skipped("No way for current Nakadi docker image to detect \"wrong\" tokens") }
Example 78
Source File: ParserTests.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import io.circe.Json import org.scalatest.EitherValues import org.scalatest.flatspec.AnyFlatSpec import io.circe.syntax._ import org.scalatest.matchers.should.Matchers class ParserTests extends AnyFlatSpec with Matchers with EitherValues { // the laws should do a pretty good job of surfacing errors; these are mainly to ensure test coverage "Parser" should "fail on invalid tagged numbers" in { assert(parser.parse("!!int 12foo").isLeft) } it should "fail to parse complex keys" in { assert(parser.parse(""" |? - foo | - bar |: 1 """.stripMargin).isLeft) } it should "fail to parse invalid YAML" in { assert( parser .parse( """foo: - bar""" ) .isLeft ) } it should "parse yes as true" in { assert( parser .parse( """foo: yes""" ) .isRight ) } it should "parse hexadecimal" in { assert( parser .parse( """[0xFF, 0xff, 0xab_cd]""" ) .contains(Seq(0xFF, 0xff, 0xabcd).asJson) ) } it should "parse decimal with underscore breaks" in { assert( parser .parse( """foo: 1_000_000""" ) .contains(Map("foo" -> 1000000).asJson) ) } it should "parse empty string as false" in { assert( parser .parse( "" ) .right .value == Json.False ) } it should "parse blank string as false" in { assert( parser .parse( " " ) .right .value == Json.False ) } }
Example 79
Source File: SyntaxTests.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import io.circe.Json import org.scalatest.flatspec.AnyFlatSpec import syntax._ import org.scalatest.matchers.should.Matchers class SyntaxTests extends AnyFlatSpec with Matchers { val json = Json.obj( "foo" -> Json.obj( "bar" -> Json.fromString("baz") ) ) "spaces2" should "have double space indent" in { json.asYaml.spaces2 shouldEqual """foo: | bar: baz |""".stripMargin } "spaces4" should "have quadruple space indent" in { json.asYaml.spaces4 shouldEqual """foo: | bar: baz |""".stripMargin } }
Example 80
Source File: SymmetricSerializationLaws.scala From circe-yaml with Apache License 2.0 | 5 votes |
package io.circe.yaml import cats.Eq import cats.instances.either._ import cats.laws._ import cats.laws.discipline._ import io.circe.{ Decoder, Encoder, Json, ParsingFailure } import org.scalacheck.{ Arbitrary, Prop, Shrink } import org.typelevel.discipline.Laws trait SymmetricSerializationLaws { def printerRoundTrip[A: Eq: Encoder: Decoder]( parse: String => Either[ParsingFailure, Json], print: Json => String, a: A ): IsEq[Either[io.circe.Error, A]] = parse(print(Encoder[A].apply(a))).right.flatMap(_.as[A]) <-> Right(a) } object SymmetricSerializationLaws { def apply(): SymmetricSerializationLaws = new SymmetricSerializationLaws {} } trait SymmetricSerializationTests extends Laws { def laws: SymmetricSerializationLaws def symmetricPrinter[A: Eq: Arbitrary: Shrink: Encoder: Decoder]( print: Json => String, parse: String => Either[ParsingFailure, Json] ): RuleSet = new DefaultRuleSet( name = "printer", parent = None, "roundTrip" -> Prop.forAll { (a: A) => laws.printerRoundTrip(parse, print, a) } ) } object SymmetricSerializationTests { def apply[A: Eq: Arbitrary: Decoder: Encoder]( print: Json => String, parse: String => Either[ParsingFailure, Json] ): SymmetricSerializationTests = new SymmetricSerializationTests { val laws: SymmetricSerializationLaws = SymmetricSerializationLaws() symmetricPrinter[A](print, parse) } }
Example 81
Source File: CirceJSONSerializer.scala From scala-json-rpc with MIT License | 5 votes |
package io.github.shogowada.scala.jsonrpc.serializers import io.circe.{Decoder, Encoder, Error, Json} import scala.language.experimental.macros import scala.reflect.macros.blackbox object CirceJSONCoder { def encode[T](value: T)(implicit encoder: Encoder[T]): Json = { encoder(value) } def decode[T](json: String)(implicit decoder: Decoder[T]): Either[Error, T] = { io.circe.parser.decode[T](json) } } class CirceJSONSerializer extends JSONSerializer { override def serialize[T](value: T): Option[String] = macro CirceJSONSerializerMacro.serialize[T] override def deserialize[T](json: String): Option[T] = macro CirceJSONSerializerMacro.deserialize[T] } object CirceJSONSerializer { def apply(): CirceJSONSerializer = { new CirceJSONSerializer } } object CirceJSONSerializerMacro { def serialize[T](c: blackbox.Context)(value: c.Expr[T]): c.Expr[Option[String]] = { import c.universe._ c.Expr[Option[String]]( q""" { import io.circe.generic.auto._ scala.util.Try(io.circe.Printer.noSpaces.pretty(io.github.shogowada.scala.jsonrpc.serializers.CirceJSONCoder.encode($value))).toOption } """ ) } def deserialize[T: c.WeakTypeTag](c: blackbox.Context)(json: c.Expr[String]): c.Expr[Option[T]] = { import c.universe._ val deserializeType = weakTypeOf[T] c.Expr[Option[T]]( q""" { import io.circe.generic.auto._ io.github.shogowada.scala.jsonrpc.serializers.CirceJSONCoder.decode[$deserializeType]($json).toOption } """ ) } }
Example 82
Source File: CdxBasedRecord.scala From ArchiveSpark with MIT License | 5 votes |
package org.archive.archivespark.specific.warc import io.circe.Json import org.archive.archivespark.model.TypedEnrichRoot import org.archive.archivespark.sparkling.cdx.CdxRecord import org.archive.archivespark.util.Json._ import scala.collection.immutable.ListMap trait CdxBasedRecord extends TypedEnrichRoot[CdxRecord] { override def metaToJson: Json = { val cdx = get json(ListMap[String, Any]( "surtUrl" -> cdx.surtUrl, "timestamp" -> cdx.timestamp, "originalUrl" -> cdx.originalUrl, "mime" -> cdx.mime, "status" -> cdx.status, "digest" -> cdx.digest, "redirectUrl" -> cdx.redirectUrl, "meta" -> cdx.meta, "compressedSize" -> cdx.compressedSize )) } } object CdxBasedRecord { implicit def cdxBasedRecordToCdxRecord(record: CdxBasedRecord): CdxRecord = record.get }
Example 83
Source File: CirceSupportSpec.scala From sangria-circe with Apache License 2.0 | 5 votes |
package sangria.marshalling import sangria.marshalling.circe._ import sangria.marshalling.testkit._ import io.circe.Json import io.circe.generic.auto._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class CirceSupportSpec extends AnyWordSpec with Matchers with MarshallingBehaviour with InputHandlingBehaviour { "Circe integration" should { behave like `value (un)marshaller` (CirceResultMarshaller) behave like `AST-based input unmarshaller` (circeFromInput) behave like `AST-based input marshaller` (CirceResultMarshaller) behave like `case class input unmarshaller` behave like `case class input marshaller` (CirceResultMarshaller) } val toRender = Json.obj( "a" → Json.arr(Json.Null, Json.fromInt(123), Json.arr(Json.obj("foo" → Json.fromString("bar")))), "b" → Json.obj( "c" → Json.fromBoolean(true), "d" → Json.Null)) "InputUnmarshaller" should { "throw an exception on invalid scalar values" in { an [IllegalStateException] should be thrownBy CirceInputUnmarshaller.getScalarValue(Json.obj()) } "throw an exception on variable names" in { an [IllegalArgumentException] should be thrownBy CirceInputUnmarshaller.getVariableName(Json.fromString("$foo")) } "render JSON values" in { val rendered = CirceInputUnmarshaller.render(toRender) rendered should be ("""{"a":[null,123,[{"foo":"bar"}]],"b":{"c":true,"d":null}}""") } } "ResultMarshaller" should { "render pretty JSON values" in { val rendered = CirceResultMarshaller.renderPretty(toRender) rendered.replaceAll("\r", "") should be ( """{ | "a" : [ | null, | 123, | [ | { | "foo" : "bar" | } | ] | ], | "b" : { | "c" : true, | "d" : null | } |}""".stripMargin.replaceAll("\r", "")) } "render compact JSON values" in { val rendered = CirceResultMarshaller.renderCompact(toRender) rendered should be ("""{"a":[null,123,[{"foo":"bar"}]],"b":{"c":true,"d":null}}""") } } }
Example 84
Source File: Server.scala From zio-metrics with Apache License 2.0 | 5 votes |
package zio.metrics.dropwizard import scala.util.Properties.envOrNone import cats.data.Kleisli import org.http4s.server.blaze._ import org.http4s.{ Request, Response } import zio.{ RIO, ZIO } import zio.system.System import zio.clock.Clock import zio.console.Console import zio.random.Random import zio.blocking.Blocking import zio.interop.catz._ import io.circe.Json import org.http4s.circe._ import org.http4s.dsl.impl.Root import org.http4s.dsl.io._ import org.http4s.{ HttpRoutes, Response } import zio.RIO import zio.interop.catz._ import zio.metrics.dropwizard.typeclasses._ import zio.metrics.dropwizard.DropwizardExtractor._ import cats.instances.list._ import com.codahale.metrics.MetricRegistry object Server { val port: Int = envOrNone("HTTP_PORT").fold(9090)(_.toInt) type HttpEnvironment = Clock with Console with System with Random with Blocking type HttpTask[A] = RIO[HttpEnvironment, A] type KleisliApp = Kleisli[HttpTask, Request[HttpTask], Response[HttpTask]] //type HttpApp[R <: Registry] = R => KleisliApp def builder[Ctx]: KleisliApp => HttpTask[Unit] = (app: KleisliApp) => ZIO .runtime[HttpEnvironment] .flatMap { implicit rts => BlazeServerBuilder[HttpTask] .bindHttp(port) .withHttpApp(app) .serve .compile .drain } def serveMetrics: MetricRegistry => HttpRoutes[Server.HttpTask] = registry => HttpRoutes.of[Server.HttpTask] { case GET -> Root / filter => { println(s"filter: $filter") val optFilter = if (filter == "ALL") None else Some(filter) RegistryPrinter .report[List, Json](registry, optFilter)( (k: String, v: Json) => Json.obj((k, v)) ) .map(m => Response[Server.HttpTask](Ok).withEntity(m)) } } }
Example 85
Source File: DockerComposeFileOps.scala From sbt-docker-compose with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.github.ehsanyou.sbt.docker.compose.io import java.io.FileNotFoundException import java.util.UUID import cats.syntax.either._ import com.github.ehsanyou.sbt.docker.compose.io.DataTypes.ServiceName import com.github.ehsanyou.sbt.docker.compose.io.DataTypes.ServiceWithTag import io.circe.Json import sbt.File import sbt._ trait IDockerComposeFileOps { def store: File def getServices: Seq[ServiceName] def getServicesWithTag: Seq[ServiceWithTag] def withImageTags(tags: Seq[(String, String)]): IDockerComposeFileOps } case class DockerComposeFileOps( jsonAST: Json, cwd: File ) extends IDockerComposeFileOps { def asPrettyYaml: String = Printer.spaces2.pretty(jsonAST) override def getServices: Seq[ServiceName] = jsonAST.hcursor .downField("services") .fields .map(_.map(ServiceName).toSeq) .getOrElse(Seq.empty) override def getServicesWithTag: Seq[ServiceWithTag] = getServices flatMap { service => jsonAST.hcursor .downField("services") .downField(service.name) .get[String]("image") .toOption .map { image => val split = image.split(":").toSeq ServiceWithTag(service.name, split.drop(1).lastOption) } } def withImageTags(tags: Seq[(String, String)]): DockerComposeFileOps = tags.foldLeft(this) { case (acc, (serviceName, tag)) => acc.replaceServiceTag(serviceName, tag) match { case Some(json) => acc.copy(json) case None => acc } } private def replaceServiceTag(serviceName: String, tag: String): Option[Json] = jsonAST.hcursor .downField("services") .downField(serviceName) .downField("image") .withFocus(_.mapString { image => val split = image.split(":").toSeq s"${split.head}:$tag" }) .top override def store: File = { val f: File = cwd / s"docker-compose-modified-${UUID.randomUUID()}.yml" sbt.IO.write(f, asPrettyYaml) f } } object DockerComposeFileOps { def apply(path: String, workingDir: File): DockerComposeFileOps = DcFileReader(path) match { case Right(json) => DockerComposeFileOps(json, workingDir) case Left(err) => throw new FileNotFoundException(err.msg) } }
Example 86
Source File: LawsSpec.scala From seals with Apache License 2.0 | 5 votes |
package dev.tauri.seals package circe import cats.Eq import cats.implicits._ import io.circe.Json import io.circe.numbers.BiggerDecimal import io.circe.testing.instances.{ arbitraryJson, cogenJson } import org.scalacheck.{ Arbitrary, Gen } import cats.kernel.laws.discipline.OrderTests class LawsSpec extends tests.BaseLawsSpec { import Atoms._ implicit val eqBiggerDecimal: Eq[BiggerDecimal] = Eq.fromUniversalEquals implicit def arbBiggerDecimal( implicit arbBd: Arbitrary[BigDecimal], arbBi: Arbitrary[BigInt], arbDbl: Arbitrary[Double] ): Arbitrary[BiggerDecimal] = Arbitrary { Gen.oneOf( // fits into a BigDecimal: arbBd.arbitrary.map { x => BiggerDecimal.fromBigDecimal(x.underlying) }, // doesn't fit into a BigDecimal: arbBi.arbitrary.map { n => val str = s"${n}e${n max Int.MaxValue.toLong + 1L}" BiggerDecimal.parseBiggerDecimal(str).getOrElse { core.impossible(s"cannot parse BiggerDecimal from '${str}'") } }, // can contain negative zero: arbDbl.arbitrary.map(d => BiggerDecimal.fromDoubleUnsafe(- d)) ) } checkAtomicLaws[BiggerDecimal]("BiggerDecimal") checkAll("Codecs.orderForJson.Order", OrderTests[Json](Codecs.orderForJson).order) }
Example 87
Source File: HadoopPointCloudRDD.scala From geotrellis-pointcloud with Apache License 2.0 | 5 votes |
package geotrellis.pointcloud.spark.store.hadoop import geotrellis.pointcloud.spark.store.hadoop.formats._ import geotrellis.store.hadoop._ import geotrellis.vector.Extent import io.circe.Json import io.pdal._ import io.pdal.pipeline._ import org.apache.hadoop.fs.Path import org.apache.spark.SparkContext import org.apache.spark.rdd.RDD def apply(path: Path, options: Options = Options.DEFAULT)(implicit sc: SparkContext): RDD[(HadoopPointCloudHeader, List[PointCloud])] = { val conf = sc.hadoopConfiguration.withInputDirectory(path, options.filesExtensions) options.tmpDir.foreach(PointCloudInputFormat.setTmpDir(conf, _)) options.dimTypes.foreach(PointCloudInputFormat.setDimTypes(conf, _)) PointCloudInputFormat.setPipeline(conf, options.pipeline) options.filterExtent match { case Some(filterExtent) => PointCloudInputFormat.setFilterExtent(conf, filterExtent) sc.newAPIHadoopRDD( conf, classOf[PointCloudInputFormat], classOf[HadoopPointCloudHeader], classOf[List[PointCloud]] ).filter { case (header, _) => header.extent3D.map(_.toExtent.intersects(filterExtent)).getOrElse(false) } case None => sc.newAPIHadoopRDD( conf, classOf[PointCloudInputFormat], classOf[HadoopPointCloudHeader], classOf[List[PointCloud]] ) } } }
Example 88
Source File: S3PointCloudInputFormat.scala From geotrellis-pointcloud with Apache License 2.0 | 5 votes |
package geotrellis.pointcloud.spark.store.s3 import geotrellis.spark.store.s3._ import geotrellis.pointcloud.spark.store.hadoop.formats._ import geotrellis.pointcloud.util.Filesystem import io.pdal._ import io.circe.Json import io.circe.syntax._ import cats.syntax.either._ import org.apache.hadoop.mapreduce.{InputSplit, TaskAttemptContext} import org.apache.commons.io.FileUtils import java.io.{File, InputStream} import java.net.URI import scala.collection.JavaConverters._ mode match { case "s3" => new S3URIRecordReader[S3PointCloudHeader, List[PointCloud]](s3Client) { def read(key: String, uri: URI): (S3PointCloudHeader, List[PointCloud]) = { val s3Pipeline = pipeline .hcursor .downField("pipeline").downArray .downField("filename").withFocus(_ => uri.toString.asJson) .top.fold(pipeline)(identity) executePipeline(context)(key, s3Pipeline) } } case _ => val tmpDir = { val dir = PointCloudInputFormat.getTmpDir(context) if (dir == null) Filesystem.createDirectory() else Filesystem.createDirectory(dir) } new S3StreamRecordReader[S3PointCloudHeader, List[PointCloud]](s3Client) { def read(key: String, is: InputStream): (S3PointCloudHeader, List[PointCloud]) = { // copy remote file into local tmp dir tmpDir.mkdirs() // to be sure that dirs created val localPath = new File(tmpDir, key.replace("/", "_")) FileUtils.copyInputStreamToFile(is, localPath) is.close() // use local filename path if it's present in json val localPipeline = pipeline .hcursor .downField("pipeline").downArray .downField("filename").withFocus(_ => localPath.getAbsolutePath.asJson) .top.fold(pipeline)(identity) try executePipeline(context)(key, localPipeline) finally { localPath.delete() tmpDir.delete() } } } } } }
Example 89
Source File: EncryBaseApiRoute.scala From EncryCore with GNU General Public License v3.0 | 5 votes |
package encry.api.http.routes import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes} import akka.http.scaladsl.server.{Directive, Directive1, Route} import encry.api.http.ApiRoute import io.circe.Json import org.encryfoundation.common.crypto.encoding.Base58Check import org.encryfoundation.common.modifiers.mempool.transaction.EncryAddress.Address import org.encryfoundation.common.utils.Algos import org.encryfoundation.common.utils.TaggedTypes.{ADKey, ModifierId} import scala.concurrent.{ExecutionContextExecutor, Future} import scala.util.Success trait EncryBaseApiRoute extends ApiRoute { implicit val ec: ExecutionContextExecutor = context.dispatcher protected def toJsonResponse(js: Json): Route = { val resp = complete(HttpEntity(ContentTypes.`application/json`, js.spaces2)) withCors(resp) } protected def toJsonResponse(fn: Future[Json]): Route = onSuccess(fn) { toJsonResponse } protected def toJsonOptionalResponse(fn: Future[Option[Json]]): Route = { onSuccess(fn) { case Some(v) => toJsonResponse(v) case None => withCors(complete(StatusCodes.NotFound)) } } val paging: Directive[(Int, Int)] = parameters("offset".as[Int] ? 0, "limit".as[Int] ? 50) val modifierId: Directive1[ModifierId] = pathPrefix(Segment).flatMap { h => Algos.decode(h) match { case Success(header) => provide(ModifierId @@ header) case _ => reject } } implicit class OkJsonResp(fn: Future[Json]) { def okJson(): Route = toJsonResponse(fn) } implicit class OkJsonOptResp(fn: Future[Option[Json]]) { def okJson(): Route = toJsonOptionalResponse(fn) } }
Example 90
Source File: InfoApiRoute.scala From EncryCore with GNU General Public License v3.0 | 5 votes |
package encry.api.http.routes import java.net.InetSocketAddress import akka.actor.{ ActorRef, ActorRefFactory } import akka.http.scaladsl.server.Route import akka.pattern.ask import encry.api.http.DataHolderForApi._ import encry.local.miner.Miner.MinerStatus import encry.settings._ import encry.utils.NetworkTimeProvider import io.circe.Json import io.circe.syntax._ import io.circe.generic.auto._ import org.encryfoundation.common.modifiers.history.{ Block, Header } import org.encryfoundation.common.utils.Algos import org.encryfoundation.common.utils.constants.Constants case class InfoApiRoute(dataHolder: ActorRef, settings: RESTApiSettings, nodeId: Array[Byte], timeProvider: NetworkTimeProvider)(implicit val context: ActorRefFactory) extends EncryBaseApiRoute { override val route: Route = (path("info") & get) { (dataHolder ? GetAllInfoHelper) .mapTo[Json] .okJson() } } object InfoApiRoute { def makeInfoJson(nodeId: Array[Byte], minerInfo: MinerStatus, connectedPeersLength: Int, readers: Readers, stateType: String, nodeName: String, knownPeers: Seq[InetSocketAddress], storage: String, nodeUptime: Long, mempoolSize: Int, connectWithOnlyKnownPeer: Boolean, header: Option[Header], block: Option[Block], constants: Constants ): Json = { val stateVersion: Option[String] = readers.s.map(_.version).map(Algos.encode) val stateRoot: Option[String] = readers.s.map(_.tree.rootHash).map(Algos.encode) val prevFullHeaderId: String = block.map(b => Algos.encode(b.header.parentId)).getOrElse("") InfoApi( nodeName, stateType, block.map(_.header.difficulty.toString).getOrElse(constants.InitialDifficulty.toString), block.map(_.encodedId).getOrElse(""), header.map(_.encodedId).getOrElse(""), connectedPeersLength, mempoolSize, prevFullHeaderId, block.map(_.header.height).getOrElse(0), header.map(_.height).getOrElse(0), stateVersion.getOrElse(""), nodeUptime, storage, connectWithOnlyKnownPeer, minerInfo.isMining, knownPeers.map { x => x.getHostName + ":" + x.getPort }, stateRoot.getOrElse("") ).asJson } }
Example 91
Source File: MultiNodeConsulConstructrSpec.scala From constructr-consul with Apache License 2.0 | 5 votes |
package com.tecsisa.constructr.akka.consul import akka.actor.{ Address, AddressFromURIString } import io.circe.Json import io.circe.parser.parse import java.util.Base64._ class MultiNodeConsulConstructrSpecMultiJvmNode1 extends MultiNodeConsulConstructrSpec class MultiNodeConsulConstructrSpecMultiJvmNode2 extends MultiNodeConsulConstructrSpec class MultiNodeConsulConstructrSpecMultiJvmNode3 extends MultiNodeConsulConstructrSpec class MultiNodeConsulConstructrSpecMultiJvmNode4 extends MultiNodeConsulConstructrSpec class MultiNodeConsulConstructrSpecMultiJvmNode5 extends MultiNodeConsulConstructrSpec object MultiNodeConsulConstructrSpec { def toNodes(s: String): Set[Address] = { def jsonToNode(json: Json) = { val a = json.hcursor .get[String]("Key") .fold(throw _, identity) .stripPrefix("constructr/MultiNodeConstructrSpec/nodes/") AddressFromURIString(new String(getUrlDecoder.decode(a), "UTF-8")) } import cats.syntax.either._ // for Scala 2.11 parse(s) .fold(throw _, identity) .as[Set[Json]] .getOrElse(Set.empty) .map(jsonToNode) } } abstract class MultiNodeConsulConstructrSpec extends MultiNodeConstructrSpec( 8501, "/v1/kv/constructr/MultiNodeConstructrSpec?recurse", "/v1/kv/constructr/MultiNodeConstructrSpec/nodes?recurse", MultiNodeConsulConstructrSpec.toNodes )
Example 92
Source File: StructFormat.scala From scalapb-circe with MIT License | 5 votes |
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 93
Source File: AnyFormat.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.any.{Any => PBAny} import io.circe.Json import scalapb_json._ object AnyFormat { val anyWriter: (Printer, PBAny) => Json = { case (printer, any) => // Find the companion so it can be used to JSON-serialize the message. Perhaps this can be circumvented by // including the original GeneratedMessage with the Any (at least in memory). val cmp = printer.typeRegistry .findType(any.typeUrl) .getOrElse( throw new IllegalStateException( s"Unknown type ${any.typeUrl}; you may have to register it via FormatRegistry.registerCompanion" ) ) // Unpack the message... val message = any.unpack(cmp) // ... and add the @type marker to the resulting JSON printer.toJson(message).asObject match { case Some(fields) => Json.obj(("@type" -> Json.fromString(any.typeUrl)) :: fields.toList: _*) case value => // Safety net, this shouldn't happen throw new IllegalStateException(s"Message of type ${any.typeUrl} emitted non-object JSON: $value") } } val anyParser: (Parser, Json) => PBAny = { case (parser, json) => json.asObject match { case Some(obj) => obj.toMap.get("@type").flatMap(_.asString) match { case Some(typeUrl) => val cmp = parser.typeRegistry .findType(typeUrl) .getOrElse(throw new JsonFormatException(s"""Unknown type: "$typeUrl"""")) val message = parser.fromJson(json)(cmp) PBAny(typeUrl = typeUrl, value = message.toByteString) case unknown => throw new JsonFormatException(s"Expected string @type field, got $unknown") } case _ => throw new JsonFormatException(s"Expected an object, got $json") } } }
Example 94
Source File: PrimitiveWrappersSpec.scala From scalapb-circe with MIT License | 5 votes |
package scalapb_circe import com.google.protobuf.ByteString import jsontest.test3._ import io.circe.{Encoder, Json} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class PrimitiveWrappersSpec extends AnyFlatSpec with Matchers { private[this] def render[A](a: A)(implicit A: Encoder[A]): Json = A.apply(a) "Empty object" should "give empty json for Wrapper" in { JsonFormat.toJson(Wrapper()) must be(render(Map.empty[String, Json])) } "primitive values" should "serialize properly" in { JsonFormat.toJson(Wrapper(wBool = Some(false))) must be(render(Map("wBool" -> Json.fromBoolean(false)))) JsonFormat.toJson(Wrapper(wBool = Some(true))) must be(render(Map("wBool" -> Json.fromBoolean(true)))) JsonFormat.toJson(Wrapper(wDouble = Some(3.1))) must be(render(Map("wDouble" -> Json.fromDouble(3.1)))) JsonFormat.toJson(Wrapper(wFloat = Some(3.0f))) must be(render(Map("wFloat" -> Json.fromDouble(3.0)))) JsonFormat.toJson(Wrapper(wInt32 = Some(35544))) must be(render(Map("wInt32" -> Json.fromLong(35544)))) JsonFormat.toJson(Wrapper(wInt32 = Some(0))) must be(render(Map("wInt32" -> Json.fromLong(0)))) JsonFormat.toJson(Wrapper(wInt64 = Some(125))) must be(render(Map("wInt64" -> Json.fromString("125")))) JsonFormat.toJson(Wrapper(wUint32 = Some(125))) must be(render(Map("wUint32" -> Json.fromLong(125)))) JsonFormat.toJson(Wrapper(wUint64 = Some(125))) must be(render(Map("wUint64" -> Json.fromString("125")))) JsonFormat.toJson(Wrapper(wString = Some("bar"))) must be(render(Map("wString" -> Json.fromString("bar")))) JsonFormat.toJson(Wrapper(wString = Some(""))) must be(render(Map("wString" -> Json.fromString("")))) JsonFormat.toJson(Wrapper(wBytes = Some(ByteString.copyFrom(Array[Byte](3, 5, 4))))) must be( render(Map("wBytes" -> Json.fromString("AwUE"))) ) JsonFormat.toJson(Wrapper(wBytes = Some(ByteString.EMPTY))) must be(render(Map("wBytes" -> Json.fromString("")))) new Printer(formattingLongAsNumber = true).toJson(Wrapper(wUint64 = Some(125))) must be( render(Map("wUint64" -> Json.fromLong(125))) ) new Printer(formattingLongAsNumber = true).toJson(Wrapper(wInt64 = Some(125))) must be( render(Map("wInt64" -> Json.fromLong(125))) ) } "primitive values" should "parse properly" in { JsonFormat.fromJson[Wrapper](render(Map("wBool" -> Json.fromBoolean(false)))) must be(Wrapper(wBool = Some(false))) JsonFormat.fromJson[Wrapper](render(Map("wBool" -> Json.fromBoolean(true)))) must be(Wrapper(wBool = Some(true))) JsonFormat.fromJson[Wrapper](render(Map("wDouble" -> Json.fromDouble(3.1)))) must be(Wrapper(wDouble = Some(3.1))) JsonFormat.fromJson[Wrapper](render(Map("wFloat" -> Json.fromDouble(3.0)))) must be(Wrapper(wFloat = Some(3.0f))) JsonFormat.fromJson[Wrapper](render(Map("wInt32" -> Json.fromLong(35544)))) must be(Wrapper(wInt32 = Some(35544))) JsonFormat.fromJson[Wrapper](render(Map("wInt32" -> Json.fromLong(0)))) must be(Wrapper(wInt32 = Some(0))) JsonFormat.fromJson[Wrapper](render(Map("wInt64" -> Json.fromString("125")))) must be(Wrapper(wInt64 = Some(125))) JsonFormat.fromJson[Wrapper](render(Map("wUint32" -> Json.fromLong(125)))) must be(Wrapper(wUint32 = Some(125))) JsonFormat.fromJson[Wrapper](render(Map("wUint64" -> Json.fromString("125")))) must be(Wrapper(wUint64 = Some(125))) JsonFormat.fromJson[Wrapper](render(Map("wString" -> Json.fromString("bar")))) must be( Wrapper(wString = Some("bar")) ) JsonFormat.fromJson[Wrapper](render(Map("wString" -> Json.fromString("")))) must be(Wrapper(wString = Some(""))) JsonFormat.fromJson[Wrapper](render(Map("wBytes" -> Json.fromString("AwUE")))) must be( Wrapper(wBytes = Some(ByteString.copyFrom(Array[Byte](3, 5, 4)))) ) JsonFormat.fromJson[Wrapper](render(Map("wBytes" -> Json.fromString("")))) must be( Wrapper(wBytes = Some(ByteString.EMPTY)) ) } }
Example 95
Source File: package.scala From tsec with MIT License | 5 votes |
package tsec import cats.{Eq, MonadError} import cats.instances.string._ import cats.syntax.either._ import io.circe.{Decoder, Encoder, HCursor, Json} import tsec.cipher.common.padding.NoPadding import tsec.cipher.symmetric._ import tsec.cipher.symmetric.jca._ import tsec.common._ import tsec.mac.MAC import tsec.mac.jca.MacVerificationError package object cookies { type AEADCookie[A] = AEADCookie.Cookie[A] implicit object AEADCookie { type Cookie[A] <: String @inline def fromEncrypted[A](a: CipherText[A], aad: AAD): AEADCookie[A] = apply[A](a.toConcatenated.toB64String + "-" + aad.toB64String) @inline def subst[G[_], A](fa: G[String]): G[AEADCookie[A]] = fa.asInstanceOf[G[AEADCookie[A]]] @inline def unsubst[G[_], A](fa: G[AEADCookie[A]]): G[String] = fa.asInstanceOf[G[String]] @inline def apply[A](raw: String): AEADCookie[A] = raw.asInstanceOf[AEADCookie[A]] def getEncryptedContent[F[_], A: AES]( signed: AEADCookie[A] )(implicit encryptor: AADEncryptor[F, A, SecretKey]): Either[CipherTextError, CipherText[A]] = { val split = signed.split("-") if (split.length != 2) Left(CipherTextError("String encoded improperly")) else { split(0).b64Bytes match { case Some(e) => CTOPS.ciphertextFromArray[A, GCM, NoPadding](e) case None => Left(CipherTextError("String encoded improperly")) } } } implicit def circeDecoder[A]: Decoder[AEADCookie[A]] = new Decoder[AEADCookie[A]] { def apply(c: HCursor) = c.as[String].map(AEADCookie.apply[A]) } implicit def circeEncoder[A]: Encoder[AEADCookie[A]] = new Encoder[AEADCookie[A]] { def apply(a: AEADCookie[A]): Json = Json.fromString(a) } } type SignedCookie[A] = SignedCookie.Cookie[A] implicit object SignedCookie { type Cookie[A] <: String @inline def from[A](signed: MAC[A], joined: String): SignedCookie[A] = apply[A](joined + "-" + signed.toB64String) @inline def apply[A](raw: String): SignedCookie[A] = raw.asInstanceOf[SignedCookie[A]] @inline def subst[G[_], A](fa: G[String]): G[SignedCookie[A]] = fa.asInstanceOf[G[SignedCookie[A]]] @inline def unsubst[G[_], A](fa: G[SignedCookie[A]]): G[String] = fa.asInstanceOf[G[String]] def fromDecodedString[F[_]](original: String)(implicit F: MonadError[F, Throwable]): F[String] = original.split("-") match { case Array(orig, nonce) => orig.b64Bytes match { case Some(o) => F.pure(o.toUtf8String) case None => F.raiseError(MacVerificationError("String encoded improperly")) } case _ => F.raiseError(MacVerificationError("String encoded improperly")) } } implicit final def cookieEQ[A]: Eq[SignedCookie[A]] = SignedCookie.subst(Eq[String]) implicit final def ecookieEQ[A]: Eq[AEADCookie[A]] = Eq.by[AEADCookie[A], String](identity[String]) }
Example 96
Source File: JsonUnmarshaller.scala From akka-http-oauth2-client with Apache License 2.0 | 5 votes |
package com.github.dakatsuka.akka.http.oauth2.client.utils import akka.http.scaladsl.model.ContentTypeRange import akka.http.scaladsl.model.MediaTypes.`application/json` import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, Unmarshaller } import akka.util.ByteString import io.circe.{ jawn, Decoder, Json } trait JsonUnmarshaller { def unmarshallerContentTypes: Seq[ContentTypeRange] = List(`application/json`) implicit def jsonUnmarshaller: FromEntityUnmarshaller[Json] = Unmarshaller.byteStringUnmarshaller .forContentTypes(unmarshallerContentTypes: _*) .map { case ByteString.empty => throw Unmarshaller.NoContentException case data => jawn.parseByteBuffer(data.asByteBuffer).fold(throw _, identity) } implicit def unmarshaller[A: Decoder]: FromEntityUnmarshaller[A] = { def decode(json: Json) = implicitly[Decoder[A]].decodeJson(json).fold(throw _, identity) jsonUnmarshaller.map(decode) } }
Example 97
Source File: Schema.scala From circe-json-schema with Apache License 2.0 | 5 votes |
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 98
Source File: TestSuiteTests.scala From circe-json-schema with Apache License 2.0 | 5 votes |
package io.circe.schema import cats.data.Validated import io.circe.{ Decoder, Json } import java.io.File import org.scalatest.flatspec.AnyFlatSpec case class SchemaTestCase(description: String, data: Json, valid: Boolean) case class SchemaTest(description: String, schema: Json, tests: List[SchemaTestCase]) object SchemaTestCase { implicit val decodeSchemaTestCase: Decoder[SchemaTestCase] = io.circe.generic.semiauto.deriveDecoder } object SchemaTest { implicit val decodeSchemaTest: Decoder[SchemaTest] = io.circe.generic.semiauto.deriveDecoder } class TestSuiteTests(path: String) extends AnyFlatSpec { val tests: List[SchemaTest] = io.circe.jawn .decodeFile[List[SchemaTest]](new File(path)) .getOrElse( throw new Exception(s"Unable to load test file: $path") ) tests.foreach { case SchemaTest(description, schema, tests) => tests.foreach { case SchemaTestCase(caseDescription, data, valid) => val expected = if (valid) "validate successfully" else "fail to validate" s"$description: $caseDescription" should expected in { val errors = Schema.load(schema).validate(data) if (valid) { assert(errors == Validated.valid(())) } else { assert(errors.isInvalid) } } it should s"$expected when schema is loaded from a string" in { val errors = Schema.loadFromString(schema.noSpaces).get.validate(data) if (valid) { assert(errors == Validated.valid(())) } else { assert(errors.isInvalid) } } } } } class AdditionalItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/additionalItems.json") class AdditionalPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/additionalProperties.json") class AllOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/allOf.json") class AnyOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/anyOf.json") class BooleanSchemaTestSuiteTests extends TestSuiteTests("tests/tests/draft7/boolean_schema.json") class ConstTestSuiteTests extends TestSuiteTests("tests/tests/draft7/const.json") class ContainsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/contains.json") class DefaultTestSuiteTests extends TestSuiteTests("tests/tests/draft7/default.json") //class DefinitionsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/definitions.json") class EnumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/enum.json") class ExclusiveMaximumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/exclusiveMaximum.json") class ExclusiveMinimumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/exclusiveMinimum.json") class FormatTestSuiteTests extends TestSuiteTests("tests/tests/draft7/format.json") class IfThenElseTestSuiteTests extends TestSuiteTests("tests/tests/draft7/if-then-else.json") class ItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/items.json") class MaximumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maximum.json") class MaxItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maxItems.json") class MaxLengthTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maxLength.json") class MaxPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/maxProperties.json") class MinimumTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minimum.json") class MinItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minItems.json") class MinLengthTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minLength.json") class MinPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/minProperties.json") class MultipleOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/multipleOf.json") class NotTestSuiteTests extends TestSuiteTests("tests/tests/draft7/not.json") class OneOfTestSuiteTests extends TestSuiteTests("tests/tests/draft7/oneOf.json") class PatternTestSuiteTests extends TestSuiteTests("tests/tests/draft7/pattern.json") class PatternPropertiesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/patternProperties.json") class PropertyNamesTestSuiteTests extends TestSuiteTests("tests/tests/draft7/propertyNames.json") // Not currently running remote tests. //class RefTestSuiteTests extends TestSuiteTests("tests/tests/draft7/ref.json") //class RefRemoteTestSuiteTests extends TestSuiteTests("tests/tests/draft7/refRemote.json") class RequiredTestSuiteTests extends TestSuiteTests("tests/tests/draft7/required.json") class TypeTestSuiteTests extends TestSuiteTests("tests/tests/draft7/type.json") class UniqueItemsTestSuiteTests extends TestSuiteTests("tests/tests/draft7/uniqueItems.json")
Example 99
Source File: HttpHelper.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.core.utils import io.circe.parser.parse import io.circe.{Json, ParsingFailure} import scalaj.http.{Http, HttpRequest, HttpResponse} class HttpHelper(apiUrl: Option[String], extraHeaders: Map[String, String]) { private lazy val connectionTimeoutMs = 2000 private lazy val readTimeoutMs = 5000 private val remoteUrl = apiUrl.getOrElse("https://api.codacy.com") + "/2.0" def get(endpoint: String): Either[ParsingFailure, Json] = { val headers: Map[String, String] = Map("Content-Type" -> "application/json") ++ extraHeaders val response: HttpResponse[String] = Http(s"$remoteUrl$endpoint").headers(headers).timeout(connectionTimeoutMs, readTimeoutMs).asString parse(response.body) } def post(endpoint: String, dataOpt: Option[Json] = None): Either[ParsingFailure, Json] = { val headers: Map[String, String] = dataOpt.fold(Map.empty[String, String]) { _ => Map("Content-Type" -> "application/json") } ++ extraHeaders val request: HttpRequest = dataOpt.map { data => Http(s"$remoteUrl$endpoint").postData(data.toString) }.getOrElse(Http(s"$remoteUrl$endpoint")) .method("POST") .headers(headers) .timeout(connectionTimeoutMs, readTimeoutMs) parse(request.asString.body) } }
Example 100
Source File: CodacyConfigurationFile.scala From codacy-analysis-cli with GNU Affero General Public License v3.0 | 5 votes |
package com.codacy.analysis.core.configuration import better.files.File import cats.syntax.show._ import com.codacy.analysis.core.files.Glob import com.codacy.plugins.api.languages.{Language, Languages} import io.circe.generic.auto._ import io.circe.yaml.parser import io.circe.{Decoder, Json, _} import play.api.libs.json.JsValue import scala.util.{Properties, Try} final case class LanguageConfiguration(extensions: Option[Set[String]]) final case class EngineConfiguration(excludePaths: Option[Set[Glob]], baseSubDir: Option[String], extraValues: Option[Map[String, JsValue]]) final case class CodacyConfigurationFile(engines: Option[Map[String, EngineConfiguration]], excludePaths: Option[Set[Glob]], languages: Option[Map[Language, LanguageConfiguration]]) { lazy val languageCustomExtensions: Map[Language, Set[String]] = languages.fold(Map.empty[Language, Set[String]])(_.map { case (lang, config) => (lang, config.extensions.getOrElse(Set.empty[String])) }) } class CodacyConfigurationFileLoader { val filenames: Set[String] = Set(".codacy.yaml", ".codacy.yml") def load(directory: File): Either[String, CodacyConfigurationFile] = { search(directory).flatMap(configDir => parse(configDir.contentAsString)) } def search(root: File): Either[String, File] = { filenames .map(root / _) .find(f => f.exists && f.isRegularFile) .fold[Either[String, File]]( Left(s"Could not find Codacy configuration file. Make sure you have a file named like one of ${filenames .mkString(", ")}."))(Right(_)) } def parse(yamlString: String): Either[String, CodacyConfigurationFile] = { for { json <- parser.parse(yamlString).left.map(_.show) cursor = HCursor.fromJson(json) configurationEither = Decoder[CodacyConfigurationFile].decodeAccumulating(cursor).toEither configuration <- configurationEither.left.map(_.toList.map(_.show).mkString(Properties.lineSeparator)) } yield configuration } } object CodacyConfigurationFile { implicit val globDecoder: Decoder[Glob] = (c: HCursor) => c.as[String].map(Glob) implicit val languageKeyDecoder: KeyDecoder[Language] = (languageStr: String) => Languages.fromName(languageStr) implicit val decodeEngineConfiguration: Decoder[EngineConfiguration] = new Decoder[EngineConfiguration] { val engineConfigurationKeys = Set("enabled", "exclude_paths", "base_sub_dir") def apply(c: HCursor): Decoder.Result[EngineConfiguration] = { val extraKeys = c.keys.fold(List.empty[String])(_.to[List]).filter(key => !engineConfigurationKeys.contains(key)) for { excludePaths <- c.downField("exclude_paths").as[Option[Set[Glob]]] baseSubDir <- c.downField("base_sub_dir").as[Option[String]] } yield { val extraToolConfigurations: Map[String, JsValue] = extraKeys.flatMap { extraKey => c.downField(extraKey) .as[Json] .fold[Option[JsValue]]( { _ => Option.empty }, { json => Try(play.api.libs.json.Json.parse(json.noSpaces)).toOption }) .map(value => (extraKey, value)) }(collection.breakOut) EngineConfiguration(excludePaths, baseSubDir, Option(extraToolConfigurations).filter(_.nonEmpty)) } } } implicit val decodeCodacyConfigurationFile: Decoder[CodacyConfigurationFile] = Decoder.forProduct3("engines", "exclude_paths", "languages")(CodacyConfigurationFile.apply) }
Example 101
Source File: MagnoliaEncoder.scala From circe-magnolia with Apache License 2.0 | 5 votes |
package io.circe.magnolia import io.circe.magnolia.configured.Configuration import io.circe.{Encoder, Json} import magnolia._ private[magnolia] object MagnoliaEncoder { private[magnolia] def combine[T](caseClass: CaseClass[Encoder, T])(implicit config: Configuration): Encoder[T] = { val paramJsonKeyLookup = caseClass.parameters.map { p => val jsonKeyAnnotation = p.annotations.collectFirst { case ann: JsonKey => ann } jsonKeyAnnotation match { case Some(ann) => p.label -> ann.value case None => p.label -> config.transformMemberNames(p.label) } }.toMap if (paramJsonKeyLookup.values.toList.distinct.size != caseClass.parameters.length) { throw new DerivationError( "Duplicate key detected after applying transformation function for case class parameters" ) } new Encoder[T] { def apply(a: T): Json = Json.obj(caseClass.parameters.map { p => val label = paramJsonKeyLookup.getOrElse(p.label, throw new IllegalStateException("Looking up a parameter label should always yield a value. This is a bug")) label -> p.typeclass(p.dereference(a)) }: _*) } } private[magnolia] def dispatch[T]( sealedTrait: SealedTrait[Encoder, T] )(implicit config: Configuration): Encoder[T] = { { val origTypeNames = sealedTrait.subtypes.map(_.typeName.short) val transformed = origTypeNames.map(config.transformConstructorNames).distinct if (transformed.length != origTypeNames.length) { throw new DerivationError( "Duplicate key detected after applying transformation function for " + "sealed trait child classes" ) } } new Encoder[T] { def apply(a: T): Json = { sealedTrait.dispatch(a) { subtype => val baseJson = subtype.typeclass(subtype.cast(a)) val constructorName = config .transformConstructorNames(subtype.typeName.short) config.discriminator match { case Some(discriminator) => { // Note: Here we handle the edge case where a subtype of a sealed trait has a custom encoder which does not encode // encode into a JSON object and thus we cannot insert the discriminator key. In this case we fallback // to the non-discriminator case for this subtype. This is same as the behavior of circe-generic-extras baseJson.asObject match { case Some(jsObj) => Json.fromJsonObject(jsObj.add(discriminator, Json.fromString(constructorName))) case None => Json.obj(constructorName -> baseJson) } } case None => Json.obj(constructorName -> baseJson) } } } } } }
Example 102
Source File: CodecEquivalenceTests.scala From circe-magnolia with Apache License 2.0 | 5 votes |
package io.circe.magnolia import cats.instances.either._ import cats.kernel.Eq import cats.laws._ import cats.laws.discipline._ import io.circe.magnolia.tags.{TaggedDecoder, TaggedEncoder} import io.circe.{Decoder, Encoder, Json} import org.scalacheck.{Arbitrary, Prop, Shrink} import org.typelevel.discipline.Laws import shapeless.tag.@@ trait CodecEquivalenceLaws[A] { def circeDecoder: Decoder[A] @@ tags.Circe def magnoliaDecoder: Decoder[A] @@ tags.Magnolia def circeEncoder: Encoder[A] @@ tags.Circe def magnoliaEncoder: Encoder[A] @@ tags.Magnolia def encoderEq(a: A): IsEq[Json] = circeEncoder(a) <-> magnoliaEncoder(a) def decoderEq(a: A): IsEq[Decoder.Result[A]] = { val encoded = magnoliaEncoder(a) encoded.as(circeDecoder) <-> encoded.as(magnoliaDecoder) } } object CodecEquivalenceLaws { def apply[A]( implicit circeDecode: Decoder[A] @@ tags.Circe, magnoliaDecode: Decoder[A] @@ tags.Magnolia, circeEncode: Encoder[A] @@ tags.Circe, magnoliaEncode: Encoder[A] @@ tags.Magnolia) = new CodecEquivalenceLaws[A] { override val circeDecoder = circeDecode override val magnoliaDecoder = magnoliaDecode override val circeEncoder = circeEncode override val magnoliaEncoder = magnoliaEncode } } trait CodecEquivalenceTests[A] extends Laws { def laws: CodecEquivalenceLaws[A] def codecEquivalence( implicit arbitraryA: Arbitrary[A], shrinkA: Shrink[A], eqA: Eq[A]): RuleSet = new DefaultRuleSet( name = "codec equality", parent = None, "encoder equivalence" -> Prop.forAll { (a: A) => laws.encoderEq(a) }, "decoder equivalence" -> Prop.forAll { (a: A) => laws.decoderEq(a) } ) // Use codecEquivalence if possible. Use only when only // derived Encoder can be equivalent and should be documented def encoderEquivalence( implicit arbitraryA: Arbitrary[A], shrinkA: Shrink[A] ): RuleSet = new DefaultRuleSet( name = "codec equality", parent = None, "encoder equivalence" -> Prop.forAll { (a: A) => laws.encoderEq(a) }, ) } object CodecEquivalenceTests { def apply[A]( implicit circeDecode: Decoder[A] @@ tags.Circe, magnoliaDecode: Decoder[A] @@ tags.Magnolia, circeEncode: Encoder[A] @@ tags.Circe, magnoliaEncode: Encoder[A] @@ tags.Magnolia): CodecEquivalenceTests[A] = new CodecEquivalenceTests[A] { val laws: CodecEquivalenceLaws[A] = CodecEquivalenceLaws[A]( circeDecode, magnoliaDecode, circeEncode, magnoliaEncode) } def useTagged[A]( implicit circeDecode: TaggedDecoder[tags.Circe, A], magnoliaDecode: TaggedDecoder[tags.Magnolia, A], circeEncode: TaggedEncoder[tags.Circe, A], magnoliaEncode: TaggedEncoder[tags.Magnolia, A]): CodecEquivalenceTests[A] = new CodecEquivalenceTests[A] { val laws: CodecEquivalenceLaws[A] = CodecEquivalenceLaws[A]( circeDecode.toTagged, magnoliaDecode.toTagged, circeEncode.toTagged, magnoliaEncode.toTagged) } }
Example 103
Source File: AutoDerivedSuite.scala From circe-magnolia with Apache License 2.0 | 5 votes |
package io.circe.magnolia import io.circe.magnolia.derivation.decoder.auto._ import io.circe.magnolia.derivation.encoder.auto._ import io.circe.testing.CodecTests import io.circe.tests.CirceSuite import io.circe.tests.examples._ import io.circe.{Decoder, Encoder, Json} import shapeless.tag import shapeless.tag.@@ import shapeless.test.illTyped class AutoDerivedSuite extends CirceSuite { import AutoDerivedSuiteInputs._ // TODO: All these imports are temporary workaround for https://github.com/propensive/magnolia/issues/89 import Encoder._ import Decoder._ private implicit val encodeStringTag: Encoder[String @@ Tag] = Encoder[String].narrow private implicit val decodeStringTag: Decoder[String @@ Tag] = Decoder[String].map(tag[Tag](_)) checkLaws("Codec[Tuple1[Int]]", CodecTests[Tuple1[Int]].unserializableCodec) checkLaws("Codec[(Int, Int, Foo)]", CodecTests[(Int, Int, Foo)].unserializableCodec) checkLaws("Codec[Qux[Int]]", CodecTests[Qux[Int]].unserializableCodec) checkLaws("Codec[Seq[Foo]]", CodecTests[Seq[Foo]].unserializableCodec) checkLaws("Codec[Baz]", CodecTests[Baz].unserializableCodec) checkLaws("Codec[Foo]", CodecTests[Foo].unserializableCodec) checkLaws("Codec[OuterCaseClassExample]", CodecTests[OuterCaseClassExample].unserializableCodec) checkLaws("Codec[RecursiveAdtExample]", CodecTests[RecursiveAdtExample].unserializableCodec) checkLaws("Codec[RecursiveWithOptionExample]", CodecTests[RecursiveWithOptionExample].unserializableCodec) checkLaws("Codec[RecursiveWithListExample]", CodecTests[RecursiveWithListExample].unserializableCodec) checkLaws("Codec[AnyValInside]", CodecTests[AnyValInside].unserializableCodec) "A generically derived codec" should "not interfere with base instances" in forAll { (is: List[Int]) => val json = Encoder[List[Int]].apply(is) assert(json === Json.fromValues(is.map(Json.fromInt)) && json.as[List[Int]] === Right(is)) } it should "not be derived for Object" in { illTyped("Decoder[Object]") illTyped("Encoder[Object]") } it should "not be derived for AnyRef" in { illTyped("Decoder[AnyRef]") illTyped("Encoder[AnyRef]") } "Generic decoders" should "not interfere with defined decoders" in forAll { (xs: List[String]) => val json = Json.obj("SubtypeWithExplicitInstance" -> Json.fromValues(xs.map(Json.fromString))) val ch = Decoder[Sealed].apply(json.hcursor) val res = ch === Right(SubtypeWithExplicitInstance(xs): Sealed) assert(res) } "Generic encoders" should "not interfere with defined encoders" in forAll { (xs: List[String]) => val json = Json.obj("SubtypeWithExplicitInstance" -> Json.fromValues(xs.map(Json.fromString))) assert(Encoder[Sealed].apply(SubtypeWithExplicitInstance(xs): Sealed) === json) } // TODO: tagged types don't work ATM, might be related to https://github.com/propensive/magnolia/issues/89 // checkLaws("Codec[WithTaggedMembers]", CodecTests[WithTaggedMembers].unserializableCodec) checkLaws("Codec[Seq[WithSeqOfTagged]]", CodecTests[Seq[WithSeqOfTagged]].unserializableCodec) }
Example 104
Source File: SemiautoDerivedSuite.scala From circe-magnolia with Apache License 2.0 | 5 votes |
package io.circe.magnolia import io.circe.magnolia.derivation.decoder.semiauto._ import io.circe.magnolia.derivation.encoder.semiauto._ import io.circe.testing.CodecTests import io.circe.tests.CirceSuite import io.circe.tests.examples._ import io.circe.{Decoder, Encoder, Json} import shapeless.test.illTyped class SemiautoDerivedSuite extends CirceSuite { import SemiautoDerivedSuiteInputs._ implicit def decodeBox[A: Decoder]: Decoder[Box[A]] = deriveMagnoliaDecoder implicit def encodeBox[A: Encoder]: Encoder[Box[A]] = deriveMagnoliaEncoder implicit def decodeQux[A: Decoder]: Decoder[Qux[A]] = deriveMagnoliaDecoder implicit def encodeQux[A: Encoder]: Encoder[Qux[A]] = deriveMagnoliaEncoder implicit val decodeWub: Decoder[Wub] = deriveMagnoliaDecoder implicit val encodeWub: Encoder[Wub] = deriveMagnoliaEncoder implicit val decodeFoo: Decoder[Foo] = deriveMagnoliaDecoder implicit val encodeFoo: Encoder[Foo] = deriveMagnoliaEncoder implicit val decodeAnyValInside: Decoder[AnyValInside] = deriveMagnoliaDecoder implicit val encodeAnyValInside: Encoder[AnyValInside] = deriveMagnoliaEncoder implicit val decodeRecursiveAdtExample: Decoder[RecursiveAdtExample] = deriveMagnoliaDecoder implicit val encodeRecursiveAdtExample: Encoder[RecursiveAdtExample] = deriveMagnoliaEncoder implicit val decodeRecursiveWithOptionExample: Decoder[RecursiveWithOptionExample] = deriveMagnoliaDecoder implicit val encodeRecursiveWithOptionExample: Encoder[RecursiveWithOptionExample] = deriveMagnoliaEncoder checkLaws("Codec[Tuple1[Int]]", CodecTests[Tuple1[Int]].unserializableCodec) checkLaws("Codec[(Int, Int, Foo)]", CodecTests[(Int, Int, Foo)].unserializableCodec) checkLaws("Codec[Box[Int]]", CodecTests[Box[Int]].unserializableCodec) checkLaws("Codec[Qux[Int]]", CodecTests[Qux[Int]].unserializableCodec) checkLaws("Codec[Seq[Foo]]", CodecTests[Seq[Foo]].unserializableCodec) checkLaws("Codec[Baz]", CodecTests[Baz].unserializableCodec) checkLaws("Codec[Foo]", CodecTests[Foo].unserializableCodec) checkLaws("Codec[RecursiveAdtExample]", CodecTests[RecursiveAdtExample].unserializableCodec) checkLaws("Codec[RecursiveWithOptionExample]", CodecTests[RecursiveWithOptionExample].unserializableCodec) checkLaws("Codec[AnyValInside]", CodecTests[AnyValInside].unserializableCodec) "A generically derived codec" should "not interfere with base instances" in forAll { (is: List[Int]) => val json = Encoder[List[Int]].apply(is) assert(json === Json.fromValues(is.map(Json.fromInt)) && json.as[List[Int]] === Right(is)) } it should "not come from nowhere" in { illTyped("Decoder[OvergenerationExampleInner]") illTyped("Encoder[OvergenerationExampleInner]") illTyped("Decoder[OvergenerationExampleOuter0]") illTyped("Encoder[OvergenerationExampleOuter0]") illTyped("Decoder[OvergenerationExampleOuter1]") illTyped("Encoder[OvergenerationExampleOuter1]") } it should "require instances for all parts" in { illTyped("deriveMagnoliaDecoder[OvergenerationExampleInner0]") illTyped("deriveMagnoliaDecoder[OvergenerationExampleInner1]") illTyped("deriveMagnoliaEncoder[OvergenerationExampleInner0]") illTyped("deriveMagnoliaEncoder[OvergenerationExampleInner1]") } }
Example 105
Source File: PriorityIssueTest.scala From circe-magnolia with Apache License 2.0 | 5 votes |
package io.circe.magnolia.incompat import io.circe.{Encoder, Json} import io.circe.magnolia.CirceMagnoliaSuite import io.circe.magnolia.derivation.encoder.auto._ import org.scalatest.OptionValues case class MapContainer(theMap: Map[String, List[Int]]) class PriorityIssueTest extends CirceMagnoliaSuite with OptionValues { // todo: uncomment when https://github.com/propensive/magnolia/issues/89 is fixed "Circe Magnolia Encoder" should "use instances from companion even if they are not imported" ignore { val encoder = Encoder[MapContainer] val json = encoder(MapContainer(Map("f" -> List(1, 2, 3)))) json.hcursor.downField("theMap").downField("f").focus.value shouldBe Json.arr(Json.fromInt(1), Json.fromInt(2), Json.fromInt(3)) } "Circe Magnolia Encoder" should "use instances from companion if they are explicitly imported" in { import Encoder._ val encoder = Encoder[MapContainer] val json = encoder(MapContainer(Map("f" -> List(1, 2, 3)))) json.hcursor.downField("theMap").downField("f").focus.value shouldBe Json.arr(Json.fromInt(1), Json.fromInt(2), Json.fromInt(3)) } }
Example 106
Source File: Types.scala From CloudGenesis with Apache License 2.0 | 5 votes |
package com.lifeway.cloudops.cloudformation import io.circe.{Decoder, Encoder, Json} sealed trait EventType case object CreateUpdateEvent extends EventType case object DeletedEvent extends EventType object EventType { implicit val encoder: Encoder[EventType] = Encoder[EventType] { case CreateUpdateEvent => Json.fromString("CreateUpdateEvent") case DeletedEvent => Json.fromString("DeletedEvent") } implicit val decoder: Decoder[EventType] = Decoder[EventType] { c => for { eType <- c.as[String] } yield { eType match { case "CreateUpdateEvent" => CreateUpdateEvent case "DeletedEvent" => DeletedEvent } } } } case class S3File(bucket: String, key: String, versionId: String, eventType: EventType) object S3File { implicit val decoder: Decoder[S3File] = Decoder.forProduct4("bucketName", "key", "versionId", "eventType")(S3File.apply) implicit val encoder: Encoder[S3File] = Encoder.forProduct4("bucketName", "key", "versionId", "eventType")(f => (f.bucket, f.key, f.versionId, f.eventType)) }
Example 107
Source File: Http4sClientSpec.scala From canoe with MIT License | 5 votes |
package canoe.api.clients import canoe.api._ import canoe.methods.Method import canoe.models.InputFile import cats.effect.IO import io.circe.{Decoder, Encoder} import org.http4s.HttpApp import org.http4s.client.Client import org.http4s.dsl.io._ import io.circe.Json import io.chrisdavenport.log4cats.slf4j.Slf4jLogger import org.scalatest.freespec.AnyFreeSpec class Http4sClientSpec extends AnyFreeSpec { private case class TestMethod(name: String = "test", encoder: Encoder[String] = Encoder.encodeString, decoder: Decoder[String] = Decoder.decodeString, files: List[InputFile] = Nil) extends Method[String, String] { def attachments(request: String): List[(String, InputFile)] = files.map("" -> _) } private implicit val testMethod = TestMethod() private def response(s: String) = s"""{"ok" : true, "result" : "$s"}""" private implicit val logger = Slf4jLogger.getLogger[IO] "Client" - { "sends" - { "to correct Telegram endpoint" in { val client: Client[IO] = Client.fromHttpApp(HttpApp(r => Ok(response(r.uri.toString)))) val tgClient = new Http4sTelegramClient("token", client) assert(tgClient.execute("any").unsafeRunSync() == s"https://api.telegram.org/bottoken/${testMethod.name}") } val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO] { r => Ok(response(r.headers.get(org.http4s.headers.`Content-Type`).map(_.value.replace("\"", "''")).getOrElse(""))) })) "json POST request if attachments contain file upload" in { assert(tgClient.execute("any").unsafeRunSync() == "application/json") } "multipart POST request if attachments contain file upload" in { val resp = tgClient.execute("any")(testMethod.copy(files = List(InputFile.Upload("", Array.emptyByteArray)))) assert(resp.unsafeRunSync().startsWith("multipart/form-data")) } } "encodes/decodes" - { "request entity with method encoder" in { val tgClient = new Http4sTelegramClient( "", Client.fromHttpApp(HttpApp[IO](_.bodyAsText.compile.string.flatMap(s => Ok(response(s.replace("\"", "'")))))) ) val res = tgClient.execute("")(testMethod.copy(encoder = Encoder.instance(_ => Json.fromString("encoded")))) assert(res.unsafeRunSync() == "'encoded'") } "result entity with method decoder" in { val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO](_ => Ok(response(""))))) val res = tgClient.execute("")(testMethod.copy(decoder = Decoder.const("decoded"))) assert(res.unsafeRunSync() == "decoded") } } "handles" - { "decode failure as ResponseDecodingError" in { val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO](_ => Ok("{}")))) assertThrows[ResponseDecodingError](tgClient.execute("any").unsafeRunSync()) } "unsuccessful result as FailedMethod" in { val response = """{"ok" : false, "result" : "any"}""" val tgClient = new Http4sTelegramClient("", Client.fromHttpApp(HttpApp[IO](_ => Ok(response)))) assertThrows[FailedMethod[String, String]](tgClient.execute("any").unsafeRunSync()) } } } }
Example 108
Source File: CodecsSpec.scala From canoe with MIT License | 5 votes |
package canoe.marshalling import canoe.marshalling.codecs._ import io.circe.generic.semiauto._ import io.circe.{Decoder, Encoder, Json} import org.scalatest.freespec.AnyFreeSpec class CodecsSpec extends AnyFreeSpec { case class Inner(longName: String) case class Outer(longInt: Int, inner: Inner) implicit val innerDecoder: Decoder[Inner] = deriveDecoder implicit val innerEncoder: Encoder[Inner] = deriveEncoder val decoder: Decoder[Outer] = deriveDecoder val encoder: Encoder[Outer] = deriveEncoder val instance: Outer = Outer(12, Inner("name")) "encoder works as expected" in { assert(allJsonKeys(encoder(instance)) == List("longInt", "inner", "longName")) } "snake case encoder encodes keys in snake_case manner" in { val encodedKeys = allJsonKeys(encoder.snakeCase(instance)) assert(encodedKeys.map(_.snakeCase) == encodedKeys) } "encoded snake_case is decoded in camelCase" in { val encodedDecoded = decoder.camelCase.decodeJson(encoder.snakeCase(instance)) assert(encodedDecoded.contains(instance)) } def allJsonKeys(json: Json): List[String] = json.asObject.toList.flatMap(_.toList).flatMap { case (k, json) => k :: allJsonKeys(json) } }
Example 109
Source File: VersionEndpoint.scala From temperature-machine with Apache License 2.0 | 5 votes |
package bad.robot.temperature.server import bad.robot.temperature._ import cats.effect.IO import io.circe.Json import org.http4s.HttpService import org.http4s.dsl.io._ object VersionEndpoint { private val version = Json.obj( ("name", Json.fromString(BuildInfo.name)), ("version", Json.fromString(BuildInfo.version)), ("latestSha", Json.fromString(BuildInfo.latestSha)), ("scalaVersion", Json.fromString(BuildInfo.scalaVersion)), ("sbtVersion", Json.fromString(BuildInfo.sbtVersion)) ) def apply() = HttpService[IO] { case GET -> Root / "version" => Ok(version)(implicitly, jsonEncoder) } }
Example 110
Source File: ServerSpec.scala From Learn-Scala-Programming with MIT License | 5 votes |
import ch14.{Config, Server} import cats.effect.IO import cats.implicits._ import io.circe.Json import io.circe.literal._ import org.http4s.circe._ import org.http4s.client.blaze.Http1Client import org.http4s.{Method, Request, Status, Uri} import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec} import org.http4s.server.{Server => Http4sServer} class ServerSpec extends WordSpec with Matchers with BeforeAndAfterAll { private lazy val client = Http1Client[IO]().unsafeRunSync() private lazy val configIO = Config.load("test.conf") private lazy val config = configIO.unsafeRunSync() private lazy val rootUrl = s"http://${config.server.host}:${config.server.port}" private val server: Option[Http4sServer[IO]] = (for { builder <- Server.createServer(configIO) } yield builder.start.unsafeRunSync()).compile.last.unsafeRunSync() override def afterAll(): Unit = { client.shutdown.unsafeRunSync() server.foreach(_.shutdown.unsafeRunSync()) } "The server" should { "get an empty inventory" in { val json = client.expect[Json](s"$rootUrl/inventory").unsafeRunSync() json shouldBe json"""{}""" } "create articles" in { val eggs = Request[IO](method = Method.POST, uri = Uri.unsafeFromString(s"$rootUrl/articles/eggs")) client.status(eggs).unsafeRunSync() shouldBe Status.NoContent val chocolate = Request[IO](method = Method.POST, uri = Uri.unsafeFromString(s"$rootUrl/articles/chocolate")) client.status(chocolate).unsafeRunSync() shouldBe Status.NoContent val json = client.expect[Json](s"$rootUrl/inventory").unsafeRunSync() json shouldBe json"""{"eggs" : 0,"chocolate" : 0}""" } "update inventory" in { val restock = Request[IO](method = Method.POST, uri = Uri.unsafeFromString(s"$rootUrl/restock")).withBody(json"""{ "inventory" : { "eggs": 10, "chocolate": 20 }}""") client.expect[Json](restock).unsafeRunSync() shouldBe json"""{ "eggs" : 10, "chocolate" : 20 }""" client.expect[Json](restock).unsafeRunSync() shouldBe json"""{ "eggs" : 20, "chocolate" : 40 }""" } "deliver purchase if there is enough inventory" in { val purchase = Request[IO](method = Method.POST, uri = Uri.unsafeFromString(s"$rootUrl/purchase")).withBody(json"""{ "order" : { "eggs": 5, "chocolate": 5 }}""") client.expect[Json](purchase).unsafeRunSync() shouldBe json"""{ "eggs" : 5, "chocolate" : 5 }""" } "not deliver purchase if there is not enough inventory" in { val purchase = Request[IO](method = Method.POST, uri = Uri.unsafeFromString(s"$rootUrl/purchase")).withBody(json"""{ "order" : { "eggs": 5, "chocolate": 45 }}""") client.expect[Json](purchase).unsafeRunSync() shouldBe json"""{ "eggs" : 0, "chocolate" : 0 }""" } } }
Example 111
Source File: QueriesEndpoints.scala From endpoints4s with MIT License | 5 votes |
package cqrs.queries import java.util.UUID import endpoints4s.algebra.{BuiltInErrors, MuxEndpoints, MuxRequest, circe} import io.circe.{Decoder, Encoder, Json} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} // TODO Enrich with failure information //#mux-responses sealed trait QueryResp case class MaybeResource(value: Option[Meter]) extends QueryResp case class ResourceList(value: List[Meter]) extends QueryResp //#mux-responses object QueryResp { implicit val queryDecoder: Decoder[QueryResp] = deriveDecoder implicit val queryEncoder: Encoder[QueryResp] = deriveEncoder }
Example 112
Source File: RequestId.scala From lsp4s with Apache License 2.0 | 5 votes |
package scala.meta.jsonrpc import io.circe.Json import io.circe.Decoder import io.circe.Encoder sealed trait RequestId object RequestId { def apply(n: Int): RequestId.String = RequestId.String(Json.fromString(n.toString)) implicit val decoder: Decoder[RequestId] = Decoder.decodeJson.map { case s if s.isString => RequestId.String(s) case n if n.isNumber => RequestId.Number(n) case n if n.isNull => RequestId.Null } implicit val encoder: Encoder[RequestId] = Encoder.encodeJson.contramap { case RequestId.Number(v) => v case RequestId.String(v) => v case RequestId.Null => Json.Null } // implicit val encoder: Decoder = case class Number(value: Json) extends RequestId case class String(value: Json) extends RequestId case object Null extends RequestId }
Example 113
Source File: BaseProtocolMessage.scala From lsp4s with Apache License 2.0 | 5 votes |
package scala.meta.jsonrpc import java.io.InputStream import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.util import io.circe.Json import io.circe.syntax._ import monix.reactive.Observable import scribe.LoggerSupport final class BaseProtocolMessage( val header: Map[String, String], val content: Array[Byte] ) { override def equals(obj: scala.Any): Boolean = this.eq(obj.asInstanceOf[Object]) || { obj match { case m: BaseProtocolMessage => header.equals(m.header) && util.Arrays.equals(content, m.content) } } override def toString: String = { val bytes = MessageWriter.write(this) StandardCharsets.UTF_8.decode(bytes).toString } } object BaseProtocolMessage { val ContentLen = "Content-Length" def apply(msg: Message): BaseProtocolMessage = fromJson(msg.asJson) def fromJson(json: Json): BaseProtocolMessage = fromBytes(json.noSpaces.getBytes(StandardCharsets.UTF_8)) def fromBytes(bytes: Array[Byte]): BaseProtocolMessage = new BaseProtocolMessage( Map("Content-Length" -> bytes.length.toString), bytes ) def fromInputStream( in: InputStream, logger: LoggerSupport ): Observable[BaseProtocolMessage] = fromBytes(Observable.fromInputStream(in), logger) def fromBytes( in: Observable[Array[Byte]], logger: LoggerSupport ): Observable[BaseProtocolMessage] = fromByteBuffers(in.map(ByteBuffer.wrap), logger) def fromByteBuffers( in: Observable[ByteBuffer], logger: LoggerSupport ): Observable[BaseProtocolMessage] = in.executeAsync.liftByOperator(new BaseProtocolMessageParser(logger)) }
Example 114
Source File: Message.scala From lsp4s with Apache License 2.0 | 5 votes |
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 115
Source File: ErrorCodeSuite.scala From lsp4s with Apache License 2.0 | 5 votes |
package tests import io.circe.Json import minitest.SimpleTestSuite import scala.meta.jsonrpc.ErrorCode import scala.meta.jsonrpc.ErrorCode._ import io.circe.syntax._ object ErrorCodeSuite extends SimpleTestSuite { def check(code: Int, expected: ErrorCode): Unit = test(expected.toString) { val Right(obtained) = Json.fromInt(code).as[ErrorCode] assertEquals(obtained, expected) val obtainedJson = expected.asJson.noSpaces assertEquals(obtainedJson, code.toString) } check(666, Unknown(666)) check(-32000, Unknown(-32000)) check(-32099, Unknown(-32099)) ErrorCode.builtin.foreach { code => check(code.value, code) } }
Example 116
Source File: GenericApi.scala From freestyle with Apache License 2.0 | 5 votes |
package examples.todolist package http import cats.effect.Effect import cats.implicits._ import examples.todolist.model.Pong import freestyle.tagless.logging.LoggingM import io.circe.Json import org.http4s.circe._ import org.http4s.dsl.Http4sDsl import org.http4s.HttpService class GenericApi[F[_]: Effect](implicit log: LoggingM[F]) extends Http4sDsl[F] { val endpoints = HttpService[F] { case GET -> Root / "ping" => for { _ <- log.error("Not really an error") _ <- log.warn("Not really a warn") _ <- log.debug("GET /ping") response <- Ok(Json.fromLong(Pong.current.time)) } yield response case GET -> Root / "hello" => for { _ <- log.error("Not really an error") _ <- log.warn("Not really a warn") _ <- log.debug("GET /Hello") response <- Ok("Hello World") } yield response } } object GenericApi { implicit def instance[F[_]: Effect](implicit log: LoggingM[F]): GenericApi[F] = new GenericApi[F] }
Example 117
Source File: RepositoryResponse.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.bitbucket.http4s import cats.implicits._ import io.circe.{ACursor, Decoder, DecodingFailure, Json} import org.http4s.Uri import org.scalasteward.core.git.Branch import org.scalasteward.core.util.uri._ import org.scalasteward.core.vcs.data.{Repo, UserOut} import scala.annotation.tailrec final private[http4s] case class RepositoryResponse( name: String, mainBranch: Branch, owner: UserOut, httpsCloneUrl: Uri, parent: Option[Repo] ) private[http4s] object RepositoryResponse { implicit private val repoDecoder: Decoder[Repo] = Decoder.instance { c => c.as[String].map(_.split('/')).flatMap { parts => parts match { case Array(owner, name) => Repo(owner, name).asRight case _ => DecodingFailure("Repo", c.history).asLeft } } } implicit val decoder: Decoder[RepositoryResponse] = Decoder.instance { c => for { name <- c.downField("name").as[String] owner <- c.downField("owner") .downField("username") .as[String] .orElse(c.downField("owner").downField("nickname").as[String]) cloneUrl <- c.downField("links") .downField("clone") .downAt { p => p.asObject .flatMap(o => o("name")) .flatMap(_.asString) .contains("https") } .downField("href") .as[Uri] defaultBranch <- c.downField("mainbranch").downField("name").as[Branch] maybeParent <- c.downField("parent").downField("full_name").as[Option[Repo]] } yield RepositoryResponse(name, defaultBranch, UserOut(owner), cloneUrl, maybeParent) } def downAt(p: Json => Boolean): ACursor = { @tailrec def find(c: ACursor): ACursor = if (c.succeeded) if (c.focus.exists(p)) c else find(c.right) else c find(cursor.downArray) } } }
Example 118
Source File: CreatePullRequestRequest.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.bitbucket.http4s import io.circe.{Encoder, Json} import org.scalasteward.core.git.Branch import org.scalasteward.core.vcs.data.Repo private[http4s] case class CreatePullRequestRequest( title: String, sourceBranch: Branch, sourceRepo: Repo, destinationBranch: Branch, description: String ) private[http4s] object CreatePullRequestRequest { implicit val encoder: Encoder[CreatePullRequestRequest] = Encoder.instance { d => Json.obj( ("title", Json.fromString(d.title)), ( "source", Json.obj( ("branch", Json.obj(("name", Json.fromString(d.sourceBranch.name)))), ( "repository", Json.obj(("full_name", Json.fromString(s"${d.sourceRepo.owner}/${d.sourceRepo.repo}"))) ) ) ), ("description", Json.fromString(d.description)), ( "destination", Json.obj( ("branch", Json.obj(("name", Json.fromString(d.destinationBranch.name)))) ) ) ) } }
Example 119
Source File: JsonCodecTest.scala From scala-steward with Apache License 2.0 | 5 votes |
package org.scalasteward.core.bitbucket.http4s import io.circe.Json import org.scalasteward.core.vcs.data.PullRequestState import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class JsonCodecTest extends AnyFunSuite with Matchers { test("PullRequestStatus decoding of expected values") { val mapping = Map( "OPEN" -> PullRequestState.Open, "MERGED" -> PullRequestState.Closed, "SUPERSEDED" -> PullRequestState.Closed, "DECLINED" -> PullRequestState.Closed ) mapping.foreach { case (string, state) => json.pullRequestStateDecoder.decodeJson(Json.fromString(string)) shouldBe Right(state) } } }
Example 120
Source File: LogstashWriter.scala From scribe with MIT License | 5 votes |
package scribe.logstash import io.circe.Json import io.youi.client.HttpClient import io.youi.http.content.Content import io.youi.http.HttpResponse import io.youi.net._ import profig.JsonUtil import scribe.{LogRecord, MDC} import scribe.writer.Writer import perfolation._ import scribe.output.{EmptyOutput, LogOutput} import scala.concurrent.{Await, Future} import scala.concurrent.duration._ import scribe.Execution.global case class LogstashWriter(url: URL, service: String, additionalFields: Map[String, String] = Map.empty, asynchronous: Boolean = true) extends Writer { private lazy val client = HttpClient.url(url).post override def write[M](record: LogRecord[M], output: LogOutput): Unit = { val future = log(record) if (!asynchronous) { Await.result(future, 10.seconds) } } def log[M](record: LogRecord[M]): Future[HttpResponse] = { val l = record.timeStamp val timestamp = p"${l.t.F}T${l.t.T}.${l.t.L}${l.t.z}" val r = LogstashRecord( message = record.message.plainText, service = service, level = record.level.name, value = record.value, throwable = record.throwable.map(LogRecord.throwable2LogOutput(EmptyOutput, _).plainText), fileName = record.fileName, className = record.className, methodName = record.methodName, line = record.line, thread = record.thread.getName, `@timestamp` = timestamp, mdc = MDC.map.map { case (key, function) => key -> function() } ) val jsonObj = JsonUtil.toJson(r).asObject.get val jsonWithFields = additionalFields.foldLeft(jsonObj) { (obj, field) => obj.add(field._1, Json.fromString(field._2)) } val json = Json.fromJsonObject(jsonWithFields).noSpaces val content = Content.string(json, ContentType.`application/json`) client.content(content).send() } }
Example 121
Source File: TemplateId.scala From openlaw-core with Apache License 2.0 | 5 votes |
package org.adridadou.openlaw.values import cats.Eq import io.circe.{Decoder, Encoder, HCursor, Json, KeyDecoder, KeyEncoder} import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder} import cats.implicits._ import org.adridadou.openlaw.parser.template.variableTypes.EthereumAddress final case class TemplateId(id: String = "") extends Comparable[TemplateId] { override def toString: String = id override def compareTo(o: TemplateId): Int = id.compareTo(o.id) } object TemplateId { def apply(data: Array[Byte]): TemplateId = TemplateId(EthereumAddress.bytes2hex(data)) implicit val templateIdEnc: Encoder[TemplateId] = deriveEncoder implicit val templateIdDec: Decoder[TemplateId] = deriveDecoder implicit val eq: Eq[TemplateId] = Eq.by(_.id) } final case class TemplateIdentifier(title: TemplateTitle, version: Int) final case class TemplateTitle(originalTitle: String, title: String) { override def toString: String = title override def equals(obj: Any): Boolean = obj match { case other: TemplateTitle => this === other case _ => false } override def hashCode(): Int = this.title.hashCode } object TemplateTitle { def apply(): TemplateTitle = TemplateTitle("") def apply(title: String): TemplateTitle = TemplateTitle(originalTitle = title, title = title.toLowerCase()) implicit val eq: Eq[TemplateTitle] = (x: TemplateTitle, y: TemplateTitle) => x.title === y.title implicit val templateTitleEnc: Encoder[TemplateTitle] = (a: TemplateTitle) => Json.fromString(a.originalTitle) implicit val templateTitleDec: Decoder[TemplateTitle] = (c: HCursor) => (for { title <- c.downField("title").as[String] } yield TemplateTitle(title)) match { case Right(title) => Right(title) case Left(_) => c.as[String].map(TemplateTitle(_)) } implicit val templateTitleKeyEnc: KeyEncoder[TemplateTitle] = (key: TemplateTitle) => key.title implicit val templateTitleKeyDec: KeyDecoder[TemplateTitle] = (key: String) => Some(TemplateTitle(key)) }
Example 122
Source File: ContractAccess.scala From openlaw-core with Apache License 2.0 | 5 votes |
package org.adridadou.openlaw.values import cats.Eq import io.circe.{Decoder, Encoder, HCursor, Json} sealed abstract class ContractAccess(val name: String) case object ContractSignable extends ContractAccess("signable") case object ContractNoAccess extends ContractAccess("noaccess") case object ContractReadonly extends ContractAccess("readonly") case object ContractEditable extends ContractAccess("editable") object ContractAccess { def apply(name: String): ContractAccess = name match { case ContractReadonly.name => ContractReadonly case ContractNoAccess.name => ContractNoAccess case ContractSignable.name => ContractSignable case ContractEditable.name => ContractEditable } def unapply(arg: ContractAccess): String = arg.name implicit val accessDecoder: Decoder[ContractAccess] = (c: HCursor) => { for { name <- c.as[String] } yield ContractAccess(name) } implicit val accessEncoder: Encoder[ContractAccess] = (a: ContractAccess) => Json.fromString(a.name) implicit val eqForContractAccess: Eq[ContractAccess] = Eq.fromUniversalEquals }
Example 123
Source File: TemplateTitleSpec.scala From openlaw-core with Apache License 2.0 | 5 votes |
package org.adridadou.openlaw import io.circe.Json import org.adridadou.openlaw.values.TemplateTitle import org.scalatest.check.Checkers import org.scalatest.{FlatSpec, Matchers} import io.circe.syntax._ import io.circe.parser._ class TemplateTitleSpec extends FlatSpec with Matchers with Checkers { val title = TemplateTitle("This is a Title") "Template title" should "serialize" in { title.asJson.noSpaces shouldBe "\"This is a Title\"" } it should "deserialize plain string" in { val Right(dTitle) = decode[TemplateTitle](Json.fromString(title.originalTitle).noSpaces) dTitle shouldEqual title } it should "deserialize json titles as well" in { val json = "{\"title\":\"This is a Title\"}" decode[TemplateTitle](json) shouldEqual Right(title) } }
Example 124
Source File: PackageSpec.scala From openlaw-core with Apache License 2.0 | 5 votes |
package org.adridadou.openlaw import io.circe.Json import org.adridadou.openlaw.values.TemplateTitle import org.scalatest.check.Checkers import org.scalatest.{FlatSpec, Matchers} import io.circe.syntax._ import io.circe.parser._ class PackageSpec extends FlatSpec with Matchers with Checkers { "An OpenlawValue instance" should "be equal" in { OpenlawString("test") should be(OpenlawString("test")) OpenlawString("test") shouldNot be(OpenlawString("TEST")) OpenlawBigDecimal(BigDecimal(1L)) should be( OpenlawBigDecimal(BigDecimal(1L)) ) OpenlawBigDecimal(BigDecimal(1L)) shouldNot be( OpenlawBigDecimal(BigDecimal(2L)) ) } it should "be comparable" in { OpenlawString("test").compareTo(OpenlawString("test")) should be(0) OpenlawString("test").compareTo(OpenlawString("TEST")) shouldNot be(0) } it should "implicitly convert to its underlying type" in { val string: String = OpenlawString("test") string should be("test") val bigDecimal: BigDecimal = OpenlawBigDecimal(BigDecimal(1L)) bigDecimal should be(BigDecimal(1L)) } }
Example 125
Source File: package.scala From kafka-journal with MIT License | 5 votes |
package com.evolutiongaming.kafka.journal import cats.Eval import cats.implicits._ import io.circe.Json import play.api.libs.json._ package object circe { def convertPlayToCirce(jsValue: JsValue): Json = { def convert(jsValue: JsValue): Eval[Json] = jsValue match { case JsNull => Eval.now(Json.Null) case JsString(value) => Eval.now(Json.fromString(value)) case JsNumber(value) => Eval.now(Json.fromBigDecimal(value)) case JsBoolean(value) => Eval.now(Json.fromBoolean(value)) case JsArray(values) => values.toList .traverse { value => Eval.defer(convert(value)) } .map(Json.arr(_: _*)) case JsObject(fields) => fields.toList .traverse { case (field, value) => Eval.defer(convert(value)).map(field -> _) } .map(Json.fromFields) } convert(jsValue).value } def convertCirceToPlay(json: Json): Either[String, JsValue] = { def convert(json: Json): Eval[Either[String, JsValue]] = json.fold( Eval.now(JsNull.asRight[String]), bool => Eval.now(JsBoolean(bool).asRight[String]), num => Eval.now(num.toBigDecimal.map(JsNumber).toRight(s"Failed to convert JsonNumber $num to JsNumber")), str => Eval.now(JsString(str).asRight[String]), arr => arr.toList .traverse { value => Eval.defer(convert(value)) } .map(_.sequence.map(JsArray(_))), obj => obj.toList .traverse { case (field, value) => Eval.defer(convert(value)).map(_.map(field -> _)) } .map(_.sequence.map(JsObject(_))) ) convert(json).value } }
Example 126
Source File: package.scala From telegram with Apache License 2.0 | 5 votes |
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 127
Source File: json_support.scala From sbt-kubeyml with MIT License | 5 votes |
package kubeyml.ingress import io.circe.{Encoder, Json} import io.circe.generic.auto._ import io.circe.syntax._ import kubeyml.protocol.json_support._ object json_support { private val defaultIngressParts: Json = Json.obj( "kind" -> "Ingress".asJson ) implicit val apiVersionEncoder: Encoder[ApiVersion] = Encoder.instance(_.show.asJson) implicit val hostEncoder: Encoder[Host] = Encoder.encodeString.contramap(_.value) implicit val pathEncoder: Encoder[Path] = Encoder.instance { case Path(ServiceMapping(serviceName, servicePort), path) => Json.obj( "backend" -> Json.obj( "serviceName" -> serviceName.asJson, "servicePort" -> servicePort.asJson ), "path" -> path.asJson ) } private val httpRuleEncoder: Encoder[HttpRule] = Encoder.instance { httpRule => Json.obj( "host" -> httpRule.host.asJson, "http" -> Json.obj("paths" -> httpRule.paths.asJson) ) } implicit val ruleEncoder: Encoder[Rule] = Encoder.instance { case r: HttpRule => httpRuleEncoder(r) } private val customIngressEncoder: Encoder[CustomIngress] = Encoder.instance( custom => Json.obj( "apiVersion" -> custom.apiVersion.asJson, "metadata" -> Json.obj( "annotations" -> custom.annotations.asJson, "name" -> custom.name.asJson, "namespace" -> custom.namespace.asJson ), "spec" -> custom.spec.asJson ) ) implicit val ingressEncoder: Encoder[Ingress] = Encoder.instance { case custom: CustomIngress => defaultIngressParts deepMerge customIngressEncoder(custom) } }
Example 128
Source File: json_support.scala From sbt-kubeyml with MIT License | 5 votes |
package kubeyml.service import io.circe.{Encoder, Json} import io.circe.syntax._ import io.circe.generic.semiauto._ import kubeyml.protocol.json_support._ object json_support { implicit val serviceTypeEncoder: Encoder[ServiceType] = Encoder.encodeString.contramap { case NodePort => "NodePort" } implicit val selectorEncoder: Encoder[Selector] = Encoder.instance { case AppSelector(appName) => Json.obj("app" -> appName.asJson) } implicit val networkProtocolEncoder: Encoder[NetworkProtocol] = Encoder.encodeString.contramap { case TCP => "TCP" } implicit val targetPortEncoder: Encoder[TargetPort] = Encoder.instance { case NamedTargetPort(name) => name.asJson case NumberedTargetPort(num) => num.asJson } implicit val portEncoder: Encoder[Port] = deriveEncoder implicit val specEncoder: Encoder[Spec] = deriveEncoder implicit val serviceEncoder: Encoder[Service] = Encoder.instance { service => Json.obj( "kind" -> "Service".asJson, "apiVersion" -> "v1".asJson, "metadata" -> Json.obj( "name" -> service.name.asJson, "namespace" -> service.namespace.asJson ), "spec" -> service.spec.asJson ) } }
Example 129
Source File: json_support.scala From sbt-kubeyml with MIT License | 5 votes |
package kubeyml.roles import io.circe.{Encoder, Json} import io.circe.generic.auto._ import io.circe.syntax._ object json_support { import kubeyml.protocol.json_support._ implicit val verbsEncoder: Encoder[Verb] = Encoder.encodeString.contramap { case Verb.Get => "get" case Verb.Watch => "watch" case Verb.List => "list" } implicit val apiGroupEncoder: Encoder[ApiGroup] = Encoder.encodeString.contramap { case ApiGroup.Core => "" } implicit val resourceEncoder: Encoder[Resource] = Encoder.encodeString.contramap { case Pods => "pods" } implicit val roleEncoder: Encoder[Role] = Encoder.instance { case role => Json.obj("metadata" -> role.metadata.asJson, "rules" -> role.rules.asJson, "kind" -> "Role".asJson, "apiVersion" -> "rbac.authorization.k8s.io/v1".asJson ) } implicit val roleRefEncoder: Encoder[RoleRef] = Encoder.instance { case RoleRef(Role(RoleMetadata(name, _), _)) => Json.obj( "kind" -> "Role".asJson, "name" -> name.asJson, "apiGroup" -> "rbac.authorization.k8s.io".asJson ) } implicit val subjectEncoder: Encoder[Subject] = Encoder.instance { case UserSubject(serviceAccount, namespace) => val identifier = s"system:serviceaccount:${namespace.value}:${serviceAccount.value}" Json.obj( "kind" -> "User".asJson, "name" -> identifier.asJson ) } implicit val roleBindingEncoder: Encoder[RoleBinding] = Encoder.instance { case RoleBinding(metadata, subjects, roleRef) => Json.obj( "kind" -> "RoleBinding".asJson, "apiVersion" -> "rbac.authorization.k8s.io/v1".asJson, "metadata" -> metadata.asJson, "subjects" -> subjects.asJson, "roleRef" -> roleRef.asJson ) } }
Example 130
Source File: KubernetesRole.scala From sbt-kubeyml with MIT License | 5 votes |
package kubeyml.roles import io.circe.Json import kubeyml.protocol.NonEmptyString import org.scalacheck.Gen import io.circe.yaml.parser._ import io.circe.generic.auto._ import io.circe.syntax._ import kubeyml.deployment.api._ import kubeyml.roles.ApiGroup.Core trait KubernetesRole { private val arbitraryNonEmptyString: Gen[NonEmptyString] = Gen.nonEmptyListOf(Gen.alphaChar).map(_.mkString).map(NonEmptyString) case class ValidDefinition(metadata: MetadataDefinition, rules: List[RuleDefinition]) case class MetadataDefinition(name: String, namespace: String) case class RuleDefinition(apiGroups: Set[String], resources: Set[String], verbs: Set[String]) val ruleDefinition = Gen.listOf(for { apiGroups <- Gen.listOf(Gen.oneOf(Seq(""))).map(_.toSet) resources <- Gen.listOf(Gen.oneOf(Seq("pods"))).map(_.toSet) verbs <- Gen.listOf(Gen.oneOf("get", "watch", "list")).map(_.toSet) } yield RuleDefinition(apiGroups, resources, verbs)) val validDefinition = for { name <- arbitraryNonEmptyString namespace <- arbitraryNonEmptyString rules <- ruleDefinition } yield ValidDefinition(MetadataDefinition(name.value, namespace.value), rules) def roleToJson(validDefinition: ValidDefinition): Json = parse( """ |kind: Role |apiVersion: rbac.authorization.k8s.io/v1 |""".stripMargin ).right.get deepMerge validDefinition.asJson def toRole(validDefinition: ValidDefinition): Role = { val rules = for { rule <- validDefinition.rules apiGroups = rule.apiGroups.map { case "" => Core }.toList resources = rule.resources.map { case "pods" => Pods }.toList verbs = rule.verbs.map { case "watch" => Verb.Watch case "list" => Verb.List case "get" => Verb.Get }.toList } yield Rule(apiGroups, resources, verbs) Role( RoleMetadata(validDefinition.metadata.name, validDefinition.metadata.namespace), rules ) } }
Example 131
Source File: TileEndpoints.scala From franklin with Apache License 2.0 | 5 votes |
package com.azavea.franklin.api.endpoints import com.azavea.franklin.datamodel.{ ItemRasterTileRequest, MapboxVectorTileFootprintRequest, Quantile } import com.azavea.franklin.error.NotFound import eu.timepit.refined.types.numeric.NonNegInt import eu.timepit.refined.types.string.NonEmptyString import io.circe.Json import sttp.model.StatusCode.{NotFound => NF} import sttp.tapir._ import sttp.tapir.codec.refined._ import sttp.tapir.json.circe._ class TileEndpoints(enableTiles: Boolean) { val basePath = "tiles" / "collections" val zxyPath = path[Int] / path[Int] / path[Int] val itemRasterTilePath: EndpointInput[(String, String, Int, Int, Int)] = (basePath / path[String] / "items" / path[String] / "WebMercatorQuad" / zxyPath) val collectionFootprintTilePath: EndpointInput[(String, Int, Int, Int)] = (basePath / path[String] / "footprint" / "WebMercatorQuad" / zxyPath) val collectionFootprintTileParameters: EndpointInput[(String, Int, Int, Int, NonEmptyString)] = collectionFootprintTilePath.and(query[NonEmptyString]("colorField")) val collectionFootprintTileJsonPath: EndpointInput[String] = (basePath / path[String] / "footprint" / "tile-json") val itemRasterTileParameters: EndpointInput[ItemRasterTileRequest] = itemRasterTilePath .and(query[String]("asset")) .and(query[Option[Int]]("redBand")) .and(query[Option[Int]]("greenBand")) .and(query[Option[Int]]("blueBand")) .and(query[Option[Quantile]]("upperQuantile")) .and(query[Option[Quantile]]("lowerQuantile")) .and(query[Option[NonNegInt]]("singleBand")) .mapTo(ItemRasterTileRequest) val itemRasterTileEndpoint: Endpoint[ItemRasterTileRequest, NotFound, Array[Byte], Nothing] = endpoint.get .in(itemRasterTileParameters) .out(rawBinaryBody[Array[Byte]]) .out(header("content-type", "image/png")) .errorOut(oneOf(statusMapping(NF, jsonBody[NotFound].description("not found")))) .description("Raster Tile endpoint for Collection Item") .name("collectionItemTiles") val collectionFootprintTileEndpoint : Endpoint[MapboxVectorTileFootprintRequest, NotFound, Array[Byte], Nothing] = endpoint.get .in(collectionFootprintTileParameters.mapTo(MapboxVectorTileFootprintRequest)) .out(rawBinaryBody[Array[Byte]]) .out(header("content-type", "application/vnd.mapbox-vector-tile")) .errorOut(oneOf(statusMapping(NF, jsonBody[NotFound].description("not found")))) .description("MVT endpoint for a collection's footprint") .name("collectionFootprintTiles") val collectionFootprintTileJson: Endpoint[String, NotFound, Json, Nothing] = endpoint.get .in(collectionFootprintTileJsonPath) .out(jsonBody[Json]) .errorOut(oneOf(statusMapping(NF, jsonBody[NotFound].description("not found")))) .description("TileJSON representation of this collection's footprint tiles") .name("collectionFootprintTileJSON") val endpoints = enableTiles match { case true => List(itemRasterTileEndpoint, collectionFootprintTileEndpoint, collectionFootprintTileJson) case _ => List.empty } }
Example 132
Source File: package.scala From franklin with Apache License 2.0 | 5 votes |
package com.azavea.franklin.api import cats.implicits._ import com.azavea.franklin.database.{temporalExtentFromString, temporalExtentToString} import com.azavea.franklin.datamodel.PaginationToken import com.azavea.franklin.error.InvalidPatch import com.azavea.franklin.extensions.validation.ExtensionName import com.azavea.stac4s._ import geotrellis.vector.Geometry import io.circe.{Encoder, Json} import sttp.tapir.Codec.PlainCodec import sttp.tapir.json.circe._ import sttp.tapir.{Codec, DecodeResult, Schema} import scala.util.Try package object schemas { implicit val extensionNameCodec: PlainCodec[ExtensionName] = Codec.string.mapDecode(s => DecodeResult.Value(ExtensionName.fromString(s)))(_.toString) implicit val schemaForTemporalExtent: Schema[TemporalExtent] = Schema( schemaForCirceJson.schemaType ) implicit val schemaForGeometry: Schema[Geometry] = Schema(schemaForCirceJson.schemaType) implicit val schemaForStacItem: Schema[StacItem] = Schema(schemaForCirceJson.schemaType) implicit val schemaForInvalidPatch: Schema[InvalidPatch] = Schema(schemaForCirceJson.schemaType) def decode(s: String): DecodeResult[TemporalExtent] = { temporalExtentFromString(s) match { case Left(e) => DecodeResult.Mismatch("valid timestamp", e) case Right(v) => DecodeResult.Value(v) } } // or, using the type alias for codecs in the TextPlain format and String as the raw value: implicit val teCodec: PlainCodec[TemporalExtent] = Codec.string .mapDecode(decode)(temporalExtentToString) def bboxFromString(s: String): DecodeResult[Bbox] = { val numberList = s.split(",").map(d => Try(d.toDouble).toEither) val failed = numberList.find(_.isLeft) failed match { case Some(Left(error)) => DecodeResult.Error("invalid bbox", error) case _ => { numberList.flatMap(_.toOption).toList match { case xmin :: ymin :: zmin :: xmax :: ymax :: zmax :: _ => DecodeResult.Value(ThreeDimBbox(xmin, ymin, zmin, xmax, ymax, zmax)) case xmin :: ymin :: xmax :: ymax :: _ => DecodeResult.Value(TwoDimBbox(xmin, ymin, xmax, ymax)) case _ => DecodeResult.Mismatch("must be 4 or 6 numbers separated by commas", s) } } } } def bboxToString(bbox: Bbox): String = bbox match { case ThreeDimBbox(xmin, ymin, zmin, xmax, ymax, zmax) => s"$xmin,$ymin,$zmin,$xmax,$ymax,$zmax" case TwoDimBbox(xmin, ymin, xmax, ymax) => s"$xmin,$ymin,$xmax,$ymax" } implicit val bboxCodec: PlainCodec[Bbox] = Codec.string.mapDecode(bboxFromString)(bboxToString) def commaSeparatedStrings(s: String): DecodeResult[List[String]] = DecodeResult.Value(s.split(",").toList) def listToCSV(collections: List[String]): String = collections.mkString(",") implicit val csvListCodec: PlainCodec[List[String]] = Codec.string.mapDecode(commaSeparatedStrings)(listToCSV) def decStacItem(json: Json): DecodeResult[StacItem] = json.as[StacItem] match { case Left(err) => DecodeResult.Error(err.getMessage, err) case Right(v) => DecodeResult.Value(v) } def encStacItem(stacItem: StacItem): Json = Encoder[StacItem].apply(stacItem) val jsonCodec: Codec.JsonCodec[Json] = implicitly[Codec.JsonCodec[Json]] implicit val codecStacItem: Codec.JsonCodec[StacItem] = jsonCodec.mapDecode(decStacItem)(encStacItem) implicit val codecPaginationToken: Codec.PlainCodec[PaginationToken] = Codec.string.mapDecode(PaginationToken.decPaginationToken)(PaginationToken.encPaginationToken) }
Example 133
Source File: PagingLinkExtension.scala.scala From franklin with Apache License 2.0 | 5 votes |
package com.azavea.franklin.extensions.paging import com.azavea.franklin.database.SearchFilters import com.azavea.stac4s.extensions.LinkExtension import eu.timepit.refined.types.string.NonEmptyString import io.circe.generic.semiauto._ import io.circe.refined._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Json} // https://github.com/radiantearth/stac-api-spec/blob/7a6e12868113c94b17dead8989f49d978d5dd865/api-spec.md#paging-extension // the method for us is always POST, since otherwise we toss the params in the query string // and don't use this final case class PagingLinkExtension( headers: Map[NonEmptyString, String], body: SearchFilters, merge: Boolean ) object PagingLinkExtension { implicit val decPagingLinkExtension: Decoder[PagingLinkExtension] = deriveDecoder implicit val encPagingLinkExtension: Encoder.AsObject[PagingLinkExtension] = Encoder .AsObject[Map[String, Json]] .contramapObject((linkExtensionFields: PagingLinkExtension) => Map( "method" -> "POST".asJson, "headers" -> linkExtensionFields.headers.asJson, "body" -> linkExtensionFields.body.asJson, "merge" -> linkExtensionFields.merge.asJson ) ) implicit val linkExtensionPagingLinkExtension: LinkExtension[PagingLinkExtension] = LinkExtension.instance }
Example 134
Source File: JsonObjectOptics.scala From circe-optics with Apache License 2.0 | 5 votes |
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 135
Source File: JsonOptics.scala From circe-optics with Apache License 2.0 | 5 votes |
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 136
Source File: OpticsSuite.scala From circe-optics with Apache License 2.0 | 5 votes |
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 137
Source File: CirceJsonInputOutput.scala From scala-commons with MIT License | 5 votes |
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 138
Source File: CirceYaml.scala From bazel-deps with MIT License | 5 votes |
package com.github.johnynek.bazel_deps import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import io.circe.jackson.CirceJsonModule import io.circe.{Decoder, Json, ParsingFailure, Parser} import scala.util.control.NonFatal object Yaml extends Parser { private[this] val mapper = new ObjectMapper(new YAMLFactory()).registerModule(CirceJsonModule) private[this] val factory = mapper.getFactory override def parse(input: String): Either[ParsingFailure, Json] = try { Right(mapper.readValue(factory.createParser(input), classOf[Json])) } catch { case NonFatal(error) => Left(ParsingFailure(error.getMessage, error)) } }
Example 139
Source File: RestResource.scala From pizza-auth-3 with MIT License | 5 votes |
package moe.pizza.auth.webapp.rest import moe.pizza.auth.config.ConfigFile.ConfigFile import moe.pizza.auth.graphdb.EveMapDb import moe.pizza.auth.interfaces.{PilotGrader, UserDatabase, BroadcastService} import BroadcastService._ import moe.pizza.auth.tasks.Update import moe.pizza.crestapi.CrestApi import org.http4s.{HttpService, _} import org.http4s.dsl.{Root, _} import org.http4s.server._ import org.http4s.server.staticcontent.ResourceService import org.http4s.server.syntax.ServiceOps import org.joda.time.DateTime import play.twirl.api.Html import moe.pizza.eveapi._ import scala.concurrent.ExecutionContext.Implicits.global import org.http4s.twirl._ import scala.concurrent.Future import scala.util.Try import scalaz._ import Scalaz._ import scala.util.{Success => TSuccess} import scala.util.{Failure => TFailure} import scala.concurrent.duration._ import scala.concurrent.Await import moe.pizza.crestapi.character.location.Types.Location import org.slf4j.LoggerFactory import io.circe.generic.auto._ import io.circe.syntax._ import org.http4s.circe._ import io.circe.Json import io.circe.generic.JsonCodec class RestResource(fullconfig: ConfigFile, graders: PilotGrader, portnumber: Int = 9021, ud: UserDatabase, crestapi: Option[CrestApi] = None, eve: Option[EVEAPI] = None, mapper: Option[EveMapDb] = None, updater: Option[Update] = None, broadcasters: List[BroadcastService] = List.empty[BroadcastService]) { case class ApiError(`type`: String, message: String) case class PingRequest(message: String, from: String, to: String) case class PingResponse(total: Int) def resource = HttpService { case req @ GET -> Root / "api" / "v1" / "ping" / "group" / group => { req.decode[Json] { p => p.as[PingRequest] match { case Left(failure) => BadRequest(ApiError( "bad_post_body", "Unable to process your post body, please format it correctly").asJson) case Right(pingreq) => val users = ud.getUsers(s"authgroup=${group}") val templatedMessage = templates.txt.broadcast(pingreq.message, pingreq.to, pingreq.from, DateTime.now()) val sendreqs = ud.sendGroupAnnouncement(broadcasters, templatedMessage.toString(), pingreq.from, users) val r = Await.result(Future.sequence(sendreqs), 2 seconds).sum Ok(PingResponse(r).asJson) } } } } }
Example 140
Source File: StringUnmarshaller.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.admin.directives import akka.http.scaladsl.unmarshalling.{FromStringUnmarshaller, Unmarshaller} import ch.epfl.bluebrain.nexus.admin.exceptions.AdminError.InvalidFormat import com.typesafe.scalalogging.Logger import io.circe.parser._ import io.circe.{Decoder, Json} object StringUnmarshaller { private val logger = Logger[this.type] def unmarshallJson[A: Decoder]: FromStringUnmarshaller[A] = unmarshaller { value => parse(value).left.map { err => logger.warn(s"Failed to convert string '$value' to Json", err) InvalidFormat } } private def unmarshaller[A]( f: String => Either[Throwable, Json] )(implicit dec: Decoder[A]): FromStringUnmarshaller[A] = Unmarshaller.strict[String, A] { case "" => throw Unmarshaller.NoContentException case string => f(string).flatMap(_.as[A]) match { case Right(value) => value case Left(err) => throw new IllegalArgumentException(err) } } }
Example 141
Source File: AdminError.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.admin.exceptions import akka.http.scaladsl.model.StatusCodes import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import ch.epfl.bluebrain.nexus.service.exceptions.ServiceError import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn final case object InvalidFormat extends AdminError("The json representation is incorrectly formatted.") @nowarn("cat=unused") implicit val adminErrorEncoder: Encoder[AdminError] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[AdminError].mapJson(_ addContext errorCtxUri) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } implicit val adminErrorStatusFrom: StatusFrom[AdminError] = { case NotFound => StatusCodes.NotFound case AuthenticationFailed => StatusCodes.Unauthorized case AuthorizationFailed => StatusCodes.Forbidden case InvalidFormat => StatusCodes.BadRequest case _ => StatusCodes.InternalServerError } }
Example 142
Source File: ProjectRejection.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.admin.projects import java.util.UUID import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound} import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import ch.epfl.bluebrain.nexus.service.routes.ResourceRejection import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn sealed abstract class ProjectRejection(val msg: String) extends ResourceRejection object ProjectRejection { final case class IncorrectRev(expected: Long, provided: Long) extends ProjectRejection( s"Incorrect revision '$provided' provided, expected '$expected', the project may have been updated since last seen." ) @nowarn("cat=unused") implicit val projectRejectionEncoder: Encoder[ProjectRejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[ProjectRejection].mapJson(_ addContext errorCtxUri) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } implicit val projectStatusFrom: StatusFrom[ProjectRejection] = StatusFrom { case _: IncorrectRev => Conflict case _: ProjectAlreadyExists => Conflict case _: ProjectNotFound => NotFound case _: OrganizationNotFound => NotFound case _: ProjectIsDeprecated => BadRequest case _: OrganizationIsDeprecated => BadRequest case _: InvalidProjectFormat => BadRequest } }
Example 143
Source File: Project.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.admin.projects import java.util.UUID import ch.epfl.bluebrain.nexus.rdf.Iri.{AbsoluteIri, Path} import ch.epfl.bluebrain.nexus.rdf.Iri.Path._ import io.circe.{Encoder, Json} def path: Path = organizationLabel / label } object Project { implicit val projectEncoder: Encoder[Project] = Encoder.encodeJson.contramap { p => Json .obj( "_label" -> Json.fromString(p.label), "_organizationUuid" -> Json.fromString(p.organizationUuid.toString), "_organizationLabel" -> Json.fromString(p.organizationLabel), "apiMappings" -> Json.arr(p.apiMappings.toList.map { case (prefix, namespace) => Json.obj("prefix" -> Json.fromString(prefix), "namespace" -> Json.fromString(namespace.asString)) }: _*), "base" -> Json.fromString(p.base.asString), "vocab" -> Json.fromString(p.vocab.asString) ) .deepMerge(p.description match { case Some(desc) => Json.obj("description" -> Json.fromString(desc)) case None => Json.obj() }) } }
Example 144
Source File: OrganizationRejection.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.admin.organizations import java.util.UUID import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound} import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import ch.epfl.bluebrain.nexus.service.routes.ResourceRejection import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn sealed abstract class OrganizationRejection(val msg: String) extends ResourceRejection object OrganizationRejection { final case class IncorrectRev(expected: Long, provided: Long) extends OrganizationRejection( s"Incorrect revision '$provided' provided, expected '$expected', the organization may have been updated since last seen." ) @nowarn("cat=unused") implicit val organizationRejectionEncoder: Encoder[OrganizationRejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[OrganizationRejection].mapJson(_ addContext errorCtxUri) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } implicit val organizationStatusFrom: StatusFrom[OrganizationRejection] = StatusFrom { case _: IncorrectRev => Conflict case _: OrganizationAlreadyExists => Conflict case _: OrganizationNotFound => NotFound case _: InvalidOrganizationFormat => BadRequest } }
Example 145
Source File: OrganizationEvent.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.admin.organizations import java.time.Instant import java.util.UUID import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto._ import io.circe.syntax._ import io.circe.{Encoder, Json} import scala.annotation.nowarn final case class OrganizationDeprecated( id: UUID, rev: Long, instant: Instant, subject: Subject ) extends OrganizationEvent object JsonLd { @nowarn("cat=unused") implicit private val config: Configuration = Configuration.default .withDiscriminator("@type") .copy(transformMemberNames = { case nxv.`@id`.name => nxv.uuid.prefix case nxv.label.name => nxv.label.prefix case nxv.rev.name => nxv.rev.prefix case nxv.instant.name => nxv.instant.prefix case nxv.eventSubject.name => nxv.eventSubject.prefix case other => other }) @nowarn("cat=unused") implicit private def subjectIdEncoder(implicit http: HttpConfig): Encoder[Subject] = Encoder.encodeJson.contramap(_.id.asJson) @nowarn("cat=unused") implicit final def orgEventEncoder(implicit http: HttpConfig): Encoder[OrganizationEvent] = Encoder.encodeJson.contramap[OrganizationEvent] { ev => deriveConfiguredEncoder[OrganizationEvent] .mapJson { json => val rev = Json.obj(nxv.rev.prefix -> Json.fromLong(ev.rev)) json .deepMerge(rev) .addContext(adminCtxUri) .addContext(resourceCtxUri) } .apply(ev) } } }
Example 146
Source File: StaticResourceRoutes.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.http.routes import java.util.regex.Pattern.quote import akka.http.scaladsl.model.Uri import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport._ import ch.epfl.bluebrain.nexus.commons.http.directives.PrefixDirectives import io.circe.Json import io.circe.parser.parse import scala.io.Source class StaticResourceRoutes(resourcePaths: Map[String, String], prefix: String, baseUri: Uri) extends PrefixDirectives { private def contentOf(file: String): String = { val source = Source.fromInputStream(getClass.getResourceAsStream(file)) val contents = source.mkString source.close() contents } private def contentOf(file: String, replacements: Map[String, String]): String = replacements.foldLeft(contentOf(file)) { case (value, (regex, replacement)) => value.replaceAll(regex, replacement) } private val baseReplacement: Map[String, String] = Map(quote("{{base}}") -> baseUri.toString) private lazy val resources: Map[String, Json] = resourcePaths.view .mapValues { resource => parse(contentOf(resource, baseReplacement)).toOption } .flatMap { case (key, value) => value match { case Some(v) => Some((key, v)) case None => None } } .toMap def routes: Route = uriPrefix(baseUri) { (get & pathPrefix(prefix)) { extractUnmatchedPath { resourcePath => resources.get(resourcePath.toString) match { case Some(json) => complete(json) case None => reject } } } } }
Example 147
Source File: ElasticSearchDecoder.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.es.client import cats.implicits._ import ch.epfl.bluebrain.nexus.commons.search.QueryResult.{ScoredQueryResult, UnscoredQueryResult} import ch.epfl.bluebrain.nexus.commons.search.{QueryResult, QueryResults} import ch.epfl.bluebrain.nexus.commons.search.QueryResults.{ScoredQueryResults, UnscoredQueryResults} import io.circe.{Decoder, Json} class ElasticSearchDecoder[A](implicit D: Decoder[A]) { private type ErrorOrResults = Either[Json, List[QueryResult[A]]] private def queryResults(json: Json, scored: Boolean): ErrorOrResults = { def queryResult(result: Json): Option[QueryResult[A]] = { result.hcursor.get[A]("_source") match { case Right(s) if scored => Some(ScoredQueryResult(result.hcursor.get[Float]("_score").getOrElse(0f), s)) case Right(s) => Some(UnscoredQueryResult(s)) case _ => None } } val hitsList = json.hcursor.downField("hits").downField("hits").focus.flatMap(_.asArray).getOrElse(Vector.empty) hitsList .foldM(List.empty[QueryResult[A]])((acc, json) => queryResult(json).map(_ :: acc).toRight(json)) .map(_.reverse) } private def token(json: Json): Option[String] = { val hits = json.hcursor.downField("hits").downField("hits") val length = hits.values.fold(1)(_.size) hits.downN(length - 1).downField("sort").focus.map(_.noSpaces) } private def decodeScoredQueryResults(maxScore: Float): Decoder[QueryResults[A]] = Decoder.decodeJson.emap { json => queryResults(json, scored = true) match { case Right(list) => Right(ScoredQueryResults(fetchTotal(json), maxScore, list, token(json))) // $COVERAGE-OFF$ case Left(errJson) => Left(s"Could not decode source from value '$errJson'") // $COVERAGE-ON$ } } private val decodeUnscoredResults: Decoder[QueryResults[A]] = Decoder.decodeJson.emap { json => queryResults(json, scored = false) match { case Right(list) => Right(UnscoredQueryResults(fetchTotal(json), list, token(json))) // $COVERAGE-OFF$ case Left(errJson) => Left(s"Could not decode source from value '$errJson'") // $COVERAGE-ON$ } } private def fetchTotal(json: Json): Long = json.hcursor.downField("hits").downField("total").get[Long]("value").getOrElse(0L) val decodeQueryResults: Decoder[QueryResults[A]] = Decoder.decodeJson.flatMap( _.hcursor.downField("hits").get[Float]("max_score").toOption.filterNot(f => f.isInfinite || f.isNaN) match { case Some(maxScore) => decodeScoredQueryResults(maxScore) case None => decodeUnscoredResults } ) } object ElasticSearchDecoder { final def apply[A](implicit D: Decoder[A]): Decoder[QueryResults[A]] = new ElasticSearchDecoder[A].decodeQueryResults }
Example 148
Source File: TagRoutes.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import akka.http.scaladsl.model.StatusCodes.{Created, OK} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import ch.epfl.bluebrain.nexus.admin.client.types.Project import ch.epfl.bluebrain.nexus.iam.acls.Acls import ch.epfl.bluebrain.nexus.iam.realms.Realms import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject import ch.epfl.bluebrain.nexus.iam.types.{Caller, Permission} import ch.epfl.bluebrain.nexus.kg.config.Contexts.tagCtxUri import ch.epfl.bluebrain.nexus.kg.directives.ProjectDirectives._ import ch.epfl.bluebrain.nexus.kg.marshallers.instances._ import ch.epfl.bluebrain.nexus.kg.resources._ import ch.epfl.bluebrain.nexus.kg.resources.syntax._ import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.Iri.Path._ import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import ch.epfl.bluebrain.nexus.service.directives.AuthDirectives import io.circe.syntax._ import io.circe.{Encoder, Json} import kamon.Kamon import kamon.instrumentation.akka.http.TracingDirectives.operationName import monix.eval.Task import monix.execution.Scheduler.Implicits.global class TagRoutes private[routes] ( resourceType: String, tags: Tags[Task], acls: Acls[Task], realms: Realms[Task], schema: Ref, write: Permission )(implicit caller: Caller, project: Project, config: ServiceConfig ) extends AuthDirectives(acls, realms) { private val projectPath = project.organizationLabel / project.label implicit private val subject: Subject = caller.subject def routes(id: AbsoluteIri): Route = // Consume the tag segment pathPrefix("tags") { concat( // Create tag (post & parameter("rev".as[Long]) & pathEndOrSingleSlash) { rev => operationName(opName) { (authorizeFor(projectPath, write) & projectNotDeprecated) { entity(as[Json]) { source => Kamon.currentSpan().tag("resource.operation", "create") complete(tags.create(Id(project.ref, id), rev, source, schema).value.runWithStatus(Created)) } } } }, // Fetch a tag (get & projectNotDeprecated & pathEndOrSingleSlash) { operationName(opName) { authorizeFor(projectPath, read)(caller) { parameter("rev".as[Long].?) { case Some(rev) => complete(tags.fetch(Id(project.ref, id), rev, schema).value.runWithStatus(OK)) case _ => complete(tags.fetch(Id(project.ref, id), schema).value.runWithStatus(OK)) } } } } ) } implicit private def tagsEncoder: Encoder[TagSet] = Encoder.instance(tags => Json.obj("tags" -> Json.arr(tags.map(_.asJson).toSeq: _*)).addContext(tagCtxUri)) private def opName: String = resourceType match { case "resources" => s"/${config.http.prefix}/resources/{org}/{project}/{schemaId}/{id}/tags" case _ => s"/${config.http.prefix}/$resourceType/{org}/{project}/{id}/tags" } }
Example 149
Source File: Clients.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import ch.epfl.bluebrain.nexus.admin.client.AdminClient import ch.epfl.bluebrain.nexus.commons.es.client.ElasticSearchClient import ch.epfl.bluebrain.nexus.commons.http.HttpClient import ch.epfl.bluebrain.nexus.commons.http.HttpClient.UntypedHttpClient import ch.epfl.bluebrain.nexus.commons.search.QueryResults import ch.epfl.bluebrain.nexus.commons.sparql.client.BlazegraphClient import ch.epfl.bluebrain.nexus.storage.client.StorageClient import io.circe.Json import monix.eval.Task final case class Clients[F[_]]()(implicit val sparql: BlazegraphClient[F], val elasticSearch: ElasticSearchClient[F], val admin: AdminClient[F], val defaultRemoteStorage: StorageClient[F], val rsSearch: HttpClient[F, QueryResults[Json]], val http: UntypedHttpClient[Task], val uclJson: HttpClient[Task, Json] ) object Clients { implicit def esClient[F[_]](implicit clients: Clients[F]): ElasticSearchClient[F] = clients.elasticSearch implicit def sparqlClient[F[_]](implicit clients: Clients[F]): BlazegraphClient[F] = clients.sparql }
Example 150
Source File: ArchiveRoutes.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import akka.http.scaladsl.model.StatusCodes.{Created, OK} import akka.http.scaladsl.model.headers.Accept import akka.http.scaladsl.model.{HttpEntity, MediaTypes} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import ch.epfl.bluebrain.nexus.admin.client.types.Project import ch.epfl.bluebrain.nexus.iam.acls.Acls import ch.epfl.bluebrain.nexus.iam.realms.Realms import ch.epfl.bluebrain.nexus.iam.types.Caller import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject import ch.epfl.bluebrain.nexus.kg.KgError.{InvalidOutputFormat, UnacceptedResponseContentType} import ch.epfl.bluebrain.nexus.kg.archives.Archive._ import ch.epfl.bluebrain.nexus.kg.directives.PathDirectives._ import ch.epfl.bluebrain.nexus.kg.directives.ProjectDirectives._ import ch.epfl.bluebrain.nexus.kg.directives.QueryDirectives.outputFormat import ch.epfl.bluebrain.nexus.kg.marshallers.instances._ import ch.epfl.bluebrain.nexus.kg.resources._ import ch.epfl.bluebrain.nexus.kg.resources.syntax._ import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.Tar import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.Iri.Path._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import ch.epfl.bluebrain.nexus.service.directives.AuthDirectives import io.circe.Json import kamon.instrumentation.akka.http.TracingDirectives.operationName import monix.eval.Task import monix.execution.Scheduler.Implicits.global class ArchiveRoutes private[routes] (archives: Archives[Task], acls: Acls[Task], realms: Realms[Task])(implicit project: Project, caller: Caller, config: ServiceConfig ) extends AuthDirectives(acls, realms) { private val responseType = MediaTypes.`application/x-tar` private val projectPath = project.organizationLabel / project.label implicit private val subject: Subject = caller.subject def routes(id: AbsoluteIri): Route = { val resId = Id(project.ref, id) concat( // Create archive (put & pathEndOrSingleSlash) { operationName(s"/${config.http.prefix}/archives/{org}/{project}/{id}") { (authorizeFor(projectPath, write) & projectNotDeprecated) { entity(as[Json]) { source => complete(archives.create(resId, source).value.runWithStatus(Created)) } } } }, // Fetch archive (get & outputFormat(strict = true, Tar) & pathEndOrSingleSlash) { case Tar => getArchive(resId) case format: NonBinaryOutputFormat => getResource(resId)(format) case other => failWith(InvalidOutputFormat(other.toString)) } ) } private def getResource(resId: ResId)(implicit format: NonBinaryOutputFormat): Route = completeWithFormat(archives.fetch(resId).value.runWithStatus(OK)) private def getArchive(resId: ResId): Route = { (parameter("ignoreNotFound".as[Boolean] ? false) & extractCallerAcls(anyProject)) { (ignoreNotFound, acls) => onSuccess(archives.fetchArchive(resId, ignoreNotFound)(acls, caller).value.runToFuture) { case Right(source) => headerValueByType[Accept](()) { accept => if (accept.mediaRanges.exists(_.matches(responseType))) complete(HttpEntity(responseType, source)) else failWith( UnacceptedResponseContentType( s"File Media Type '$responseType' does not match the Accept header value '${accept.mediaRanges.mkString(", ")}'" ) ) } case Left(err) => complete(err) } } } }
Example 151
Source File: ResourceEncoder.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import ch.epfl.bluebrain.nexus.admin.client.types.Project import ch.epfl.bluebrain.nexus.kg.config.Contexts.{resourceCtx, resourceCtxUri} import ch.epfl.bluebrain.nexus.kg.resources.{Resource, ResourceV} import ch.epfl.bluebrain.nexus.kg.resources.Views._ import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.{Compacted, Expanded} import ch.epfl.bluebrain.nexus.rdf.Graph import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.Json object ResourceEncoder { def json(r: Resource)(implicit config: ServiceConfig, project: Project): Either[String, Json] = Graph(r.id.value, r.metadata()).toJson(resourceCtx).map(_.replaceContext(resourceCtxUri)) def json(res: ResourceV)(implicit output: JsonLDOutputFormat): Either[String, Json] = output match { case Compacted => jsonCompacted(res) case Expanded => jsonExpanded(res) } private val resourceKeys: List[String] = resourceCtx.contextValue.asObject.map(_.keys.toList).getOrElse(List.empty) private def jsonCompacted(res: ResourceV): Either[String, Json] = { val flattenedContext = Json.obj("@context" -> res.value.ctx) mergeContext resourceCtx res.value.graph.toJson(flattenedContext).map { fieldsJson => val contextJson = Json.obj("@context" -> res.value.source.contextValue.removeKeys(resourceKeys: _*)).addContext(resourceCtxUri) val json = fieldsJson deepMerge contextJson if (res.types.contains(nxv.View.value)) transformFetch(json) else json } } private def jsonExpanded(r: ResourceV): Either[String, Json] = r.value.graph.toJson() }
Example 152
Source File: RejectionEncoder.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.routes import cats.implicits._ import ch.epfl.bluebrain.nexus.admin.client.types.Project import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidJsonLD import ch.epfl.bluebrain.nexus.kg.resources.{Rejection, Resource, ResourceV} import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.Compacted import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import io.circe.Json def apply(value: A): Either[Rejection, Json] } object RejectionEncoder { implicit final def rejectionEncoder(implicit outputFormat: JsonLDOutputFormat = Compacted ): RejectionEncoder[ResourceV] = new RejectionEncoder[ResourceV] { override def apply(value: ResourceV): Either[Rejection, Json] = ResourceEncoder.json(value).leftMap(err => InvalidJsonLD(err)) } implicit final def rejectionEncoder(implicit config: ServiceConfig, project: Project): RejectionEncoder[Resource] = new RejectionEncoder[Resource] { override def apply(value: Resource): Either[Rejection, Json] = ResourceEncoder.json(value).leftMap(err => InvalidJsonLD(err)) } }
Example 153
package ch.epfl.bluebrain.nexus.kg.resources import cats.implicits._ import ch.epfl.bluebrain.nexus.kg.config.Contexts._ import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.syntax._ import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.rdf.{GraphDecoder, NonEmptyString} import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.{Encoder, Json} final def apply(resId: ResId, json: Json): Either[Rejection, Tag] = { val completeJson = (json deepMerge tagCtx).id(resId.value) for { g <- completeJson.toGraph(resId.value).leftMap(_ => InvalidResourceFormat(resId.ref, "Empty or wrong Json-LD.")) t <- tagGraphDecoder(g.cursor).leftRejectionFor(resId.ref) } yield t } // format: on implicit final val tagEncoder: Encoder[Tag] = Encoder.instance { case Tag(rev, tag) => Json.obj("tag" -> Json.fromString(tag), "rev" -> Json.fromLong(rev)) } implicit final val tagGraphDecoder: GraphDecoder[Tag] = GraphDecoder.instance { c => for { rev <- c.down(nxv.rev).as[Long] tag <- c.down(nxv.tag).as[NonEmptyString].map(_.asString) } yield Tag(rev, tag) } }
Example 154
Source File: IdentifiedProgress.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.indexing import cats.Functor import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import io.circe.{Encoder, Json} import io.circe.syntax._ final case class IdentifiedProgress[A](sourceId: Option[AbsoluteIri], projectionId: Option[AbsoluteIri], value: A) object IdentifiedProgress { def apply[A](sourceId: AbsoluteIri, projectionId: AbsoluteIri, value: A): IdentifiedProgress[A] = IdentifiedProgress(Some(sourceId), Some(projectionId), value) def apply[A](sourceId: AbsoluteIri, value: A): IdentifiedProgress[A] = IdentifiedProgress(Some(sourceId), None, value) def apply[A](value: A): IdentifiedProgress[A] = IdentifiedProgress(None, None, value) private def optionalIdJson(prefix: String, value: Option[AbsoluteIri]): Json = value.map(id => Json.obj(prefix -> id.asString.asJson)).getOrElse(Json.obj()) implicit val functorProgress: Functor[IdentifiedProgress] = new Functor[IdentifiedProgress] { override def map[A, B](fa: IdentifiedProgress[A])(f: A => B): IdentifiedProgress[B] = fa.copy(value = f(fa.value)) } implicit def encoderProgressIdentifiedValue[A: Encoder]: Encoder[IdentifiedProgress[A]] = Encoder.instance { case IdentifiedProgress(sourceId, projectionId, value) => optionalIdJson("sourceId", sourceId) deepMerge optionalIdJson( "projectionId", projectionId ) deepMerge value.asJson } implicit def orderingIdentifiedProgress[A]: Ordering[IdentifiedProgress[A]] = (x: IdentifiedProgress[A], y: IdentifiedProgress[A]) => { val sourceId1 = x.sourceId.map(_.asString).getOrElse("") val sourceId2 = y.sourceId.map(_.asString).getOrElse("") val projectionId1 = x.projectionId.map(_.asString).getOrElse("") val projectionId2 = y.projectionId.map(_.asString).getOrElse("") s"$sourceId1$projectionId1" compareTo s"$sourceId2$projectionId2" } }
Example 155
Source File: QueryResultEncoder.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.search import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.Query import ch.epfl.bluebrain.nexus.commons.search.QueryResult.{ScoredQueryResult, UnscoredQueryResult} import ch.epfl.bluebrain.nexus.commons.search.QueryResults.{ScoredQueryResults, UnscoredQueryResults} import ch.epfl.bluebrain.nexus.commons.search.{FromPagination, QueryResult, QueryResults} import ch.epfl.bluebrain.nexus.kg.config.Contexts.{resourceCtxUri, searchCtxUri} import ch.epfl.bluebrain.nexus.kg.directives.QueryDirectives.{after, from, size} import ch.epfl.bluebrain.nexus.kg.indexing.SparqlLink import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.syntax._ import io.circe.{Encoder, Json} trait LowPriorityQueryResultsEncoder { implicit def qrsEncoderLowPrio[A: Encoder]: Encoder[QueryResults[A]] = Encoder.instance(qrsEncoderJsonLinks[A](None).apply(_)) implicit private val uriEncoder: Encoder[Uri] = Encoder.encodeString.contramap(_.toString) protected def qrsEncoderJsonLinks[A: Encoder](next: Option[Uri]): Encoder[QueryResults[A]] = { implicit def qrEncoderJson: Encoder[QueryResult[A]] = Encoder.instance { case UnscoredQueryResult(v) => v.asJson.removeKeys(nxv.original_source.prefix) case ScoredQueryResult(score, v) => v.asJson.removeKeys(nxv.original_source.prefix) deepMerge Json.obj(nxv.score.prefix -> Json.fromFloatOrNull(score)) } def json(total: Long, list: List[QueryResult[A]]): Json = Json .obj(nxv.total.prefix -> Json.fromLong(total), nxv.results.prefix -> Json.arr(list.map(qrEncoderJson(_)): _*)) .addContext(searchCtxUri) .addContext(resourceCtxUri) Encoder.instance { case UnscoredQueryResults(total, list, _) => json(total, list) deepMerge Json.obj(nxv.next.prefix -> next.asJson) case ScoredQueryResults(total, maxScore, list, _) => json(total, list) deepMerge Json.obj(nxv.maxScore.prefix -> maxScore.asJson, nxv.next.prefix -> next.asJson) } } } object QueryResultEncoder extends LowPriorityQueryResultsEncoder { implicit def qrsEncoderJson(implicit searchUri: Uri, http: HttpConfig): Encoder[QueryResults[Json]] = Encoder.instance { results => val nextLink = results.token.flatMap(next(searchUri, _)) qrsEncoderJsonLinks[Json](nextLink).apply(results) } implicit def qrsEncoderJson(implicit searchUri: Uri, pagination: FromPagination, http: HttpConfig ): Encoder[QueryResults[SparqlLink]] = Encoder.instance { results => val nextLink = next(searchUri, results.total, pagination) qrsEncoderJsonLinks[SparqlLink](nextLink).apply(results) } private def next(current: Uri, total: Long, pagination: FromPagination)(implicit http: HttpConfig): Option[Uri] = { val nextFrom = pagination.from + pagination.size if (nextFrom < total.toInt) { val params = current.query().toMap + (from -> nextFrom.toString) + (size -> pagination.size.toString) Some(toPublic(current).withQuery(Query(params))) } else None } private def next(current: Uri, afterToken: String)(implicit http: HttpConfig): Option[Uri] = current.query().get(after) match { case Some(`afterToken`) => None case _ => val params = current.query().toMap + (after -> afterToken) - from Some(toPublic(current).withQuery(Query(params))) } private def toPublic(uri: Uri)(implicit http: HttpConfig): Uri = uri.copy(scheme = http.publicUri.scheme, authority = http.publicUri.authority) }
Example 156
Source File: QueryBuilder.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.search import ch.epfl.bluebrain.nexus.kg.routes.SearchParams import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.syntax._ import io.circe.{Encoder, Json} import ch.epfl.bluebrain.nexus.kg.indexing.View.ElasticSearchView._ import ch.epfl.bluebrain.nexus.service.config.Vocabulary._ object QueryBuilder { private def baseQuery(terms: List[Json], withScore: Boolean): Json = { val eval = if (withScore) "must" else "filter" Json.obj("query" -> Json.obj("bool" -> Json.obj(eval -> Json.arr(terms: _*)))) } private def term[A: Encoder](k: String, value: A): Json = Json.obj("term" -> Json.obj(k -> value.asJson)) private def `match`[A: Encoder](k: String, value: A): Json = Json.obj("match" -> Json.obj(k -> value.asJson)) def queryFor(params: SearchParams): Json = baseQuery( terms = params.types.map(term("@type", _)) ++ params.id.map(term("@id", _)) ++ params.q .map(`match`(allField, _)) ++ params.schema.map(term(nxv.constrainedBy.prefix, _)) ++ params.deprecated .map(term(nxv.deprecated.prefix, _)) ++ params.rev.map(term(nxv.rev.prefix, _)) ++ params.createdBy .map(term(nxv.createdBy.prefix, _)) ++ params.updatedBy.map(term(nxv.updatedBy.prefix, _)), withScore = params.q.isDefined ) }
Example 157
Source File: Schemas.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.config import ch.epfl.bluebrain.nexus.commons.test.Resources._ import ch.epfl.bluebrain.nexus.kg.config.Contexts._ import ch.epfl.bluebrain.nexus.kg.resources.syntax._ import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json import org.apache.jena.rdf.model.Model @SuppressWarnings(Array("OptionGet")) object Schemas { val base = url"https://bluebrain.github.io/nexus/schemas/" //Schema URIs val shaclSchemaUri: AbsoluteIri = base + "shacl-20170720.ttl" val resolverSchemaUri: AbsoluteIri = base + "resolver.json" val unconstrainedSchemaUri: AbsoluteIri = base + "unconstrained.json" val fileSchemaUri: AbsoluteIri = base + "file.json" val viewSchemaUri: AbsoluteIri = base + "view.json" val storageSchemaUri: AbsoluteIri = base + "storage.json" val archiveSchemaUri: AbsoluteIri = base + "archive.json" val ontologySchemaUri: AbsoluteIri = base + "ontology.json" //Schema payloads val resolverSchema: Json = jsonContentOf("/schemas/resolver.json") val viewSchema: Json = jsonContentOf("/schemas/view.json") val storageSchema: Json = jsonContentOf("/schemas/storage.json") val archiveSchema: Json = jsonContentOf("/schemas/archive.json") //Schema models val resolverSchemaModel: Model = resolveSchema(resolverSchema).toGraph(resolverSchemaUri).toOption.get.asJena val viewSchemaModel: Model = resolveSchema(viewSchema).toGraph(viewSchemaUri).toOption.get.asJena val storageSchemaModel: Model = resolveSchema(storageSchema).toGraph(storageSchemaUri).toOption.get.asJena val archiveSchemaModel: Model = resolveSchema(archiveSchema).toGraph(archiveSchemaUri).toOption.get.asJena // Schema references val viewRef = viewSchemaUri.ref val storageRef = storageSchemaUri.ref val archiveRef = archiveSchemaUri.ref val resolverRef = resolverSchemaUri.ref val unconstrainedRef = unconstrainedSchemaUri.ref val shaclRef = shaclSchemaUri.ref val fileRef = fileSchemaUri.ref private def resolveSchema(schema: Json): Json = { val ctx = schema.hcursor.downField("@context").as[Json].getOrElse(Json.obj()) schema.replaceContext(Json.obj("@context" -> removeContextIris(ctx))).appendContextOf(shaclCtx) } private def removeContextIris(ctx: Json): Json = (ctx.asString, ctx.asObject, ctx.asArray) match { case (Some(_), _, _) => Json.obj() case (_, Some(_), _) => ctx case (_, _, Some(arr)) => Json.arr(arr.filter(!_.isString): _*) case _ => ctx } }
Example 158
Source File: Contexts.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.config import ch.epfl.bluebrain.nexus.commons.test.Resources._ import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json object Contexts { val base = url"https://bluebrain.github.io/nexus/contexts/" val errorCtxUri: AbsoluteIri = base + "error.json" val tagCtxUri: AbsoluteIri = base + "tag.json" val archiveCtxUri: AbsoluteIri = base + "archive.json" val fileAttrCtxUri: AbsoluteIri = base + "file-attr.json" val statisticsCtxUri: AbsoluteIri = base + "statistics.json" val offsetCtxUri: AbsoluteIri = base + "offset.json" val resourceCtxUri: AbsoluteIri = base + "resource.json" val resolverCtxUri: AbsoluteIri = base + "resolver.json" val viewCtxUri: AbsoluteIri = base + "view.json" val storageCtxUri: AbsoluteIri = base + "storage.json" val shaclCtxUri: AbsoluteIri = base + "shacl-20170720.json" val searchCtxUri: AbsoluteIri = base + "search.json" val tagCtx: Json = jsonContentOf("/contexts/tags-context.json") val archiveCtx: Json = jsonContentOf("/contexts/archive-context.json") val fileAttrCtx: Json = jsonContentOf("/contexts/file-attr-context.json") val statisticsCtx: Json = jsonContentOf("/contexts/statistics-context.json") val offsetCtx: Json = jsonContentOf("/contexts/offset-context.json") val resourceCtx: Json = jsonContentOf("/contexts/resource-context.json") val resolverCtx: Json = jsonContentOf("/contexts/resolver-context.json") val viewCtx: Json = jsonContentOf("/contexts/view-context.json") val storageCtx: Json = jsonContentOf("/contexts/storage-context.json") val shaclCtx: Json = jsonContentOf("/contexts/shacl-context.json") val searchCtx: Json = jsonContentOf("/contexts/search-context.json") }
Example 159
Source File: AclRejection.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.acls import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound} import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom import ch.epfl.bluebrain.nexus.iam.types.Permission import ch.epfl.bluebrain.nexus.rdf.Iri.Path import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts.errorCtxUri import ch.epfl.bluebrain.nexus.service.routes.ResourceRejection import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn sealed abstract class AclRejection(val msg: String) extends ResourceRejection object AclRejection { final case class UnknownPermissions(permissions: Set[Permission]) extends AclRejection( s"Some of the permissions specified are not known: '${permissions.mkString("\"", ", ", "\"")}'" ) @nowarn("cat=unused") implicit val aclRejectionEncoder: Encoder[AclRejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[AclRejection].mapJson(_ addContext errorCtxUri) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } implicit val aclRejectionStatusFrom: StatusFrom[AclRejection] = StatusFrom { case _: NothingToBeUpdated => BadRequest case _: AclIsEmpty => BadRequest case _: AclCannotContainEmptyPermissionCollection => BadRequest case _: AclNotFound => NotFound case _: IncorrectRev => Conflict case _: UnknownPermissions => BadRequest } }
Example 160
Source File: ActiveRealm.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.realms import ch.epfl.bluebrain.nexus.iam.types.GrantType.Camel._ import ch.epfl.bluebrain.nexus.iam.types.{GrantType, Label} import ch.epfl.bluebrain.nexus.rdf.Iri.Url import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import com.nimbusds.jose.jwk.{JWK, JWKSet} import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.util.Try final case class ActiveRealm( id: Label, name: String, openIdConfig: Url, issuer: String, grantTypes: Set[GrantType], logo: Option[Url], authorizationEndpoint: Url, tokenEndpoint: Url, userInfoEndpoint: Url, revocationEndpoint: Option[Url], endSessionEndpoint: Option[Url], keys: Set[Json] ) { private[realms] lazy val keySet: JWKSet = { val jwks = keys.foldLeft(Set.empty[JWK]) { case (acc, e) => Try(JWK.parse(e.noSpaces)).map(acc + _).getOrElse(acc) } import scala.jdk.CollectionConverters._ new JWKSet(jwks.toList.asJava) } } object ActiveRealm { implicit private[ActiveRealm] val config: Configuration = Configuration.default.copy(transformMemberNames = { case "issuer" => nxv.issuer.prefix case "grantTypes" => nxv.grantTypes.prefix case "authorizationEndpoint" => nxv.authorizationEndpoint.prefix case "tokenEndpoint" => nxv.tokenEndpoint.prefix case "userInfoEndpoint" => nxv.userInfoEndpoint.prefix case "revocationEndpoint" => nxv.revocationEndpoint.prefix case "endSessionEndpoint" => nxv.endSessionEndpoint.prefix case other => other }) implicit val activeEncoder: Encoder[ActiveRealm] = { val default = deriveConfiguredEncoder[ActiveRealm] Encoder .instance[ActiveRealm] { realm => default(realm) deepMerge Json.obj( nxv.label.prefix -> Json.fromString(realm.id.value), nxv.deprecated.prefix -> Json.fromBoolean(false) ) } .mapJson(_.removeKeys("keys", "id")) } }
Example 161
Source File: ResourceF.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import java.time.Instant import ch.epfl.bluebrain.nexus.iam.syntax._ import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.syntax._ import io.circe.{Encoder, Json} def unit( id: AbsoluteIri, rev: Long, types: Set[AbsoluteIri], createdAt: Instant, createdBy: Subject, updatedAt: Instant, updatedBy: Subject ): ResourceF[Unit] = ResourceF(id, rev, types, createdAt, createdBy, updatedAt, updatedBy, ()) implicit val permsEncoder: Encoder[Set[Permission]] = Encoder.instance(perms => Json.obj("permissions" -> Json.fromValues(perms.toList.sortBy(_.value).map(_.asJson)))) implicit def resourceFEncoder[A: Encoder](implicit http: HttpConfig): Encoder[ResourceF[A]] = Encoder.encodeJson.contramap { r => resourceMetaEncoder.apply(r.discard) deepMerge r.value.asJson } implicit def resourceMetaEncoder(implicit http: HttpConfig): Encoder[ResourceMetadata] = Encoder.encodeJson.contramap { case ResourceF(id, rev, types, createdAt, createdBy, updatedAt, updatedBy, _: Unit) => val jsonTypes = types.toList match { case Nil => Json.Null case t :: Nil => Json.fromString(t.lastSegment.getOrElse(t.asString)) case _ => Json.arr(types.map(t => Json.fromString(t.lastSegment.getOrElse(t.asString))).toSeq: _*) } Json .obj( "@id" -> id.asJson, "@type" -> jsonTypes, nxv.rev.prefix -> Json.fromLong(rev), nxv.createdBy.prefix -> createdBy.id.asJson, nxv.updatedBy.prefix -> updatedBy.id.asJson, nxv.createdAt.prefix -> Json.fromString(createdAt.toString), nxv.updatedAt.prefix -> Json.fromString(updatedAt.toString) ) .addContext(iamCtxUri) .addContext(resourceCtxUri) } }
Example 162
Source File: Caller.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import ch.epfl.bluebrain.nexus.iam.acls.AccessControlLists import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Subject} import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectLabel import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import io.circe.{Encoder, Json} val anonymous: Caller = Caller(Anonymous: Subject, Set[Identity](Anonymous)) object JsonLd { implicit final def callerEncoder(implicit I: Encoder[Identity], http: HttpConfig ): Encoder[Caller] = Encoder.instance[Caller] { caller => Json .obj( "identities" -> Encoder.encodeList(I)(caller.identities.toList.sortBy(_.id.asUri)) ) .addContext(iamCtxUri) .addContext(resourceCtxUri) } } }
Example 163
Source File: TokenRejection.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.auth import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn final case object InvalidAccessToken extends TokenRejection( "The token is invalid; possible causes are: incorrect signature, the token is expired or the 'nbf' value was not met." ) @nowarn("cat=unused") implicit val tokenRejectionEncoder: Encoder[TokenRejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[TokenRejection] Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } }
Example 164
Source File: ServiceError.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.service.exceptions import ch.epfl.bluebrain.nexus.admin.exceptions.AdminError import ch.epfl.bluebrain.nexus.iam.types.IamError import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.Contexts._ import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn @SuppressWarnings(Array("IncorrectlyNamedExceptions")) abstract class ServiceError(val msg: String) extends Exception with Product with Serializable object ServiceError { @SuppressWarnings(Array("IncorrectlyNamedExceptions")) final case class InternalError(reason: String) extends ServiceError(reason) @nowarn("cat=unused") implicit val internalErrorEncoder: Encoder[InternalError] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[InternalError].mapJson(_ addContext errorCtxUri) Encoder.instance(r => { enc(r) deepMerge Json .obj("@type" -> Json.fromString(r.getClass.getSimpleName), "reason" -> Json.fromString(r.msg)) }) } implicit val serviceErrorEncoder: Encoder[ServiceError] = Encoder.instance { case i: IamError => IamError.iamErrorEncoder(i) case a: AdminError => AdminError.adminErrorEncoder(a) case r => Json.obj( "@type" -> Json.fromString(r.getClass.getSimpleName), "reason" -> Json.fromString(r.msg) ) addContext errorCtxUri } }
Example 165
Source File: QueryResultsSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.search import cats.syntax.functor._ import ch.epfl.bluebrain.nexus.commons.search.QueryResult._ import ch.epfl.bluebrain.nexus.commons.search.QueryResults._ import io.circe.Json import io.circe.generic.auto._ import io.circe.syntax._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class QueryResultsSpec extends AnyWordSpecLike with Matchers { "A QueryResults Functor" should { "transform the source and score values of the results" in { val qrs = ScoredQueryResults(1L, 1f, List(ScoredQueryResult(1f, 1))) qrs.map(_ + 1) shouldEqual ScoredQueryResults(1L, 1f, List(ScoredQueryResult(1f, 2))) } "transform the score values of the results" in { val qrs = UnscoredQueryResults(1L, List(UnscoredQueryResult(1))) qrs.map(_ + 1) shouldEqual UnscoredQueryResults(1L, List(UnscoredQueryResult(2))) } "transform the generic queryResults values" in { val qrs = UnscoredQueryResults(1L, List(UnscoredQueryResult(1))): QueryResults[Int] qrs.map(_ + 1) shouldEqual UnscoredQueryResults(1L, List(UnscoredQueryResult(2))) } "encodes a queryResults" in { val result = ScoredQueryResult(1f, 1): QueryResult[Int] val results = ScoredQueryResults(10L, 1f, List(result), Some("token")): QueryResults[Int] results.asJson shouldEqual Json.obj( "total" -> Json.fromLong(results.total), "token" -> Json.fromString("token"), "maxScore" -> Json.fromFloatOrNull(1f), "results" -> Json.arr(result.asJson) ) } "build from apply method" in { QueryResults(0L, List.empty[QueryResult[Int]]) shouldEqual UnscoredQueryResults(0L, List.empty[QueryResult[Int]]) QueryResults(0L, 1f, List.empty[QueryResult[Int]]) shouldEqual ScoredQueryResults( 0L, 1f, List.empty[QueryResult[Int]] ) } "change the underlying list type with copy method" in { val unscored = QueryResults(1L, List(UnscoredQueryResult(1))) unscored.copyWith(unscored.results.map(_.map(_.toString))) shouldEqual QueryResults( 1L, List(UnscoredQueryResult("1")) ) val scored = QueryResults(1L, List(ScoredQueryResult(1f, 1))) scored.copyWith(scored.results.map(_.map(_.toString))) shouldEqual QueryResults( 1L, List(ScoredQueryResult(1f, "1")) ) } } }
Example 166
Source File: QueryResultSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.search import cats.syntax.functor._ import ch.epfl.bluebrain.nexus.commons.search.QueryResult.ScoredQueryResult import io.circe.generic.auto._ import io.circe.{Encoder, Json} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class QueryResultSpec extends AnyWordSpecLike with Matchers { "A QueryResult Functor" should { implicit val queryResultEncoder: Encoder[ScoredQueryResult[Int]] = Encoder.encodeJson.contramap { qr => Json.obj( "resultId" -> Json.fromString("/some/path"), "score" -> Json.fromFloatOrString(qr.score), "source" -> Json.fromInt(qr.source) ) } "transform the source value" in { ScoredQueryResult(1f, 1).map(_ + 1) shouldEqual ScoredQueryResult(1f, 2) } "encodes a queryResult" in { import io.circe.syntax._ val result = ScoredQueryResult(1f, 1): QueryResult[Int] result.asJson shouldEqual Json.obj( "resultId" -> Json.fromString("/some/path"), "score" -> Json.fromFloatOrString(1f), "source" -> Json.fromInt(result.source) ) } } }
Example 167
Source File: RejectionHandlingSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.http import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Rejection import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.util.EitherValues import com.typesafe.config.{Config, ConfigFactory} import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._ import io.circe.{Json, Printer} import io.circe.parser._ import org.scalatest.Inspectors import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class RejectionHandlingSpec extends AnyWordSpecLike with Matchers with Inspectors with ScalatestRouteTest with EitherValues { class Custom extends Rejection override def testConfig: Config = ConfigFactory.empty() implicit private val printer: Printer = Printer.spaces2.copy(dropNullValues = true) "A default rejection handler" should { val handler = RejectionHandling { _: Custom => StatusCodes.InternalServerError -> Json.obj("reason" -> Json.fromString("custom")) }.withFallback(RejectionHandling.notFound) "handle not found" in { val route = handleRejections(handler)(pathEnd(complete("ok"))) Get("/a") ~> route ~> check { val expected = s"""{ | "@context": "https://bluebrain.github.io/nexus/contexts/error.json", | "@type": "NotFound", | "reason": "The requested resource could not be found." |}""".stripMargin status shouldEqual StatusCodes.NotFound responseAs[Json] shouldEqual parse(expected).rightValue } } "handle missing query param" in { val route = handleRejections(handler)(parameter("rev".as[Long])(_ => complete("ok"))) Get("/a") ~> route ~> check { val expected = s"""{ | "@context": "https://bluebrain.github.io/nexus/contexts/error.json", | "@type": "MissingQueryParam", | "reason": "Request is missing required query parameter 'rev'." |}""".stripMargin status shouldEqual StatusCodes.BadRequest responseAs[Json] shouldEqual parse(expected).rightValue } } "handle custom" in { val route = handleRejections(handler)(reject(new Custom)) Get("/a") ~> route ~> check { val expected = s"""{ | "reason": "custom" |}""".stripMargin status shouldEqual StatusCodes.InternalServerError responseAs[Json] shouldEqual parse(expected).rightValue } } } }
Example 168
Source File: ElasticSearchDecoderSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.es.client import ch.epfl.bluebrain.nexus.commons.search.QueryResults import ch.epfl.bluebrain.nexus.commons.search.QueryResult.ScoredQueryResult import ch.epfl.bluebrain.nexus.commons.search.QueryResults.{ScoredQueryResults, UnscoredQueryResults} import ch.epfl.bluebrain.nexus.util.Resources import io.circe.{Decoder, Json} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class ElasticSearchDecoderSpec extends AnyWordSpecLike with Matchers with Resources { "A ElasticSearchDecoder" should { implicit val D: Decoder[QueryResults[Json]] = ElasticSearchDecoder[Json] "decode ElasticSearch response " in { val response = jsonContentOf("/commons/es/elastic_response.json") val json1 = Json.obj("key" -> Json.fromString("a"), "key2" -> Json.fromString("b")) val json2 = Json.obj("key" -> Json.fromString("c"), "key2" -> Json.fromString("d")) response.as[QueryResults[Json]].toOption.get shouldEqual ScoredQueryResults( 2L, 1f, List(ScoredQueryResult(0.5f, json1), ScoredQueryResult(0.8f, json2)) ) } "decode ElasticSearch empty response" in { val response = jsonContentOf("/commons/es/elastic_response_0.json") response.as[QueryResults[Json]].toOption.get shouldEqual UnscoredQueryResults(0L, List.empty) } } }
Example 169
Source File: TagSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import io.circe.Json import io.circe.syntax._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class TagSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues { abstract private class Ctx { val id = Id(ProjectRef(genUUID), genIri) def jsonTag(rev: Long, value: String): Json = Json.obj("@id" -> id.value.asString.asJson, "tag" -> value.asJson, "rev" -> rev.asJson) } "A Tag" should { "be converted to tag case class correctly" in new Ctx { val rev = genInt().toLong val tag = genString() Tag(id, jsonTag(rev, tag)).rightValue shouldEqual Tag(rev, tag) } "reject when rev is missing" in new Ctx { val json = Json.obj("@id" -> id.value.asString.asJson, "tag" -> genString().asJson) Tag(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'rev' field does not have the right format.") } "reject when rev is not a number" in new Ctx { val json = Json.obj("@id" -> id.value.asString.asJson, "tag" -> genString().asJson, "rev" -> genString().asJson) Tag(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'rev' field does not have the right format.") } "reject when tag is missing" in new Ctx { val json = Json.obj("@id" -> id.value.asString.asJson, "rev" -> genInt().toLong.asJson) Tag(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'tag' field does not have the right format.") } "reject when tag is empty" in new Ctx { val json = Json.obj("@id" -> id.value.asString.asJson, "rev" -> genInt().toLong.asJson, "tag" -> "".asJson) Tag(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'tag' field does not have the right format.") } "reject when tag is not a string" in new Ctx { val json = Json.obj("@id" -> id.value.asString.asJson, "rev" -> genInt().toLong.asJson, "tag" -> genInt().asJson) Tag(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'tag' field does not have the right format.") } } }
Example 170
Source File: LinkDescriptionSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ContentType, ContentTypes} import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.file.File.{FileDescription, LinkDescription} import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json import io.circe.syntax._ import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class LinkDescriptionSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues with OptionValues { abstract private class Ctx { val id = Id(ProjectRef(genUUID), genIri) val p = genString() + "/" + genString() val f = genString() val m = "application/json" def jsonLink(mediaType: String = m, filename: String = f, path: String = p): Json = Json.obj("filename" -> filename.asJson, "path" -> path.asJson, "mediaType" -> mediaType.asJson) } "A Link Description" should { "be decoded correctly" in new Ctx { LinkDescription(id, jsonLink()).rightValue shouldEqual LinkDescription(Path(p), Some(f), ContentType.parse(m).toOption) LinkDescription(id, Json.obj("path" -> p.asJson)).rightValue shouldEqual LinkDescription(Path(p), None, None) } "accept missing filename" in new Ctx { LinkDescription(id, jsonLink().removeKeys("filename")).rightValue shouldEqual LinkDescription(Path(p), None, ContentType.parse(m).toOption) } "reject empty filename" in new Ctx { LinkDescription(id, jsonLink(filename = "")).leftValue shouldBe a[InvalidResourceFormat] } "accept missing mediaType" in new Ctx { LinkDescription(id, jsonLink().removeKeys("mediaType")).rightValue shouldEqual LinkDescription(Path(p), Some(f), None) } "reject wrong mediaType format" in new Ctx { LinkDescription(id, jsonLink(mediaType = genString())).leftValue shouldBe a[InvalidResourceFormat] } "reject missing path" in new Ctx { LinkDescription(id, jsonLink().removeKeys("path")).leftValue shouldBe a[InvalidResourceFormat] } "be converted to a FileDescription correctly" in new Ctx { val fileDesc1 = FileDescription.from(LinkDescription(Path("/foo/bar/file.ext"), None, None)) fileDesc1.filename shouldEqual "file.ext" fileDesc1.mediaType shouldEqual None fileDesc1.defaultMediaType shouldEqual ContentTypes.`application/octet-stream` val fileDesc2 = FileDescription.from(LinkDescription(Path("/foo/bar/somedir/"), None, ContentType.parse(m).toOption)) fileDesc2.filename shouldEqual "somedir" fileDesc2.mediaType.value shouldEqual ContentTypes.`application/json` val fileDesc3 = FileDescription.from(LinkDescription(Path("/foo/bar/baz"), Some("file.json"), ContentType.parse(m).toOption)) fileDesc3.filename shouldEqual "file.json" fileDesc3.mediaType.value shouldEqual ContentTypes.`application/json` } } }
Example 171
Source File: FileAttributesSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import akka.http.scaladsl.model.ContentTypes._ import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.file.File.FileAttributes import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.storage.client.types.FileAttributes.{Digest => StorageDigest} import ch.epfl.bluebrain.nexus.storage.client.types.{FileAttributes => StorageFileAttributes} import io.circe.Json import io.circe.syntax._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class FileAttributesSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues { abstract private class Ctx { val id = Id(ProjectRef(genUUID), genIri) def jsonFileAttr( digest: StorageDigest, mediaType: String, location: String, bytes: Long, tpe: String = "UpdateFileAttributes" ): Json = Json.obj( "@id" -> id.value.asString.asJson, "@type" -> tpe.asJson, "digest" -> Json.obj("value" -> digest.value.asJson, "algorithm" -> digest.algorithm.asJson), "mediaType" -> mediaType.asJson, "location" -> location.asJson, "bytes" -> bytes.asJson ) val digest = StorageDigest("SHA-256", genString()) } "A storage FileAttributes" should { "be converted to file attributes case class correctly" in new Ctx { val expected = StorageFileAttributes("http://example.com", 10L, digest, `application/json`) val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L) FileAttributes(id, json).rightValue shouldEqual expected } "reject when algorithm digest is missing" in new Ctx { val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L).removeKeys("digest") FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'algorithm' field does not have the right format.") } "reject when digest value is empty" in new Ctx { override val digest = StorageDigest("SHA-256", "") val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L) FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'value' field does not have the right format.") } "reject when algorithm is empty" in new Ctx { override val digest = StorageDigest("", genString()) val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L) FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'algorithm' field does not have the right format.") } "reject when algorithm is invalid" in new Ctx { override val digest = StorageDigest(genString(), genString()) val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L) FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'algorithm' field does not have the right format.") } "reject when @type is missing" in new Ctx { val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L).removeKeys("@type") FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'@type' field does not have the right format.") } "reject when @type is invalid" in new Ctx { val json = jsonFileAttr(digest, "application/json", "http://example.com", 10L, genIri.asString) FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'@type' field does not have the right format.") } "reject when mediaType is invalid" in new Ctx { val json = jsonFileAttr(digest, "wrong", "http://example.com", 10L) FileAttributes(id, json).leftValue shouldEqual InvalidResourceFormat(id.ref, "'mediaType' field does not have the right format.") } } }
Example 172
Source File: TestHelper.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg import java.time.Clock import java.util.UUID import akka.stream.Materializer import akka.stream.scaladsl.Source import akka.util.ByteString import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.iam.acls.AccessControlList import ch.epfl.bluebrain.nexus.iam.types.Identity.Anonymous import ch.epfl.bluebrain.nexus.iam.types.{Identity, Permission, ResourceF => IamResourceF} import ch.epfl.bluebrain.nexus.kg.config.Schemas.unconstrainedSchemaUri import ch.epfl.bluebrain.nexus.kg.resources.ResourceF.Value import ch.epfl.bluebrain.nexus.kg.resources.{Ref, ResId, ResourceF} import ch.epfl.bluebrain.nexus.kg.storage.AkkaSource import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json trait TestHelper extends EitherValues with Randomness { private val clock = Clock.systemUTC() val read: Permission = Permission.unsafe("resources/read") val write: Permission = Permission.unsafe("files/write") def consume(source: AkkaSource)(implicit mt: Materializer): String = { import org.scalatest.concurrent.ScalaFutures._ source.runFold("")(_ ++ _.utf8String).futureValue } def produce(string: String, chunkSize: Int = 100): AkkaSource = Source(string.grouped(chunkSize).map(ByteString(_)).toList) def resourceAcls(acl: AccessControlList): IamResourceF[AccessControlList] = IamResourceF( url"http://example.com/id", 1L, Set.empty, clock.instant(), Anonymous, clock.instant(), Anonymous, acl ) def simpleV( id: ResId, value: Json, rev: Long = 1L, types: Set[AbsoluteIri] = Set.empty, deprecated: Boolean = false, schema: Ref = Ref(unconstrainedSchemaUri), created: Identity = Anonymous, updated: Identity = Anonymous )(implicit clock: Clock): ResourceF[Value] = ResourceF( id, rev, types, deprecated, Map.empty, None, clock.instant(), clock.instant(), created, updated, schema, Value(value, value.contextValue, value.toGraph(id.value).rightValue) ) def simpleV(res: ResourceF[Json])(implicit clock: Clock) = ResourceF( res.id, res.rev, res.types, res.deprecated, Map.empty, None, clock.instant(), clock.instant(), res.createdBy, res.updatedBy, res.schema, Value(res.value, res.value.contextValue, res.value.toGraph(res.id.value).rightValue) ) def genUUID: UUID = UUID.randomUUID() def genIri: AbsoluteIri = url"http://example.com/" + genUUID.toString private def sourceInChunks(input: String): AkkaSource = Source.fromIterator(() => input.grouped(10000).map(ByteString(_))) def genSource: AkkaSource = sourceInChunks(genString()) }
Example 173
Source File: TaggingAdapterSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.persistence import java.time.{Clock, Instant, ZoneId} import akka.persistence.journal.Tagged import cats.syntax.show._ import ch.epfl.bluebrain.nexus.iam.types.Identity.Anonymous import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.config.Schemas._ import ch.epfl.bluebrain.nexus.kg.persistence.TaggingAdapterSpec.Other import ch.epfl.bluebrain.nexus.kg.resources.Event._ import ch.epfl.bluebrain.nexus.kg.resources.{Id, OrganizationRef, Ref} import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.service.config.Vocabulary.nxv import io.circe.Json import org.scalatest.Inspectors import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class TaggingAdapterSpec extends AnyWordSpecLike with Matchers with Inspectors with TestHelper { "A TaggingAdapter" should { val clock = Clock.fixed(Instant.ofEpochSecond(3600), ZoneId.systemDefault()) def genJson(): Json = Json.obj("key" -> Json.fromString(genString())) val adapter = new TaggingAdapter() val orgRef = OrganizationRef(genUUID) val id = Id(ProjectRef(genUUID), nxv.projects.value) val mapping = Map( Set( s"type=${nxv.Schema.value.show}", s"type=${nxv.Resource.value.show}", s"project=${id.parent.id}", s"org=${orgRef.show}", "event" ) -> Created( id, orgRef, Ref(shaclSchemaUri), Set(nxv.Schema.value, nxv.Resource.value), genJson(), clock.instant(), Anonymous ), Set( s"type=${nxv.Resolver.value.show}", s"type=${nxv.Resource.value.show}", s"project=${id.parent.id}", s"org=${orgRef.show}", "event" ) -> Updated(id, orgRef, 1L, Set(nxv.Resource.value, nxv.Resolver.value), genJson(), clock.instant(), Anonymous), Set(s"type=${nxv.Resource.value.show}", s"project=${id.parent.id}", s"org=${orgRef.show}", "event") -> Deprecated(id, orgRef, 1L, Set(nxv.Resource.value), clock.instant(), Anonymous), Set(s"project=${id.parent.id}", s"org=${orgRef.show}", "event") -> TagAdded(id, orgRef, 2L, 1L, "tag", clock.instant(), Anonymous) ) "set the appropriate tags" in { forAll(mapping.toList) { case (tags, ev) => adapter.toJournal(ev) shouldEqual Tagged(ev, tags) } } "return an empty manifest" in { adapter.manifest(Other(genString())) shouldEqual "" } } } object TaggingAdapterSpec { final private[persistence] case class Other(value: String) }
Example 174
Source File: QueryResultEncoderSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.search import java.time.Instant import java.util.regex.Pattern.quote import akka.http.scaladsl.model.Uri import akka.http.scaladsl.model.Uri.Query import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.commons.search.QueryResult.{ScoredQueryResult, UnscoredQueryResult} import ch.epfl.bluebrain.nexus.commons.search.QueryResults import ch.epfl.bluebrain.nexus.commons.search.QueryResults.{ScoredQueryResults, UnscoredQueryResults} import ch.epfl.bluebrain.nexus.commons.test.{Randomness, Resources} import ch.epfl.bluebrain.nexus.kg.search.QueryResultEncoder._ import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import ch.epfl.bluebrain.nexus.service.config.ServiceConfig import ch.epfl.bluebrain.nexus.service.config.ServiceConfig.HttpConfig import io.circe.Json import io.circe.syntax._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class QueryResultEncoderSpec extends AnyWordSpecLike with Matchers with Resources with Randomness { implicit val orderedKeys = ServiceConfig.orderedKeys val org = genString() val proj = genString() val schema = genString() val now = Instant.now() implicit val http = HttpConfig("", 0, "v1", "http://nexus.com") implicit val uri = Uri(s"http://nexus.com/resources/$org/$proj/$schema?type=someType&from=10&size=10") val before = now.minusSeconds(60) "QueryResultsEncoder" should { def json(id: AbsoluteIri, createdAt: Instant): Json = jsonContentOf( "/resources/es-metadata.json", Map( quote("{id}") -> id.asString, quote("{org}") -> org, quote("{proj}") -> proj, quote("{schema}") -> schema, quote("{instant}") -> createdAt.toString ) ) deepMerge Json.obj("_original_source" -> Json.fromString(Json.obj("k" -> Json.fromInt(1)).noSpaces)) "encode ScoredQueryResults" in { val results: QueryResults[Json] = ScoredQueryResults[Json]( 3, 0.3f, List( ScoredQueryResult(0.3f, json(url"http://nexus.com/result1", before)), ScoredQueryResult(0.2f, json(url"http://nexus.com/result2", before)), ScoredQueryResult(0.1f, json(url"http://nexus.com/result3", now)) ), sort(now) ) results.asJson.sortKeys shouldEqual jsonContentOf( "/search/scored-query-results.json", Map( quote("{org}") -> org, quote("{proj}") -> proj, quote("{schema}") -> schema, quote("{before}") -> before.toString, quote("{lastElementCreated}") -> now.toString, quote("{after}") -> after(now) ) ) } "encode UnscoredQueryResults" in { val results: QueryResults[Json] = UnscoredQueryResults[Json]( 3, List( UnscoredQueryResult(json(url"http://nexus.com/result1", before)), UnscoredQueryResult(json(url"http://nexus.com/result2", before)), UnscoredQueryResult(json(url"http://nexus.com/result3", now)) ), sort(now) ) results.asJson.sortKeys shouldEqual jsonContentOf( "/search/unscored-query-results.json", Map( quote("{org}") -> org, quote("{proj}") -> proj, quote("{schema}") -> schema, quote("{before}") -> before.toString, quote("{lastElementCreated}") -> now.toString, quote("{after}") -> after(now) ) ) } } private def sort(instant: Instant): Option[String] = Some(Json.arr(Json.fromString(instant.toString)).noSpaces) private def after(instant: Instant): String = Query("after" -> List(Json.fromString(instant.toString)).asJson.noSpaces).toString() }
Example 175
Source File: IdentitiesRoutesSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.routes import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.headers.OAuth2BearerToken import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.iam.acls.Acls import ch.epfl.bluebrain.nexus.iam.auth.{AccessToken, TokenRejection} import ch.epfl.bluebrain.nexus.iam.realms._ import ch.epfl.bluebrain.nexus.iam.testsyntax._ import ch.epfl.bluebrain.nexus.iam.types.Caller import ch.epfl.bluebrain.nexus.iam.types.IamError.InvalidAccessToken import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Authenticated, User} import ch.epfl.bluebrain.nexus.service.config.Settings import ch.epfl.bluebrain.nexus.service.marshallers.instances._ import ch.epfl.bluebrain.nexus.service.routes.Routes import ch.epfl.bluebrain.nexus.util.Resources import com.typesafe.config.{Config, ConfigFactory} import io.circe.Json import monix.eval.Task import org.mockito.matchers.MacroBasedMatchers import org.mockito.{IdiomaticMockito, Mockito} import org.scalatest.BeforeAndAfter import org.scalatest.concurrent.ScalaFutures import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import scala.concurrent.duration._ //noinspection TypeAnnotation class IdentitiesRoutesSpec extends AnyWordSpecLike with Matchers with ScalatestRouteTest with BeforeAndAfter with MacroBasedMatchers with Resources with ScalaFutures with IdiomaticMockito { implicit override def patienceConfig: PatienceConfig = PatienceConfig(3.seconds, 100.milliseconds) override def testConfig: Config = ConfigFactory.load("test.conf") private val config = Settings(system).serviceConfig implicit private val http = config.http private val realms: Realms[Task] = mock[Realms[Task]] private val acls: Acls[Task] = mock[Acls[Task]] before { Mockito.reset(realms, acls) } "The IdentitiesRoutes" should { val routes = Routes.wrap(new IdentitiesRoutes(acls, realms).routes) "return forbidden" in { val err = InvalidAccessToken(TokenRejection.InvalidAccessToken) realms.caller(any[AccessToken]) shouldReturn Task.raiseError(err) Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check { status shouldEqual StatusCodes.Unauthorized } } "return anonymous" in { realms.caller(any[AccessToken]) shouldReturn Task.pure(Caller.anonymous) Get("/identities") ~> routes ~> check { status shouldEqual StatusCodes.OK responseAs[Json].sort shouldEqual jsonContentOf("/identities/anonymous.json") } } "return all identities" in { val user = User("theuser", "therealm") val auth = Authenticated("therealm") val caller = Caller(user, Set(user, Anonymous, auth)) realms.caller(any[AccessToken]) shouldReturn Task.pure(caller) Get("/identities").addCredentials(OAuth2BearerToken("token")) ~> routes ~> check { status shouldEqual StatusCodes.OK responseAs[Json].sort shouldEqual jsonContentOf("/identities/identities.json") } } } }
Example 176
Source File: GrantTypeSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import ch.epfl.bluebrain.nexus.util.EitherValues import ch.epfl.bluebrain.nexus.iam.types.GrantType._ import io.circe.{Decoder, Encoder, Json} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import org.scalatest.Inspectors class GrantTypeSpec extends AnyWordSpecLike with Matchers with Inspectors with EitherValues { "A GrantType" when { "using Camel encoders" should { import GrantType.Camel._ val map = Map( AuthorizationCode -> "authorizationCode", Implicit -> "implicit", Password -> "password", ClientCredentials -> "clientCredentials", DeviceCode -> "deviceCode", RefreshToken -> "refreshToken" ) "be encoded properly" in { val encoder = implicitly[Encoder[GrantType]] forAll(map.toList) { case (gt, expected) => encoder(gt) shouldEqual Json.fromString(expected) } } "be decoded properly" in { val decoder = implicitly[Decoder[GrantType]] forAll(map.toList) { case (expected, gt) => decoder.decodeJson(Json.fromString(gt)).rightValue shouldEqual expected } } "fail to decode for unknown string" in { val decoder = implicitly[Decoder[GrantType]] decoder.decodeJson(Json.fromString("incorrect")).leftValue } } "using Snake encoders" should { import GrantType.Snake._ val map = Map( AuthorizationCode -> "authorization_code", Implicit -> "implicit", Password -> "password", ClientCredentials -> "client_credentials", DeviceCode -> "device_code", RefreshToken -> "refresh_token" ) "be encoded properly" in { val encoder = implicitly[Encoder[GrantType]] forAll(map.toList) { case (gt, expected) => encoder(gt) shouldEqual Json.fromString(expected) } } "be decoded properly" in { val decoder = implicitly[Decoder[GrantType]] forAll(map.toList) { case (expected, gtString) => decoder.decodeJson(Json.fromString(gtString)).rightValue shouldEqual expected } } "fail to decode for unknown string" in { val decoder = implicitly[Decoder[GrantType]] decoder.decodeJson(Json.fromString("incorrect")).leftValue } } } }
Example 177
Source File: RdfCirceInstances.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.rdf.jsonld.instances import ch.epfl.bluebrain.nexus.rdf.{GraphDecoder, GraphEncoder, Iri} import ch.epfl.bluebrain.nexus.rdf.Iri.{AbsoluteIri, Path, RelativeIri, Url, Urn} import io.circe.{Decoder, Encoder, Json} import io.circe.parser._ import cats.implicits._ trait RdfCirceInstances { implicit final val absoluteIriEncoder: Encoder[AbsoluteIri] = Encoder.encodeString.contramap(_.asString) implicit final val absoluteIriDecoder: Decoder[AbsoluteIri] = Decoder.decodeString.emap(Iri.absolute) implicit final val iriPathEncoder: Encoder[Path] = Encoder.encodeString.contramap(_.asString) implicit final val iriPathDecoder: Decoder[Path] = Decoder.decodeString.emap(Path.apply) implicit final val iriEncoder: Encoder[Iri] = Encoder.encodeString.contramap(_.asString) implicit final val iriDecoder: Decoder[Iri] = Decoder.decodeString.emap(Iri.apply) implicit final def urlEncoder(implicit E: Encoder[AbsoluteIri]): Encoder[Url] = E.contramap(identity) implicit final val urlDecoder: Decoder[Url] = Decoder.decodeString.emap(Url.apply) implicit final def urnEncoder(implicit E: Encoder[AbsoluteIri]): Encoder[Urn] = E.contramap(identity) implicit final val urnDecoder: Decoder[Urn] = Decoder.decodeString.emap(Urn.apply) implicit final val relativeIriEncoder: Encoder[RelativeIri] = Encoder.encodeString.contramap(_.asString) implicit final val relativeIriDecoder: Decoder[RelativeIri] = Decoder.decodeString.emap(Iri.relative) implicit final val jsonGraphEncoder: GraphEncoder[Json] = GraphEncoder.graphEncodeString.contramap(_.noSpaces) implicit final val jsonGraphDecoder: GraphDecoder[Json] = GraphDecoder.graphDecodeString.emap(str => parse(str).leftMap(_.message)) } object RdfCirceInstances extends RdfCirceInstances
Example 178
Source File: ValidationReport.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.rdf.shacl import cats.implicits._ import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.Node.{BNode, IriNode} import ch.epfl.bluebrain.nexus.rdf.jena.syntax.all._ import ch.epfl.bluebrain.nexus.rdf.jsonld.syntax._ import ch.epfl.bluebrain.nexus.rdf.shacl.Vocabulary._ import ch.epfl.bluebrain.nexus.rdf.syntax.all._ import io.circe.parser.parse import io.circe.{Encoder, Json} import org.apache.jena.rdf.model.Resource import scala.io.Source def isValid(ignoreTargetedNodes: Boolean = false): Boolean = (ignoreTargetedNodes && conforms) || (!ignoreTargetedNodes && targetedNodes > 0 && conforms) } object ValidationReport { final def apply(report: Resource): Either[String, ValidationReport] = // format: off for { tmp <- report.getModel.asRdfGraph(BNode()) subject <- tmp.triples.find { case (_, p ,_ ) => p == IriNode(sh.conforms) }.map(_._1).toRight("Unable to find predicate sh:conforms in the validation report graph") graph = tmp.withRoot(subject) cursor = graph.cursor conforms <- cursor.down(sh.conforms).as[Boolean].leftMap(_.message) targeted <- cursor.down(nxsh.targetedNodes).as[Int].leftMap(_.message) json <- graph.toJson(shaclCtx) } yield ValidationReport(conforms, targeted, json.removeKeys("@context", "@id").addContext(shaclCtxUri)) // format: on private val shaclCtxUri: AbsoluteIri = url"https://bluebrain.github.io/nexus/contexts/shacl-20170720.json" private val shaclCtx: Json = jsonContentOf("/shacl-context-resp.json") implicit val reportEncoder: Encoder[ValidationReport] = Encoder.instance(_.json) private def jsonContentOf(resourcePath: String): Json = parse(Source.fromInputStream(getClass.getResourceAsStream(resourcePath)).mkString) .getOrElse(throw new IllegalArgumentException) }
Example 179
Source File: ValidationReportSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.rdf.shacl import ch.epfl.bluebrain.nexus.rdf.RdfSpec import io.circe.Json import io.circe.syntax._ import org.apache.jena.rdf.model.{ModelFactory, Resource} import org.apache.jena.riot.system.StreamRDFLib import org.apache.jena.riot.{Lang, RDFParser} class ValidationReportSpec extends RdfSpec { private def resource(json: Json): Resource = { val m = ModelFactory.createDefaultModel RDFParser.create.fromString(json.noSpaces).base("").lang(Lang.JSONLD).parse(StreamRDFLib.graph(m.getGraph)) m.createResource() } "A ValidationReport" should { val ctx = jsonContentOf("/shacl-context-resp.json") val conforms = jsonContentOf("/shacl/conforms.json") val failed = jsonContentOf("/shacl/failed.json") "be constructed correctly when conforms" in { ValidationReport(resource(conforms deepMerge ctx)).rightValue shouldEqual ValidationReport(true, 1, conforms) } "be constructed correctly when fails" in { val report = ValidationReport(resource(failed deepMerge ctx)).rightValue report.conforms shouldEqual false report.targetedNodes shouldEqual 1 report.isValid() shouldEqual false val array = report.json.hcursor.downField("result").downField("detail").focus.flatMap(_.asArray).value array.map(_.hcursor.get[String]("resultMessage").rightValue).sorted shouldEqual Vector( "Focus node has 2^^http://www.w3.org/2001/XMLSchema#integer of the shapes from the 'exactly one' list", "Value does not have shape http://localhost/v0/schemas/nexus/schemaorg/quantitativevalue/v0.1.0/shapes/QuantitativeValueShape" ).sorted } "be encoded as json" in { val report = ValidationReport(resource(failed deepMerge ctx)).rightValue report.asJson shouldEqual report.json } } }
Example 180
Source File: InfluxClient.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.cli.clients import cats.effect.{Sync, Timer} import cats.implicits._ import ch.epfl.bluebrain.nexus.cli._ import ch.epfl.bluebrain.nexus.cli.config.influx.InfluxConfig import ch.epfl.bluebrain.nexus.cli.config.{AppConfig, EnvConfig} import io.circe.Json import org.http4s.client.Client import org.http4s.{Method, Request, UrlForm} trait InfluxClient[F[_]] { final def apply[F[_]: Sync: Timer]( client: Client[F], config: AppConfig, console: Console[F] ): InfluxClient[F] = { implicit val c: Console[F] = console new LiveInfluxDbClient[F](client, config.influx, config.env) } }
Example 181
Source File: Event.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.cli.sse import java.time.Instant import java.util.UUID import ch.epfl.bluebrain.nexus.cli.utils.Codecs import io.circe.generic.semiauto.deriveDecoder import io.circe.{Decoder, Json} import org.http4s.Uri final case class Event( eventType: EventType, resourceId: Uri, rev: Long, organization: OrgUuid, project: ProjectUuid, resourceTypes: Set[Uri], instant: Instant, raw: Json ) object Event extends Codecs { final private[Event] case class APIEvent( `_organizationUuid`: UUID, `_projectUuid`: UUID, `@type`: EventType, `_types`: Option[Set[Uri]], `_resourceId`: Uri, `_rev`: Option[Long], `_instant`: Instant ) { def asEvent(raw: Json): Event = Event( `@type`, `_resourceId`, `_rev`.getOrElse(1L), OrgUuid(`_organizationUuid`), ProjectUuid(`_projectUuid`), `_types`.getOrElse(Set.empty[Uri]), `_instant`, raw ) } private[Event] object APIEvent { implicit val apiEventDecoder: Decoder[APIEvent] = deriveDecoder[APIEvent] } implicit final val eventDecoder: Decoder[Event] = Decoder.instance { cursor => cursor.as[APIEvent].map(_.asEvent(cursor.value)) } }
Example 182
Source File: TestSparqlClient.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.cli.dummies import java.io.ByteArrayOutputStream import cats.effect.Sync import cats.implicits._ import ch.epfl.bluebrain.nexus.cli.CliError.ClientError.SerializationError import ch.epfl.bluebrain.nexus.cli.ClientErrOr import ch.epfl.bluebrain.nexus.cli.clients.{SparqlClient, SparqlResults} import ch.epfl.bluebrain.nexus.cli.sse.{Event, OrgLabel, ProjectLabel} import io.circe.Json import org.http4s.Uri class TestSparqlClient[F[_]](events: List[Event])(implicit F: Sync[F]) extends SparqlClient[F] { import io.circe.parser._ import org.apache.jena.query.{Dataset, DatasetFactory, QueryFactory, ReadWrite, ResultSetFormatter, _} import org.apache.jena.rdf.model.{Model, ModelFactory} import org.apache.jena.riot.system.StreamRDFLib import org.apache.jena.riot.{Lang, RDFParser} private def toJenaModel(j: Json): Model = { val model = ModelFactory.createDefaultModel() val stream = StreamRDFLib.graph(model.getGraph) RDFParser.create.fromString(j.noSpaces).lang(Lang.JSONLD).parse(stream) model } val ds: Dataset = DatasetFactory.createTxnMem() events.foreach { event => val jsonGraph = event.raw.hcursor.get[Json]("_source").getOrElse(Json.obj()) val graphUri = event.resourceId.addSegment("graph").renderString val model = toJenaModel(jsonGraph) ds.begin(ReadWrite.WRITE) try { ds.removeNamedModel(graphUri) ds.commit() } finally { ds.end() } ds.begin(ReadWrite.WRITE) try { ds.addNamedModel(graphUri, model) ds.commit() } finally { ds.end() } } ds.setDefaultModel(ds.getUnionModel) override def query( org: OrgLabel, proj: ProjectLabel, view: Option[Uri], queryStr: String ): F[ClientErrOr[SparqlResults]] = { F.delay { ds.begin(ReadWrite.READ) try { val query = QueryFactory.create(queryStr) val qexec = QueryExecutionFactory.create(query, ds.asDatasetGraph()) val results = qexec.execSelect val outputStream = new ByteArrayOutputStream() ResultSetFormatter.outputAsJSON(outputStream, results) val json = new String(outputStream.toByteArray) decode[SparqlResults](json).leftMap(_ => SerializationError("Unable to decode sparql results", classOf[SparqlResults].getSimpleName, Some(json)) ) } finally { ds.end() } } } } object TestSparqlClient { final def apply[F[_]](events: List[Event])(implicit F: Sync[F]): F[TestSparqlClient[F]] = F.delay(new TestSparqlClient[F](events)) }
Example 183
Source File: JsonLdCirceSupport.scala From nexus with Apache License 2.0 | 5 votes |
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 184
Source File: StorageError.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.Uri.Path import ch.epfl.bluebrain.nexus.storage.routes.StatusFrom import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.annotation.nowarn final case class OperationTimedOut(override val msg: String) extends StorageError(msg) @nowarn("cat=unused") implicit private val config: Configuration = Configuration.default.withDiscriminator("@type") private val derivedEncoder = deriveConfiguredEncoder[StorageError].mapJson(jsonError) implicit val storageErrorEncoder: Encoder[StorageError] = Encoder.instance(r => derivedEncoder(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) implicit val storageErrorStatusFrom: StatusFrom[StorageError] = { case _: PathNotFound => StatusCodes.NotFound case _: PathInvalid => StatusCodes.BadRequest case AuthenticationFailed => StatusCodes.Unauthorized case AuthorizationFailed => StatusCodes.Forbidden case _ => StatusCodes.InternalServerError } }
Example 185
Source File: Rejection.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.server.{Rejection => AkkaRejection} import ch.epfl.bluebrain.nexus.storage.routes.StatusFrom import scala.annotation.nowarn import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} final case class EmptyFilename(name: String) implicit def statusCodeFrom: StatusFrom[Rejection] = StatusFrom { case _: PathContainsLinks => StatusCodes.BadRequest case _: PathAlreadyExists => StatusCodes.Conflict case _: BucketNotFound => StatusCodes.NotFound case _: PathNotFound => StatusCodes.NotFound } @nowarn("cat=unused") implicit val rejectionEncoder: Encoder[Rejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[Rejection].mapJson(jsonError) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } }
Example 186
Source File: StorageDirectivesSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage.routes import java.util.regex.Pattern.quote import akka.http.scaladsl.model.{StatusCodes, Uri} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.storage.JsonLdCirceSupport._ import ch.epfl.bluebrain.nexus.storage.routes.Routes.exceptionHandler import ch.epfl.bluebrain.nexus.storage.routes.StorageDirectives._ import ch.epfl.bluebrain.nexus.storage.utils.Resources import io.circe.Json import org.scalatest.Inspectors import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class StorageDirectivesSpec extends AnyWordSpecLike with Matchers with ScalatestRouteTest with Inspectors with Resources { "the storage directives" when { def pathInvalidJson(path: Uri.Path): Json = jsonContentOf( "/error.json", Map( quote("{type}") -> "PathInvalid", quote( "{reason}" ) -> s"The provided location inside the bucket 'name' with the relative path '$path' is invalid." ) ) "dealing with file path extraction" should { val route = handleExceptions(exceptionHandler) { (extractRelativeFilePath("name") & get) { path => complete(s"$path") } } "reject when path contains 2 slashes" in { Get("///") ~> route ~> check { status shouldEqual StatusCodes.BadRequest responseAs[Json] shouldEqual pathInvalidJson(Uri.Path.Empty) } } "reject when path does not end with a segment" in { Get("/some/path/") ~> route ~> check { status shouldEqual StatusCodes.BadRequest responseAs[Json] shouldEqual pathInvalidJson(Uri.Path("some/path/")) } } "return path" in { Get("/some/path/file.txt") ~> route ~> check { responseAs[String] shouldEqual "some/path/file.txt" } } } "dealing with path validation" should { def route(path: Uri.Path) = handleExceptions(exceptionHandler) { (validatePath("name", path) & get) { complete(s"$path") } } "reject when some of the segments is . or .." in { val paths = List(Uri.Path("/./other/file.txt"), Uri.Path("/some/../file.txt")) forAll(paths) { path => Get(path.toString()) ~> route(path) ~> check { status shouldEqual StatusCodes.BadRequest responseAs[Json] shouldEqual pathInvalidJson(path) } } } "pass" in { Get("/some/path") ~> route(Uri.Path("/some/path")) ~> check { handled shouldEqual true } } } } }
Example 187
Source File: AppInfoRoutesSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.storage.routes import java.util.regex.Pattern.quote import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Route import akka.http.scaladsl.testkit.ScalatestRouteTest import ch.epfl.bluebrain.nexus.storage.config.{AppConfig, Settings} import ch.epfl.bluebrain.nexus.storage.routes.instances._ import ch.epfl.bluebrain.nexus.storage.utils.Resources import ch.epfl.bluebrain.nexus.storage.{AkkaSource, IamIdentitiesClient, Storages} import io.circe.Json import monix.eval.Task import org.mockito.IdiomaticMockito import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class AppInfoRoutesSpec extends AnyWordSpecLike with Matchers with ScalatestRouteTest with IdiomaticMockito with Resources { "the app info routes" should { implicit val config: AppConfig = Settings(system).appConfig implicit val iamIdentities: IamIdentitiesClient[Task] = mock[IamIdentitiesClient[Task]] val route: Route = Routes(mock[Storages[Task, AkkaSource]]) "return application information" in { Get("/") ~> route ~> check { status shouldEqual OK responseAs[Json] shouldEqual jsonContentOf("/app-info.json", Map(quote("{version}") -> config.description.version)) } } } }
Example 188
Source File: instances.scala From sbt-graphql with Apache License 2.0 | 5 votes |
package rocks.muki.graphql import cats.Monoid import io.circe.Json import sangria.ast.Document import sangria.marshalling.InputUnmarshaller package object instances { implicit object CirceInputUnmarshaller extends InputUnmarshaller[Json] { def getRootMapValue(node: Json, key: String) = node.asObject.get(key) def isMapNode(node: Json) = node.isObject def getMapValue(node: Json, key: String) = node.asObject.get(key) def getMapKeys(node: Json) = node.asObject.get.keys def isListNode(node: Json) = node.isArray def getListValue(node: Json) = node.asArray.get def isDefined(node: Json) = !node.isNull def getScalarValue(node: Json) = { def invalidScalar = throw new IllegalStateException(s"$node is not a scalar value") node.fold( jsonNull = invalidScalar, jsonBoolean = identity, jsonNumber = num => num.toBigInt orElse num.toBigDecimal getOrElse invalidScalar, jsonString = identity, jsonArray = _ => invalidScalar, jsonObject = _ => invalidScalar ) } def getScalaScalarValue(node: Json) = getScalarValue(node) def isEnumNode(node: Json) = node.isString def isScalarNode(node: Json) = node.isBoolean || node.isNumber || node.isString def isVariableNode(node: Json) = false def getVariableName(node: Json) = throw new IllegalArgumentException("variables are not supported") def render(node: Json) = node.noSpaces } }
Example 189
Source File: PostgresBookingViewRepository.scala From ticket-booking-aecor with Apache License 2.0 | 5 votes |
package ru.pavkin.booking.booking.view import java.sql.Timestamp import java.time.Instant import cats.Monad import cats.implicits._ import doobie._ import doobie.implicits._ import doobie.util.transactor.Transactor import io.circe.{ Decoder, Encoder, Json } import io.circe.parser._ import org.postgresql.util.PGobject import ru.pavkin.booking.common.models._ class PostgresBookingViewRepository[F[_]: Monad](transactor: Transactor[F], tableName: String = "bookings") extends BookingViewRepository[F] { implicit val jsonMeta: Meta[Json] = Meta.Advanced .other[PGobject]("json") .timap[Json](a => parse(a.getValue).leftMap[Json](e => throw e).merge)(a => { val o = new PGobject o.setType("json") o.setValue(a.noSpaces) o }) implicit val seatsMeta: Meta[List[Seat]] = jsonMeta.timap( j => Decoder[List[Seat]].decodeJson(j).right.get )(s => Encoder[List[Seat]].apply(s)) implicit val ticketsMeta: Meta[List[Ticket]] = jsonMeta.timap( j => Decoder[List[Ticket]].decodeJson(j).right.get )(s => Encoder[List[Ticket]].apply(s)) implicit val instantMeta: Meta[Instant] = Meta[Timestamp].timap(_.toInstant)(Timestamp.from) implicit val bookingStatusMeta: Meta[BookingStatus] = Meta[String].timap(BookingStatus.withName)(_.entryName) def get(bookingId: BookingKey): F[Option[BookingView]] = queryView(bookingId).option.transact(transactor) def byClient(clientId: ClientId): F[List[BookingView]] = queryForClient(clientId).to[List].transact(transactor) def set(view: BookingView): F[Unit] = Update[BookingView](setViewQuery).run(view).transact(transactor).void def expired(now: Instant): fs2.Stream[F, BookingKey] = queryExpired(now).stream.transact(transactor) def createTable: F[Unit] = createTableQuery.transact(transactor).void private val setViewQuery = s"""INSERT INTO $tableName (booking_id, client_id, concert_id, seats, tickets, status, confirmed_at, expires_at, version) VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT (booking_id) DO UPDATE SET tickets = EXCLUDED.tickets, status = EXCLUDED.status, confirmed_at = EXCLUDED.confirmed_at, expires_at = EXCLUDED.expires_at, version = EXCLUDED.version;""" private def queryView(bookingId: BookingKey) = (fr"SELECT * FROM " ++ Fragment.const(tableName) ++ fr"WHERE booking_id = $bookingId;") .query[BookingView] private def queryExpired(now: Instant) = (fr"SELECT booking_id FROM " ++ Fragment.const(tableName) ++ fr"WHERE status = ${BookingStatus.Confirmed: BookingStatus} AND expires_at < $now;") .query[BookingKey] private def queryForClient(clientId: ClientId) = (fr"SELECT * FROM " ++ Fragment.const(tableName) ++ fr"WHERE client_id = $clientId;") .query[BookingView] private val createTableQuery = (fr""" CREATE TABLE IF NOT EXISTS """ ++ Fragment.const(tableName) ++ fr""" ( booking_id text NOT NULL PRIMARY KEY, client_id text NOT NULL, concert_id text NOT NULL, seats json NOT NULL, tickets json NOT NULL, status text NOT NULL, confirmed_at timestamptz, expires_at timestamptz, version bigint NOT NULL ); """).update.run }
Example 190
Source File: SGraph.scala From shaclex with MIT License | 5 votes |
package es.weso.rdf.sgraph import es.weso.rdf.PrefixMap import es.weso.rdf.nodes._ import io.circe.Json /** * Representation of RDF graphs as simple graphs * It is used to serialize RDF graphs to DOT or JSON * @param rdfNodeIdMap * @param edges */ case class SGraph(rdfNodeIdMap: Map[RDFNode, Node], edges: List[Edge] ) { def addNode(node: RDFNode, pm: PrefixMap): (SGraph, Node) = rdfNodeIdMap.get(node) match { case None => { val id = "N" + nextId val label = pm.qualify(node) println(s"Label: $label, node: $node\nPrefixMap: $pm") val n = Node(id, label, node, pm) val newMap = rdfNodeIdMap.updated(node, n) (this.copy(rdfNodeIdMap = newMap), n) } case Some(n) => (this, n) } private def nextId = rdfNodeIdMap.size def addEdge(edge: Edge): SGraph = { this.copy(edges = edge +: edges) } def toDot(prefs: RDFDotPreferences): String = { val sb = new StringBuilder sb.append("digraph {\n") rdfNodeIdMap.values.foreach { node => sb.append(node.toDot(prefs) + "\n") } edges.foreach { edge => sb.append(edge.toDot(prefs) + "\n") } sb.append("}") sb.toString } def toJson: Json = Json.fromValues( rdfNodeIdMap.values.map(_.toJson) ++ edges.map(_.toJson) ) } object SGraph { def empty: SGraph = SGraph(Map(),List()) }
Example 191
Source File: Node.scala From shaclex with MIT License | 5 votes |
package es.weso.rdf.sgraph import es.weso.rdf.PrefixMap import es.weso.rdf.nodes._ import io.circe.Json case class Node(id: String, label: String, rdfNode: RDFNode, pm: PrefixMap) { private def jsonLabel(node: RDFNode): Json = node match { case _: IRI => Json.fromString(label) case _: BNode => Json.fromString("") case l: Literal => Json.fromString(labelLiteral(l)) } private def jsonType(node: RDFNode): Json = node match { case _: IRI => Json.fromString("iri") case _: BNode => Json.fromString("bNode") case _: Literal => Json.fromString("lit") } private def labelLiteral(l: Literal): String = l match { case s: StringLiteral => s.getLexicalForm case i: IntegerLiteral => i.int.toString case l: LangLiteral => l.lexicalForm + "@" + l.lang.lang case dt: DatatypeLiteral => l.getLexicalForm + "^^" + pm.qualify(l.dataType) case _ => l.getLexicalForm } def toDot(dotPreferences: RDFDotPreferences): String = rdfNode match { case i: IRI => s"""node [shape=${dotPreferences.irisPrefs.shape.name}, style=${dotPreferences.irisPrefs.style.name}, color=${dotPreferences.irisPrefs.color.name}, label="$label", href="${i.str}"] $id ;""" case l: Literal => s"""node[shape=${dotPreferences.literalPrefs.shape.name}, style=${dotPreferences.literalPrefs.style.name}, color=${dotPreferences.literalPrefs.color.name}, label="${labelLiteral(l)}"] $id ;""" case _: BNode => s"""node[shape=${dotPreferences.bnodesPrefs.shape.name}, style=${dotPreferences.bnodesPrefs.style.name}, color=${dotPreferences.bnodesPrefs.color.name}, label=""] $id ;""" } def toJson: Json = Json.fromFields(List(("data", Json.fromFields(List( ("id", Json.fromString(id)), ("label", jsonLabel(rdfNode)), ("type", jsonType(rdfNode)) )) ))) }
Example 192
Source File: Edge.scala From shaclex with MIT License | 5 votes |
package es.weso.rdf.sgraph import io.circe.Json case class Edge(n1: Node, n2: Node, label: String, href: String) { def toDot(prefs: RDFDotPreferences): String = { s"""${n1.id} -> ${n2.id} [label = "$label", href = "$href"] ;""" } def toJson: Json = Json.fromFields( List(("data",Json.fromFields( List( ("source", Json.fromString(n1.id)), ("target", Json.fromString(n2.id)), ("label", Json.fromString(label)), ("href", Json.fromString(href)) )) )) ) }
Example 193
Source File: ErrorInfo.scala From shaclex with MIT License | 5 votes |
package es.weso.schema import cats.Show import com.typesafe.scalalogging.LazyLogging import io.circe.JsonObject._ import io.circe.{ Decoder, Encoder, Json } case class ErrorInfo(msg: String) { def show: String = msg } object ErrorInfo extends LazyLogging { implicit val showErrorInfo = new Show[ErrorInfo] { override def show(e: ErrorInfo): String = e.show } implicit val encodeErrorInfo: Encoder[ErrorInfo] = new Encoder[ErrorInfo] { final def apply(e: ErrorInfo): Json = Json.fromJsonObject( singleton("type", Json.fromString("ErrorInfo")). add("error", Json.fromString(e.msg))) } implicit val decodeErrorInfo: Decoder[ErrorInfo] = Decoder.instance { c => logger.debug(s"Decoding error info: $c") for { msg <- c.get[String]("error") } yield ErrorInfo(msg) } }
Example 194
Source File: CirceSerialization.scala From kafka-serialization with Apache License 2.0 | 5 votes |
package com.ovoenergy.kafka.serialization.circe import java.nio.charset.StandardCharsets import cats.syntax.either._ import com.ovoenergy.kafka.serialization.core._ import io.circe.parser._ import io.circe.syntax._ import io.circe.{Decoder, Encoder, Error, Json} import org.apache.kafka.common.serialization.{Deserializer => KafkaDeserializer, Serializer => KafkaSerializer} private[circe] trait CirceSerialization { def circeJsonSerializer[T: Encoder]: KafkaSerializer[T] = serializer { (_, data) => data.asJson.noSpaces.getBytes(StandardCharsets.UTF_8) } def circeJsonDeserializer[T: Decoder]: KafkaDeserializer[T] = deserializer { (_, data) => (for { json <- parse(new String(data, StandardCharsets.UTF_8)): Either[Error, Json] t <- json.as[T]: Either[Error, T] } yield t).fold(error => throw new RuntimeException(s"Deserialization failure: ${error.getMessage}", error), identity _) } }
Example 195
Source File: BsonCodecInstancesTest.scala From circe-bson with Apache License 2.0 | 5 votes |
package io.circe.bson import io.circe.{ Json, JsonNumber } import io.circe.testing.ArbitraryInstances import org.scalatest.funsuite.AnyFunSuite import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import reactivemongo.bson.BSONDecimal import scala.util.{ Failure, Success, Try } class BsonCodecInstancesTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks with ArbitraryInstances { override def transformJsonNumber(n: JsonNumber): JsonNumber = Try(BSONDecimal.parse(n.toString)).flatten match { case Success(_) => n case Failure(_) => JsonNumber.fromString("0").get } test("BsonCodecInstances should round-trip JSON values") { forAll { json: Json => assert(Right(json) === jsonToBson(json).flatMap(bsonToJson)) } } test("BsonCodecInstances should support BSON Date values") { val json = Json.obj("myDate" -> Json.obj("$date" -> Json.fromLong(1570040789432L))) assert(Right(json) === jsonToBson(json).flatMap(bsonToJson)) } }
Example 196
Source File: AccessControlLists.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.acls import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig import ch.epfl.bluebrain.nexus.iam.config.Contexts._ import ch.epfl.bluebrain.nexus.iam.config.Vocabulary.nxv import ch.epfl.bluebrain.nexus.iam.types.Identity import ch.epfl.bluebrain.nexus.rdf.Iri.Path import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.syntax._ import io.circe.{Encoder, Json} import scala.collection.immutable.ListMap final def apply(tuple: (Path, Resource)*): AccessControlLists = AccessControlLists(tuple.toMap) implicit def aclsEncoder(implicit http: HttpConfig): Encoder[AccessControlLists] = Encoder.encodeJson.contramap { case AccessControlLists(value) => val arr = value.map { case (path, acl) => Json.obj("_path" -> Json.fromString(path.asString)) deepMerge acl.asJson.removeKeys("@context") } Json .obj(nxv.total.prefix -> Json.fromInt(arr.size), nxv.results.prefix -> Json.arr(arr.toSeq: _*)) .addContext(resourceCtxUri) .addContext(iamCtxUri) .addContext(searchCtxUri) } }
Example 197
Source File: AclRejection.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.acls import akka.http.scaladsl.model.StatusCodes.{BadRequest, Conflict, NotFound} import ch.epfl.bluebrain.nexus.commons.http.directives.StatusFrom import ch.epfl.bluebrain.nexus.iam.config.Contexts.errorCtxUri import ch.epfl.bluebrain.nexus.iam.types.{Permission, ResourceRejection} import ch.epfl.bluebrain.nexus.rdf.Iri.Path import ch.epfl.bluebrain.nexus.rdf.implicits._ import com.github.ghik.silencer.silent import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} sealed abstract class AclRejection(val msg: String) extends ResourceRejection object AclRejection { final case class UnknownPermissions(permissions: Set[Permission]) extends AclRejection( s"Some of the permissions specified are not known: '${permissions.mkString("\"", ", ", "\"")}'" ) @silent // rejectionConfig is not recognized as being used implicit val aclRejectionEncoder: Encoder[AclRejection] = { implicit val rejectionConfig: Configuration = Configuration.default.withDiscriminator("@type") val enc = deriveConfiguredEncoder[AclRejection].mapJson(_ addContext errorCtxUri) Encoder.instance(r => enc(r) deepMerge Json.obj("reason" -> Json.fromString(r.msg))) } implicit val aclRejectionStatusFrom: StatusFrom[AclRejection] = StatusFrom { case _: NothingToBeUpdated => BadRequest case _: AclIsEmpty => BadRequest case _: AclCannotContainEmptyPermissionCollection => BadRequest case _: AclNotFound => NotFound case _: IncorrectRev => Conflict case _: UnknownPermissions => BadRequest } }
Example 198
Source File: ActiveRealm.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.realms import ch.epfl.bluebrain.nexus.iam.config.Vocabulary.nxv import ch.epfl.bluebrain.nexus.iam.types.GrantType.Camel._ import ch.epfl.bluebrain.nexus.iam.types.{GrantType, Label} import ch.epfl.bluebrain.nexus.rdf.Iri.Url import ch.epfl.bluebrain.nexus.rdf.implicits._ import com.nimbusds.jose.jwk.{JWK, JWKSet} import io.circe.generic.extras.Configuration import io.circe.generic.extras.semiauto.deriveConfiguredEncoder import io.circe.{Encoder, Json} import scala.util.Try final case class ActiveRealm( id: Label, name: String, openIdConfig: Url, issuer: String, grantTypes: Set[GrantType], logo: Option[Url], authorizationEndpoint: Url, tokenEndpoint: Url, userInfoEndpoint: Url, revocationEndpoint: Option[Url], endSessionEndpoint: Option[Url], keys: Set[Json] ) { private[realms] lazy val keySet: JWKSet = { val jwks = keys.foldLeft(Set.empty[JWK]) { case (acc, e) => Try(JWK.parse(e.noSpaces)).map(acc + _).getOrElse(acc) } import scala.jdk.CollectionConverters._ new JWKSet(jwks.toList.asJava) } } object ActiveRealm { private[ActiveRealm] implicit val config: Configuration = Configuration.default.copy(transformMemberNames = { case "issuer" => nxv.issuer.prefix case "grantTypes" => nxv.grantTypes.prefix case "authorizationEndpoint" => nxv.authorizationEndpoint.prefix case "tokenEndpoint" => nxv.tokenEndpoint.prefix case "userInfoEndpoint" => nxv.userInfoEndpoint.prefix case "revocationEndpoint" => nxv.revocationEndpoint.prefix case "endSessionEndpoint" => nxv.endSessionEndpoint.prefix case other => other }) implicit val activeEncoder: Encoder[ActiveRealm] = { val default = deriveConfiguredEncoder[ActiveRealm] Encoder .instance[ActiveRealm] { realm => default(realm) deepMerge Json.obj( nxv.label.prefix -> Json.fromString(realm.id.value), nxv.deprecated.prefix -> Json.fromBoolean(false) ) } .mapJson(_.removeKeys("keys", "id")) } }
Example 199
Source File: ResourceF.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import java.time.Instant import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig import ch.epfl.bluebrain.nexus.iam.config.Contexts._ import ch.epfl.bluebrain.nexus.iam.config.Vocabulary.nxv import ch.epfl.bluebrain.nexus.iam.syntax._ import ch.epfl.bluebrain.nexus.iam.types.Identity.Subject import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.syntax._ import io.circe.{Encoder, Json} def unit( id: AbsoluteIri, rev: Long, types: Set[AbsoluteIri], createdAt: Instant, createdBy: Subject, updatedAt: Instant, updatedBy: Subject ): ResourceF[Unit] = ResourceF(id, rev, types, createdAt, createdBy, updatedAt, updatedBy, ()) implicit val permsEncoder: Encoder[Set[Permission]] = Encoder.instance(perms => Json.obj("permissions" -> Json.fromValues(perms.toList.sortBy(_.value).map(_.asJson)))) implicit def resourceFEncoder[A: Encoder](implicit http: HttpConfig): Encoder[ResourceF[A]] = Encoder.encodeJson.contramap { r => resourceMetaEncoder.apply(r.discard) deepMerge r.value.asJson } implicit def resourceMetaEncoder(implicit http: HttpConfig): Encoder[ResourceMetadata] = Encoder.encodeJson.contramap { case ResourceF(id, rev, types, createdAt, createdBy, updatedAt, updatedBy, _: Unit) => val jsonTypes = types.toList match { case Nil => Json.Null case t :: Nil => Json.fromString(t.lastSegment.getOrElse(t.asString)) case _ => Json.arr(types.map(t => Json.fromString(t.lastSegment.getOrElse(t.asString))).toSeq: _*) } Json .obj( "@id" -> id.asJson, "@type" -> jsonTypes, nxv.rev.prefix -> Json.fromLong(rev), nxv.createdBy.prefix -> createdBy.id.asJson, nxv.updatedBy.prefix -> updatedBy.id.asJson, nxv.createdAt.prefix -> Json.fromString(createdAt.toString), nxv.updatedAt.prefix -> Json.fromString(updatedAt.toString) ) .addContext(iamCtxUri) .addContext(resourceCtxUri) } }
Example 200
Source File: Caller.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.types import ch.epfl.bluebrain.nexus.iam.config.AppConfig.HttpConfig import ch.epfl.bluebrain.nexus.iam.config.Contexts._ import ch.epfl.bluebrain.nexus.iam.types.Identity.{Anonymous, Subject} import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.{Encoder, Json} val anonymous: Caller = Caller(Anonymous: Subject, Set[Identity](Anonymous)) object JsonLd { final implicit def callerEncoder( implicit I: Encoder[Identity], http: HttpConfig ): Encoder[Caller] = Encoder.instance[Caller] { caller => Json .obj( "identities" -> Encoder.encodeList(I)(caller.identities.toList.sortBy(_.id.asUri)) ) .addContext(iamCtxUri) .addContext(resourceCtxUri) } } }