Tag: dsl

The Power of Gradle Kotlin DSL

The Power of Gradle Kotlin DSL

-The following is based on Gradle 4.3.1-

A few weeks ago I started migrating most of my Groovy-based gradle.build scripts to Kotlin-backed gradle.build.kts scripts using the Kotlin DSL. Why would I do that? Kotlin is my language of choice and I love the idea of using a single language to do all my work. I never learned programming with Groovy and only know the bloody basics, which always makes me think: “This can’t be the best way to do things…”. Kotlin, on the other hand, is a language I use on a daily basis and therefore I know how to use the language appropriately. Additionally, Kotlin is a statically-typed language, whereas Groovy isn’t. IDEs are having hard times offering code completion and error detection at compile time when a Groovy build script is being edited. As for the Kotlin DSL, this isn’t true. Especially IntelliJ knows how to help us with Kotlin development, even in gradle.build.kts files. All these reasons made me take a deeper look at the new style Gradle offers.

Minor Impediments

It can sometimes be a bit tedious to rewrite your gradle.build into gradle.build.kts files, especially in the IDE with all its caches malfunctioning during that process. I often had to reopen my project or even reimport it before IntelliJ understood what was going on. It also often helps to use “Refresh all Gradle projects” button in the Gradle view.

Let’s take a look

The following snippet shows the first part of a working example. It was taken from one of my projects, which is a Kotlin web application based on the Vert.x toolkit. Learn more about the technology in this post I wrote earlier.

The script first defines a few global variables, mostly containing version numbers, which are used throughout the build file. Next, we can observe the plugins block that simply defines a few plugins used for the build. Most importantly, the Kotlin Gradle plugin for JVM applications is included, which we can do with the DSL-specific function kotlin(module: String), that takes its module argument and appends it to "org.jetbrains.kotlin.", which then is put into the id(plugin: String) method, the default api for applying plugins. Last but not least, we can see the listing of dependencies, which again provides a kotlin convenience method we can use to reduce redundant declarations. A similar approach can be seen with the definition of the io.vertx dependencies. In order to only once write the "io.vertx.vertx" String, which is part of every single Vert.x dependency, it’s used as a receiver of let. A first example of real idiomatic code within the build script.

//imports

//taken from the `plugins` defined later in the file
val kotlinVersion = plugins.getPlugin(KotlinPluginWrapper::class.java).kotlinPluginVersion
val kotlinCoroutinesVersion = "0.19.3"

val vertxVersion = "3.5.0" //
val nexusRepo = "http://x.x.x.x:8080/nexus/content/repositories/releases"

plugins {
    kotlin("jvm").version("1.2.0")
    application
    java
    `maven-publish`
}

dependencies {
    compile(kotlin("stdlib", kotlinVersion))
    compile(kotlin("reflect", kotlinVersion))
    compile("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutinesVersion")

    "io.vertx:vertx".let { v ->
        compile("$v-lang-kotlin:$vertxVersion")
        compile("$v-lang-kotlin-coroutines:$vertxVersion")
        compile("$v-web:$vertxVersion")
        compile("$v-mongo-client:$vertxVersion")
        compile("$v-health-check:$vertxVersion")
        compile("$v-web-templ-thymeleaf:$vertxVersion")
    }

    compile("org.slf4j:slf4j-api:1.7.14")
    compile("ch.qos.logback:logback-classic:1.1.3")
    compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.9.0.pr3")

    testCompile(kotlin("test", kotlinVersion))
    testCompile(kotlin("test-junit", kotlinVersion))
    testCompile("io.vertx:vertx-unit:$vertxVersion")
    testCompile("org.mockito:mockito-core:2.6.2")
    testCompile("junit:junit:4.11")
}

// Part 2
}

The second part of the example project starts with defining repositories, which are used to find dependencies and plugins declared earlier. Again, we see an example of simplifying the code with the help of using the language: The custom Maven repositories are defined using the functional method forEach, and thus shortens the boilerplate. After that, the plugins are being configured, which for instance is necessary for enabling coroutine support or defining the application properties. Finally, we can observe a sequence of task configurations that control the behavior of single build steps, e.g. tests.

// ...Part 1

repositories {
    mavenCentral()
    jcenter()
    listOf("https://www.seasar.org/maven/maven2/",
            "https://plugins.gradle.org/m2/",
            nexusRepo).forEach {
        maven { url = uri(it) }
    }
}

kotlin {
    experimental.coroutines = Coroutines.ENABLE
}

application {
    group = "de.swirtz"
    version = "1.0.0"
    applicationName = "gradle-kotlindsl"
    mainClassName = "de.swirtz.ApplicationKt"
}

publishing {
    repositories {
        maven {
            url = uri(nexusRepo)
        }
    }
    if (!project.hasProperty("jenkins")) {
        println("Property 'jenkins' not set. Publishing only to MavenLocal")
    } else {
        (publications) {
            "maven"(MavenPublication::class) {
                from(components["java"])
            }
        }
    }
}

tasks {
    withType<KotlinCompile> {
        kotlinOptions.jvmTarget = "1.8"
    }

    withType<Test> {
        testLogging.showStandardStreams = true
    }

    withType<Jar> {
        manifest {
            attributes["Main-Class"] = application.mainClassName
        }
        from(configurations.runtime.map { if (it.isDirectory) it else zipTree(it) })
    }

    withType<GradleBuild> {
        finalizedBy("publishToMavenLocal")
    }
}

The Result

We’ve seen a rather simple build script written with the Gradle Kotlin DSL. I made use of a few idiomatic Kotlin functions in order to show the power of such .kts files. Especially for Kotlin developers, it can make much sense to completely switch to the shown approach. IntelliJ does support the creation of new build.gradle.kts files by default when you open the “New” option in “Project” view.

There will be situations, which make you want to ask somebody for help. I recommend reaching out directly in the corresponding Kotlin Slack channel: gradle.

I hope I could inspire you to give it a try! Good Luck 🙂

The whole script as a Gist

Please follow and like me 🙂
Web Applications with Kotlin ktor

Web Applications with Kotlin ktor

Disclaimer: This article was originally published in the Dzone Web Development Guide, which can be downloaded here.

Introduction

When Google made Kotlin an official language for Android a few months ago at Google I/O, the language gained a lot of popularity in the Android world quickly. On the server side though, Kotlin is not as broadly adopted yet and some people still seem to be cautious when backend services are involved. Other developers are convinced that Kotlin is mature enough and can safely be used for any server application in which Java could play a role otherwise.
If you want to develop web apps with Kotlin, you can choose from various web frameworks like Spring MVC/WebFlux, Vert.x, Vaadin and basically everything available for the JVM. Besides the mentioned frameworks there’s also a Kotlin specific library available for creating web applications, called ktor. After reading this article, you’ll know what ktor and its advantages are and how you can quickly develop a web application in Kotlin.

Ktor

The web application framework ktor, itself written in Kotlin, is meant to provide a tool for quickly creating web applications with Kotlin. The resulting software may be hosted in common servlet containers like Tomcat or standalone in a Netty for example. Whatever kind of hosting you choose, ktor is making heavy use of Kotlin Coroutines, so that it’s implemented 100% asynchronously and mainly non-blocking. ktor does not dictate which frameworks or tools to be used, so that you can choose whatever logging, DI, or templating engine you like. The library is pretty light-weight in general, still being very extensible through a plugin mechanism.
One of the greatest advantages attributed to Kotlin is its ability to provide type-safe builders, also known as Domain Specific Languages (DSL). Many libraries already provide DSLs as an alternative to common APIs, such as the Android lib anko, the Kotlin html builder or the freshly released Spring 5 framework. As we will see in the upcoming examples, ktor also makes use of such DSLs, which enable the user to define the web app’s endpoints in a very declarative way.

Example Application

In the following, a small RESTful (Not sure, if everyone will agree) web service will be developed with ktor. The service will use an in-memory repository with simple Person resources, which it exposes through a JSON API. Let’s look at the components.

Person Resource and Repository

According to the app’s requirements, a resource “Person” is defined as a data class and the corresponding repository as an object, Kotlin’s way of applying the Singleton pattern to a class.


data class Person(val name: String, val age: Int){
    var id: Int? = null
}

The resource has two simple properties, which need to be defined when a new object is constructed, whereas the id property is set later when stored in the repository.
The Person repository is rather unspectacular and not worth observing. It uses an internal data store and provides common CRUD operations.

Endpoints

The most important part of the web application is the configuration of its endpoints, exposed as a REST API. The following endpoints will be implemented:

Endpoint HTTP Method Description
/persons GET Requests all Person resources
/persons/{id} GET Requests a specific Person resource by its ID
/persons DELETE Requests all Person resources to be removed
/persons/{id} DELETE Requests a specific Person resource to be removed by its ID
/persons POST Requests to store a new Person resource
/ GET Delivers a simple HTML page welcoming the client

The application won’t support an update operator via PUT.

Routing with Ktor

Now ktor comes into play with its structured DSL, which will be used for defining the previously shown endpoints, a process often referred to as “routing”. Let’s see how it works:


fun Application.main() {
    install(DefaultHeaders)
    install(CORS) {
        maxAge = Duration.ofDays(1)
    }
    install(ContentNegotiation){
        register(ContentType.Application.Json, GsonConverter())
    }

    routing {
        get("/persons") {
            LOG.debug("Get all Person entities")
            call.respond(PersonRepo.getAll())
        }
    }
    // more routings
}

The fundamental class in the ktor library is Application, which represents a configured and eventually running web service instance. In the snippet, an extension function main() is defined on Application, in which it’s possible to call functions defined in Application directly, without additional qualifiers. This is done by invoking install() multiple times, a function for adding certain ApplicationFeatures into the request processing pipeline of the application. These features are optional and the user can choose from various types. The only interesting feature in the shown example is ContentNegotiation, which is used for the (de-)serialization of Kotlin objects to and from JSON, respectively. The Gson library is used as a backing technology.
The routing itself is demonstrated by defining the GET endpoint for retrieving all Person resources here. It’s actually straight-forward since the result of the repository call getAll() is just delegated back to the client. The call.respond() invocation will eventually reach the GsonSupport feature taking care of transforming the Person into its JSON representation. The same happens for the remaining four REST endpoints, which will not be shown explicitly here.

The HTML builder

Another cool feature of ktor is its integration with other Kotlin DSLs like the HTML builder, which can be found on GitHub. By adding a single additional dependency to a ktor app, this builder can be used with the extension function call.respondHtml(), which expects type-safe HTML code to be provided. In the following example, a simple greeting to the readers is included, which the web service exposes as its index page.


get("/") {
    call.respondHtml {
        head {
            title("ktor Example Application")
        }
        body {
            h1 { +"Hello DZone Readers" }
            p {
                +"How are you doing?"
            }
        }
    }
}

Starting the Application

After having done the configuration of a ktor application, there’s still a need to start it through a regular main method. In the demo, a Netty server is started standalone by doing the following:


fun main(args: Array) {
    embeddedServer(Netty, 8080, module = Application::main).start(wait = true)
}

The starting is made pretty simple by just calling the embeddedServer() method with a Netty environment, a port and the module to be started, which happens to be the thingy defined in the Application.main() extension function from the previously shown example.

Testing

A web framework or library is only applicable if it comes with integrated testing means, which ktor actually does. Since the GET routing for retrieving all Person resources was already shown, let’s have a look at how the endpoint can be tested.


 @Test
    fun getAllPersonsTest() = withTestApplication(Application::main) {
        val person = savePerson(gson.toJson(Person("Bert", 40)))
        val person2 = savePerson(gson.toJson(Person("Alice", 25)))
        handleRequest(HttpMethod.Get, "/persons") {
            addHeader("Accept", json)
        }.response.let {
            assertEquals(HttpStatusCode.OK, it.status())
            val response = gson.fromJson(it.content, Array::class.java)
            response.forEach { println(it) }
            response.find { it.name == person.name } ?: fail()
            response.find { it.name == person2.name } ?: fail()
        }
        assertEquals(2, PersonRepo.getAll().size)
    }

This one is quite simple: Two resource objects are added to the repository, then the GET request is executed and some assertions are done against the web service response. The important part is withTestApplication(), which ktor offers through its testing module and makes it possible to directly test the Application.
The article presented basically everything worth knowing in order to get started with ktor web applications. For more details, I recommend the ktor homepage or the samples included in the ktor repository.

Takeaways

In this article we had a look at the Kotlin web service library ktor that provides simple tools for writing a light-weight web application in Kotlin very quickly. ktor makes heavy use of Kotlin’s beautiful features, especially DSLs, Coroutines and extension functions, all of which make the language and ktor itself so elegant. This mainly separates ktor from other powerful frameworks, which in fact can be used with Kotlin very smoothly, but, since not completely written in Kotlin, lack certain features you can find in ktor. It’s a great place to start with web applications because of its simplicity and ability to be extended with custom features if needed, following the principle “simple is easy, complex is available”.
The complete source code of the developed web application can be found on GitHub, it’s backed by a Gradle build.

Please follow and like me 🙂
Spring WebFlux with Kotlin – Reactive Web

Spring WebFlux with Kotlin – Reactive Web

Spring 5.0 – even fancier

In this article I will show how Spring and Kotlin can be used together. If you’re not familiar with my recent articles, have a look at the other Kotlin related posts here. Besides Kotlin, I’ve always been interested in working with Spring ever since I started with Java back in 2011. I still like the framework although it’s getting bigger and bigger and you often don’t quite know which feature to choose amongst all the alternatives. As the framework itself is growing, the documentation, which is one of best you’ll ever get to see, also is.

The thing I like most about Spring is that you can focus on your business logic from day one and don’t have much technical, infrastructural stuff to set up before kicking off. Spring does that by encapsulating a lot of boilerplate that’s necessary for certain tasks and provides simple annotations we can apply in order to make use of these features. One of the most famous modules certainly is Spring Web MVC, which is widely used whenever it comes to web services on the JVM.

Reactive Programming – The non-blocking way

You might have noticed, that Reactive Programming is getting more attention recently. There are many frameworks emerging that want to encourage this style of programming, namely RxJava, Vert.X or Akka for example. If you’ve never come across these, you can read my post on Kotlin with Vert.X as a first step.

Spring reactive

What does this have to do with Spring though? Well, of course, there’s yet another library for building reactive systems, which in fact is powered by Spring: [Project Reactor] https://projectreactor.io). Reactor is used in the current Spring Release 5.0, released in September, which introduces a reactive web framework called WebFlux.
This fact on its own is a good reason for me to dive into it as it sounds fairly fantastic knowing Web MVC as Spring’s outstanding module already. But, there’s yet another great reason to take this expansion into account: Spring is greatly supporting Kotlin and even introduced Kotlin dedicated features with the recent major release 🙂 This was achieved by making use of extension functions in order to extend existing APIs and also by introducing Kotlin DSLs, also a topic I’m really interested in, as you can read in my post on creating a DSL with Kotlin. One of these new DSLs goes hand in hand with Spring WebFlux: A functional DSL for describing the WebFlux-backed web service. This, in fact, is what I am going to present to you in a very short example up next…

WebFlux and Kotlin in Action

Let’s have a look at a very basic application using Spring WebFlux in a Kotlin application. The initial setup can easily be downloaded as a SpringBoot application from Spring Initializr, if you choose Kotlin as the programming language and also enable the “Reactive Web” dependency, which is available since SpringBoot 2.0.0.

spring boot initilizr

As soon as we’ve imported this project into our IDE, we can start with creating a reactive web service. For the sake of brevity, I chose a very simple, not very useful, example: An internally managed repository of
simple Strings that is populated through the web interface and also is searchable from it. Thanks to Kotlin, and also Spring, there’s not much code to be written:

Repo and Handler

@Component
class ReactiveHandler(val repo: StringRepo) {
    fun getText(search: String): Mono<String> =
        repo.get(search).toMono().map { "Result: $it!" }
    fun addText(text: String): Mono<String> =
        repo.add(text).toMono().map { "Result: $it!" }
    fun getAllTexts(): Flux<String> =
        repo.getAll().toFlux().map { "Result: $it" }
}

@Component
class StringRepo {
    private val entities = mutableListOf<String>()
    fun add(s: String) = entities.add(s)
    fun get(s: String) = entities.find { it == s } ?: "not found!"
    fun getAll() = listOf(entities)
}

We simply create a repository that maintains a list of Strings and another class ReactiveHandler, which is responsible for delegating to the repository and providing “reactive types” defined in Reactor. These are mandatory for WebFlux: Flux and Mono (Read about them here). Regardless of their intention, have a look at how they are created: toMono() and toFlux() are examples of extension functions added in Spring 5.0, a feature dedicated to Kotlin. The much more interesting part though is where the web routing is defined. This part, in particular, is where the already mentioned functional DSL comes into play. Let’s observe how it works.

Functional WebFlux DSL.

@Configuration
class RoutingConfiguration {

    @Bean
    fun routerFunction(handler: ReactiveHandler): RouterFunction<ServerResponse> = router {
        ("/reactive").nest {
            val searchPathName = "search"
            val savePathName = "save"
            GET("/{$searchPathName}") { req ->
                val pathVar = req.pathVariable(searchPathName)
                ServerResponse.ok().body(
                        handler.getText(pathVar)
                )
            }
            GET("/") {
                ServerResponse.ok().body(handler.getAllTexts())
            }
            PUT("/{$savePathName}") { req ->
                val pathVar = req.pathVariable(savePathName)
                ServerResponse.ok().body(
                        handler.addText(pathVar)
                )
            }
        }
    }
}

The router function is the entry point of the new DSL, whose definition you can observe on GitHub. The shown solution is just one out of many since the DSL provides more ways you can choose from. With my definition, the server starts a web service under “/reactive” and accepts two GET and one PUT request, each of which is delegated to the previously shown ReactiveHandler (see method parameter) before the results are put into a ServerResponse. Of course, you’d have to handle errors in a real-world scenario and “ok” wouldn’t be the only response.

Benefit

If you ask me, this approach is very clean structured and even provides the opportunity of using any Kotlin code for defining variables, loops, conditions, whatsoever inside the actual DSL code. Given that, you have a very powerful tool that can be utilized in a very natural programmatic way.

If your like to check this out, the code is available in my repository.

Wrap-up and Perspective

I’ve presented a small project that’s making use of Spring 5.0 and its new module WebFlux in combination with Kotlin. I think, the fact, that Spring officially uses and supports Kotlin is a very important one, I’d like to emphasize once again.

Kotlin – It’s not only Android!

We all know that Kotlin made its way into Android, which was possible because Google announced the official support a few months ago. On the server-side though, people and especially companies hesitate when it comes to Kotlin. They tend to have doubts as to whether Kotlin’s really mature enough already.
When you ask me, there’s no good reason for hesitation. Many projects use Kotlin already, frameworks support Kotlin and even extend their libraries with dedicated Kotlin features. Spring, as one of the most common Java frameworks, seems to think the same as they quickly adopted Kotlin as an alternative to Java and Groovy for SpringBoot applications. The most recent developments, which are part of Spring 5.0, are the next step, some of which we’ve observed in this little article. If you’re, same as me, interested in spreading Kotlin as an alternative to Java, talk about it and tell your colleagues about Spring’s support and what’s actually
happening 😉

Special Thanks

As you can read in this article, Spring’s introducing quite a few Kotlin features. There’s one guy, Sébastien Deleuze, who’s highly responsible for this development in the Spring Framework. He has also been part of talkingkotlin
already, as one of the first discussion partners of Hadi Hariri. It’s really great to have such influencers in the Kotlin community, many thanks to you! Keep up the great work 🙂

If you like to have a look at my examples, the code is available here:
Git. Feel free to give any feedback, I’m always happy to help. Also, if you like, have a look at my Twitter account and follow if you’re interested in more Kotlin stuff 🙂 Thanks a lot.

Please follow and like me 🙂
Creating your own DSL in Kotlin

Creating your own DSL in Kotlin

Motivation

If you’ve been following my recent posts about Kotlin, you’ve probably noticed me mentioning Domain Specific Languages (DSL) already. Kotlin as a programming language provides some powerful features that allow us to create those DSLs. One of these features, I also already introduced, is called Function Literals with Receiver, others are the invoke convention or infix notation.

In this post we’ll have a look at the concept of DSLs and certainly see how we can create one with Kotlin in a relatively simple example:
I’ve often been struggling with Java’s API for setting up SSL/TLS connections in scenarios where https communication is required for example. Just recently, I had to implement different kinds of these in one of our applications. Doing this, I once again felt like wanting to write a little library that can support me with that task, hiding away all the difficulties and of course the boilerplate.

Read More Read More

Please follow and like me 🙂
Kotlin Conventions – Operator Overloading

Kotlin Conventions – Operator Overloading

Operator Overloading and Conventions in Kotlin

Introduction

Kotlin supports a technique called conventions, everyone should be familiar with. For example, if you define a special method plus in your class, you can use the + operator by convention.
In this article I want to show you which conventions can be used and will provide some Kotlin code demonstrating the concepts of course.

Read More Read More

Please follow and like me 🙂
Kotlin Function Literals with Receiver – Quick Introduction

Kotlin Function Literals with Receiver – Quick Introduction

Function Literals with Receiver – The Foundation for DSLs and many Library Functions

Today I want to give a quick introduction to Function Literals with Receiver. This concept is what makes Kotlin great for designing Domain Specific Languages as we know it from Groovy for example. Also, Kotlins standard library includes many functions which many of you have already used or at least seen probably: apply and with are the most prominent ones.

Read More Read More

Please follow and like me 🙂

Enjoy this blog? Please spread the word :)