Monday, September 26, 2016

Kotlin and Continuous Integration with TeamCity

We’re going to see how to set up TeamCity to build our Kotlin project. For more information and basics of TeamCity please check the Documentation page which contains information about installation, basic configuration, etc.
Kotlin works with different build tools, so if we’re using a standard tool such as Ant, Maven or Gradle, the process for setting up a Kotlin project is no different to any other language or library that integrates with these tools. Where there are some minor requirements and differences is when using JBS, which is the internal build system that IntelliJ IDEA uses, which is also supported on TeamCity.

Using a standard build tool

If using Ant, Maven or Gradle, the setup process is straightforward. All that is needed is to define the Build Step. In our case, if using Gradle we’d simply define the required parameters such as the Step Name and Gradle tasks that need executing for the Runner Type.

Gradle Build Step
Since all the dependencies required for Kotlin are defined in the Gradle file, nothing else needs to be configured specifically for Kotlin to run correctly.
If using Ant or Maven, the same configuration applies. The only difference being that the Runner Type would be Ant or Maven respectively.

Using IntelliJ IDEA Build System

If using IntelliJ IDEA build system with TeamCity, we need to make sure that the version of Kotlin being used by IntelliJ IDEA is the same as that that TeamCity runs. This would mean that we need to download the specific version of the Kotlin plugin and install it on TeamCity.
Fortunately, there is a meta-runner already available that takes care of most of the manual work. If not familiar with the concept of TeamCity meta-runners, check the documentation. They are very easy and powerful way to introduce custom Runners without the need to write plugins

Download and install the meta-runner.

The meta-runner for Kotlin is available on GitHub. If using TeamCity 9 or above, we can now simply import that meta-runner from the TeamCity user interface

Meta-runner
If using a previous version, refer to the documentation on how to add meta-runners.

Setup Kotlin Compiler Fetching Step

Basically this step is limited to defining the Step Name and the version of Kotlin we need. Tags can be used.

Setup Kotlin Compiler 
The runner will set the value for the property system.path.macro.KOTLIN.BUNDLED to the correct one based on the path settings from the IntelliJ IDEA project. However this value needs to be defined in TeamCity (and can be set to any value). Therefore we need to define it as a system variable.

Setup Kotlin Compilation Step

The final step is to define the actual compilation of the project, which uses the standard IntelliJ IDEA Runner Type

IntelliJ IDEA Runner
With that, our project should now build and produce the corresponding artifacts.

Other CI Server

If using a Continuous Integration tool different to TeamCity, as long as it supports any of the build tools, or calling command line tools, compiling Kotlin and automating things as part of a CI process should be possible.

Kotlin Android Extensions

This tutorial describes how to use Kotlin Android Extensions to improve support for Android development. 

In this tutorial we’ll walk through the steps required to use the Kotlin Android Extensions plugin, enhancing the development experience with Android.

Background

Every Android developer knows well the findViewById() function. It is, without a doubt, a source of potential bugs and nasty code which is hard to read and support. While there are several libraries available that provide solutions to this problem, being libraries dependent on runtime, they require annotating fields for each View.
The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code or shipping any additional runtime.
In essence, this would allow for the following code:
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView.setText("Hello, world!")
        // Instead of findView(R.id.textView) as TextView
    }
}
textView is an extension property for Activity, and it has the same type as declared inactivity_main.xml.

Using Kotlin Android Extensions

Configuring the dependency

In this tutorial we’re going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see Using Gradle.
Android Extensions is a part of the Kotlin IDEA plugin. You do not need to install additional plugins.
All you need is to enable the Android Extensions Gradle plugin in your project-local build.gradle file:
apply plugin: 'kotlin-android-extensions'

Importing synthetic properties

It is convenient to import all widget properties for a specific layout in one go:
import kotlinx.android.synthetic.main.<layout>.*
Thus if the layout filename is activity_main.xml, we’d importkotlinx.android.synthetic.main.activity_main.*.
If we want to call the synthetic properties on View (useful in adapter classes), we should also importkotlinx.android.synthetic.main.activity_main.view.*.
Once we do that, we can then invoke the corresponding extensions, which are properties named after the views in the XML file. For example, for this view:
    <TextView
            android:id="@+id/hello"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Hello World, MyActivity"
            />
There will be property named hello:
activity.hello.setText("Hi!")

Android Flavors

Android Extensions plugin supports Android flavors. Suppose you have a flavor named free in yourbuild.gradle file:
android {
    productFlavors {
        free {
            versionName "1.0-free"
        }
    }
}
So you can import all synthetic properties for the free/res/layout/activity_free.xml layout by adding this import:
import kotlinx.android.synthetic.free.activity_free.*

Under the hood

Kotlin Android Extensions is a plugin for the Kotlin compiler, and it does two things:
  1. Adds a hidden caching function and a field inside each Kotlin Activity. The method is pretty small so it doesn’t increase the size of APK much.
  2. Replaces each synthetic property call with a function call.
How this works is that when invoking a synthetic property, where the receiver is a Kotlin Activity/Fragment class that is in module sources, the caching function is invoked. For instance, given
class MyActivity: Activity()
fun MyActivity.a() { 
    this.textView.setText(“”) 
}
a hidden caching function is generated inside MyActivity, so we can use the caching mechanism.
However in the following case:
fun Activity.b() { 
    this.textView.setText(“”)     
}
We wouldn’t know if this function would be invoked on only Activities from our sources or on plain Java Activities also. As such, we don’t use caching there, even if MyActivity instance from the previous example is the receiver.

Getting started with Android and Kotlin

This tutorial walks us through creating a simple Kotlin application for Android using Android Studio. 

Creating a project

It’s extremely easy to start using Kotlin for Android development! In this tutorial we’ll follow the warming up process with Android Studio. If using Intellij IDEA with Android, the process is almost the same.
First let’s create a new project. We choose Start a new Android Studio project or File | New project. The following dialogs walk us through the process of new project creation. We need to name the project and choose which Android SDK version we have installed. Most options can be left with their default values, so we can press ‘Enter’ several times.
Name the project: Dialog 1
Choose the Android version:
Dialog 2
Choose creating an activity that will be generated for you:
Dialog 3
Name the activity:
Dialog 4
We’ve created a new project with one Java activity that was generated for us.
But now we’d like to add some code in Kotlin. The easiest way to start using Kotlin is to convert automatically Java activity into Kotlin one. Please note that anytime instead of looking through documentation for a new way to express an old pattern, you can write it in Java, then copy-paste Java code into Kotlin file, and Intellij (or Android Studio) will suggest to convert it.

Converting Java code to Kotlin

Open MainActivity.java file. Then invoke action Convert Java File to Kotlin File. You can do it by several ways. The easiest one is to invoke Find Action and start typing an action name (like in a screencast below). Alternatively we can call this option via the Code | Convert Java File to Kotlin File menu entry or by using the corresponding shortcut (we can find it at the menu entry).
Convert
After the conversion we should have an activity written in Kotlin.
Koltin-Activity

Configuring Kotlin in the project

When adding a new Kotlin file, IntelliJ IDEA (and Android Studio) automatically prompts us as to whether we’d like to configure the Kotlin runtime for the project. However, currently, converting existing Java file does not prompt this action. Therefore we have to invoke it manually (via Find Action):
Config-Kotlin
We are then prompted for the version of Kotlin. Choose the latest available from the list of installed versions.
Config-Kotlin-Details
After we configure Kotlin, build.gradle file for the application should be updated. Now we can see that apply plugin: ‘kotlin-android’ and the dependencies were added.
(For more details how to set up gradle for your project, please check Using Gradle)
The last thing to do is to sync the project. We can press ‘Sync Now’ in a prompt or invoke an action Sync Project with Gradle Files.
Sync-Project-With-Gradle

Making user interface changes

Now that the project has been set up, we can work with the layout using IntelliJ IDEA’s visual designer. There is nothing different in terms of layout when working with Kotlin, thus this is similar to regular Android Java development. While using layout designer in IntelliJ IDEA, note there are two tabs in the designer: Text andDesign. The latter shows how the layout looks, while the former allows fine tuning with XML editing.
Layout Editor

Building and publishing the Kotlin application for Android

Kotlin has a rather small runtime file size: the library is approximately 736KB (as of 1.0.4). This means Kotlin adds just a little to .apk file size.
We are now ready to build the application in debug mode (<Shift+F9>), run it on an emulator or device (<Shift+F10>), or build signed release of the application to upload it to Google Play or another application store.
We can make a release of the application and sign it similarly to what we do for an Android application written in Java.
Kotlin compiler produces byte-code, thus there really is no difference in terms of look and feel of Kotlin applications versus those written in Java.

What’s next?

Read about Kotlin Android Extensions plugin. If you want to learn different Kotlin features, try Kotlin Koans.

Creating a RESTful Web Service with Spring Boot

This tutorial walks us through the process of creating a simple REST controller with Spring Boot 

Kotlin works quite smoothly with Spring Boot and many of the steps found on the Spring Guides for creating a RESTful service can be followed verbatim for Kotlin. There are some minor differences however when it comes to defining the Gradle configuration and the project layout structure, as well as the initialization code.
In this tutorial we’ll walk through the steps required. For a more thorough explanation of Spring Boot and RESTful services, please see Building a RESTful Web Service.
Note that all classes in this tutorial are in the kotlin.demo package.

Defining the project and dependencies

In this tutorial we’re going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see Using Gradle.
The Gradle file is pretty much standard for Spring Boot. The only difference is the structure layout for source folders for Kotlin, and the required Kotlin dependencies
buildscript {
    ext.kotlin_version = '1.0.0' // Required for Kotlin integration
    ext.spring_boot_version = '1.3.0.RELEASE'
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'kotlin' // Required for Kotlin integration
apply plugin: 'spring-boot'
apply plugin: 'application'

jar {
    baseName = 'gs-rest-service'
    version = '0.1.0'
}

repositories {
    jcenter()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
    compile 'org.springframework.boot:spring-boot-starter-web'
    testCompile 'junit:junit'
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.9'
}

Creating a Greeting Data Class and Controller

The next step is to create Greeting Data class that has two properties: id and a content
data class Greeting(val id: Long, val content: String)
We now define the GreetingController which serves requests of the form /greeting?name={value} and returns a JSON object representing an instance of Greeting
@RestController
class GreetingController {

    val counter = AtomicLong()

    @RequestMapping("/greeting")
    fun greeting(@RequestParam(value = "name", defaultValue = "World") name: String): Greeting {
        return Greeting(counter.incrementAndGet(), "Hello, $name")
    }
}
As can be seen, this is again pretty much a one-to-one translation of Java to Kotlin, with nothing special required for Kotlin.

Creating the Application class

Finally we need to define an Application class. As Spring Boot looks for a public static main method, we need to define this in Kotlin using the @JvmStatic annotation. For this, we create a standard Application class and define a companion object inside where we can then create a function annotated with @JvmStatic
Note: JvmStatic is an annotation in Kotlin which is used for interoperability with Java, so that the resulting method is defined as static when called from Java.
The other change needed for Spring Boot is to mark the class as open. Spring boot @Configuration classes cannot be final. Classes in Kotlin are final by default without the open modifier.
@SpringBootApplication
open class Application {
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            SpringApplication.run(Application::class.java, *args)
        }
    }
}

Alternative Application class definition

In Java, the main() method of a Spring Boot application is conventionally defined within the annotated application class. This is because Java does not support top-level methods. In Kotlin, however, we do have top-level functions. Thus, we can make the Spring main entry point much simpler:
@SpringBootApplication
open class Application

fun main(args: Array<String>) {
 SpringApplication.run(Application::class.java, *args)
}
The only requirement for this variant to work is to declare in your build.gradle file to look for this main function. This is done through the mainClass property of the springBoot section:
springBoot {
    mainClass = 'my.package.YourMainClass'
}
In Kotlin, top-level functions are compiled into static members of an automatically-generated class. The name of this class is derived from the name of the source file. For instance, a top-level function in theApplication.kt file would be defined in a class named ApplicationKt. You may add the following lines to your build.gradle:
springBoot {
    mainClass = 'kotlin.demo.ApplicationKt'
}

Running the application

We can now use the any of the standard Gradle tasks for Spring Boot to run the application. As such, running
    gradle bootRun
the application is compiled, resources bundled and launched, allowing us to access is via the browser (default port is 8080)
Running App

Creating Web Applications with Http Servlets

This tutorial walks us through the process of creating a simple controller using HttpServlet to display Hello World. 

Java EE Http servlets can be used from Kotlin much like any other Java library or framework. We’ll see how to make a simple controller that returns “Hello, World!”.

Defining the project and dependencies

In this tutorial we’re going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see Using Gradle. The main dependency required for using HTTP servlets is the JavaEE API:
dependencies {
    compile group: 'javax', name: 'javaee-api', version: '7.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
We also need to use the war plugin that helps us generate the corresponding WAR artifacts for running/deploying
apply plugin: war
To see the full Gradle script check out the source of the project on GitHub.

Creating a Home Controller

Once we have the build script defined with the correct dependencies, we can now create a controller
@WebServlet(name = "Hello", value = "/hello")
class HomeController : HttpServlet() {
    override fun doGet(req: HttpServletRequest, res: HttpServletResponse) {
        res.writer.write("Hello, World!")
    }
}

Running the application

Using IntelliJ IDEA we can easily run and debug the application in any of the possible application servers defined such as Tomcat, Glassfish or WildFly. In this case we’re going to use Tomcat which has previouslybeen defined as an application server in IntelliJ IDEA
In order to run, we need the corresponding WAR(s) for deploying. We can generate these using the war task in Gradle which can easily be executed via the Gradle tool window in IntelliJ IDEA.
Gradle Tasks
Alternatively, we can build it using the command line:
gradle war
The next step is to create a Run Configuration in IntelliJ IDEA under Tomcat / Local which deploys the WAR and starts up Tomcat.
Run Config
Once we run the application (using this previous run configuration), and on successful deployment, we should be able to navigate to the browser with the correct url and see the response:
Browser Run

Mixing Java and Kotlin in one project

This tutorials walks us through the process of using Java and Kotlin in a single IntelliJ IDEA project. 

We’ll be using IntelliJ IDEA (Ultimate or Community edition). If using build tools, please see the corresponding entry under Build Tools. To understand how to start a new Kotlin project using IntelliJ IDEA, please see theGetting-Started tutorial.

Adding Java source code to an existing Kotlin project

To add a new Java class to a Kotlin project is very straightforward. All we need to do is create a new Java file (Ctrl+N/Cmd+N) in the correct folder/package.
New Java Class
We can now consume the Java Class from Kotlin or vice versa without any further actions. For instance, adding the following Java class:
public class Customer {

    private String name;

    public Customer(String s){
        name = s;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
allows us to call it from Kotlin like any other type in Kotlin.
    val customer = Customer("Phase")

    println(customer.getName())

Adding Kotlin source code to an existing Java project

Adding a Kotlin file to an existing Java project is pretty much the same process. The only difference here is that depending on how we do this, slightly different actions need to be taken:

Creating a new Kotlin file

To create a new Kotlin file we simply decide on the location in the project folder and create it.
New Kotlin File
If this is the first time we’re adding a Kotlin file, IntelliJ IDEA will prompt us to add the required Kotlin runtime.
Add Kotlin Runtime
As we’re working with a Java project, we’d most likely want to configure it as a Kotlin Java Module. The next step is to decide which modules to configure (if our project has more than one module) and whether we want to add the runtime library to the project or use those provided by the current Kotlin plugin.
Bundling Kotlin Runtime

Adding an existing Kotlin file

If instead of creating a new file, we want to add an existing Kotlin file to the project, IntelliJ IDEA won’t prompt us to configure the Kotlin runtime. We have to invoke this action manually. This can be done via theTools|Kotlin menu option
Kotlin Menu
which then prompts the same dialog and process as when we create a new Kotlin file.

Converting an existing Java file to Kotlin with J2K

The Kotlin plugin also bundles a Java to Kotlin compiler which is located under the Code menu in IntelliJ IDEA.
Convert Java to Kotlin Menu
Selecting an existing Java file, we can use this option to convert it automatically into Kotlin. While the converter is not full-proof, it does a pretty decent job of converting most boiler-plate code from Java to Kotlin. Some manual tweaking however is sometimes required.

Creating Kotlin/JavaScript library with the Command Line Compiler

This tutorial walks us through creating a Kotlin/JavaScript library using the command line compiler. 

Creating a Kotlin/JavaScript library

We will create a simple Kotlin/JavaScript library.
  1. Using our favorite editor, we create a new file called library.kt:
    package org.sample
       
    fun factorial(n: Int): Long = if (n == 0) 1 else n * factorial(n - 1)
       
    inline fun IntRange.forOdd(f: (Int) -> Unit) {
        this.forEach { if (it % 2 == 1) f(it) }
    }
  2. Compile the library using the JS compiler
    $ kotlinc-js -output sample-library.js -meta-info library.kt
    
    The -meta-info option indicates that an additional JS file with binary meta-information about compiled kotlin code will be created.
    If you want to see all available options run
    $ kotlinc-js -help
    
    After compilation we have two new files:
    sample-library.js
    sample-library.meta.js
    
  3. You can simply distribute two JS files, sample-library.js and sample-library.meta.js. The former file contains translated JavaScript code, the latter file contains some meta-information about Kotlin code, which is needed by compiler.
    Alternatively, you can append the content of sample-library.meta.js to the end of sample-library.js and distribute only the resulting file.
    Also you can create an archive, which can be distributed as a library:
    $ jar cf sample-library.jar *.js
    

Using a Kotlin/JavaScript library.

Create binom.kt:
import org.sample.factorial
  
fun binom(m: Int, n: Int): Long =
    if (m < n) factorial(n) / factorial(m) / factorial(n-m) else 1
    
fun odd_factorial(n: Int): Long {
    var result: Long = 1L
    (1..n).forOdd { result = result * it }
    return result
}
Compile with library:
   $ kotlinc-js -output binom.js -library-files sample-library.meta.js binom.kt
Both files sample-library.js and sample-library.meta.js should be present in the latter case, because translated JavaScript file contains meta-information about inlining, which is needed by compiler.
If you have an archive sample-library.jar, which contains sample-library.js and sample-library.meta.js, you can use the following command
   $ kotlinc-js -output binom.js -library-files sample-library.jar binom.kt