Deploy Verticle with Vertx 3 and Scala - scala

I´m trying to deploy a Verticle from Scala using Vertx 3, but since Scala it´s not very extended language for Vertx I cannot find a good example.
Anybody can provide me some github examples please?.
Regards.

There is not official Vert.x support for Scala — yet. Jochen Mader (#codepitbull) is currently working on vertx-lang-scala. Even though it's possible to use the Java API of Vert.x.
If you are somehow experienced with Scala you could take a look at our project tableaux on GitHub. It's a project which is still under development but we already use it in production. I think the most important file to begin with are ScalaVerticle.scala and VertxExecutionContext.scala. With the latter you are able to use Scala's Future.
Edit: vertx-lang-scala is now officially part of Vert.x 3.4.0!

It's buried deep in the documentation but the key is to prefix with "scala:" or use the helper method ScalaVerticle.nameForVerticle.
See: http://vertx.io/docs/vertx-core/scala/#_accessing_the_vertx_instance_from_a_verticle
For example if you're following the example at http://vertx.io/blog/scala-is-here/ you can add main object with the body:
object VertxMain extends App {
val vertx = Vertx.vertx()
val startFuture = vertx.deployVerticleFuture(ScalaVerticle.nameForVerticle[HttpVerticle])
startFuture.onComplete{
case Success(stat) => println(s"Successfully deployed verticle $stat")
case Failure(ex) => println(s"Failed to deploy verticle $ex")
}
}

Related

Cannot mock the RedisClient class - method pipeline overrides nothing

I have a CacheService class that uses an instance of the scala-redis library
class CacheService(redisClient: RedisClient) extend HealthCheck {
private val client = redisClient
override def health: Future[ServiceHealth] = {
client.info
...
}
In my unit test, I'm mocking the client instance and testing the service
class CacheServiceSpec extends AsyncFlatSpec with AsyncMockFactory {
val clientMock = mock[RedisClient]
val service = new CacheService(clientMock)
"A cache service" must "return a successful future when healthy" in {
(clientMock.info _).expects().returns(Option("blah"))
service.health map {
health => assert(health.status == ServiceStatus.Running)
}
}
}
yet I'm getting this compilation error
Error:(10, 24) method pipeline overrides nothing.
Note: the super classes of <$anon: com.redis.RedisClient> contain the following, non final members named pipeline:
def pipeline(f: PipelineClient => Any): Option[List[Any]]
val clientMock = mock[RedisClient]
My research so far indicates ScalaMock 4 is NOT capable of mocking companion objects. The author suggests refactoring the code with Dependency Injection.
Am I doing DI correctly (I chose constructor args injection since our codebase is still relatively small and straightforward)? Seems like the author is suggesting putting a wrapper over the client instance. If so, I'm looking for an idiomatic approach.
Should I bother with swapping out for another redis library? The libraries being actively maintained, per redis.io's suggestion, use companion objects as well. I personally think this is is not a problem of these libraries.
I'd appreciate any further recommendations. My goal here is to create a health check for our external services (redis, postgres database, emailing and more) that is at least testable. Criticism is welcomed since I'm still new to the Scala ecosystem.
Am I doing DI correctly (I chose constructor args injection since our
codebase is still relatively small and straightforward)? Seems like
the author is suggesting putting a wrapper over the client instance.
If so, I'm looking for an idiomatic approach.
Yes, you are right and this seems to be a known issue(link1). Ideally, there needs to a wrapper around the client instance. One approach could be to create a trait that has a method say connect and extend it to RedisCacheDao and implement the connect method to give you the client instance whenever you require. Then, all you have to do is to mock this connection interface and you will be able to test.
Another approach could be to use embedded redis for unit testing though usually, it is used for integration testing.You can start a simple redis server where the tests are running via code and close it once the testing is done.
Should I bother with swapping out for another redis library? The
libraries being actively maintained, per redis.io's suggestion, use
companion objects as well. I personally think this is is not a problem
of these libraries.
You can certainly do that. I would prefer Jedis as it is easy and it's performance is better than scala-redis(while performing mget).
Let me know if it helps!!

Scala and 'different type of instance of trait Map: java.util.Map[K,V]'

I am getting the above mentioned Error from Scala compiler.
I am quite new to Scala and experimenting with it by converting a Java project that I have, to Scala. In my Java project, I am using Apache 'commons-chain' and I have a class that is extending 'org.apache.commons.chain.impl.ContextBase' and I am getting this error for it. I searched the internet it seems this problem has something to do with type erasure but my class doesn't not do anything special, just inherits from this class.
class SpecialContext extends ContextBase {
}
and here is the exact error I get..
Error:(10, 7) illegal inheritance;
class SpecialContext inherits different type instances of trait Map:
java.util.Map[K,V] and java.util.Map[K,V]
class SpecialContext extends ContextBase {
One of the attractions of Scala for me, while I can use nice language features of Scala, I would be still able to use the extensive number of open source libraries of the Java. After this experience, I am questioning this fact, considering my class not doing anything special, is it always this problematic to integrate the Java world and Scala world.
First my question is off-course is there a solution for the problem I described above?
Second question is, how is your experience integrating Scala and Java libraries? Or am I following the wrong way, are there ports of the popular Java libraries to Scala, like command-chain here, or lets say Spring....
Thx for answers.
The problem with ContextChain is that it uses raw types: in https://commons.apache.org/proper/commons-chain/apidocs/org/apache/commons/chain/impl/ContextBase.html you can see Map and HashMap instead of Map<Something, Something>.
Java only supports raw types to integrate with old, pre-generics code (to remind you, Java 5 was released in 2004), so you shouldn't see them in modern Java libraries. Scala doesn't support them at all.

How to resolve - method using in object WebSocket is deprecated: Use accept with an Akka streams flow instead

I am trying to migrate my application from play 2.4 to 2.5 While migrating I am trying to remove the deprecated functions. One such warning that I am receiving is "method using in object WebSocket is deprecated: Use accept with an Akka streams flow instead"
Below is the function that I need to change, How do I refactor this code to use Akka Stream Flows.
def test = WebSocket.using[String] { request =>
val in = Iteratee.ignore[String]
val out = Enumerator("<response>Test</response>").andThen(Enumerator.eof)
Logger.warn("Some warning")
(in, out)
}
I tried going through How to refactor this code by using akka streams. but could not get much. I am new to scala and play :(
Any pointers or examples would be of great help.
Cheers!
You can refer to the Play documentation to implement Akka Streams flow. That's quite straightforward.

What replaced RoutedHttpService in Spray

I've been following this blog post about Spray and Akka as it seems to be a reasonable way to separate out the implementation from the routing in an async service. However, this post being > 6 months old the Spray API seems to have changed and the RoutedHttpService it uses about half way down is nowhere to be found.
I'm fairly new to Scala and very new to Spray, and the Spray docs are at best obtuse, so I've been struggling what to replace that bit of the code with.
A couple of questions then:
Is the approach outlined in this post actually sensible?
If the answer to (1) is yes, then what should RoutedHttpService be replaced with?
If the answer to (1) is no, then is there some other docs of 'the right way' to do Spray?
For easy reference, the bit of code in question is this:
trait Api extends RouteConcatenation {
this: CoreActors with Core =>
private implicit val _ = system.dispatcher
val routes =
new RegistrationService(registration).route ~
new MessengerService(messenger).route
val rootService = system.actorOf(Props(new RoutedHttpService(routes))) // :-(
}
1) The approach described in this post is really nice but it is already advanced Scala programming. My advice, don't use it if you do not understand it.
2) RoutedHttpService is actually from the Eigengo's activator template not from the Spray API, you can find the source code here.
3) You can also have a look at this project, it gives a nice skeleton with less cake pattern composition.

Configure play-slick and samples

I'm currently trying to use Play! Framework 2.2 and play-slick (master branch).
In the play-slick code I would like to override driver definition in order to add the Oracle Driver (I'm using slick-extension). In the Config.Scala of play-slick I just saw /** Extend this to add driver or change driver mapping */ ...
I'm coming from far far away (currently reading Programming In Scala) so there's a lot to learn. So my questions are :
Can someone explain me how to extend this Config object ? this object is used in others classes ... Is the cake apttern useful here ?
Talking about cake pattern, I read the computer-database example provided by play-slick. This sample uses the cake pattern and import play.api.db.slick.Config.driver.simple._ If I'm using Oracle driver I cannot use this import, am I wrong ? How can I use the cake pattern to define an implicit session ?
Thanks a lot.
Waiting for your advices and I'm still studying the play-slick code at home :)
To extend the Config trait I do not think the cake pattern is required. You should be able to create your Config object like this:
import scala.slick.driver.ExtendedDriver
object MyExtendedConfig extends play.api.db.slick.Config {
override def driverByName: String => Option[ExtendedDriver] = {name: String =>
super.driverByName(name) orElse Map("oracledriverstring" -> OracleDriver).get(name)
}
lazy val app = play.api.Play.current
lazy val driver: ExtendedDriver = driver()(app)
}
To be able to use it you only need to do: import MyExtendedConfig.driver._ instead of import play.slick.db.api.Config.driver._. BTW, I see that the type of the driverByName could have been a Map instead of a Function making it easier to extend. This shouldn't break though, but it would be easier to do it.
I think Jonas Bonér's old blog is a great place to read what the cake pattern is (http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/). My naive understanding of it is that you have a cake pattern when you have layers that uses the self types:
trait FooComponent{ driver: ExtendedDriver =>
import driver.simple._
class Foo extends Table[Int]("") {
//...
}
}
There are 2 use cases for the cake pattern in slick/play-slick: 1) if you have tables that references other tables (as in the computer database sample) 2) to have control over exactly which database is used at which time or if you use many many different types. By using the Config you do not really need the cake pattern as long as you only have 2 different DBs (one for prod and one for test), which is the point of the Config.
Hope this answers your questions and good luck on reading Programming in Scala (loved that book :)