A Geospatial Messenger with Kotlin, Spring Boot and PostgreSQL

A Geospatial Messenger with Kotlin, Spring Boot and PostgreSQL

Sébastien Deleuze

Following my first Kotlin blog post, today I want introduce the new Spring Boot + Kotlin application I have developed for my upcoming Spring I/O 2016 conference talk “Developing Geospatial Web Services with Kotlin and Spring Boot”.

Dealing with native database functionalities

One of the goal of this application is to see how to take advantage of native database functionalities like we do in NoSQL world. Here we want to use Geospatial support provided by PostGIS, the spatial database extender for PostgreSQL. Native JSON support could also be a good use case.

This Geospatial Messenger sample application is available on GitHub in 2 flavors:

A Spring Data JPA + Hibernate Spatial variant would be interesting, so feel free to contribute it with a pull request ;-) Kotlin Query DSL support would be also nice but this is currently not supported (please comment on this issue if you are interested). In this blog post I will focus on the Exposed variant.

A tour of Geospatial Messenger code

Our domain model is described easily thanks to these 2 Kotlin data classes:

data class Message(
    var content  : String,
    var author   : String,
    var location : Point? = null,
    var id       : Int?   = null
)

data class User(
    var userName  : String,
    var firstName : String,
    var lastName  : String,
    var location  : Point? = null
)

Exposed allows us to describe the structure of our tables with a type-safe SQL API quite handy to use (autocomplete, refactoring and error prone):

    object Messages : Table() {
        val id       = integer("id").autoIncrement().primaryKey()
        val content  = text("content")
        val author   = reference("author", Users.userName)
        val location = point("location").nullable()
    }

    object Users : Table() {
        val userName  = text("user_name").primaryKey()
        val firstName = text("first_name")
        val lastName  = text("last_name")
        val location  = point("location").nullable()
    }

It is interesting to notice that Exposed does not support natively PostGIS functionalities like geometry types or geospatial requests. That’s where Kotlin extensions shine, and allow with a few lines of code to add such support without requiring to use extended classes:

fun Table.point(name: String, srid: Int = 4326): Column<Point>
  = registerColumn(name, PointColumnType())

infix fun ExpressionWithColumnType<*>.within(box: PGbox2d) : Op<Boolean>
  = WithinOp(this, box)

Our repository is also quite short and very flexible, since it allows you to write any kind of SQL request even with complex WHERE clause with a type-safe SQL API. Currently we need to use db.transaction{ } wrapper, I have created Exposed issue #25 to be able to use regular Spring transaction management with @Transactional annotation, feel free to add your +1 ;-)

Please notice that since we are using Spring Framework 4.3, we no longer need to specify an @Autowired annotation in such single-constructor class.

@Repository
open class UserRepository(val db: Database) {

    open fun createTable() = db.transaction {
        create(Users)
    }

    open fun create(user: User) = db.transaction {
        Users.insert( toRow(user) )
    }

    open fun updateLocation(u:String, l: Point) = db.transaction {
        location.srid = 4326
        Users.update({Users.userName eq u}) { it[Users.location] = l}
    }

    open fun findAll() = db.transaction {
        Users.selectAll().map { fromRow(it) }
    }

    open fun findByBoundingBox(box: PGbox2d) = db.transaction {
        Users.select { Users.location within box }.map { fromRow(it) }
    }

    open fun deleteAll() = db.transaction {
        Users.deleteAll()
    }

    fun toRow(u: User): Users.(UpdateBuilder<*>) -> Unit = {
        it[userName] = u.userName
        it[firstName] = u.firstName
        it[lastName] = u.lastName
        it[location] = u.location
    }

    fun fromRow(r: ResultRow) =
        User(r[Users.userName],
             r[Users.firstName],
             r[Users.lastName],
             r[Users.location])
}

Controllers are also very concise and use Spring Framework 4.3 upcoming @GetMapping / @PostMapping annotations which are just method-specific shortcuts for @RequestMapping annotations:

    @RestController
    @RequestMapping("/user")
    class UserController(val repo: UserRepository) {

        @PostMapping
        @ResponseStatus(CREATED)
        fun create(@RequestBody u: User) { repo.create(u) }

        @GetMapping
        fun list() = repo.findAll()

        @GetMapping("/bbox/{xMin},{yMin},{xMax},{yMax}")
        fun findByBoundingBox(@PathVariable xMin:Double,
                              @PathVariable yMin:Double,
                              @PathVariable xMax:Double,
                              @PathVariable yMax:Double)
                = repo.findByBoundingBox(
                            PGbox2d(Point(xMin, yMin), Point(xMax, yMax)))

        @PutMapping("/{userName}/location/{x},{y}")
        @ResponseStatus(NO_CONTENT)
        fun updateLocation(@PathVariable userName:String,
                           @PathVariable x: Double,
                           @PathVariable y: Double)
                = repo.updateLocation(userName, Point(x, y))
    }

The client side is a pure HTML + Javascript application developed with OpenLayers mapping library (see index.html and map.js for more details) that geolocalizes you and creates geolocalized messages sent/received to/from other users thanks to Server-Sent Events.

Screenshot

And last but not least, the REST API is fully tested and documented thanks to the awesome Spring REST docs project, see MessageControllerTests and index.adoc for more details.

Conclusion

The main impression I had developing this application is that it was fun, efficient, with a high level of flexibility and safety provided by the SQL API and Kotlin type system and null safety. The resulting Spring Boot application is a 18 MBytes self-contained executable jar with low memory consumption (the app can run with -Xmx32m!!!). Using Spring REST docs was also a pleasure, demonstrating again Kotlin nice Java interoperability.

The few pain points I have encountered (array annotation attributes, Java 8 Stream support, full callable reference support), are planned to be fixed in Kotlin 1.1. Exposed library is still young and need to mature, but from my point of view it is promising and shows how Kotlin could be used for building type-safe DSL API (this HTML type-safe builder is also a good example).

And keep in mind that officially supported Spring Data projects works well with Kotlin as shown in the spring-boot-kotlin-demo project in my previous blog post.

If you happen to be in Barcelona mid May (never a bad time to be in Barcelona anyway!), don’t miss the chance to join the Spring I/O conference. Also, the registration for SpringOne Platform (early August, Las Vegas) has opened recently, in case you want to benefit from early bird ticket pricing. The latter is also still open for talk proposals. So if you’re interested to give a talk about Spring or Pivotal-related technologies, feel free to submit!