Extension functions in kotlin

Kotlin language recently gained some traction owing to Google promoting it as a primary language for writing android apps. Kotlin has already been for a while in production owing to it’s creator JetBrains incorporating it in own tools, such as Intellij IDEA and so forth.

One, amongst many other neat features, is extension functions. In depth documentation can be found on official kotlin website.

About extension functions

In short – extension functions provide us useful tool to extend any existing class, no matter if it’s part of JDK, some 3rd party library or even own, custom ones.

Example, taken from this project, is the following one:

fun Random.betweenInclusive(lower: Int, upper: Int) = this.nextInt(upper - lower) + lower

Here we extend java.util.Random class from JDK, with betweenInclusive(lower: Int, upper: Int) extension method. This method helps us generate random integer between two numbers, lower and upper bounds, inclusive. Project contains couple of useful extension functions, implemented in rs/dodalovic/extension_functions/Students.kt kotlin file. Other examples are extending List<Student> with additional capabilities, taking advantage of functional programming applied on collections. Continue reading

Kotlin powered Spring Boot app consuming NBA Rest API

Ladies and gents, once again I’m sharing some sample app, this time we are building sample Spring Boot app implemented in Kotlin, talking to http://data.nba.net/ API to help us get some interesting, NBA related data. In this case we’re just listing NBA teams, but you extend this sample even further.

Creating project skeleton

The easiest way to create project skeleton is to navigate directly to Spring Boot Initializer website and download pre-configured project. In case you like kotlin – you can choose it from drop down with supported languages. If you’re using Intellij or Spring Tools Suite, you can achieve the same from within your IDE.

Application entry point

KotlinNbaApplicaiton.kt is our application entry point, it’s just a standard kotlin class containing main method and being annotated with @SpringBootApplication.

package rs.dodalovic.nba

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class KotlinNbaApplication

fun main(args: Array<String>) {
    SpringApplication.run(KotlinNbaApplication::class.java, *args)
}

Handling request with TeamController

Continue reading

Sending mail via gmail using Kotlin and commons-mail library

Continuing series of blog posts related to kotlin, today we’ll together make a sample application showing us how we could automate email sending – using kotlin. Example is quite simple, and surely – you can enhance it with own features. Application mostly demonstrates compact kotlin syntax, as well as full compatibility with Java or 3rd party libraries (in this case commons-mail library).

Let’s first take a look at our script:

package mail

import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.HtmlEmail
import java.net.URL

fun main(args: Array<String>) {
    val senderEmail = args[0]
    val password = args[1]
    val toMail = args[2]

    val email = HtmlEmail()
    email.hostName = "smtp.googlemail.com"
    email.setSmtpPort(465)
    email.setAuthenticator(DefaultAuthenticator(senderEmail, password))
    email.isSSLOnConnect = true
    email.setFrom(senderEmail)
    email.addTo(toMail)
    email.subject = "Test email with inline image sent using Kotlin"
    val kotlinLogoURL = URL("https://kotlinlang.org/assets/images/twitter-card/kotlin_800x320.png")
    val cid = email.embed(kotlinLogoURL, "Kotlin logo")
    email.setHtmlMsg("<html><h1>Kotlin logo</h1><img src=\"cid:$cid\"></html>")
    email.send()
}

Continue reading

Factory method pattern in Kotlin

Ladies & Gents, Kotlin language can come quite handy write concise and expressive code, without too much boilerplate, while keeping all advantages of being JVM citizen. Let’s quickly peek into example of creating Factory method creational design pattern implementation.

package patterns

interface Gadget {
    fun play()
    fun getInfo()
}

enum class Purpose {
    FUN, WORK
}

class GadgetFactory {
    companion object {
        fun createGadget(purpose: Purpose): Gadget = when (purpose) {
            Purpose.FUN -> object : Gadget {
                private val model = "XBox One S | year: 2016"
                override fun getInfo() {
                    println(model)
                }

                override fun play() {
                    println("I'm having great fun playing $model")
                }
            }
            Purpose.WORK -> object : Gadget {
                private val model = "Macbook Pro 2015 | year: 2015"
                override fun getInfo() = println(model)
                override fun play() {
                    println("I'm working hard using my $model")
                }
            }
        }
    }
}

val purpose: String = args[0]
val gadget = GadgetFactory.createGadget(when (purpose) {
    "FUN" -> Purpose.FUN
    "WORK" -> Purpose.WORK
    else -> throw IllegalArgumentException("No gadget for such purpose :(")
})

println("\n**** GADGET INFO ****\n")
gadget.getInfo()

println("\n**** PLAYING GADGET ****\n")
gadget.play()

Example demonstrates simple case where user enters which kind of Gadget she/he wants via command line argument, and based on value provided, he gets back some kind of Gadget dynamically instantiated. Continue reading

Strategy pattern example with Kotlin scripts

I thought it would be nice to use advantages of kotlin language to showcase strategy pattern implementation. In order to get the example running – we need to install kotlin binaries (installation). I’m running simple kotlin script in this example.

Having scripting support it makes it very easy to fire up some process with full kotlin language capabilities. You could use it to do some kind of administrative tasks in your business environment.  Continue reading

Microservices with Spring Boot, Netflix Zuul, Kotlin, Docker and MongoDB

Recently I’ve started playing with Kotlin programming language, and wanted to give it a try.

Kotlin gives us possibility to write quite concise code, such as:

@RestController
class UsersController(val userRepo: UserRepository) {

    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/users/{userId}")
    fun getUser(@PathVariable userId: String): UserDTO {
        return userRepo.findOne(userId).toUserDTO()
    }
}

You can find and download source code from GitHub. Readme file there explains how to start & use services. docker-compose comes quite handy to start / shutdown all the services with simple commands and orchestrate them via docker-compose yaml configuration file.

I’ve built sample, small microservice, composed of some kind of simple api-gateway or proxy server, implemented using Spring Boot and Netflix Zuul library for proxying requests to downstream servers.

Continue reading

Listing system / spring environment properties

Ladies & Gents, I prototyped just a small app that could help you print out some basic environment related information by exposing a few Rest controller endpoints.

Running the app

The easiest way is to run the app using Spring boot maven plugin

$ mvn spring-boot:run \
  -Drun.jvmArguments="\
    -Dfoo=foo \
    -Dbar=bar \
    -Dbaz=baz \
    -Dserver.port=8080 \
    -agentlib:jdwp=transport=dt_socket,server=y,address=1044,suspend=n"

Here, we specify some Java properties that will be used by the application:

  • foo, bar, baz custom properties
  • server.port – which is the way to instruct Spring Boot which port to use
  • we also specify to start with remote debug capabilities (if we’d like to do some remote debugging with our IDE)

Rest controller exposing various system / spring properties

package rs.dodalovic.envprops;

import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.val;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@AllArgsConstructor
public class EnvPropertiesController {
    private final Environment environment;

    @GetMapping("/sys/props")
    public Map<String, Object> getSysProperties() {
        val builder = ImmutableMap.builder();
        System.getProperties().stringPropertyNames().forEach(name -> {
            builder.put(name, environment.getProperty(name));
        });
        val systemProperties = builder.build();
        return ImmutableMap.of(
                "size", systemProperties.size(),
                "values", systemProperties
        );
    }

    @GetMapping("/sys/props/custom")
    public Map<String, Object> getCustomEnvProperties() {
        val builder = ImmutableMap.builder();
        builder.put("properties.key1", environment.getProperty("properties.key1"));
        builder.put("properties.key2", environment.getProperty("properties.key2"));

        builder.put("foo", environment.getProperty("foo"));
        builder.put("bar", environment.getProperty("bar"));
        builder.put("baz", environment.getProperty("baz"));

        val customProperties = builder.build();

        return ImmutableMap.of(
                "size", customProperties.size(),
                "values", customProperties
        );
    }

    @GetMapping("/sys/env")
    public Map<String, Object> get() {
        val env = System.getenv();
        return ImmutableMap.of(
                "size", env.size(),
                "values", env
        );
    }
}

Highlighted are lines used to get insights from running application environment. We are injecting Environment implementation which gives us access to environment properties, and application profiles.

application.properties

properties.key1=properties.val1
properties.key2=properties.val2

In the application.properties (main Spring Boot configuration file) we define two custom Spring environment properties: properties.key1 and properties.key2.

Listing system properties

$ curl -s 'http://localhost:8080/sys/props' | jq .

Response:

 {
   "size": 63,
   "values": {
     "java.runtime.name": "Java(TM) SE Runtime Environment",
     "sun.boot.library.path": "/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib",
     "java.vm.version": "25.121-b13"
     // ...
 }
}

Listing system environment

$ curl -s 'http://localhost:8080/sys/env' | jq .

Response:

{
  "size": 46,
  "values": {
    "M2": "/usr/local/Cellar/maven/3.5.0/libexec/bin",
    "GREP_COLOR": "1;33",
    "JENV_FORCEJDKHOME": "true"
    // ...
  }
}

 Listing custom spring properties

$ curl -s 'http://localhost:8080/sys/props/custom' | jq .

Response:

{
  "size": 5,
  "values": {
    "properties.key1": "properties.val1",
    "properties.key2": "properties.val2",
    "foo": "foo",
    "bar": "bar",
    "baz": "baz"
  }
}

Here we see merged collection of environment properties we either passed via command line or defined in application.properties.

You can checkout source code from GitHub

Hope you’ll find this useful. If so – don’t forget to subscribe to get notified of upcoming posts.