Ktor – A Kotlin Web Framework

Ktor is an asynchronous web framework written in and designed for Kotlin, leveraging coroutines and allowing you to write asynchronous code without having to manage any threads yourself.

Here is a bit more background information on Ktor. It is backed by Jetbrains, who are also the creators of Kotlin itself. Who better to make a Kotlin web framework than the people that work on the language?

Reading and Writing With a ConcurrentHashMap

ConcurrentHashMap provides a Map implementation with thread-safe read and write operations.

The Map and ConcurrentMap interfaces provide methods that ConcurrentHashMap takes advantage of to provide thread-safe interactions. Generally, I tend to solely really on the Map interface as it provides most of the same methods that ConcurrentMap has; however, depending on your use case, it might be beneficial to check out the ConcurrentMap methods yourself.

Getting Started With RSocket Kotlin

RSocket is a transport protocol designed for reactive applications. More information on RSocket can be found on their website, leaving me to focus on writing about how RSocket and Kotlin can be combined.

RSocket has several libraries written in various languages that implement the RSocket protocol. For Kotlin, this comes as an extension for Ktor (a Kotlin client and web-server library) named rsocket-kotlin. We will look at this extension through this post.

How to Produce a Spring REST API Following the OpenAPI Specification

The OpenAPI specification defines how to write HTTP APIs that can be consumed by any programming language and provide insight into the APIs’ functionality without access to source code or documentation. In other words, following the specification makes it easier for consumers to understand what it does and how to use it. Tools, such as Swagger, can then be used to display documentation without developers maintaining documentation separate from an API’s code.

All these described points translate into happier users while mitigating some of the burdens you’ll face while supporting your APIs.

Transaction Savepoints in Spring JDBC

Savepoints allow you to create markers within a transaction that you can rollback to, without preventing the transaction from being committed at a later point. These can be treated like intermediate transactions within a single overarching transaction. At the end of the day, you either commit the transaction and persist all the changes to the database or rollback everything. Using savepoints, you can handle potential database errors and return to a safe point within the transaction and carry on.

This post will look at how you can use savepoints within Spring JDBC.

Calling Java Functional Interfaces from Kotlin

Basics

Below is a Functional Interface defined in Java:

Java

Note, that an interface does not need to be annotated with @FunctionalInterface to be treated as one.

Serializable Java Lambdas

Recently I was presented with the following error when serializing a lambda with Kryo:

Java
 




x


 
1
com.esotericsoftware.kryo.KryoException: 
2
  java.lang.IllegalArgumentException: 
3
    Unable to serialize Java Lambda expression, unless explicitly declared e.g., 
4
    Runnable r = (Runnable & Serializable) () -> System.out.println("Hello world!");


If you do not recognize the (Runnable & Serializable) syntax, don’t worry, it is merely stating that the lambda must implement two types. This is called Type Intersection. Personally, I have never needed to use this myself, so have never really thought about it. Serializable is a bit of a unique interface in this regards, as there is nothing you actually need to implement.

Augmenting a Spring Data Repository Through Delegation

I have recently written several posts about Kotlin’s delegation. In doing so, I realized a useful way to apply it to Spring Data repositories. This would allow Spring Data to continue sprinkling some magic, while providing a route for customization.

The code shown in this post is in Kotlin, but is still relevant to Java. This post uses R2DBC, but the content is generic enough to be applicable to any Spring Data module.

Streaming Live Updates From a Reactive Spring Data Repository

Here's an example implementation of streaming updates from a database to other components

This post details a naive implementation of streaming updates from a database to any other components that are interested in that data. More precisely, we look at how to alter a Spring Data R2DBC repository to emit events to relevant subscribers.

You may also like: Reactive Streams With Spring Data and MongoDB

A little bit of background knowledge of R2DBC and Spring will be helpful for this post. My previous writings: Asynchronous RDBMS access with Spring Data R2DBC and Spring Data R2DBC for Microsoft SQL Server — these should help in that regard.

Ktor: a Kotlin Web Framework

Ktor is an asynchronous web framework written in and designed for Kotlin. Allowing the more impressive features of Kotlin, such as coroutines, to not only be used but supported. Typically, Spring is my go-to general framework, and usually what I use when I need to put a REST API together. However, after recently attending a London Kotlin meetup where there was a presentation on Ktor, I decided I’d try something new for once. That is how I ended up here, writing a blog post about Ktor. So, this post is a learning experience for both you and me. 

Implementation

Dependencies

buildscript {
  ext.kotlin_version = '1.3.41'
  ext.ktor_version = '1.2.2'

  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

apply plugin: 'java'
apply plugin: 'kotlin'

// might not be needed but my build kept defaulting to Java 12
java {
  disableAutoTargetJvm()
}

// Ktor uses coroutines
kotlin {
  experimental {
    coroutines "enable"
  }
}

compileKotlin {
  kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
  kotlinOptions.jvmTarget = "1.8"
}

dependencies {
  // Kotlin stdlib + test dependencies

  // ktor dependencies
  compile "io.ktor:ktor-server-netty:$ktor_version"
  compile "io.ktor:ktor-jackson:$ktor_version"
  // logback for logging
  compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.3'
  // kodein for dependency injection
  compile group: 'org.kodein.di', name: 'kodein-di-generic-jvm', version: '6.3.0'
}


Kotlin Primitive and Object Arrays

I initially set out to write this post because I was playing around with some reflection code and thought I found something interesting. Alas, that was definitely not the case. Instead, it was just a basic feature of Kotlin that I haven’t needed to use or focus on yet. Although this post didn’t turn out the way I wanted it to, I still think it is a nice little post to bring some clarity to this subject.

In Java, there is the concept of primitive types and their wrapped versions. Thanks to autoboxing and unboxing, types can be interchanged between their primitive and wrapped versions. In other words, in most situations, you can use a long instead of a Long or a Long instead of a long. If you didn’t notice where the capitals were in that last sentence, then I imagine it probably looked quite confusing. The wording in that sentence is also crucial. More specifically, the statement “in most situations.”

Running a Java Class as a Subprocess

Running a Java class (not a jar) as a subprocess is something I needed to do this week. More precisely, I wanted to spawn a new process from within a test, instead of running it inside the test directly (in-process). I don’t think this is anything fancy or a complex thing to do. But, this is not something I have ever needed to do before and didn’t know the exact code to write.

Luckily, a quick Google search and a few Stack Overflow posts later, I found the answer I needed. Although the answer is there, I am rewriting it here for my own benefit and as well as yours.

Should You Write Comments?

To comment or not to comment, that is the question. I had a little argument with some of my family members (who have also done some coding, although one of them is still in secondary school) about this subject. They had a quick look at some code I was writing at home and asked where my comments were. They were shocked at my reply when I told them I don't use them. So I'm going to write about some of the things I told them. When is it the right time to write them into your code, how helpful are they and what should they contain? These are the questions I want to answer.

I don't normally write comments into my code anymore, especially with the code I write at work. One of the first things I was told when I started working was to not write comments and, at first, I was a bit skeptical, but after a while, it made sense.

Corda – Extending and Overriding Flows From External CorDapps

Recently, Corda 4 was released, bringing with it a ton of new features to make Corda more enjoyable to work with. To be honest, I am kind of assuming there are a lot of new features. I had a quick browse through the changelog, mainly to see my contributions being referenced, but I remember seeing a lot of lines of text. That has to be a good thing, right?

Anyway, one of these features is the ability to extend and override Flows. It doesn’t really sound very fancy when you realize that Corda is written in Kotlin and has inheritance completely baked into it (true for Java as well). But, there is more to it than that. Corda needs to map an Initiating Flow to the counterparty Flow that is responding to it.

Asynchronous RDBMS Access With Spring Data R2DBC

Not too long ago, a reactive variant of the JDBC driver was released, known as R2DBC. It allows data to be streamed asynchronously to any endpoints that have subscribed to it. Using a reactive driver like R2DBC together with Spring WebFlux allows you to write a full application that handles the receiving and sending of data asynchronously. In this post, we will focus on the database and on connecting to the database and then finally saving and retrieving data. To do this, we will be using Spring Data. As with all Spring Data modules, it provides us with out-of-the-box configuration, decreasing the amount of boilerplate code that we need to write to get our application setup. On top of that, it provides a layer upon the database driver that makes doing the simple tasks easier and the more difficult tasks a little less painful.

For the content of this post, I am making use of a Postgres database. At the time of writing only Postgres, H2 and Microsoft SQL Server have their own implementations of R2DBC drivers.

Testing Exceptions in Kotlin With assertFailsWith

I wanted to write this short post to highlight the assertFailsWith function available to Kotlin that makes testing exceptions a bit easier. Testing exceptions isn’t something fancy or new to JVM languages (from now on, I will use Java for comparisons), but Kotlin comes with the nice extra benefit of providing this functionality as part of its standard library. Comparing this to Java, you are likely to bring AssertJ into the mix to achieve similar results.

The main purpose of this post is to make you aware of the assertFailsWith function. I personally did not know it existed for a while and defaulted to depending on AssertJ. Not that I have anything against AssertJ that is. There are many other features that the library provides, but for this specific instance, it might be possible to remove it (assuming you are not using it for anything else that is).

Storing When Block Subject in a Variable

Here is a super short post on a change introduced in Kotlin 1.3 (yes, I know it has been out for a while now). We will take a quick look at capturing the subject of a when block into a scoped variable. This is a quality of life improvement that saves a line or so of code while making the role of the variable clearer.

Below is what you would write before the change: