<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Lunatech's engineer blog]]></title><description><![CDATA[FP, Scala and Java]]></description><link>http://blog.lunatech.com</link><image><url>https://prismic-io.s3.amazonaws.com/lunatech/e835cca8cd12752589fe15810104c4e28a482ae4_photodune-6952986-system-l.jpg</url><title>Lunatech&apos;s engineer blog</title><link>http://blog.lunatech.com</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 03 Oct 2017 08:07:54 GMT</lastBuildDate><atom:link href="http://blog.lunatech.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[An Introduction to Finagle by example]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>It is a challenging task to build a large-scale web application, there are fundamental characteristics to take into account: for example, efficiency, safety and robustness. Finagle is a asynchronous, Netty based JVM RPC system made by Twitter which makes it easy to build high available clients and servers in Java and Scala. And it can even simplify your application architecture. Here I want to show you how powerful Finagle is.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_quickstart">Quickstart</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Let&#8217;s first have a quick look about how to create a Finagle micro web service and a Finagle http client to consume this api.Create a sbt project and import dependencies.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">libraryDependencies ++= Seq(
"com.twitter" %% "finagle-http" % "6.38.0",
"org.scalatest" %% "scalatest" % "2.2.4" % "test"
)</code></pre>
</div>
</div>
<div class="paragraph">
<p>First, let&#8217;s define a service. Here we define a service to receive a http request and get its url parameter as Integer then return a http response by plus 10.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import com.twitter.finagle.Serviceimport
import com.twitter.util.Futureimport
import com.twitter.finagle.http

// This is a plus 10 service
class PlusTenService extends Service[http.Request, http.Response] {

  override def apply(request: http.Request): Future[http.Response] = {
  	Future {
  		val input = request.getIntParam("num")
  		val output = input + 10
  		val response = http.Response(request.version, http.Status.Ok)
        response.setContentString(output.toString)
        response
    }
  }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then initiate and start our server</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import com.twitter.finagle.{http, Service, Http}
import com.twitter.util.Await

object QuickLookServer {
	def main(args: Array[String]): Unit = {
    val service: Service[http.Request, http.Response] = new PlusTenService    	  val server = Http.serve(":9090", service)
    Await.ready(server)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Last let&#8217;s define a client to consume this server.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import com.twitter.finagle.{Service, Http}
import com.twitter.finagle.http
import com.twitter.util.Await

object QuickLookClient {
	def main(args: Array[String]): Unit = {
    	//define a client
    	val client: Service[http.Request, http.Response] = Http.newService("localhost:9090")
		//define a request
		val request = http.Request(http.Method.Get, "/?num=5")
		//apply request on the client
		val response = client(request)
		// print response
		response.foreach(rep =&gt; println(rep.getContentString()))
		Await.result(response)
    }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you run the two application you will see the server running on localhost:9090 and client get response 15. Simple right? As you can see our service and client are both type of Service[http.Request, http.Response] . This data type really confuse me in the beginning. I will explan what&#8217;s the differences between them.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_core_of_finagle">The core of Finagle</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_service">Service</h3>
<div class="paragraph">
<p>Now let&#8217;s first have a look at the core of finagle Service[-Req, +Rep] . You can find the definition in com.twitter.finagle.Service . In Finagle 6.38.0 the definition of Service is an abstract class, in previous version it was a trait</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">abstract class Service[-Req, +Rep] extends (Req =&gt; Future[Rep])</code></pre>
</div>
</div>
<div class="paragraph">
<p>A service is a function that takes request of type Req, and return a response of Future of Rep. This Services type are used to represent both clients and servers. To answer my previous question, the differences between service and client is that a Finagle client “imports” a Service from the network. However, a Finagle server “exports” a Service to the network.Note: the Future here is twitter future not scala future. There is no differences on conception.</p>
</div>
</div>
<div class="sect2">
<h3 id="_filter">Filter</h3>
<div class="paragraph">
<p>Some times we want to add application-agnostic behaviour, we can use Filter to achieve this.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">abstract class Filter[-ReqIn, +RepOut, +ReqOut, -RepIn]
extends ((ReqIn, Service[ReqOut, RepIn])
=&gt; Future[RepOut])</code></pre>
</div>
</div>
<div class="imageblock">
<div class="content">
<img src="https://prismic-io.s3.amazonaws.com/lunatech/4694105fa7ee7fd867da04057d2fae977d89cdbc_yue1.png" alt="4694105fa7ee7fd867da04057d2fae977d89cdbc yue1.png">
</div>
</div>
<div class="paragraph">
<p>If it is not clear please check image below.</p>
</div>
<div class="imageblock">
<div class="content">
<img src="http://blog.lunatech.com/images/:https://prismic-io.s3.amazonaws.com/lunatech/4694105fa7ee7fd867da04057d2fae977d89cdbc_yue1.png" alt="4694105fa7ee7fd867da04057d2fae977d89cdbc yue1.png">
</div>
</div>
<div class="paragraph">
<p>In most common cases, ReqIn is equal to ReqOut, and RepIn is equal to RepOut. So we have this SimpleFilter class</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">abstract class SimpleFilter[Req, Rep] extends Filter[Req, Rep, Req, Rep]</code></pre>
</div>
</div>
<div class="paragraph">
<p>A filter can attached to client and server side. Let&#8217;s try to implement a simple timeout filter.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import com.twitter.finagle.{SimpleFilter, Service}import com.twitter.util.{Duration, Timer, Future}

class TimeoutFilter[Req, Rep](timeout: Duration, timer: Timer)
extends SimpleFilter[Req, Rep] {

  def apply(request: Req, service: Service[Req, Rep]): Future[Rep] = {
  val res = service(request)
  res.within(timer, timeout)  }
  }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here, a timeout filter is a class extends SimpleFilter trait. Below is how to use this filter on client side</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">client = Http.newService("localhost:9090")

val timeoutFilter = new TimeoutFilter[http.Request, http.Response](Duration.fromSeconds(1),
new JavaTimer(false))

val clientWithTimeoutFilter = timeoutFilter.andThen(quickLookClient)</code></pre>
</div>
</div>
<div class="paragraph">
<p>A filter can be applied on server side too. Here is an example. First let&#8217;s define a filter.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">class CountFilter[Req, Rep](countClient: Service[http.Request, http.Response])
extends SimpleFilter[Req, Rep]
{  override def apply(request: Req, service: Service[Req, Rep]): Future[Rep] =
{    val countRequest = http.Request(http.Method.Post, "/?count=5")    countClient(countRequest)    service(request)  }}</code></pre>
</div>
</div>
<div class="paragraph">
<p>And then let&#8217;s use it on our plusTen service</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">al service: Service[http.Request, http.Response] = new PlusTenService

val countClient = Http.newService("localhost:9010")

val countFilter = new CountFilter[http.Request, http.Response](countClient)

val serviceWithCountFilter = countFilter.andThen(service)</code></pre>
</div>
</div>
<div class="paragraph">
<p>You may notice the way to chain filter and service together is by using andThen method. Actually andThen method can not only chain filter with service but also chain multiple filters, like filter1 andThen filter2 andThen myservice</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_client">Client</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This is the part that I like the most in finagle. Finagle http client is designed to maximize success and minimize latency. Each request will flow through various modules. These modules are logically separated into three stacks: Client stack, Endpoint stack, connection stack.</p>
</div>
<div class="paragraph">
<p><strong>Client stack</strong></p>
</div>
<div class="paragraph">
<p>manages name resolution and balances requests across multiple endpoints.</p>
</div>
<div class="paragraph">
<p><strong>Endpoint stack</strong></p>
</div>
<div class="paragraph">
<p>provides circuit breakers and connection pooling.</p>
</div>
<div class="paragraph">
<p><strong>connection stack</strong></p>
</div>
<div class="paragraph">
<p>provides connection life-cycle management and implements the wire protocol.</p>
</div>
<div class="paragraph">
<p>To use finagle http client is very simple. Define a client first and define a http request, then apply request on the client.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">// create a http clientval client =
Http.client.newService("example.com:80")
// create a http requestval req =
Request("/foo", ("my-query-string", "bar")
)
// apply request on the clientval resp: Future[Response] = client(req)Note: client(req) is equal to client.apply(req)</code></pre>
</div>
</div>
<div class="paragraph">
<p>What I want to emphasis here is the Load Balancer module. This module brings a lot of benefit for your application. It can simplify your application infstracture. Let&#8217;s compare it with traditional solution.</p>
</div>
<div class="paragraph">
<p>image</p>
</div>
<div class="paragraph">
<p>As you can see, the traditional solution highly rely on nginx as load balancer, once nginx dead your service is not reachable, in real production environment, you have master-slave nginx wiht keeplived installed on nginx machine for heartbeat detection. This looks really complex, what about if we can get rid of these nginx?Let&#8217;s have look at following code.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">name: Name =
Name.bound(Address("localhost", 10010), Address("localhost", 10011), Address("localhost", 10012)
)
//define a clientval client: Service[http.Request, http.Response] = Http.newService(name, "client")</code></pre>
</div>
</div>
<div class="paragraph">
<p>This means you supply three addresses and put it into finagle http client. Finagle client will dispatch the request to one of address based on certain load balance algorithmn. The default algorithmn is "Exponentially Weighted Moving Average (EWMA)". Now your infstracture architechture becomes like following</p>
</div>
<div class="paragraph">
<p>image</p>
</div>
<div class="paragraph">
<p>Pretty simple right. Your apis talk to each other directly.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_protocol_agnostic">Protocol-agnostic</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Finagle is a protocol-agnostic RPC system. It means Finagle supports every protocol if people implement it. For example: finagle-thrift is using thrift protocol. finagle-mysql implements the mysql protocol.Now, let&#8217;s look at this scenario</p>
</div>
<div class="paragraph">
<p>image</p>
</div>
<div class="paragraph">
<p>We want to make a api count service to count how many times the web service has been called. In section Service and Filter. We send http request and put number as query parameter. It just feel strange that I just want to send a number to count server, to achieve that I have to send a http request. Because I don&#8217;t use any data from header, cookie and body. If the application is running on AWS, it those junk information cost money. So it&#8217;s ideal to just send a integer number to api count service. Let&#8217;s implement this by customize finagle protocol.First, we should tell finagle how to converts an scodec codec into a Netty encoder</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import org.jboss.netty.buffer.{ChannelBuffer, ChannelBuffers}import org.jboss.netty.channel.{Channel, ChannelHandlerContext}import org.jboss.netty.handler.codec.oneone.{OneToOneDecoder, OneToOneEncoder}import scodec.Codecimport scodec.bits.BitVector

trait CodecConversions {  /**    * Converts an scodec codec into a Netty encoder.    */  protected def encoder[A: Codec] =
new OneToOneEncoder {
override def encode(ctx: ChannelHandlerContext, channel: Channel, msg: Object) =

ChannelBuffers.wrappedBuffer(        Codec.encodeValid(msg.asInstanceOf[A]).toByteBuffer      )
}

  /**    * Converts an scodec codec into a Netty decoder.
  */  protected def decoder[A: Codec] = new OneToOneDecoder {
  override def decode(ctx: ChannelHandlerContext, channel: Channel, msg: Object) =
  msg match {
  case cb: ChannelBuffer =&gt;          Codec.decodeValidValue[A](BitVector(cb.toByteBuffer)).asInstanceOf[Object]        case other =&gt; other      }
  }
  }</code></pre>
</div>
</div>
<div class="paragraph">
<p>And then channel pipeline and codec factories</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">trait Factories { this: CodecConversions =&gt;  import com.twitter.finagle.{Codec =&gt; FinagleCodec, CodecFactory}  import org.jboss.netty.channel.{ChannelPipelineFactory, Channels}

  /**   * Creates a Netty channel pipeline factory given input and output types.   */  private[this] def pipeline[I: Codec, O: Codec] = new ChannelPipelineFactory {    def getPipeline = {      val pipeline = Channels.pipeline()      pipeline.addLast("encoder", encoder[I])      pipeline.addLast("decoder", decoder[O])
  pipeline    }
  }
  /**   * Creates a Finagle codec factory given input and output types.   */  protected def codecFactory[I: Codec, O: Codec] = new CodecFactory[I, O] {
  def server = Function.const {
  new FinagleCodec[I, O] { def pipelineFactory = pipeline[O, I] }
  }
    def client = Function.const {
    new FinagleCodec[I, O] { def pipelineFactory = pipeline[I, O] }
    }
    }
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>And then the code that actually creates our Finagle server and client</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import java.net.InetSocketAddress

import com.twitter.conversions.time._import com.twitter.finagle.Serviceimport com.twitter.finagle.builder.{ClientBuilder, ServerBuilder}import com.twitter.util.{Duration, Future}import scodec.Codec

object IntegerServerAndClient extends Factories with CodecConversions {

  /**    * Creates a Finagle server from a service that we have scodec codecs    * for both the input and output types.    */  def server[I, O](port: Int)(service: Service[I, O])(implicit ic: Codec[I], oc: Codec[O]) =    ServerBuilder()
  .name("server")
  .codec(codecFactory[I, O])
  .bindTo(new InetSocketAddress(port))      .build(service)

  /**    * Creates a Finagle client given input and output types with scodec codecs.    */  def client[I, O](host: String, timeout: Duration = 3.second)                  (implicit ic: Codec[I], oc: Codec[O]) =    ClientBuilder()
  .name("client")
  .codec(codecFactory[I, O])
  .hosts(host)
  .timeout(timeout)
  .build()
  }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Define our simple service</p>
</div>
<div class="listingblock">
<div class="content">
<pre>import com.twitter.finagle.Serviceimport com.twitter.util.Future

class IntegerService extends Service[Int, Int]{  var count = 0  override def apply(request: Int): Future[Int] = {    Future.value(count + request)  }
}</pre>
</div>
</div>
<div class="paragraph">
<p>Run a server</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import com.twitter.finagle.Serviceimport com.twitter.util.Awaitimport scodec.codecs.implicits.{ implicitIntCodec =&gt; _, _ }

object Server {  def main(args: Array[String]): Unit = {    implicit val intgerCodec =
scodec.codecs.uint8

    val service: Service[Int, Int] =
    new IntegerService
    val server = IntegerServerAndClient.server[Int, Int](9191)(service)    Await.ready(server)
    }
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Run a client</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import com.twitter.finagle.Serviceimport com.twitter.util.Awaitimport scodec.codecs.implicits.{ implicitIntCodec =&gt; _, _ }

object Client {  def main(args: Array[String]): Unit = {

    implicit val intgerCodec = scodec.codecs.uint8

    //define a client
    val client: Service[Int, Int] = IntegerServerAndClient.client[Int, Int]("localhost:9191")    //define a request
    val request = 4
    //apply request on the client
    val response = client(request)
    //print response    response.foreach(rep =&gt; println(s"This is response $rep"))
    Await.result(response)
    }
    }</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_conclusion">Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Finagle is a very flexible asychronous, protocol-agnostic RPC framework. It can help you to build high performance micro service with any protocol. It is worth to take a look at Finch the web framework based on Finagle. You can find more detail introduction from <a href="https://blog.twitter.com/2011/finagle-a-protocol-agnostic-rpc-system">Twitter blog</a> and more detailed example from <a href="http://twitter.github.io/scala_school/searchbird.html">Twitter scala school</a>.</p>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/11/28/An-Introduction-to-Finagle-by-example.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/11/28/An-Introduction-to-Finagle-by-example.html</guid><category><![CDATA[Finagle]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 28 Nov 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Functional IO with FS2 Streams]]></title><description><![CDATA[<div class="sect1">
<h2 id="_functional_io_with_fs2_streams">Functional IO with FS2 Streams</h2>
<div class="sectionbody">
<div class="paragraph">
<p>One of the main principles of functional programming is to avoid side-effects. For the most part, working with immutable instances would be sufficient to satisfy that principle. But sometimes it&#8217;s needed to do some side effects e.g. when we want to read from file. One straight-forward way of doing it is to get a <code>BufferedSource</code>, and process it using an iterator as shown below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def readFromFile(fileName: String) {
val src: BufferedSource = io.Source.fromFile(fileName)
val it: Iterator[String] = src.getLines
val _ = while(it.hasNext) {
val line = it.next()
println(line)
}
src.close()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then it is not too difficult to recursively convert the iterator to a Scala Stream of lines, without processing the whole iterator, using lazy evaluation. So we would end up with a function with signature:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">   def read(pathToFile: Path): Stream[String]</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are few problems that can arise from this function:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>First, if an exception occurs and we still haven&#8217;t reached the end of the resulting Stream, or if we forget to close the <code>BufferedSource</code>, then the file would stay open, which is called resource leaking. Therefore, the above function is not resource-safe.- Second and more tricky, when we call the function read for a 2nd time, it may return a different result as someone may have modified the file between the two calls. We are forced to have some intrinsic knowledge about the file, therefore, the function <code>read</code> breaks referential transparency.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In this blog-post we are going to tackle those two problems and learn how to avoid imperative troublesome IO using a specialized Scala library - FS2 (previously known as Scalaz-Stream).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_idea_of_functional_streams">The Idea of Functional Streams</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The idea for solving the problem of resource-safety is to define a wrapper data type - <code>Process[F[<em>],O]</code>, where the left generic type <code>F</code> would know how to close the resource (the file) when it&#8217;s needed. In that way we can guarantee resource-safety without having to do anything non-related to reading from file (such as handling an exception). We can think of <code>Process[F[</em>],O]</code> as a type that represents a <strong>Stream builder</strong>, possibly producing/using some side effect. For example when reading from file we would work with <code>Process[Task, String]</code>, where <code>Task</code> knows how to execute and handle an operation (by assigning it to a thread). But note that it doesn&#8217;t start the execution immediately. It only starts when we call some of its executor-methods. Another example is when writing to output stream, in which case we  would use <code>Process[Task, Unit]</code>. Hence, we can say <code>Process[F[_],O]</code> is like a function <code>F[O] &#8658; Stream[O]</code>, but more powerful, and we will see exactly how is it more powerful.</p>
</div>
<div class="paragraph">
<p>The idea for solving the second problem is <strong>to separate the logic of computation from actual computation</strong>. Note that the logic of how reading from file is done doesn&#8217;t change through the course of our program&#8217;s lifecycle. Only the result of executing that logic changes (since it involves a side-effect). So we are going to say that the left type - <code>F[O]</code> in <code>Process</code> knows how to evaluate effects. In that way we can represent our logic of computation, and delegate the responsibilities of executing that logic (and handling possible exceptions of the execution) to <code>F</code>. Most often we would substitute the generic type <code>F</code>  with  <code>Task</code> (which in addition allows concurrent composition of streams).</p>
</div>
<div class="paragraph">
<p>Right now it may seem too much is going on. But as with every other paradigm, once we get a hands-on experience, we are going to feel comfortable working with it. The important conceptual thing to remember is that the left type <code>F</code> is responsible for closing resources and assigning operations to threads. In what follows, we are going to see examples of functional streams using the library <strong>FS2</strong>, a library that implements the above ideas.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_how_to_use_fs2">How to Use FS2</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This is how we use FS2 for reading a file&#8230;&#8203;</p>
</div>
<div class="paragraph">
<p>First we must add its dependencies:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">"co.fs2" %% "fs2-core" % "0.9.1",
"co.fs2" %% "fs2-io" % "0.9.1",</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then, similar to Scala&#8217;s <code>Future</code>, we must provide a strategy for execution:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">implicit val strategy = Strategy.fromFixedDaemonPool(4)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then we define the pipeline of transformations:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val lines: Stream[Task, String] =
io.file.readAllAsync[Task](pathToFile, 4096)
.through(text.utf8Decode)
 .through(text.lines)
----
val lines: Stream[Task, String] =	io.file.readAllAsync[Task](pathToFile, 4096)` - we get a Stream[Task, Byte].through(text.utf8Decode)` - we get a Stream[Task, String], but newline is disregarded.through(text.lines)` - we get the final Stream[Task, String] representing lines.</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>Stream[F[<em>], O]</code> is the FS2 implementation of what we denoted by <code>Process[F[</em>],O]</code>.</p>
</div>
<div class="paragraph">
<p>Note that the above code doesn&#8217;t read anything. We postpone it as much as possible, usually until the end of the world (our <code>main</code> method). At that point we must do two things:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>First, we compile the pipeline of transformations, combining all the intermediate Tasks into a single Task. We do that by calling <code>lines.run</code>, which gives us a` Task[Unit]<code>.- Second, we execute the pipeline by calling `lines.run.unsafeRun()</code>, so we end up with a single result-value, in this case <code>Unit</code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In addition, <code>Stream[F[<em>], O]</code> is also a <code>Monad</code>, so we can do almost everything that we can do with a <code>Seq</code>. That is one argument why the FS2 is much more powerful than a builder-function <code>F[</em>] &#8658; O</code>.</p>
</div>
</div>
</div>
<h1 id="_pulling" class="sect0">Pulling</h1>
<div class="paragraph">
<p>Another very useful and powerful functionality that FS2 supports is pulling. Sometimes we don&#8217;t want to map over all the elements of an FS2Stream , but halt the process of mapping and end up with a smaller FS2Stream. We can implement that with the method <code>pull</code> defined on FS2Stream:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">.pull[Task, Path](using: (Handle[Task, Path]) =&gt; Pull[Task, Path, Nothing]))</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that we wrote FS2Stream, so to avoid mixing it with the standard Scala <code>Stream</code>.</p>
</div>
<div class="paragraph">
<p>Now comes the tricky part - how to define the auxiliary function <code>using</code>. The simplest  way to explain that function is to say <code>Handle</code> knows how to retrieve the next element in a FS2Stream, and <code>Pull</code> knows how to pick up elements that we want to select and output as a side-effect of the pulling.</p>
</div>
<div class="paragraph">
<p>For example, imagine we want to output elements produced in the process of iterating, but produce element only in some steps of the iteration. Then we can do the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def using(): (Handle[Task, A], accumulator: FS2Stream[Task,
B]) =&gt; Pull[Task, A, Nothing] = {  newHandle: Handle[Task, A]

=&gt;    val nextPull: Pull[Task, A, Handle[Task, A]] =
for {      (nextElement: A, newHandle: Handle[Task, A])
&lt;- newHandle.await1

updatedAcc = ...

//update the accumulator and pass back the updated one      _ &lt;- someCheckingOfA match {
case ... =&gt;          Pull.pure(())
//nothing to pick up         case ... =&gt;          Pull.output1(something)
//pick up something
}
} yield (nextHandle, updatedAcc)

    nextPull.flatMap((nextHandle: Handle[Task, A]) =&gt;      using()(nextHandle)    )
    }`</code></pre>
</div>
</div>
<div class="paragraph">
<p>, and we would apply <code>using()</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">someFS2Stream.pull[Task, A]((handle: Handle[Task, A])
=&gt;                             using()(handle, emptyAccumulator)
)</code></pre>
</div>
</div>
<div class="sect1">
<h2 id="_conclusion">Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p><strong>FS2</strong> is a masterpiece library that allows us to work with side effects in a resource-safe, consistent, and memory-efficient way. It does all that in a fully functional and composable way, and on top of all that, it supports concurrency. In another blog-post I am going to explain how we can do concurrent computations with FS2.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_useful_links">Useful Links</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p><a href="https://www.youtube.com/watch?v=cahvyadYfX8&amp;list=PLFrwDVdSrYE6PVD_p6YQLAbNaEHagx9bW&amp;index=1Intro">to Functional Streams for Scala</a></p>
</li>
<li>
<p><a href="http://www.slideshare.net/InfoQ/compositional-io-stream-in-scalaCompositional">I/O Stream in Scala</a></p>
</li>
<li>
<p><a href="https://github.com/functional-streams-for-scala/fs2Github">official repository for FS2</a></p>
</li>
<li>
<p><a href="https://gist.github.com/djspiewak/d93a9c4983f63721c41cTutorial">for scalaz-stream</a></p>
</li>
<li>
<p><a href="https://github.com/eamelink/fs2-keystores-poc/blob/master/src/main/scala/MyApp.scala">Example of FS2 pulling</a></p>
</li>
</ul>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/11/14/My-English-Title.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/11/14/My-English-Title.html</guid><category><![CDATA[fp]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 14 Nov 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Functional IO with FS2 Streams]]></title><description><![CDATA[<div class="sect1">
<h2 id="_functional_io_with_fs2_streams">Functional IO with FS2 Streams</h2>
<div class="sectionbody">
<div class="paragraph">
<p>One of the main principles of functional programming is to avoid side-effects. For the most part, working with immutable instances would be sufficient to satisfy that principle. But sometimes it&#8217;s needed to do some side effects e.g. when we want to read from file. One straight-forward way of doing it is to get a <code>BufferedSource</code>, and process it using an iterator as shown below.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def readFromFile(fileName: String) {
	val src: BufferedSource = io.Source.fromFile(fileName)
	val it: Iterator[String] = src.getLines
	val _ = while(it.hasNext) {
		val line = it.next()
		println(line)
	}
	src.close()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then it is not too difficult to recursively convert the iterator to a Scala Stream of lines, without processing the whole iterator, using lazy evaluation. So we would end up with a function with signature:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">   def read(pathToFile: Path): Stream[String]</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are few problems that can arise from this function:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>First, if an exception occurs and we still haven&#8217;t reached the end of the resulting Stream, or if we forget to close the <code>BufferedSource</code>, then the file would stay open, which is called resource leaking. Therefore, the above function is not resource-safe.- Second and more tricky, when we call the function read for a 2nd time, it may return a different result as someone may have modified the file between the two calls. We are forced to have some intrinsic knowledge about the file, therefore, the function <code>read</code> breaks referential transparency.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In this blog-post we are going to tackle those two problems and learn how to avoid imperative troublesome IO using a specialized Scala library - FS2 (previously known as Scalaz-Stream).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_idea_of_functional_streams">The Idea of Functional Streams</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The idea for solving the problem of resource-safety is to define a wrapper data type - <code>Process[F[<em>],O]</code>, where the left generic type <code>F</code> would know how to close the resource (the file) when it&#8217;s needed. In that way we can guarantee resource-safety without having to do anything non-related to reading from file (such as handling an exception). We can think of <code>Process[F[</em>],O]</code> as a type that represents a <strong>Stream builder</strong>, possibly producing/using some side effect. For example when reading from file we would work with <code>Process[Task, String]</code>, where <code>Task</code> knows how to execute and handle an operation (by assigning it to a thread). But note that it doesn&#8217;t start the execution immediately. It only starts when we call some of its executor-methods. Another example is when writing to output stream, in which case we  would use <code>Process[Task, Unit]</code>. Hence, we can say <code>Process[F[_],O]</code> is like a function <code>F[O] &#8658; Stream[O]</code>, but more powerful, and we will see exactly how is it more powerful.</p>
</div>
<div class="paragraph">
<p>The idea for solving the second problem is <strong>to separate the logic of computation from actual computation</strong>. Note that the logic of how reading from file is done doesn&#8217;t change through the course of our program&#8217;s lifecycle. Only the result of executing that logic changes (since it involves a side-effect). So we are going to say that the left type - <code>F[O]</code> in <code>Process</code> knows how to evaluate effects. In that way we can represent our logic of computation, and delegate the responsibilities of executing that logic (and handling possible exceptions of the execution) to <code>F</code>. Most often we would substitute the generic type <code>F</code>  with  <code>Task</code> (which in addition allows concurrent composition of streams).</p>
</div>
<div class="paragraph">
<p>Right now it may seem too much is going on. But as with every other paradigm, once we get a hands-on experience, we are going to feel comfortable working with it. The important conceptual thing to remember is that the left type <code>F</code> is responsible for closing resources and assigning operations to threads. In what follows, we are going to see examples of functional streams using the library <strong>FS2</strong>, a library that implements the above ideas.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_how_to_use_fs2">How to Use FS2</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This is how we use FS2 for reading a file&#8230;&#8203;</p>
</div>
<div class="paragraph">
<p>First we must add its dependencies:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>"co.fs2" %% "fs2-core" % "0.9.1",
"co.fs2" %% "fs2-io" % "0.9.1",</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then, similar to Scala&#8217;s <code>Future</code>, we must provide a strategy for execution:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">implicit val strategy = Strategy.fromFixedDaemonPool(4)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then we define the pipeline of transformations:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val lines: Stream[Task, String] =
	io.file.readAllAsync[Task](pathToFile, 4096)
						.through(text.utf8Decode)
 						.through(text.lines)</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>val lines: Stream[Task, String] =	io.file.readAllAsync[Task](pathToFile, 4096)</code> - we get a <code>Stream[Task, Byte].through(text.utf8Decode)</code> - we get a <code>Stream[Task, String], but newline is disregarded.through(text.lines)</code> - we get the final <code>Stream[Task, String]</code> representing lines.</p>
</div>
<div class="paragraph">
<p><code>Stream[F[<em>], O]</code> is the FS2 implementation of what we denoted by <code>Process[F[</em>],O]</code>.</p>
</div>
<div class="paragraph">
<p>Note that the above code doesn&#8217;t read anything. We postpone it as much as possible, usually until the end of the world (our <code>main</code> method). At that point we must do two things:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>First, we compile the pipeline of transformations, combining all the intermediate Tasks into a single Task. We do that by calling <code>lines.run</code>, which gives us a <code>Task[Unit]</code>.- Second, we execute the pipeline by calling <code>lines.run.unsafeRun()</code>, so we end up with a single result-value, in this case <code>Unit</code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In addition, <code>Stream[F[<em>], O]</code> is also a <code>Monad</code>, so we can do almost everything that we can do with a <code>Seq</code>. That is one argument why the FS2 is much more powerful than a builder-function <code>F[</em>] &#8658; O</code>.</p>
</div>
</div>
</div>
<h1 id="_pulling" class="sect0">Pulling</h1>
<div class="paragraph">
<p>Another very useful and powerful functionality that FS2 supports is pulling. Sometimes we don&#8217;t want to map over all the elements of an FS2Stream , but halt the process of mapping and end up with a smaller FS2Stream. We can implement that with the method <code>pull</code> defined on FS2Stream:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">.pull[Task, Path](using: (Handle[Task, Path]) =&gt; Pull[Task, Path, Nothing]))</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that we wrote FS2Stream, so to avoid mixing it with the standard Scala <code>Stream</code>.</p>
</div>
<div class="paragraph">
<p>Now comes the tricky part - how to define the auxiliary function <code>using</code>. The simplest  way to explain that function is to say <code>Handle</code> knows how to retrieve the next element in a FS2Stream, and <code>Pull</code> knows how to pick up elements that we want to select and output as a side-effect of the pulling.</p>
</div>
<div class="paragraph">
<p>For example, imagine we want to output elements produced in the process of iterating, but produce element only in some steps of the iteration. Then we can do the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def using(): (Handle[Task, A], accumulator: FS2Stream[Task, B]) =&gt; Pull[Task, A, Nothing] = {
	newHandle: Handle[Task, A] =&gt;
    	val nextPull: Pull[Task, A, Handle[Task, A]] =
          for {
              (nextElement: A, newHandle: Handle[Task, A]) &lt;- newHandle.await1   			  updatedAcc = ...
              //update the accumulator and pass back the updated one
              _ &lt;- someCheckingOfA match {
                      case ... =&gt; Pull.pure(())
                      //nothing to pick up
                      case ... =&gt;  Pull.output1(something)
                      //pick up something
              }
          } yield (nextHandle, updatedAcc)
        nextPull.flatMap((nextHandle: Handle[Task, A]) =&gt; using()(nextHandle))
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>, and we would apply <code>using()</code> as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">someFS2Stream.pull[Task, A]((handle: Handle[Task, A]) =&gt; using()(handle, emptyAccumulator))</code></pre>
</div>
</div>
<div class="sect1">
<h2 id="_conclusion">Conclusion</h2>
<div class="sectionbody">
<div class="paragraph">
<p><strong>FS2</strong> is a masterpiece library that allows us to work with side effects in a resource-safe, consistent, and memory-efficient way. It does all that in a fully functional and composable way, and on top of all that, it supports concurrency. In another blog-post I am going to explain how we can do concurrent computations with FS2.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_useful_links">Useful Links</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p><a href="https://www.youtube.com/watch?v=cahvyadYfX8&amp;list=PLFrwDVdSrYE6PVD_p6YQLAbNaEHagx9bW&amp;index=1Intro">to Functional Streams for Scala</a></p>
</li>
<li>
<p><a href="http://www.slideshare.net/InfoQ/compositional-io-stream-in-scalaCompositional">I/O Stream in Scala</a></p>
</li>
<li>
<p><a href="https://github.com/functional-streams-for-scala/fs2Github">official repository for FS2</a></p>
</li>
<li>
<p><a href="https://gist.github.com/djspiewak/d93a9c4983f63721c41cTutorial">for scalaz-stream</a></p>
</li>
<li>
<p><a href="https://github.com/eamelink/fs2-keystores-poc/blob/master/src/main/scala/MyApp.scala">Example of FS2 pulling</a></p>
</li>
</ul>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/11/14/Functional-IO-with-F-S-Streams.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/11/14/Functional-IO-with-F-S-Streams.html</guid><category><![CDATA[fp]]></category><dc:creator><![CDATA[Nicolas Leroux]]></dc:creator><pubDate>Mon, 14 Nov 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Side Effects and How To Deal With Them The Cool Way, Part 2: Monads Introduction]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>In <a href="http://www.lunatech.com/blog/WASQJiQAANmjwKxf/side-effects-and-how-to-deal-with-them-the-cool-way-part-1-pure-fonctions-and-functors">part 1</a> of this series we learnt how to decouple the code that deals with side effects from our pure functions by using functors (Any type constructor which implements the map function). Now lets see how we can extend our functors so that we can sequence computations that each fall under the indeterminism of side effects.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_function_composition_and_a_slight_issue">Function Composition And a Slight Issue</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Remember that we mentioned that the <code>Option[A]</code> type in the standard library of scala is a functor, that actually handles the side effect of possible missing values. Now lets create two pure functions to compute integers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val f: Int =&gt; Int =
x =&gt; x + 5

val g: Int =&gt; Boolean =
x =&gt; x &gt; 10

val gof: Int =&gt; Boolean = g compose f

gof(6)
&gt; true</code></pre>
</div>
</div>
<div class="paragraph">
<p>The essence of functional programming is doing this, create programs from composing small functions into larger functions, which provide us with the type safety and the determinism of pure functions. but what happens when we have functions that require to handle a side effect and return the appropriate type constructor?</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val f: Int =&gt; Int =
x =&gt; x + 5

val filter10: Int =&gt; Option[Int] =
x =&gt; if (x &gt; 10) Some(x) else None

val gof: Int =&gt; Boolean = f compose filter10&gt;
error: type mismatch;
found   : Int =&gt; Option[Int] required: ? =&gt; Int
f compose filter</code></pre>
</div>
</div>
<div class="paragraph">
<p>On this case our <code>map</code> function from our functor can help us:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val sumIfMoreThan10: Int =&gt; Option[Int] =	x =&gt; filter10(x).map(f)

sumIfMoreThan10(15)&gt;
Option[Int] = Some(20)

sumIfMoreThan10(9)&gt;
Option[Int] = None</code></pre>
</div>
</div>
<div class="paragraph">
<p>Great the <code>map</code> function is allowing a type of function composition, but now what happens when we want to compose more functions that return our functor?</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val f: Int =&gt; Int =
x =&gt; x + 5

val filter10: Int =&gt; Option[Int] =
x =&gt; if (x &gt; 10) Some(x) else None

val sumIfMoreThan10: Int =&gt; Option[Int] =
x =&gt; filter10(x).map(f)

val sumIfPositive: Int =&gt; Option[Int] =
x =&gt; if (x &gt; 0) Some(f(x)) else None

val total: Int =&gt; Option[Int] =
x =&gt; sumIfPositive(6).map(sumIfMoreThan10)
&gt; error: type mismatch;
found   : Int =&gt; Option[Int]
required: Int =&gt; Int
val total: Int =&gt; Option[Int] =
x =&gt; sumIfPositive(6).map(sumIfMoreThan10)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Oh no, we have a problem, we cannot compose side effects only using <code>map</code>, we need a new mechanism for combination. Lets do it then! lets introduce a function similar to <code>map</code> but called <code>flatMap</code>! (Because it will 'flatten' the structure between two functors.)</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_monads_the_combinator_we_were_looking_for">Monads! The Combinator We Were Looking For</h2>
<div class="sectionbody">
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">trait Option[+A] {
def value: A

	def isDefined: Boolean

	def map[B](f: A=&gt;B): Option[B] =
    flatMap(x =&gt; Some(f(x)))

	def flatMap[B](f: A=&gt;Option[B]): Option[B] =
    if(isDefined) f(value) else None
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you may have already guessed, the scala library already implements this function, but lets analyse it any way: <code>flatMap</code> is very similar to our last definition to <code>map</code>, but since the provided effectful function <code>f</code> is already giving us an <code>Option</code> then we do not need to wrap it. Also notice that we redefined <code>map</code> in terms of our new <code>flatMap</code>, clever right?</p>
</div>
<div class="paragraph">
<p>Now this new mechanism will allow us to combine effectful functions! (functions that return a functor instead of a pure value).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">val f: Int =&gt; Int =
x =&gt; x + 5
val filter10: Int =&gt; Option[Int] =
x =&gt; if (x &gt; 10) Some(x) else None
val sumIfMoreThan10: Int =&gt; Option[Int] =
x =&gt; filter10(x).map(f)
val sumIfPositive: Int =&gt; Option[Int] =
x =&gt; if (x &gt; 0) Some(f(x)) else None
val total: Int =&gt; Option[Int] =
x =&gt; sumIfPositive(x).flatMap(sumIfMoreThan10)
total(6)
&gt; Option[Int] = Some(16)
total(-1)
&gt; Option[Int] = None</code></pre>
</div>
</div>
<div class="paragraph">
<p>Amazing right! And you just have been introduced to the concept of a monad! Any type constructor that supports the <code>flatMap</code> function is known as a monad. <code>flatMap</code> and <code>map</code> (a monad) allow us to not just decouple the side effect handling code from our functions, but also gives us the mechanism to compose our functions (effectful or pure) to make bigger programs that handle side effects perfectly and are more maintainable because we can split the program into smaller peaces which are easy to combine.</p>
</div>
</div>
</div>
<h1 id="_more_about_monads" class="sect0">More About Monads</h1>
<div class="paragraph">
<p>On the last post we created a type class to generalise the concept of a functor, lets do the same for a monad. Notice that we implemented <code>map</code> in terms of <code>flatMap</code>, which means that every type constructor with <code>flatMap</code> can automatically have a <code>map</code> function, hence every Monad is also a Functor!</p>
</div>
<div class="paragraph">
<p>To further formalise the definition of a monad we need also a function called <code>pure</code> (which is actually the signature of an Applicative, but we can view Applicatives in another post [every Monad is an Applicative, and every Applicative is a Functor]). The <code>pure</code> function "lifts" a pure value into the context of a monad:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">trait Monad[F[_]] extends Functor[F] {
def pure[A](a: A): F[A]
def map[A, B](M: F[A])(f: A =&gt; B): F[B] =
flatMap(M)(x =&gt; pure(f(x)))
def flatMap[A, B](M: F[A])(f: A =&gt; F[B]): F[B]
}</code></pre>
</div>
</div>
<h1 id="_left_identity" class="sect0">Left identity:</h1>
<div class="paragraph">
<p>If we lift a pure value, and then flatMap with a monadic function (a function with the signature <code>A &#8658; F[A]</code> where <code>A</code> is a pure value and <code>F[_]</code> a Monad type constructor) then that must be equal to just passing the pure value through the monadic function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">pure(a).flatMap(f) === f(a)</code></pre>
</div>
</div>
<h1 id="_right_identity" class="sect0">Right identity:</h1>
<div class="paragraph">
<p>If we take a monadic value <code>m</code> (a pure value that has been lifted to the context of a monad, has signature <code>M[A]</code>) and flatMap the <code>pure</code> function from it, that must be equal to the original <code>m</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">m.flatMap(pure) === m</code></pre>
</div>
</div>
<h1 id="_associativity" class="sect0">Associativity:</h1>
<div class="paragraph">
<p>Let <code>m</code> be a monadic value, and <code>f</code> and <code>g</code> monadic functions, then it must be that flat mapping <code>f</code> and then <code>g</code> be equal to composing <code>f</code> and <code>g</code> first (using flatMap) and then using the resulting monadic function to flatMap from <code>m</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">m.flatMap(f).flatMap(g) === m.flatMap(\x =&gt; f(x).flatMap g)</code></pre>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/10/31/Side-Effects-and-How-To-Deal-With-Them-The-Cool-Way-Part-2-Monads-Introduction.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/10/31/Side-Effects-and-How-To-Deal-With-Them-The-Cool-Way-Part-2-Monads-Introduction.html</guid><category><![CDATA[monad]]></category><dc:creator><![CDATA[Nicolas Leroux]]></dc:creator><pubDate>Mon, 31 Oct 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Play Framework - Beginner Tutorial : Make a post request and save the form data in Mongodb]]></title><description><![CDATA[<div class="sect1">
<h2 id="_before_the_tutorial">Before the tutorial</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You should : - read  - <a href="https://www.playframework.com/documentation/2.5.x/ScalaActions">Play Documentation : ScalaActions</a> - <a href="https://www.playframework.com/documentation/2.5.x/ScalaForms">Play Documentation : ScalaForms</a> - <a href="https://www.playframework.com/documentation/2.5.x/ScalaForms">Play Documentation : ScalaJsonAutomated</a> - have  basic understanding of scala future transformation (map, flatMap) - have basic understanding of scala implicits - <a href="https://github.com/harrylaou/play2.5-skeleton-compileDI">clone play2.5-skeleton-compileDI</a>.</p>
</div>
<div class="paragraph">
<p>This example uses <a href="https://www.playframework.com/documentation/2.5.x/ScalaCompileTimeDependencyInjection">compile-time dependency injection</a>. You can use <a href="https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection">run-time DI</a> if you feel confident about it. - download and install <a href="https://www.mongodb.com/download-center?jmp=homepage#community">mongodb</a> (brew install mongo for mac or check the video) - download and install <a href="http://3t.io/mongochef/">mongochef</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_tutorial">Tutorial</h2>
<div class="sectionbody">
<div class="videoblock">
<div class="content">
<iframe src="https://www.youtube.com/embed/-iPKaW1RuTI?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_after_the_tutorial">After the tutorial</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You should be able to : - create a compile-time DI play project  - create a form in a play template - understand that a simple post in play requires two endpoints. - one to serve the form   - one to handle the post request - create a  model class - map a play Form to a case class - mapping - save a case class in Mongo DB</p>
</div>
<div class="paragraph">
<p>Play2-reactivemongo documentation</p>
</div>
<div class="paragraph">
<p>Be careful: we are using <strong>play2-reactivemongo</strong> plugin and not <strong>reactivemongo</strong> driver</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_bonus">Bonus</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Do you know the difference between Action and Action.async ?
Find out how to return different result statuses pages.
check</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://www.playframework.com/documentation/2.5.x/api/scala/index.html#play.api.mvc.Results">Play Results documentation</a></p>
</li>
<li>
<p><a href="https://www.playframework.com/documentation/2.5.x/api/scala/index.html#play.api.mvc.Results">Play JSON basics</a></p>
</li>
<li>
<p><a href="https://www.playframework.com/documentation/2.5.x/ScalaJsonHttp">Play JSON with HTTP</a></p>
</li>
<li>
<p><a href="http://PlayJSONReads/Writes/FormatCombinators">Play JSON Reads/Writes/Format Combinators</a></p>
</li>
</ul>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/10/03/Play-Framework-Beginner-Tutorial-Make-a-post-request-and-save-the-form-data-in-Mongodb.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/10/03/Play-Framework-Beginner-Tutorial-Make-a-post-request-and-save-the-form-data-in-Mongodb.html</guid><category><![CDATA[play]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 03 Oct 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Shapeless : Computing deltas]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p><strong>A real life exemple</strong></p>
</div>
<div class="paragraph">
<p>This is the code and some personal notes from the <a href="https://www.youtube.com/watch?v=JKaCCYZYBWo">Shapeless? - Easy!</a> talk where <a href="https://twitter.com/valentinkasas">Valentin Kasas</a> explains in a great way an advanced example of a real life use case (with <a href="https://gist.github.com/vil1/29f2d155679c703edfbe402f067962f6">slides</a>).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_computing_deltas">Computing deltas</h2>
<div class="sectionbody">
<div class="ulist">
<ul>
<li>
<p>Imagine we want to be able to determine what are the difference between two objects of the same type</p>
</li>
<li>
<p>For example, we need to know what have changed in our DB since the last backup</p>
</li>
<li>
<p>We need to be able to compute such deltas over a wide variety of classes, that are unrelated</p>
</li>
<li>
<p>Of course, doing this by hand for each and every class is not an option</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Our diff representation</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">sealed trait Diff[A]
final case class Identical[A](value: A) extends Diff[A]
final case class Different[A](left: A, right: A) extends Diff[A]
object Diff {
	def apply[A](left: A, right: A): Diff[A] =
    	if (left == right) Identical(left) else Different(left, right)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>A first Delta implementation</strong></p>
</div>
<div class="paragraph">
<p>We are creating a superclass here using DepFn . The return type differs according to the input type</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">trait SimpleDelta[R &lt;: HList] extends DepFn2[R, R] {
  type Out &lt;: HList //Result is bounded by HList
}

object SimpleDelta {
 /** type alias Aux adds as a type parameter the return Type.
  * It is convenient in order to constrain it
  * by passing it as a type parameter.
  */
	type Aux[I &lt;: HList, O &lt;: HList] = SimpleDelta[I] {
    	type Out = O
	}

	//Recursive Algorithm
	implicit def hnilDelta: Aux[HNil, HNil] = new SimpleDelta[HNil] {
		type Out = HNil
		def apply(l: HNil, r: HNil): Out = HNil
	}

	implicit def hconsDelta[H, T &lt;: HList, DT &lt;: HList](implicit tailDelta: Aux[T, DT]) : Aux[H::T, Diff[H] :: DT] = new SimpleDelta[H :: T] {
		type Out = Diff[H] :: DT
		def apply(l: H :: T, r: H :: T) : Out = Diff(l.head, r.head) :: tailDelta(l.tail, r.tail)
	}

	def apply[A, R &lt;: HList](l: A, r: A)(implicit genA: Generic.Aux[A, R], delta: SimpleDelta[R]): delta.Out = delta(genA.to(l), genA.to(r))
}</code></pre>
</div>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/09/19/Shapeless-Computing-deltas.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/09/19/Shapeless-Computing-deltas.html</guid><category><![CDATA[shapeless]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 19 Sep 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[A journey to ScalaCheck]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>From the Spanish good weather to the Dutch every-possible-weather-in-one-day, from Waterfall to Agile, from just testing to property based testing. The path I took when joining Lunatech was an interesting one.</p>
</div>
<div class="paragraph">
<p>I want to share some of that and show how my journey to <a href="https://gist.github.com/mariadroman/816d5b6848592aaacfa722c372dbccba">ScalaCheck</a> started. I will prove that it&#8217;s not complicated to start with and it can uncover deeply hidden bugs in your code.</p>
</div>
<div class="paragraph">
<p>As developers, we need to be sure that we create code that performs exactly how it is meant to. This should be true in every possible scenario. However, how can we prove that our codebase actually does this for a wide range of data? Sometimes it is just not feasible to write innumerable amount of test cases for a specific function. We need to find a way to somehow prove our function works as expected in every possible case.</p>
</div>
<div class="paragraph">
<p>Property-based testing provides another way of thinking, that was new to me, about writing tests. Sometimes it is better to prove that a function satisfies a specific property, rather than to write a number of tests which try to confirm it is working fine. One way of proving is to generate an appropriate amount of data and apply these data to your test suite. These generated data should all have the same specific property, hence the name property-based testing.</p>
</div>
<div class="paragraph">
<p>As an example, imagine we want to test String concatenation. To do this we need to be sure that: <strong>For all given two strings, str1 and str2, the result of concatenating both strings must satisfy: str1.length + str2.length &gt;= str1.length</strong></p>
</div>
<div class="paragraph">
<p>Traditionally, we would write a test like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">test("Concatenate should generate a String of length s1+s2") {
concatenate("", "").length == 0
concatenate("Hello, ", "world.").length == 13 //Hello, world.    concatenate("Welcome to ","Lunatech.").length == 20
//Welcome to Lunatech.
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>But testing all possible combinations of 2 strings is impractical this way. In these cases, ScalaCheck is the recommended solution.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s first understand the basic concepts in ScalaCheck: Properties and Generators.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_properties">Properties</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In ScalaCheck you can specify what the input parameters are and what their properties are that must be satisfied by the input. It uses a very elegant and intuitive way for defining properties:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">property(
"Concatenation length of two strings should be greater or equal to length of first string"
)
= forAll { (s1: String, s2: String) =&gt;
   (s1 + s2).length &gt;= s1.length
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this small piece of code, we declare a property ("Concatenation length of two strings &#8230;&#8203;"), that holds forAll possible cases of concatenating 2 strings (s1 and s2). This seems reasonable but how can we prove what this property holds true. One way is by creating a lot of tests. And that is where Generators come in handy.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_generators">Generators</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To generate this input data, ScalaCheck provides us with a wide range of generators available in objects Arbitraty and Gen.</p>
</div>
<div class="paragraph">
<p>The org.scalacheck.Arbitrary module defines implicit Arbitrary instances for common types, for convenient use in your properties and generators:</p>
</div>
<div class="paragraph">
<p><code>returns an arbitrary generator for the type T</code></p>
</div>
<div class="paragraph">
<p>The org.scalacheck.Gen uses Arbitrary and offers various generators:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>alphaLowerChar, alphaUpperChar, alphaNumChar</p>
</li>
<li>
<p>identifier, alphaStr, numStr</p>
</li>
<li>
<p>negNum, posNum, chooseNum</p>
</li>
<li>
<p>listOf, listOfN, nonEmptyListOf</p>
</li>
<li>
<p>choose, oneOf, someOf</p>
</li>
<li>
<p>const</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Some examples using arbitrary/generators:</p>
</div>
<div class="paragraph">
<p><code>id &#8592; arbitrary[Int]</code></p>
</div>
<div class="paragraph">
<p><code>married &#8592; arbitrary[Boolean]</code></p>
</div>
<div class="paragraph">
<p><code>age &#8592; choose(0, 120)</code></p>
</div>
<div class="paragraph">
<p><code>currency &#8592; const("euro")</code></p>
</div>
<div class="paragraph">
<p><code>description &#8592; arbitrary[String]</code></p>
</div>
<div class="paragraph">
<p>However, most of the time we do not want to check such a general data type. For this, ScalaCheck also offers the possibility of defining <strong>custom generators</strong> where we can establish what the input data should look like.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s use a simple example to understand the usage of custom generators. Imagine we are a Benelux bank that wants to verify that their Dutch customers who have a negative balance in at least one of their accounts, should be notified by email. For simplicity, we define customer and bank account as below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>case class Account(accountId: String, balance: Double, country: String)
case class Customer(customerId: String, name: String, nationality: String, accounts: Seq[Account])</code></pre>
</div>
</div>
<div class="paragraph">
<p>So first we want to generate Account data. To do this, we make use of Arbitrary and Gen. Because we are only interested in Benelux accounts the country field will be one of "BE", "NL" or "LU"</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala"> // Account generator - only Benelux accounts
val genAccount = for {
accountId &lt;- Gen.identifier
balance &lt;- arbitrary[Double]
country &lt;- Gen.oneOf("NL", "BE", "LU")} yield Account(accountId, balance, country)</code></pre>
</div>
</div>
<div class="paragraph">
<p>As a next step, we generate customer data. Because we are only interested in Dutch clients the nationality of the customers will be forced to be always "NL"</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">// Forcing customers to be Dutch will be as easy as:
val genDutchCustomer = for {
customerId &lt;- Gen.identifier
name &lt;- arbitrary[String].suchThat(_.nonEmpty)
nationality &lt;- Gen.const("NL")
accounts &lt;- nonEmptyListOf(genAccount)} yield Customer(customerId, name, nationality, accounts)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Finally, from the Dutch customers, we are interested on those having at least one account with negative balance</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">// Forcing customer to be Dutch and having negative balance:
val genDutchInRed = for {
customer &lt;- genDutchCustomer.suchThat(_.accounts.exists(_.balance &lt; 0))
} yield customer</code></pre>
</div>
</div>
<div class="paragraph">
<p>Something which is worth mentioning at this point is the usage of .suchThat. It is recommended not to write very restrictive conditions in this filter, because ScalaCheck first generates all input data, and filters it later based on the condition provided. If the condition is too restrictive, it may end up with too many inputs discarded and the tests will not run.</p>
</div>
<div class="paragraph">
<p>To conclude with generators, let&#8217;s have a look to a sample of our Dutch customer with at least one account with negative balance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>scala&gt; genDutchInRed.sample
res0: Option[Customer] = Some(
 Customer(uhcamdsjupssGeVftisrdb86mfbzflr,
 ïˆ¥ç§“é²›í—€ë€§ì–�å¤�î´‡å�½é”£ï°–ã¼½í˜‹á‘€æ§µÝ’ì…
 ¡ì†‰åš¿Ó”Ú¸å‚„íŽ½î³™ç‹‚ç±˜ï«©å¸•î¶™å’œáŠ¿æ¦�è˜žîŠ‡é�¥ï�¿ë‰Ÿá§¨áºŠë’¯á·”á´Žå‡ŸëŒ�ä¼“ä‹¨ç¹—
 ï¾•â‘£ä¼šæžºå³¸è£”â‡ºå¯œçŠ¼ê‡„è¼†ç‹Šç¯©ë—žâ™§ëžƒâ¶ªã«’êŽ™íˆ¥ì¦©,
   NL,
   List(

 Account(onScof2s4kBuphlrsal5ldWdh0oqbqbpgt03Snnrpryvlvzs89tnkh3fkreSsuoue0ntesrSlrpvDo7a4pe6bb
 qDly4cox,1.875359772688297E94),
 Account(yksznv4f48xezgep0daoyqtztcvruezwm,-3.9701238543851655E178),
 Account(uezzrfUxtbqPywvkXPbezZqtuX,4.8011482377734943E179),

 Account(htnlbxvtnDxiptwojhy4n36mzz2uovy5Xljoxgznkqomsk4rlhAxc9z6ebcwi6eMdnsass4cjhaerHfamcvzz0h6wtqn0pdgo6,6.04591158308268E-244),
  Account(s,-1.5255297073815315E-254),

  Account(vubpajf828dewljoarfp2uu0t9i3idnzhgDvjyediqyfax2fkfO6gAtgDqqNgaxkacswrcTzWpwkoopqt,-1.8
 68869258123239E-125),

 Account(guukirryuthlx4ejvhym6bVdiv8lleylBVfEkvslcvUskjlpzagtm2clfx4ashzdFQQWW,
 1.519776982857599E-66)
)
)
)</code></pre>
</div>
</div>
<div class="paragraph">
<p>This shows us that maybe we should add some conditions to the accountId or the balance, because it is not normal to deal with such values in real life. This was for example one of the reasons to create <a href="https://47deg.github.io/scalacheck-datetime/">scalaCheck-datetime</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_writing_tests">Writing tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Now that we are familiar with properties and generators, it is time to write tests. We have good examples in the Scala community, because ScalaCheck is used by many Scala open source projects (like Akka or Play).
In this case, we will continue with our concatenate example.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>import org.scalacheck.Properties
import org.scalacheck.Prop.forAll
class StringProperties extends Properties("String Properties") {
property("Concatenation length equal or greater than zero") = forAll { (s1: String, s2:
String) =&gt;
s1.length + s2.length &gt;= 0
 }
 property("Concatenation length equal to length addition") = forAll { (s: String) =&gt;
 val len = s.length
 (s + s).length == len + len
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Our properties file can be as simple as that, or we can make it as complicated as we need. We can also integrate it with <a href="http://www.scalatest.org/user_guide/writing_scalacheck_style_properties">ScalaTest</a> or <a href="https://etorreborre.github.io/specs2/guide/SPECS2-3.0/org.specs2.guide.UseScalaCheck.html">Specs2</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_running_scalacheck_tests">Running ScalaCheck tests</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Using sbt, we run ScalaCheck tests in the same way we run ScalaTest tests: sbt test:compile test. If our code is correct and all the tests generated by ScalaCheck are successful, we can see the following as output:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">+ String Properties.Concatenation length equal to length addition: OK, passed 100 tests.
+ String Properties.Concatenation length equal or greater than zero: OK, passed 100 tests.
ScalaCheck
Passed: Total 2, Failed 0, Errors 0, Passed 2</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default, ScalaCheck generates 100 tests per property, which must be satisfied for the test to pass.</p>
</div>
<div class="paragraph">
<p>In case a property is not satisfied by the generated test data, ScalaCheck yields an error. And not only shows the input data which makes the property to fail, but it also simplifies as much as possible to show you the minimum value which makes the test to fail. This helps us a lot when going back to the code and applying a solution to fix the wrong implementation.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_how_scalacheck_helps_with_finding_bugs">How ScalaCheck helps with finding bugs</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you are not yet convinced we&#8217;ll give you another example of code that looks fine at first glance, but will not meet the requirements.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">property("Absolute value should not be negative") = forAll { (input: Int) =&gt;
input.abs &gt;= 0
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Looks reasonable, if we apply abs to a number, we will get a positive one (or zero). But&#8230;&#8203; voilà! Here it is what ScalaCheck yields after running the test:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">! String Properties.absolute value should not be negative: Falsified after 1 passed tests.
&gt; ARG_0: -2147483648
ScalaCheck
Failed: Total 1, Failed 1, Errors 0, Passed 0</code></pre>
</div>
</div>
<div class="paragraph">
<p>What ScalaCheck is showing is that the property fails for <code>input = -2147483648</code> Then, we realize that Int numbers are not symmetric <code>Int.MaxValue = 2147483647 Int.MinValue = -2147483648</code> So, when trying to apply abs to Int.MinValue, we get <code>Int.MinValue.abs = -2147483648</code> which does not satisfy the condition of <code>input.abs &gt;= 0.</code></p>
</div>
<div class="paragraph">
<p>It is very likely that we write our code without thinking about these kind of corner cases, because we probably never expect an input with <code>value -2147483648</code> But <code>since -2147483648</code> is valid input our code will accept it and will crash if we do not add conditions to prevent it.</p>
</div>
<div class="paragraph">
<p>ScalaCheck focuses mainly on corner cases, where our functions are more sensible to fail. So for Int values, it will first test with MIN_VALUE, MAX_VALUE and 0; for String values will test with symbols and non-roman alphabet.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_useful_links_to_get_started">Useful links to get started</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="https://github.com/rickynils/scalacheck/blob/master/doc/UserGuide.md">GitHub</a>, <a href="http://www.scalatest.org/user_guide/generator_driven_property_checks">projectScalaTest</a>, <a href="http://www.artima.com/shop/scalacheck">integrationBook</a>, and <a href="http://booksites.artima.com/scalacheck/examples/index.html">code examples</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_summary">Summary</h2>
<div class="sectionbody">
<div class="paragraph">
<p>When you feel you are adding many tests based on input data, stop for a moment and think twice about the possibility of translating the functionality into a property that ScalaCheck can test for you.</p>
</div>
<div class="paragraph">
<p>If we can write properties for a given function, ScalaCheck provides an easy and very intuitive way of writing tests, which automatically generate large amounts of data for us, mainly focusing on corner and special cases.It is very helpful that ScalaCheck shrinks test cases to the minimal case.</p>
</div>
<div class="paragraph">
<p>ScalaCheck does NOT substitute ScalaTest or Specs2, but it complements them with property testing.Don&#8217;t forget that ScalaCheck is generating a finite number of tests, which means that there is always a chance that within this randomized set of tests, a bug might not be found (although it does exist in your code). However in case your input type is more constrained e.g. Byte, it can even generate all possible input data.</p>
</div>
<div class="paragraph">
<p>I started with ScalaCheck soon after I started with Scala and it changed the way I look at tests. Be always open to explore and try new options, because from all of them you will always learn something useful.</p>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/09/12/A-journey-to-Scala-Check.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/09/12/A-journey-to-Scala-Check.html</guid><category><![CDATA[scala]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 12 Sep 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Shapeless: Introduction resources]]></title><description><![CDATA[<div class="sect1">
<h2 id="_where_to_start_if_you_want_to_learn_shapeless">Where to start if you want to learn shapeless</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Recently I decided to have a better look at <a href="https://github.com/milessabin/shapeless">shapeless</a>, the generic programming library for Scala. In the previous couple of years I had bookmarked several links and have recently read all of them. In this blog post I present the most useful ones for someone who want to be introduced to the library.</p>
</div>
<div class="paragraph">
<p>The following blog posts are introductory to shapeless. Basically they are a smooth introduction to shapeless, something to warm up</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://jto.github.io/articles/getting-started-with-shapeless/">Getting started with Shapeless</a> by <a href="https://twitter.com/skaalf">Julien Tournay</a> (heterogenous lists, polymorphic function values, generic, tuples, lenses)</p>
</li>
<li>
<p><a href="https://enear.github.io/2016/04/05/bits-shapeless-1-hlists/">Bits of Shapeless part 1: HLists</a> by <a href="https://twitter.com/ragb">Rui Batista</a> (Heterogenous lists)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Also these slides on <a href="http://slick.lightbend.com/talks/scalaio2014/Type-Level_Computations.pdf">Type-Level Computations in Scala</a> by <a href="https://twitter.com/StefanZeiger">Stefan Zeiger</a> (not shapeless per se , but a lot of examples for type-level scala, like type-level booleans, type-level natural numbers, translation to types, recursion with types, type functions, type lambdas, heterogenous lists, hlist fold). I tried to find the video talk, but couldn’t find it online.</p>
</div>
<div class="paragraph">
<p>The <a href="https://rnduja.github.io/2016/01/19/a_shapeless_primer/">Α shapeless primer</a> blog post by <a href="https://twitter.com/evacchi">Edoardo Vacchi</a> is the best and most complete introductory blog post I could find. It really goes into a lot of explaining hlists, product types, Generic[T], FnToProduct[F] object, implicit value resolution, evidences and typeclasses, the Aux Pattern). There is also a <a href="https://rnduja.github.io/2015/10/07/scala-dependent-types/">video</a> presentation by the author Edoardo Vacchi <a href="https://speakerdeck.com/evacchi/be-like-water-scala-italy-2016">(with slides)</a>. In this blog post I find very interesting the comparison of Scala with Prolog and how implicit variables, implicit functions, type parameters in functions and implicit parameter lists of functions can be “interpreted” in a rule-based context.</p>
</div>
<div class="paragraph">
<p><strong>Scala</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>implicit vals</p>
</li>
<li>
<p>implicit defs</p>
</li>
<li>
<p>type parameters in def</p>
</li>
<li>
<p>implicit parameters lists</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>Prolog</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>facts</p>
</li>
<li>
<p>rules</p>
</li>
<li>
<p>variable in a rule</p>
</li>
<li>
<p>bodies of a rule</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In <a href="https://www.youtube.com/watch?v=JKaCCYZYBWo">Shapeless? - Easy!</a>, <a href="https://twitter.com/valentinkasas">Valentin Kasas</a> explains in a great way an advanced example of a real life use case (computing deltas) (with <a href="https://twitter.com/valentinkasas">slides</a>). From this presentation I took the following <a href="http://harrylaou.com/scala/shapeless/deltas/">notes</a>. There are also available two nice blog posts by Valentin : Shapeless : not a tutorial - <a href="http://kanaka.io/blog/2015/11/09/shapeless-not-a-tutorial-part-1.html">part 1</a> (Heterogenous lists, polymorphic function values, high order poly functions) and part 2 (Generic, singleton types, records and LabelledGeneric)</p>
</div>
<div class="paragraph">
<p>In First-class polymorphic function values in shapeless (2 of 3) — Natural Transformations in Scala, <a href="https://twitter.com/milessabin">Miles Sabin</a> the creator of <a href="https://github.com/milessabin/shapeless">shapeless</a> explains the concepts of polymorphic functions and natural transformations.</p>
</div>
<div class="paragraph">
<p>In the <a href="https://github.com/fommil/shapeless-for-mortals">Shapeless for Mortals</a> talk, <a href="https://twitter.com/fommil">Sam Halliday</a> explains shapeless fundamentals like : type classes (not shapeless per se , but used extensively when using the library), singleton types, HList, LabelledGeneric, Coproduct, Hipster.Aux (SI-823), Higher Order Unification, Implicit Resolution: Recursion , Cycles and Priority, Tags (<a href="https://fommil.github.io/scalax15/scalax-shapeless-mortals-notes.html">Notes</a> from the talk)</p>
</div>
<div class="paragraph">
<p>The page <a href="https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0">Shapeless features</a> provides a short overview of the main features of the library : polymorphic function values, heterogenous lists, HList-style operations on standard Scala tuples, facilities for abstracting over arity, heterogenous maps, singleton-typed literals, singleton-typed symbols, extensible records, coproducts and discriminated unions, generic representation of (sealed families of) case classes, boilerplate-free lenses for arbitrary case classes, automatic type class instance derivation, first class lazy values tie implicit recursive knots, collections with statically known sizes, type safe cast(Typeable/TypeCase), testing for non-compilation (illTyped)</p>
</div>
<div class="paragraph">
<p>After reading Shapeless features , the natural thing to follow is the <a href="https://www.scala-exercises.org/shapeless/polymorphic_function_values">Scala exercises in shapeless</a> by 47 deg, which is almost identical to <a href="https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0">Shapeless features</a>, but you will need to fill in the gaps so as to solve the exercises.</p>
</div>
<div class="paragraph">
<p>A lot of examples are available in <a href="https://github.com/milessabin/shapeless/tree/master/examples/src/main/scala/shapeless/examples">Shapeless examples</a></p>
</div>
<div class="paragraph">
<p>bonus : Although not shapeless specific, there are two very interesting talks about Lenses</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/milessabin/shapeless/tree/master/examples/src/main/scala/shapeless/examples">Lenses: Fields as Values</a> (<a href="https://github.com/SethTisue/lens-examples/tree/master/src/main/scala">examples slides</a>) where Seth Tissue explains the concept of Lenses and uses shapeless lenses.</p>
</li>
<li>
<p><a href="https://www.youtube.com/watch?v=6nyGVgGEKdA">Beyond Scala Lenses</a> where <a href="https://twitter.com/julientruffaut">Julien Truffaut</a> (the creator of the <a href="https://github.com/julien-truffaut/Monocle">Monocle</a> library which is built with shapeless) explains the optics terms  Iso, Prism, Lens and Optional.</p>
</li>
</ul>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/09/05/Shapeless-Introduction-resources.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/09/05/Shapeless-Introduction-resources.html</guid><category><![CDATA[shapeless]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 05 Sep 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Moving from Spain to the Netherlands]]></title><description><![CDATA[<div class="paragraph">
<p>Last week, I started talking about the main things I&#8217;ve faced when learning Scala, after being a Java developers for a few years. Today, I will talk about how it was to move from Spain to the Netherlands, in order to join Lunatech.</p>
</div>
<div class="paragraph">
<p>Food. Oh boy, the food. Spain is known for its Iberian ham, and you have a lot of different hams on every supermarket you visit. Usually, there is a big fridge, full of brands of ham, and also meat: pork, chicken, beef. And beef is also classified depending on the part of the animal it comes from, there are more than 10 possible kinds of beef and I don&#8217;t even know which one to choose when I go to buy something.</p>
</div>
<div class="paragraph">
<p>When I arrived to a dutch supermarket for the first time (Albert Heijn), I was surprised: there weren&#8217;t so many types of ham to choose, and most of the beef meat was ground meat, not slices. But, this supermarket shared one thing with the Spanish ones&#8230;&#8203; the big fridge. This time, the fridge was full of cheese.</p>
</div>
<div class="paragraph">
<p>I&#8217;ve never seen so many different types of cheese in my life. On Spanish supermarkets, you usually find like 5 or 6 different cheese to choose about. But here, I&#8217;ve never seen less than 20 different cheeses on every supermarket I&#8217;ve visited so far. There is also cheese with spices! Never seen that before.Main differences between spanish and dutch gastronomy</p>
</div>
<div class="paragraph">
<p>Let&#8217;s talk about the weather. When I was still doing Skype interviews with the people from Lunatech before joining them, everybody made the same joke: "why do you want to come to the Netherlands? Because of the weather?" And they laughed afterwards. I didn&#8217;t understood why.</p>
</div>
<div class="paragraph">
<p>My parents were also confused: "why do you want to move to the Netherlands? Most of the people from Europe comes to Spain because of the sun and the beach, and now you are moving to a country that is well known for its rain and wind". I was sure of my decision, I always thought that Spain was too hot for me, too dry, and the weather from the Netherlands would fit me more, with more rain and more clouds. I was so wrong.</p>
</div>
<div class="paragraph">
<p>The first week I spent here, it rained every single day. Dutch weather welcomes foreigners by making them real men, under the rain. I wasn&#8217;t prepared for that. In Spain (not in the northern regions), when we say "rain" we are usually talking about some water falling over your shoulders and walking over wet floor. A standard dutch rain would be something to tell on the news if it happened on Spain. And I even remember the day some trains got delayed because of floods. In July, in summer. In Madrid (the city where I come from) we barely have 3 or 4 days of rain between May and September.</p>
</div>
<div class="paragraph">
<p>And the worst part about the dutch rain is that is also very irregular. Usually in Spain if you have rain, you have rain the whole day, and if you have sun, the same. But then, you wake up in the Netherlands, ready to go to the office, you see the sun in the sky and then you choose to go with a T-shirt. Few hours later, when you are coming home, the sky is black, you are absolutely wet on the street and you are wondering why you didn&#8217;t picked the jacket that morning.</p>
</div>
<div class="paragraph">
<p>I remember one conversation with one of my coworkers:</p>
</div>
<div class="paragraph">
<p>Him: “<em>Oh look, the sun! Maybe you should go to the beach today</em>”</p>
</div>
<div class="paragraph">
<p>Me: “<em>But there are some clouds on the sky…</em>"</p>
</div>
<div class="paragraph">
<p>Him: “<em>This is the best you can get</em>"</p>
</div>
<div class="paragraph">
<p>Main differences between spanish and dutch weather</p>
</div>
<div class="paragraph">
<p>But there is something that I really love about the dutch culture, and I wasn&#8217;t expecting to: bikes. Bikes here are very easy to get, and the streets are prepared to be crossed by bike. In Madrid it&#8217;s almost impossible to use a bike because the streets are narrow most of the time, and the cars are going through, but here, almost every street as a bike path, so you can safely go everywhere.</p>
</div>
<div class="paragraph">
<p>You can park your bike at the station (actually, everywhere, if you are brave enough), and a lot of the people use the bike to make small distances, like going to the supermarket. I mean, this is very important: the relief of being able to carry all your bags on the bike and park it in front of your house, is almost a blessing.</p>
</div>
<div class="paragraph">
<p>But not everything is wonderful about bikes: because you are in the Netherlands, and the dutch weather wants you to become a "<em>real man</em>". Sometimes you are having a great moment on your bike, and then suddenly the strongest wind you could ever imagine decides to go exactly on the opposite direction you are going, testing if your legs are strong enough, and if your will can handle the situation. And when is not coming from the front, is coming from your side, and then you will fall to the ground if you are not experienced enough.</p>
</div>
<div class="paragraph">
<p>But you can become an expert biker too. And dutch people love to show how professional they are on this matter. You think you are strong because you can carry all your supermarket bags and still going fast enough? Look at this mother carrying their two children on the bike and passing you on the left. You think you are cool because you can handle the bike with one hand while scratching your head with the other one? I&#8217;ve seen many times people texting on their phones, with both hands, while turning the bike. I&#8217;ve so much to learn.</p>
</div>]]></description><link>http://blog.lunatech.com/2016/08/25/Moving-from-Spain-to-the-Netherlands.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/08/25/Moving-from-Spain-to-the-Netherlands.html</guid><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Thu, 25 Aug 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Moving From Java To Scala]]></title><description><![CDATA[<div class="paragraph">
<p>Sometime ago I came from Madrid to Rotterdam to join Lunatech’s international workforce. Apart from introducing me to Dutch summers (rain), this also gave me an opportunity to learn a new programming language: Scala.</p>
</div>
<div class="paragraph">
<p>Since I finished university I’ve been working with Java and I really liked it, but Scala was something entirely new to me. In this post I’ll give my first view on Scala from a Java perspective.</p>
</div>
<div class="paragraph">
<p>Many people say that Scala is like Java but without semicolons, but I disagree. It’s true that Scala doesn’t need semicolons, and that may save developers some time, but it’s just a minor feature. One of the things that really caught my eye when I started, is related to style: unlike Java developers, Scala developers like to put everything on the same line. Let’s consider the next piece of Java code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">public Foo someMethod(Foo foo, Bar bar) {
  Foo firstResult = foo.doSomething();
  Bar secondResult = bar.doOtherThing();
  Foo finalResult = doLastThing(firstResult, secondResult);
  return finalResult;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>We could have compressed that into something smaller, but usually Java developers love verbose stuff: to define variables with long names so everything looks clear and people can understand what’s happening on the code. On the other hand, a Scala developer would do something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def someMethod(foo: Foo, bar : Bar) : Foo = doLastThing(foo.doSomething, bar.doOtherThing)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Basically, the main thing that me, as a Java developer, saw when reading Scala code is “try to put everything on the same line”, and that makes things a bit difficult to understand at the beginning. But in the end your Scala code ends being very small and powerful.</p>
</div>
<div class="paragraph">
<p>Another thing that stands out are Collections. When you are learning Collections in Java, most of the times you start with arrays (Foo[]) and later you probably move to ArrayList. Then, iterating over your Collection of choice is made with for/while loops most of the time, with some logic inside the curly brackets. But Scala&#8217;s Collection library is more powerful and easy to use than the one you have available in Java.</p>
</div>
<div class="paragraph">
<p>Recent versions of Java have implemented new libraries with similar tools as in Scala, but they have been developed a few years ago, and most of the times they require weird implementations of the Stream class. Scala, on its side, was created with this kind of tools in mind, so they are far more accessible and easy to understand.</p>
</div>
<div class="paragraph">
<p>In Scala, the map method (and the rest of their friends: flatMap, flatten, head, tail, filter, etc) makes iterating through Collections so easy and safe, that you even try to use it as much as you possibly can. You don&#8217;t have to worry about IndexOutOfBoundsException anymore. When you can transform this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">for (int i = 0; i &lt; intList.size(); i++) {
	if (intList.get(i) % 2 == 0)
    	intList.set(i, intList.get(i) + 1)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Into this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">intList.map(x =&gt; if (x % 2 == 0) x + 1 else x)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Your fingers will be glad you that you&#8217;ve switched to Scala.</p>
</div>
<div class="paragraph">
<p>But the award of “most surprising thing for people that comes from Java” goes to… vals and immutable stuff!</p>
</div>
<div class="paragraph">
<p>The most common way of implementing immutability in Java is by using final on the variables/objects you want to remain constant through your code. But the way Scala uses immutability is somehow different: you try to make every single variable immutable. If you declare an Int or a String, you go immutable.</p>
</div>
<div class="paragraph">
<p>When you&#8217;re learning Java, you are told to declare as few variables as possible, and to reuse them as much as possible, in order to release memory and make the life of the garbage collector easier. But in Scala, you have two options: you can either use var (mutable variable) or val (immutable variable), but you are told to use val as much as possible, and to avoid var as much as you can. At the beginning this is confusing (you wonder "if I should use always val, why do you allow me to use var on the first place?") and many times you want to hit you head against a wall. But when you start to master Collections and your inner-developer is at peace with the Immutability Zen, it&#8217;s even rewarding and interesting to make code with everything immutable.</p>
</div>
<div class="paragraph">
<p>So I’m having fun learning Scala, and I will go with some more details next week about moving to the Netherlands.</p>
</div>]]></description><link>http://blog.lunatech.com/2016/08/17/Moving-From-Java-To-Scala.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/08/17/Moving-From-Java-To-Scala.html</guid><category><![CDATA[scala]]></category><category><![CDATA[java]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Wed, 17 Aug 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Play Framework - Beginner Tutorial : How to handle a big json file in play ( more than 22 root variables)]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>It is not a good practice to have such a big json with many root variables. Nevertheless, we might need to call a rest api that will give a json like this</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-json" data-lang="json">{  "a1": ...,  "a2" : ...,  "a3" : ...,  "a4" : ...,  "a5" : ...,  "a6" : ...,  "a7" : ...,  "a8" : ...,  "a9" : ...,  "a10" : ...,  "a11" : ...,  "a12" : ...,  "a13" : ...,  "a14" : ...,  "a15" : ...,  "a16" : ...,  "a17" : ...,  "a18" : ...,  "a19" : ...,  "a20" : ...,  "a21": ...,  "a22" : ...,  "a23" : ...,  "a24" : ...,  ....}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_first_approach">First approach</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Since scala 2.11 we can have case class with more than 22 fields, so the following compiles.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">case class JsonExample (    a1:String, a2:String, a3:String, a4:String, a5:String, a6:String,    a7:String, a8:String, a9:String, a10:String, a11:String, a12:String,    a13:String, a14:String, a15:String, a16:String, a17:String, a18:String,    a19:String, a20:String, a21:String, a22:String, a23:String, a24:String)</code></pre>
</div>
</div>
<div class="paragraph">
<p>But if we try to use Play <a href="https://www.playframework.com/documentation/2.5.x/ScalaJsonAutomated">JSON automated mapping</a></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import play.api.libs.json._implicit val jsonExampleFormat = Json.format[JsonExample]</code></pre>
</div>
</div>
<div class="paragraph">
<p>we get a compiler error</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>&lt;console&gt;:16: error: No unapply or unapplySeq function found       implicit val jsonExampleFormat = Json.format[JsonExample]                                                   ^</code></pre>
</div>
</div>
<div class="paragraph">
<p>Instead we can use <a href="https://www.playframework.com/documentation/2.5.x/ScalaJsonCombinators">Play-Json extensions</a>(requires play-json &gt;= 2.4)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import ai.x.play.json.Jsonximplicit val jsonExampleFormat = Jsonx.formatCaseClass[JsonExample]

jsonExampleFormat: play.api.libs.json.Format[JsonExample] = $anon$1@b7f7890</code></pre>
</div>
</div>
<div class="paragraph">
<p>So now we have a Play Json format for a case class with more than 22 fields, and can use it as described in <a href="https://www.playframework.com/documentation/2.5.x/ScalaJsonCombinators">Play Json documentation</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_second_approach">Second approach</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I don’t consider having a case class with so many fields a good solution.</p>
</div>
<div class="paragraph">
<p>A better solution is to organize these fields in “logical” embedded case classes.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">case class A (    a1:String, a2:String, a3:String, a4:String,    a5:String, a6:String, a7:String, a8:String)

case class B (    a9:String, a10:String, a11:String, a12:String,    a13:String, a14:String, a15:String, a16:String  )case class C (    a17:String, a18:String, a19:String, a20:String,    a21:String, a22:String, a23:String, a24:String  )case class JsonExample2 (    a : A,    b : B,    c : C  )</code></pre>
</div>
</div>
<div class="paragraph">
<p>We use a “regular” play json format for the embedded case classes.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import play.api.libs.json._implicit val jsonAFormat : Format[A] = Json.format[A]implicit val jsonBFormat : Format[B]= Json.format[B]implicit val jsonCFormat : Format[C] = Json.format[C]</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the “trick” now is to use the JsPath <a href="https://www.playframework.com/documentation/2.5.x/ScalaJsonCombinators">Play Json Combinator</a> for the embedded case classes without any path.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import play.api.libs.functional.syntax._implicit val jsonExample2Format: Format[JsonExample2]  = (  (JsPath).format[A] and  (JsPath).format[B] and  (JsPath).format[C])(JsonExample2.apply, unlift(JsonExample2.unapply))</code></pre>
</div>
</div>
<div class="paragraph">
<p>That’s all folks!</p>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/08/15/Play-Framework-Beginner-Tutorial-How-to-handle-a-big-json-file-in-play-more-than-22-root-variables.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/08/15/Play-Framework-Beginner-Tutorial-How-to-handle-a-big-json-file-in-play-more-than-22-root-variables.html</guid><category><![CDATA[play]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 15 Aug 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Continuous Delivery on GitLab with Play, Scala, SBT and Heroku]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Last week we talked about <a href="http://www.lunatech.com/blog/V5tpoCQAANsPL4jw/continuous-integration-on-gitlab-with-scala-and-sbt">Continuous Integration (CI) with Scala and SBT on GitLab</a>. This week we are going to take a step further and implement Continuous Delivery (CD) on GitLab with Play and Heroku.</p>
</div>
<div class="paragraph">
<p>Let’s first recap last week’s post. To enable CI, we used the .gitlab-ci.yml file. Builds are run in Docker and to make sure we could execute our tests, we used a Java Docker image and made sure SBT was installed. The definition in our .gitlab-ci.yml file contained only a single stage: the test stage. This week we are going to extend our pipeline with a deploy stage.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_play_deployment_with_heroku">Play Deployment with Heroku</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The application we are going to deploy is a Play Framework application. For now we assume we already have such application with SBT as the build tool.</p>
</div>
<div class="paragraph">
<p>Heroku is a cloud application platform that has support for Play applications. This means that running your application on Heroku requires little setup and most important is getting the source of your application there. For that, we use the tool <a href="https://github.com/travis-ci/dpl">dpl</a> from Travis CI.</p>
</div>
<div class="paragraph">
<p>Dpl is a simple command line deployment tool that supports Heroku. We can deploy our Play application to Heroku using dpl with the following command:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>dpl --provider=heroku --app=&lt;application-name&gt; --api-key=&lt;api-key&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>First you have to create an application in Heroku.<code>&lt;application-name&gt;</code> in the command above should be substituted with the name you gave the application. Additionally, <code>&lt;api-key&gt;</code> should be substituted by your Heroku API key which you can find under (under <a href="https://dashboard.heroku.com/account">Account</a> &gt; API Key).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_putting_it_all_together">Putting It All Together</h2>
<div class="sectionbody">
<div class="paragraph">
<p>We extend the definition of our pipeline in the .gitlab-ci.yml file by adding a deploy stage and in the deploy stage, we install dpl and instruct it to deploy the new version of the application to Heroku. To hide the API key it is passed via a secret variable. This can be added in GitLab in your project’s settings under <strong>Variables</strong>.</p>
</div>
<div class="paragraph">
<p>The .gitlab-ci.yml file now looks like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>stages:
- test
- deploy
test:  stage: test
script:
# Test the project
- sbt clean test
deploy:
stage: deploy
script:
# Install dpl
- apt-get update
-yq
- apt-get install rubygems ruby-dev -y
- gem install dpl
# Deploy to Heroku
- dpl --provider=heroku --app=lunatech-demo-cd-play-scala --api-key=$HEROKU_API_KEY</code></pre>
</div>
</div>
<div class="paragraph">
<p>After pushing this .gitlab-ci.yml file to our GitLab repository containing the Play project, our continuous delivery pipeline is enabled. On every new push, the tests of the project are run and if the tests pass, the new version of the application is deployed to Heroku using dpl.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_source_code">Source Code</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The source code of a demo project implementing the pipeline described in this post can be found here: <a href="https://gitlab.com/jasperdenkers/lunatech-demo-cd-play-scala-heroku" class="bare">https://gitlab.com/jasperdenkers/lunatech-demo-cd-play-scala-heroku</a>.</p>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/08/08/Continuous-Delivery-on-Git-Lab-with-Play-Scala-SBT-and-Heroku.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/08/08/Continuous-Delivery-on-Git-Lab-with-Play-Scala-SBT-and-Heroku.html</guid><category><![CDATA[play]]></category><category><![CDATA[scala]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 08 Aug 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Continuous Integration on GitLab with Scala and SBT]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>With Continuous Integration (CI) we aim to be able to test the changes we make to our projects automatically and externally. An usual setup involves e.g. GitHub and Jenkins and requires quite some configuration.</p>
</div>
<div class="paragraph">
<p>In this post we look at an alternative approach using GitLab which offers both the features of the aforementioned services: git hosting and continuous integration.</p>
</div>
<div class="paragraph">
<p>In this post we specifically focus on Scala projects with SBT as the build tool. Let’s assume we have an SBT project that contains tests and is hosted on GitLab. Now we have to tell GitLab that we want CI. We do this by adding a <code>.gitlab-cy.yml</code> file in the root directory of our project.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_code_gitlab_ci_yml_code_file">The <code>.gitlab-ci.yml</code> File</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Builds are run in Docker and therefore we have to specify in the .gitlab-ci.yml file which Docker image we want to use. Additionally we define some commands before our tests are run. We use the Java 8 image and make sure SBT is installed and available in our builds:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yml" data-lang="yml">image: java:8

before_script:
  # Enable the usage of sources over https
  - apt-get update -yqq
  - apt-get install apt-transport-https -yqq
  # Add keyserver for SBT
  - echo "deb http://dl.bintray.com/sbt/debian /" | tee -a /etc/apt/sources.list.d/sbt.list
  - apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823
  # Install SBT
  - apt-get update -yqq
  - apt-get install sbt -yqq
  # Log the sbt version
  - sbt sbt-version</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now let’s define the stages we want to use. We add the test stage with the following lines:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yml" data-lang="yml">stages:
  - test</code></pre>
</div>
</div>
<div class="paragraph">
<p>At last, we define a job in the test stage that executes the the tests in our project:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yml" data-lang="yml">test:
  stage: test
  script:
    # Execute your project's tests
    - sbt clean test</code></pre>
</div>
</div>
<div class="paragraph">
<p>Builds within the same stage run in parallel and the jobs in a next stage are started after all previous stages are successfully finished. We can define as much stages and builds as we want. Together, they are called a pipeline.</p>
</div>
<div class="paragraph">
<p>After we commit and push the <code>.gitlab-ci.yml</code> file to GitLab, CI is enabled and the pipeline is executed on every new push to the project.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_measuring_test_coverage">Measuring Test Coverage</h2>
<div class="sectionbody">
<div class="paragraph">
<p>To display the test coverage of our test job we need to take two steps:</p>
</div>
<div class="paragraph">
<p>Add test coverage measuring in our SBT project.</p>
</div>
<div class="paragraph">
<p>Instruct GitLab how to extract the coverage percentage from the build trace.</p>
</div>
<div class="paragraph">
<p>We measure test coverage by using the SBT plugin sbt-scoverage. Add the following line to <code>/project/plugins.sbt</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yml" data-lang="yml">addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.3.5")</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can now measure test coverage with sbt clean coverage test coverageReport. We change this in <code>.gitlab-ci.yml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yml" data-lang="yml">test:
  stage: test
  script:
    # Execute your project's tests and measure test coverage
    - sbt clean coverage test coverageReport</code></pre>
</div>
</div>
<div class="paragraph">
<p>And in our project settings under CI/CD pipelines &gt; Test coverage parsing we add the following regular expression: Coverage was <code>\[\d+.\d+\%\]</code>. This enables GitLab to extract the coverage percentage from a build trace and display it next the the build results.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_source_code">Source Code</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The source code of a demo SBT project implementing the steps described in this post can be found here:</p>
</div>
<div class="paragraph">
<p><a href="https://gitlab.com/jasperdenkers/lunatech-demo-ci-scala-sbt" class="bare">https://gitlab.com/jasperdenkers/lunatech-demo-ci-scala-sbt</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_what_s_next">What’s Next?</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Next week we are going a step further and we implement continuous delivery (CD) in GitLab with the Play Framework and Heroku.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_references">References</h2>
<div class="sectionbody">
<div class="paragraph">
<p><a href="http://docs.gitlab.com/ce/ci/" class="bare">http://docs.gitlab.com/ce/ci/</a></p>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/08/01/Continuous-Integration-on-Git-Lab-with-Scala-and-SBT.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/08/01/Continuous-Integration-on-Git-Lab-with-Scala-and-SBT.html</guid><category><![CDATA[gitlabs]]></category><category><![CDATA[git]]></category><category><![CDATA[CI]]></category><dc:creator><![CDATA[Nicolas Leroux]]></dc:creator><pubDate>Mon, 01 Aug 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Recursion and Trampolines in Scala]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Recursion is beautiful. As an example, let&#8217;s consider this perfectly acceptable example of defining the functions <code>even</code> and <code>odd</code> in Scala, whose semantics you can guess:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def even(i: Int): Boolean = i match {
  case 0 =&gt; true
  case _ =&gt; odd(i - 1)
}

def odd(i: Int): Boolean = i match {
  case 0 =&gt; false
  case _ =&gt; even(i - 1)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>We&#8217;ve defined even in a very natural way: an value is <code>even</code> when it&#8217;s zero, or when it&#8217;s <code>odd</code> after subtracting one. <code>Odd</code> is defined in a similar way.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s ignore the problem this code has with negative integers, and the fact that an <code>O(n)</code> algorithm for computing <code>even</code> and <code>odd</code> is not ideal, and focus on a single problem: this code breaks for large n:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>scala&gt; even(5000)
res3: Boolean = true
scala&gt; even(50000)
java.lang.StackOverflowError
at Trampolines$Stack$.odd(trampolines.scala:14)
at Trampolines$Stack$.even(trampolines.scala:9)
at Trampolines$Stack$.odd(trampolines.scala:14)
at Trampolines$Stack$.even(trampolines.scala:9)
at Trampolines$Stack$.odd(trampolines.scala:14)
at Trampolines$Stack$.even(trampolines.scala:9)
...
at Trampolines$Stack$.even(trampolines.scala:9)
at Trampolines$Stack$.odd(trampolines.scala:14)</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the remainder of this post we look at various strategies for preventing recursive programs from running out of memory.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_but_what_s_the_problem">But what&#8217;s the problem?</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The problem manifests itself in the stack trace: even calls <code>odd</code>, then <code>odd</code> calls <code>even</code>, which calls <code>odd</code> again. Each of these invocations causes the creation of a stack frame, eating away the space that&#8217;s reserved for them.</p>
</div>
<div class="paragraph">
<p>Keeping all the stack frames would not really be necessary: when <code>even</code> calls <code>odd</code>, that is the very last thing that the even function will ever do! When <code>odd</code> returns, <code>even</code> itself returns immediately with that same value.</p>
</div>
<div class="paragraph">
<p>When we compute <code>even(500)</code>, after a bunch of recursive calls, the 501st stack frame will be created, for the invocation of <code>even(0)</code>, which returns true, and the 500 method calls that are left on the stack will one after another all return that same value, until the whole stack is unwinded.</p>
</div>
<div class="paragraph">
<p>Some languages or runtimes are smart enough to figure out that if a calling function will simply return the value that a function it calls returns, it does not need to allocate a new stack frame for the callee, but can reuse the stack frame of the caller for that.</p>
</div>
<div class="paragraph">
<p>Unfortunately, the JVM does not support this.</p>
</div>
<div class="paragraph">
<p>And so Scala, as long as it sticks to JVM method calling semantics, also can not support this.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_a_bit_of_light_at_the_end_of_the_tunnel">A bit of light at the end of the tunnel</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Luckily, there is one special case of tail calls which Scala treats differently, and that is the case of tail recursion. If a method does a tail call to itself, it&#8217;s called tail recursion, and Scala will rewrite the recursion into a loop that does not consume stack space.</p>
</div>
<div class="paragraph">
<p>Many recursive algorithms can be rewritten in a tail recursive way. For our even and odd problem, this is a possible solution:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">def even(i: Int): Boolean = i match {
case 0 =&gt; true
case 1 =&gt; false
case _ =&gt; even(i - 2)
}
def odd(i: Int): Boolean = !even(i)</code></pre>
</div>
</div>
<div class="paragraph">
<p>We&#8217;ve rewritten <code>even</code> to be tail-recursive, and now Scala will optimize it for us:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>scala&gt; even(500000000)
res25: Boolean = true</code></pre>
</div>
</div>
<div class="paragraph">
<p>it no longer blows up for large numbers.</p>
</div>
<div class="paragraph">
<p>The <code>@tailrec</code> annotation is useful in these cases. It does not change how the function will be compiled, but it does trigger an error if the function is not actually tail-recursive. So this will protect you from accidentally changing a function that you want to be tail-recursive function into something that&#8217;s no longer tail recursive.</p>
</div>
<div class="paragraph">
<p>You can try this out by putting the <code>@tailrec</code> annotation on the first and the latest version of even that we&#8217;ve defined.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_trampolines">Trampolines</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Another way of solving the problem of consuming too much stack space, is by moving the computation from the stack to the heap.</p>
</div>
<div class="paragraph">
<p>Instead of letting the even function recursively call odd, we could also let it return some recipe to it&#8217;s caller, how to continue with the computation. Let&#8217;s look at the following code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">sealed trait EvenOdd

case class Done(result: Boolean) extends EvenOdd
case class Even(value: Int) extends EvenOdd
case class Odd(value: Int) extends EvenOdd

def even(i: Int): EvenOdd = i match {
  case 0 =&gt; Done(true)
  case _ =&gt; Odd(i - 1)
}

def odd(i: Int): EvenOdd = i match {
  case 0 =&gt; Done(false)
  case _ =&gt; Even(i - 1)
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we defined a little language, EvenOdd, that can express three things:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The computation is Done, and we have the result value</p>
</li>
<li>
<p>We need to compute whether a value is Even</p>
</li>
<li>
<p>We need to compute whether a value is Odd</p>
</li>
<li>
<p>Our even and odd functions no longer return a boolean, but return an expression in this little language.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Finally, we create an interpreter, that will recursively evaluate expressions in this language:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">// Using Scala's self recursive tail call optimization
@tailrec
def run(evenOdd: EvenOdd): Boolean = evenOdd match {
  case Done(result) =&gt; result
  case Even(value) =&gt; run(even(value))
  case Odd(value) =&gt; run(odd(value))
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now we have expressed <code>even</code> and <code>odd</code> in their natural, mutually recursive way, and we still have a stack safe interpreter:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>scala&gt; run(even(5000000))
res1: Boolean = true</code></pre>
</div>
</div>
<div class="paragraph">
<p>The disadvantage of this is that this is significantly slower. Unfortunately, we can&#8217;t seem to have our cake and eat it too :(</p>
</div>
<div class="paragraph">
<p>This strategy is sometimes called trampolining, because instead of creating a big stack, we go up to <code>even</code>, then down to run, then up to <code>odd</code>, then down to run, then up to <code>even</code>, down to run, etcetera. The size of our stack keeps growing and shrinking by one frame for every step in the computation. This looks a lot like going up and down on a trampoline :)</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_generalizing">Generalizing</h2>
<div class="sectionbody">
<div class="paragraph">
<p>There is no need to specialize our little language to computing <code>even</code> and <code>odd</code>. We can also make a little language that can express recursion in a general way:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">sealed trait Computation[A]

class Continue[A](n: =&gt; Computation[A]) extends Computation[A] {
  lazy val next = n
}

case class Done[A](result: A) extends Computation[A]
  def even(i: Int): Computation[Boolean] = i match {
    case 0 =&gt; Done(true)
    case _ =&gt; new Continue(odd(i - 1))
  }

  def odd(i: Int): Computation[Boolean] = i match {
    case 0 =&gt; Done(false)
    case _ =&gt; new Continue(even(i - 1))
  }

  @tailrec
  def run[A](computation: Computation[A]): A = computation match {
    case Done(a) =&gt; a
    case c: Continue[A] =&gt; run(c.next)
  }</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_recursion_and_trampolines_in_scala">Recursion and Trampolines in Scala</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Here our even and odd functions don&#8217;t return domain specific values, but a general value that indicates whether the computation is done, or whether more steps are needed. The latter includes the next step as a by-name parameter, that the tail recursive runner function can call.</p>
</div>
<div class="paragraph">
<p>Note that our run function is no longer tied to computing <code>even</code> and <code>odd</code>, it can compute anything.</p>
</div>
<div class="paragraph">
<p><code>TailRec</code> in the standard library</p>
</div>
<div class="paragraph">
<p>Something similar in spirit, but with a better implementation is also available in the Scala standard library:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-scala" data-lang="scala">import scala.util.control.TailCalls.{ TailRec, done, tailcall }

def even(i: Int): TailRec[Boolean] = i match {
  case 0 =&gt; done(true)
  case _ =&gt; tailcall(odd(i - 1))
}

def odd(i: Int): TailRec[Boolean] = i match {
  case 0 =&gt; done(false)
  case _ =&gt; tailcall(even(i - 1))
}

even(3000).result</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_comparing_performance">Comparing performance</h2>
<div class="sectionbody">
<div class="paragraph">
<p>I compared the performance of these solutions with JMH, and these are the results:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>[info] Benchmark Mode Cnt Score Error Units
[info] Trampolines.GeneralTrampolineRunner.bench thrpt 30 44916.024 ± 388.202 ops/s
[info] Trampolines.ScalaTrampolineRunner.bench thrpt 30 52106.426 ± 408.242 ops/s
[info] Trampolines.SpecializedTrampolineRunner.bench thrpt 30 94002.234 ± 1584.913 ops/s
[info] Trampolines.StackRunner.bench thrpt 30 358382.321 ± 6622.659 ops/s</code></pre>
</div>
</div>
<div class="paragraph">
<p>As expected, the version that runs on the stack is the fastest. But remember that this is the version that breaks for a large number of recursions.</p>
</div>
<div class="paragraph">
<p>The specialized trampolining version, with the <code>EvenOdd</code> domain specific language and a runner optimized for this particular problem, takes about a 4 times speed hit compared to the stack version.</p>
</div>
<div class="paragraph">
<p>The general trampoline version that we defined here is about 2 times slower than the specialized version, and about 8 times slower than the stack version.</p>
</div>
<div class="paragraph">
<p>The <code>TailRec</code> version from the Scala standard library is about 20% faster than our general trampoline, making it about 7 times slower than the stack version.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_source_code">Source code</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The source code of the benchmarks (and all the code), is available on <a href="https://github.com/eamelink/scala-trampolines" class="bare">https://github.com/eamelink/scala-trampolines</a></p>
</div>
</div>
</div>]]></description><link>http://blog.lunatech.com/2016/07/15/Recursion-and-Trampolines-in-Scala.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/07/15/Recursion-and-Trampolines-in-Scala.html</guid><category><![CDATA[scala]]></category><category><![CDATA[recursion]]></category><category><![CDATA[fp]]></category><dc:creator><![CDATA[Nicolas Leroux]]></dc:creator><pubDate>Fri, 15 Jul 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Clever Cloud’s CEO to speak at Lunatech]]></title><description><![CDATA[<div class="paragraph">
<p>Friday 27 May 2016 Clever Cloud’s CEO, <strong>Quentin Adam</strong>, will be visiting Lunatech where he will give a presentation about using Clever Cloud with Scala.</p>
</div>
<div class="paragraph">
<p>Clever Cloud is a “Europe-based PaaS company” that helps “developers deploy and run their apps with bulletproof infrastructure, automatic scaling, fair pricing” and aims “to make an easy-to-use service, without any vendor lock-in”.</p>
</div>
<div class="paragraph">
<p>Due to his experience at Clever Cloud — where he can work a wide range of technologies and tools — he has a lot of knowledge and is able to speak about many different subjects. He regularly speaks at various tech conferences.</p>
</div>
<div class="paragraph">
<p>We are opening up the presentation to everyone. Feel free to join us at 16:00.</p>
</div>]]></description><link>http://blog.lunatech.com/2016/05/26/Clever-Clouds-CEO-to-speak-at-Lunatech.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/05/26/Clever-Clouds-CEO-to-speak-at-Lunatech.html</guid><category><![CDATA[company]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Thu, 26 May 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Scala training camp at Lunatech]]></title><description><![CDATA[<div class="paragraph">
<p>Every friday our teams work together to improve their skills on Scala and other technologies. They explore new grounds, new ideas and new techniques.  They share knowledge between teams. Join us if you want to make your passion your work.</p>
</div>]]></description><link>http://blog.lunatech.com/2016/05/19/Scala-training-camp-at-Lunatech.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/05/19/Scala-training-camp-at-Lunatech.html</guid><category><![CDATA[scala]]></category><category><![CDATA[office]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Thu, 19 May 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[On the road again: Scala days Berlin 2016]]></title><description><![CDATA[<div class="paragraph">
<p>Lunatech is proud to present the real star of this event: the Lunatech carry-on suitcase. With its class and convenience, it will accompany all Lunatech employees to the 2016 Scala days in Berlin. All suitcases are personalised with their owner’s name to make it difficult to sell them to the highest bidder and to prevent people ending up with their colleague’s suitcase.</p>
</div>]]></description><link>http://blog.lunatech.com/2016/05/16/On-the-road-again-Scala-days-Berlin-2016.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/05/16/On-the-road-again-Scala-days-Berlin-2016.html</guid><category><![CDATA[scaladays]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 16 May 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Platinum sponsor of Scala Days Berlin]]></title><description><![CDATA[<div class="paragraph">
<p>Lunatech is proud to be a <a href="http://event.scaladays.org/scaladays-berlin-2016#05-Sponsors">platinum sponsor for Scala Days Berlin 2016</a>. This year Lunatech is taking the whole team to Scala Days Berlin.</p>
</div>
<div class="paragraph">
<p>If you’re there and are looking for a job with the kind of company that sponsors and takes all its employees to Scala Days, have a chat with us, there’ll be a lot of us walking around. If you can’t wait, get in touch with us right now.</p>
</div>]]></description><link>http://blog.lunatech.com/2016/04/14/Platinum-sponsor-of-Scala-Days-Berlin.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/04/14/Platinum-sponsor-of-Scala-Days-Berlin.html</guid><category><![CDATA[scaladays]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Thu, 14 Apr 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Fast Track to Scala Training by Lunatech]]></title><description><![CDATA[<div class="paragraph">
<p>On Feb 4 and 5th <strong>Francisco Canedo</strong>, Senior Developer at Lunatech and a Typesafe certified trainer, will be teaching Typesafe’s Fast Track to Scala Course at our office.</p>
</div>
<div class="paragraph">
<p>This course is designed to give experienced developers the know-how to confidently start programming in Scala. The course ensures you will have a solid understanding of the fundamentals of the language, the tooling and the development process as well as a good appreciation of the more advanced features. If you already have Scala programming experience, then this course could be a useful refresher, yet no previous knowledge of Scala is assumed.</p>
</div>
<div class="paragraph">
<p>The course starts each day at 9:00 with breakfast, lunch is also provided, and ends between 17:00 and 18:00 depending on the needs of the students and costs €600 per person.</p>
</div>
<div class="paragraph">
<p>If you are interested in joining the course, please contact us by sending a mail to <a href="mailto:training@lunatech.com">training@lunatech.com</a> or tweet us @LunatechLabs</p>
</div>]]></description><link>http://blog.lunatech.com/2016/01/18/Fast-Track-to-Scala-Training-by-Lunatech.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/01/18/Fast-Track-to-Scala-Training-by-Lunatech.html</guid><category><![CDATA[scala]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 18 Jan 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Our first award!]]></title><description><![CDATA[<div class="paragraph">
<p>Lunatech has been awarded by the “<em>The National Business Success Award Institute</em>” as branch winner 2015 in the category “ICT”.</p>
</div>
<div class="paragraph">
<p>The jury cited the company&#8217;s service quality, technology excellence and innovation. Representatives of the award winner also make appearances on the RTL television show "<em>De Success Factor</em>" .</p>
</div>]]></description><link>http://blog.lunatech.com/2016/01/04/Our-first-award.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/01/04/Our-first-award.html</guid><category><![CDATA[company]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 04 Jan 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Functional Rotterdam - 5th Edition]]></title><description><![CDATA[<div class="paragraph">
<p>Every first Tuesday of the month, at Lunatech we are organize a meetup focussed on Functional Programming. Tomorrow is the 5th edition of the event. You can join the fun by going to our <a href="http://www.meetup.com/Functional-Rotterdam/">meetup page</a></p>
</div>
<div class="paragraph">
<p>This is an informal event where we share our experience of using functional programing in our projects and learn from others who work in different languages. In the past we had presenations about Scala, Spark, Elm, Frege apart from a coding dojo at the last event.</p>
</div>
<div class="paragraph">
<p>Do join us by RSVPing on the <a href="http://www.meetup.com/Functional-Rotterdam/">meetup page</a></p>
</div>]]></description><link>http://blog.lunatech.com/2016/01/04/Functional-Rotterdam-5th-Edition.html</link><guid isPermaLink="true">http://blog.lunatech.com/2016/01/04/Functional-Rotterdam-5th-Edition.html</guid><category><![CDATA[fp]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Mon, 04 Jan 2016 00:00:00 GMT</pubDate></item><item><title><![CDATA[Lunatech management realises MBO]]></title><description><![CDATA[<div class="paragraph">
<p><strong>Ray Kemp</strong> and <strong>Nicolas Leroux</strong>, jointly CEO, have successfully realized a management buy-out (“MBO”) of Lunatech Labs BV (“Lunatech”). Also, some staff members acquired a small stake in the company in this transaction. Lunatech is a Dutch IT service provider specialised in system integration, customised software implementation and web applications.</p>
</div>
<div class="paragraph">
<p>Main Corporate Finance has structured the MBO and arranged the debt financing. Bank financing has been provided by Rabobank. The transaction was partly financed with a mezzanine loan provided by Main Mezzanine Capital.Lunatech stands out in linking and structuring applications between back-end and front-end. Lunatech provides support for complex IT system integration and migration projects and they support IT departments of organisations. The company offers high quality solutions including consultancy and supplying project teams of Scala professionals.</p>
</div>
<div class="paragraph">
<p>Lunatech was founded in 1993 and located in Rotterdam. Lunatech provides its services to proven customers in the Netherlands and France, as for example: ING, SDU, Alcatel, Disney and UPS.</p>
</div>
<div class="paragraph">
<p>The strength of Lunatech is also recognised by the investors, says Lars van ‘t Hoenderdaal:</p>
</div>
<div class="paragraph">
<p>“<em>Lunatech is a very nice company with a strong management team and international growth potential. We experienced great interest among our funders to participate in this mezzanine proposition</em>.”</p>
</div>
<div class="paragraph">
<p>After reaching agreement on the transaction structure and financing structure, the transaction has been completed within 4 weeks. Rabobank has also shown their strength by acting quickly.</p>
</div>
<div class="paragraph">
<p>Ray Kemp, CEO Lunatech, is very satisfied with the realised MBO:</p>
</div>
<div class="paragraph">
<p><em>“Due to funding from the bank and mezzanine we were able to realise the MBO without a private equity investor. In this way we can realise our growth independently</em>.”</p>
</div>
<div class="paragraph">
<p>Main Mezzanine Capital is part of Main Capital Partners, an investment and financing company, as well as a corporate finance advisor, with a focus on growing and profitable companies in the TMT sector in the Netherlands. Main Mezzanine Capital is funded by its own shareholders, wealthy individuals, family offices and (former) entrepreneurs, who like to invest in companies with an interesting risk-return profile.</p>
</div>]]></description><link>http://blog.lunatech.com/2015/12/22/Lunatech-management-realises-MBO.html</link><guid isPermaLink="true">http://blog.lunatech.com/2015/12/22/Lunatech-management-realises-MBO.html</guid><category><![CDATA[company]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Tue, 22 Dec 2015 00:00:00 GMT</pubDate></item><item><title><![CDATA[Syntactically correct and type-safe JPA queries in Play 2.0]]></title><description><![CDATA[<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>For all three approaches we’ll use the same use case: find a <code>User</code> object by its ‘username’ property.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_java_persistence_api_query_language">Java Persistence API query language</h3>
<div class="paragraph">
<p>An easy way to read data from our database is by creating a ‘dynamic query’ with use of the Java Persistance API (JPA) query language, a string-based query language. To find a <code>User</code> by username we would write something like:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">try {
    return JPA.em()
        .createQuery("from User where username = :username", User.class)
        .setParameter("username", "foo").getSingleResult();
} catch (NoResultException nre) {
    return null;
} catch (NonUniqueResultException nure) {
    return null;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The problem with this example is syntax checking. The query language is not checked at compile time, so if we write <code>from Uzer</code> instead of <code>from User</code> no compile-time errors will occur. However, because the query is incorrect, we &lt;em&gt;will&lt;/em&gt; get a runtime error. To prevent these kind of runtime errors we need a way to create syntactically checked queries. This is where the JPA Criteria API comes in.</p>
</div>
</div>
<div class="sect2">
<h3 id="_jpa_criteria_api">JPA Criteria API</h3>
<div class="paragraph">
<p>The Criteria API is an alternative to the query language. It allows us to define object-based queries instead of the string-based approach of the query language. The advantage is that these object-based queries are more syntactically checked.</p>
</div>
<div class="paragraph">
<p>If we want to find the <code>User</code> with help of the Criteria API it becomes this piece of code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">try {
    CriteriaBuilder cb = JPA.em().getCriteriaBuilder();
    CriteriaQuery&lt;User&gt; query = cb.createQuery(User.class);
    Root&lt;User&gt; user = query.from(User.class);
    query.where(cb.equal(user.get("username"), "foo"));
    return JPA.em().createQuery(query).getSingleResult();
} catch (NoResultException nre) {
    return null;
} catch (NonUniqueResultException nure) {
    return null;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here the compiler will give us an error if we write <code>Uzer.class</code> instead of <code>User.class</code>. So more syntax checking. But as you probably already noticed, <code>user.get("username")</code> is still not checked for correct syntax. Our code will successfully compile if we replace <code>username</code> with <code>uzrname</code>. This is because the compiler doesn’t know if <code>uzrname</code> is a property of the <code>User</code> class. So we need more syntax checking to prevent these kind of errors. With the help of Java Persistence Metamodel API we can create fully syntactically checked queries.</p>
</div>
</div>
<div class="sect2">
<h3 id="_jpa_2_0_metamodels">JPA 2.0 Metamodels</h3>
<div class="paragraph">
<p>A metamodel class is a class that represents the datastructure of the corresponding model class. For example, this model class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@Entity
public class User {
    public Long id;
    public String username;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Would have the following metamodel class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@StaticMetamodel(User.class)
public abstract class User_ {
    public static volatile SingularAttribute&lt;User, String&gt; username;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now we are able to create a type-safe query:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">try {
    CriteriaBuilder cb = JPA.em().getCriteriaBuilder();
    CriteriaQuery&amp;lt;User&amp;gt; query = cb.createQuery(User.class);
    Root&amp;lt;User&amp;gt; user = query.from(User.class);
    query.where(cb.equal(user.get(User_.username), "foo"));
    return JPA.em().createQuery(query).getSingleResult();
} catch (NoResultException nre) {
    return null;
} catch (NonUniqueResultException nure) {
    return null;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>These metamodels are pretty useful because our queries are syntactically correct and type-safe&#33; Syntactically correct because all the syntax is checked. We will get an error is we replace <code>username</code> by <code>uzername</code>. So if we, for example, rename a variable, the compiler will tell us which queries we forgot to update. We won’t get a runtime error.</p>
</div>
<div class="paragraph">
<p>The query is also type-safe. Type safety means that the compiler will validate types while compiling. If a wrong type is assigned to a variable an exception is thrown at compile time. As you probably know Play 2.0 is [focused on type safety](<a href="http://www.playframework.org/documentation/2.0/Philosophy" class="bare">http://www.playframework.org/documentation/2.0/Philosophy</a>).</p>
</div>
<div class="paragraph">
<p>Because of the metamodels, the compiler knows the type of the variables. So you can’t for example do:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">try {
    CriteriaBuilder cb = JPA.em().getCriteriaBuilder();
    CriteriaQuery&amp;lt;User&amp;gt; query = cb.createQuery(User.class);
    Root&amp;lt;User&amp;gt; user = query.from(User.class);
    query.like(cb.like(user.get(User_.id), "1"));
    return JPA.em().createQuery(query).getSingleResult();
} catch (NoResultException nre) {
    return null;
} catch (NonUniqueResultException nure) {
    return null;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This query won’t compile because the <code>like</code> method needs a <code>Expression&lt;String&gt;</code> as first parameter and <code>id</code> is a <code>Expression&lt;Long&gt;</code>.</p>
</div>
<div class="paragraph">
<p>Because it takes some time to write these metamodels by hand, it would be nicer to generate them. The next paragraph will explain how to generate metamodels in Play 2.0.</p>
</div>
</div>
<div class="sect2">
<h3 id="_jpa_2_0_metamodel_genaration_in_play_2_0">JPA 2.0 Metamodel genaration in Play 2.0</h3>
<div class="paragraph">
<p>A way to generate our metamodels is by using the <code>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</code>. The processor will automatically run if the hibernate-jpamodelgen.jar is added to the classpath and when you are using JDK 6. So we add a project dependecy to our Build.scala:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">val appDependencies = Seq(
    "org.hibernate" % "hibernate-jpamodelgen" % "1.2.0.Final"
)</code></pre>
</div>
</div>
<div class="paragraph">
<p>And specify a folder where the generated source files are placed. This is done by passing an argument to the Java compiler. Passing an argument is also done in Build.scala:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings(
    javacOptions ++= Seq("-s", "metamodel")
)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that the provided folder must exist, the Java compiler won’t generate it for you. So it is probably not a good idea to put the metamodels in our target folder, because its contents are deleted when the the <code>play clean</code> command is run.</p>
</div>
<div class="paragraph">
<p>Eclipse users can add the metamodel folder to their ‘source folders’ (Project → Properties → Java Build Path → Source → Add Folder) for autocompletion etc.</p>
</div>
</div>
<div class="sect2">
<h3 id="_conclusion">Conclusion</h3>
<div class="paragraph">
<p>Using the Criteria API with metamodels gives us the opportunity to write syntactically correct and type-safe queries. It is also quite easy to generate these metamodels. So with a bit of effort we can get nice object-based, syntactically correct and type-safe queries that cause fewer runtime errors.</p>
</div>
</div>
<div class="sect2">
<h3 id="_sources">Sources</h3>
<div class="paragraph">
<p>[JSR-317 - Java Persistence 2.0](<a href="http://jcp.org/aboutJava/communityprocess/final/jsr317/" class="bare">http://jcp.org/aboutJava/communityprocess/final/jsr317/</a>)</p>
</div>
<div class="paragraph">
<p>[Hibernate JPA 2 Metamodel Generator](<a href="http://docs.jboss.org/hibernate/jpamodelgen/1.0/reference/en-US/html_single" class="bare">http://docs.jboss.org/hibernate/jpamodelgen/1.0/reference/en-US/html_single</a>)</p>
</div>
</div>]]></description><link>http://blog.lunatech.com/2015/07/15/Syntactically-correct-and-type-safe-JPA-queries-in-Play-20.html</link><guid isPermaLink="true">http://blog.lunatech.com/2015/07/15/Syntactically-correct-and-type-safe-JPA-queries-in-Play-20.html</guid><category><![CDATA[scala]]></category><category><![CDATA[recursion]]></category><category><![CDATA[fp]]></category><dc:creator><![CDATA[Antoine Laffez]]></dc:creator><pubDate>Wed, 15 Jul 2015 00:00:00 GMT</pubDate></item></channel></rss>