Skip to content

Instantly share code, notes, and snippets.

@inmyth
inmyth / playEnumIdJson.scala
Created June 12, 2018 07:23
Scala Play Enum Id to Json Reads & Writes
object OkexStatus extends Enumeration {
type OkexStatus = Value
val filled = Value(1)
val unfilled = Value(0)
implicit val enumFormat = new Format[OkexStatus] {
override def reads(json: JsValue): JsResult[OkexStatus] = json.validate[Int].map(OkexStatus(_))
override def writes(enum: OkexStatus) = JsNumber(enum.id)
}
}
@inmyth
inmyth / objectToMap.scala
Created June 12, 2018 16:21
Convert Object to Map of its fields
val p = OkexParameters(Some(signed), apiKey, Some(symbol), None, None, None, None, Some(status), Some(currentPage), Some(pageLength))
import reflect.runtime.universe._
import reflect.runtime.currentMirror
val m = currentMirror.reflect(p)
m.symbol.typeSignature.members.toStream
.collect{case s : TermSymbol if !s.isMethod => m.reflectField(s)}
.filter(r => r.get != None) // filter out None
.map(r => r.get match {
@inmyth
inmyth / dynamicInit.scala
Created November 3, 2018 03:16
Dynamic instantiation
val o = Class.forName("me.mbcu.dapackage.TwoStringConstructorClass").getConstructors()(0)
val args = Array[AnyRef]("aaaa", "bbbb")
val c = o.newInstance(args:_*).asInstanceOf[ParentAbstractClass]
@inmyth
inmyth / vertxEventLoop.scala
Created November 10, 2018 13:46
Vertx event loop blocking & non-blocking test
val vertx = Vertx.vertx()
vertx.createHttpServer.requestHandler(p => {
p.path match {
case a if a contains "/tes1" =>
val f = for {
f1 <- Future (Thread.sleep(5000))
f2 <- Future (Thread.sleep(5000))
} yield f2
f.onComplete{
@inmyth
inmyth / mediumVertxScalaBasics.scala
Created February 13, 2019 11:40
Vertx basic web setup
val vertx = Vertx.vertx()
vertx.createHttpServer().requestHandler(req => {
}).listen(8080)
@inmyth
inmyth / mediumVertxScala.scala
Last active February 13, 2019 15:12
Vertx, Scala Future example
val vertx = Vertx.vertx()
vertx.createHttpServer().requestHandler(req => {
req.path() match {
case p if p contains("/user") =>
val f = for {
f1 <- Future { req.getParam("id").get.toInt }
f2 <- if (f1 < 100) Future.unit else Future.failed(CustomException())
f3 <- Future { getUserFromDb(f1) }
} yield f3
import monix.eval.Task
import monix.reactive._
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.language.postfixOps
import scala.util.Random
import scala.concurrent.duration._
def retryOnFailure(times: Int, source: Task[Int]): Task[Int] =
@inmyth
inmyth / awspureconfig.scala
Created October 22, 2020 04:34
Config to AWS Type Converter (Scala PureConfig)
import awscala.Region
import awscala.s3.Bucket
import com.typesafe.config.ConfigValueType
import pureconfig.error.{FailureReason, WrongType}
import pureconfig.{ConfigCursor, ConfigReader}
import scala.util.{Failure, Success, Try}
object ConfUtils {