Skip to content
Hexagon is a microservices toolkit written in Kotlin. Its purpose is to ease the building of services (Web applications, APIs or queue consumers) that run inside a cloud platform
Branch: master
Clone or download
jaguililla Documentation (#185)
* Update documentation

* Set next version

* Improve site

* Clean web worker

* Update documentation

* Improve Benchmark

* Update documentation

* Update documentation

* Improve documentation footer

* Improve documentation navbar

* Set next version

* Clean site

* Clean site

* Improve site generation

* Improve pages and styles

* Add issue template metadata

* Add Google Analytics

* Fix site host

* Improve HTML structure

* Add page edition, Disqus comments and page header

* Update architecture diagram

* Refactor CSS styles

* Improve site documentation

* Upgrade Gradle

* Update version

* Ass issue templates

* Documentation page change style

* Set next version

* Fix typo

* Update Gradle wrapper

* Improve core utilities

* Port site to Bootstrap 4

* Improve core utilities

* Improve server request usage

* Improve server request usage

* Improve server request usage

* Improve server request usage

* Add dependency injection prototype

* Set next version

* Update issue templates to latest Github standard

* Refactor dependency injection

* Improve benchmark

* Improve DI coverage

* Refactor code

* Set next version

* Add Graal support (WIP)

* Improve documentation styles

* Make site generation simpler

* Improve site

* Improve site

* Improve site

* Improve site

* Site style changes

* Fix warning

* Update documentation

* Update documentation

* Add Graal benchmark (WIP)

* Small improvements

* Add new settings source

* Update quick start example

* Improve request interface

* Upgrade Gradle

* Fix Quick Start sample

* Refactor HTTP request, response and session

* Add multipart support

* Comply with Kotlin Coding Standard

* Chores

* Update Gradle

* Update Kotlin version

* Improve documentation

* Improve map helpers

* Change HTTP server use interface

* Change HTTP server usage

* Ease HTTP server usage

* Ease HTTP server usage

* Ease HTTP server usage

* Set next release version number

* Fix build problem

* Fix build problem

* Upgrade Jacoco version

* Move to package directories

* Move to package directories

* Set new release version

* Set new release version

* Set new release version

* Move to package directories

* Move to package directories

* Move to package directories

* Move to package directories

* Move to package directories

* Update dependencies' versions

* Move to package directories

* Move to package directories

* Chores

* Try Sonarqube

* Improve documentation

* Do not force test execution

* Ignore Sonarqube artifacts

* Move Sonarqube support from Travis to Gradle

* Add Sonarqube support

* Add Sonarqube token encrypted

* Update Benchmark build Docker image

* Support Sonarqube

* Small fixes

* Fix documentation link

* Fix documentation links

* Improve documentation

* Improve documentation

* Refactor HTTP server port

* Refactor HTTP server port

* Improve the starter code

* Clean tests

* Clean documentation

* Fix Dokka samples

* Improve samples

* Improve starter code

* Improve documentation

* Improve documentation

* Improve build scripts

* Use new Gradle task definition syntax

* Upgrade dependencies

* Use new Gradle task definition syntax

* Update documentation

* Use new Gradle task definition syntax

* Move build logic to Kotlin scripts

* Use widely accepted Docker Compose file

* Use widely accepted Dockerfile

* Optimize build

* Refactor benchmark

* Replace WireMock by HTTP server

* Rename readme file to adopt widely used convention

* Rename readmes

* Improve documentation

* Add test coverage

* Improve tests

* Improve tests

* Add tests

* Improve tests

* Reformat

* Refactor

* Improve documentation

* Next release version

* Improve tests

* Fix tests

* Improve examples and documentation

* Delete unused import

* Formatting

* Use fixed versions

* Remove unused test

* Allow any type in response headers

* Allow `after` filters to execute after halt

* Improve examples

* Fix documentation

* Clean test

* Clean test

* Update site

* Fix examples

* Add files example

* Fix assets serve and test file upload

* Refactor remaining unsorted tests

* Add Todo test and example

* Upgrade Gradle version

* Improve task dependencies

* Fix site style

* Change Gradle deprecated 'compile' scope

* Change Gradle deprecated 'compile' scope

* Implement Todo test

* Chores

* Add test

* Fix invalid response status when filters are used

* Modularize build scripts

* Improve build scripts

* Improve site

* Update Gradle

* Next release version

* Update documentation

* Update documentation

* Minor changes

* Make readme simpler

* Simplify documentation

* Upgrade Kotlin version

* Improve Gradle build scripts

* Improve documentation

* Improve documentation

* Upgrade versions

* Add MkDocs support

* Rename "site" Gradle helper

* Improve GitHub readme and add a pending task

* Document MkDocs usage (still a draft)

* Add MkDocs site deployment

* Style adjustments

* Fix content

* Add missing site information

* Adjust Material theme

* Add MkDocs extensions

* Fix footer

* Update documentation

* Improve documentation

* Delete JBake site generation

* Update documentation

* Test Docker Compose usage

* Upgrade dependencies

* Improve site

* Fix build

* Improve documentation

* Upgrade versions

* Improve documentation

* Fix readme links

* New release

* Update documentation

* Improve JMH helper build script

* Improve documentation

* New release version

* New release version

* Fix SonarQube warning

* Document problem with RabbitMQ container

* Add JavaScript output directory parameter

* Add build scripts documentation

* Update Developer Guide

* Improve documentation

* Improve documentation

* Add "help" page

* Add logging documentation
Latest commit 90cb6dd May 8, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Change HTTP server usage (#157) Feb 10, 2019
buildSrc Update documentation (#181) Apr 27, 2019
gradle Documentation and build scripts (#184) Apr 30, 2019
hexagon_benchmark Update documentation (#181) Apr 27, 2019
hexagon_core Documentation (#185) May 8, 2019
hexagon_scheduler Improve site (#175) Mar 24, 2019
hexagon_site Documentation (#185) May 8, 2019
hexagon_starters Improve site (#175) Mar 24, 2019
hexagon_web Documentation (#185) May 8, 2019
http_server_jetty Improve site (#175) Mar 24, 2019
http_server_servlet Improve site (#175) Mar 24, 2019
messaging_rabbitmq Improve site (#175) Mar 24, 2019
port_http_client Improve site (#175) Mar 24, 2019
port_http_server Documentation (#185) May 8, 2019
port_messaging Improve site (#175) Mar 24, 2019
port_store Improve site (#175) Mar 24, 2019
port_templates Improve site (#175) Mar 24, 2019
store_mongodb Improve site (#175) Mar 24, 2019
templates_pebble Improve site (#175) Mar 24, 2019
.editorconfig Fix merge error (#105) Nov 22, 2017
.gitignore Update documentation (#177) Apr 23, 2019
.travis.yml Documentation and build scripts (#184) Apr 30, 2019
README.md Update documentation (#182) Apr 27, 2019
build.gradle Update documentation (#181) Apr 27, 2019
code_of_conduct.md Documentation update and clean up Nov 13, 2018
contributing.md Documentation and build scripts (#184) Apr 30, 2019
docker-compose.yml Documentation and build scripts (#184) Apr 30, 2019
gradle.properties
gradlew Improve site (#175) Mar 24, 2019
gradlew.bat Improve site (#175) Mar 24, 2019
license.md Site updates (#112) Nov 27, 2017
settings.gradle Documentation (#185) May 8, 2019

README.md

Hexagon
Hexagon

The atoms of your platform

Travis CI Codecov Codebeat Bintray

Home Site | Quick Start | Developer Guide


What is Hexagon

Hexagon is a microservices toolkit (not a framework) written in Kotlin. Its purpose is to ease the building of services (Web applications, APIs or queue consumers) that run inside a cloud platform.

It is meant to provide abstraction from underlying technologies (data storage, HTTP server engines, etc.) to be able to change them with minimum impact. It is designed to fit in applications that conforms to the Hexagonal Architecture (also called Clean Architecture or Ports and Adapters Architecture).

The goals of the project are:

  1. Be simple to use: make it easy to develop user services (HTTP or message consumers) quickly. It is focused on making the usual tasks easy.
  2. Make it easy to hack: allow the user to add extensions or change the toolkit itself. The code is meant to be simple for the users to understand it.

Which are NOT project goals:

  1. To be the fastest framework. Write the code fast and optimize only the critical parts. It is not slow anyway.
  2. Support all available technologies and tools: the spirit is to define simple interfaces for the most common features , so users can implement integrations with different tools easily.
  3. To be usable from Java. Hexagon is Kotlin first.

Hexagon Structure

There are three kind of client libraries:

  • The ones that provide a single functionality that does not depend on different implementations.
  • Modules that define a "Port": An interface to a feature that may have different implementations.
  • Adapter modules, which are Port implementations for a given tool.

Ports are independent from each other.

Hexagon Core module provides convenience utilities. The main features it has are:

Simple HTTP service

You can clone a starter project (Gradle Starter or Maven Starter). Or you can create a project from scratch following these steps:

  1. Configure Kotlin in Gradle or Maven.
  2. Setup the JCenter repository (follow the link and click on the Set me up! button).
  3. Add the dependency:
  • In Gradle. Import it inside build.gradle:

    compile ("com.hexagonkt:http_server_jetty:$hexagonVersion")
  • In Maven. Declare the dependency in pom.xml:

    <dependency>
      <groupId>com.hexagonkt</groupId>
      <artifactId>http_server_jetty</artifactId>
      <version>$hexagonVersion</version>
    </dependency>
  1. Write the code in the src/main/kotlin/Hello.kt file:
// hello
import com.hexagonkt.http.httpDate
import com.hexagonkt.http.server.Server
import com.hexagonkt.http.server.ServerPort
import com.hexagonkt.http.server.jetty.JettyServletAdapter
import com.hexagonkt.injection.InjectionManager.bindObject

/**
 * Service server. It is created lazily to allow ServerPort injection (set up in main).
 */
val server: Server by lazy {
    Server {
        before {
            response.setHeader("Date", httpDate())
        }

        get("/hello/{name}") { ok("Hello, ${pathParameters["name"]}!", "text/plain") }
    }
}

/**
 * Start the service from the command line.
 */
fun main() {
    bindObject<ServerPort>(JettyServletAdapter()) // Bind Jetty server to HTTP Server Port
    server.start()
}
// hello
  1. Run the service and view the results at: http://localhost:2010/hello/world

You can check the Developer Guide for more details. Or you can clone the Gradle Starter or Maven Starter for a minimal fully working example (including tests).

Books Example

A simple CRUD example showing how to manage book resources. Here you can check the full test.

// books
data class Book(val author: String, val title: String)

private val books: MutableMap<Int, Book> = linkedMapOf(
    100 to Book("Miguel de Cervantes", "Don Quixote"),
    101 to Book("William Shakespeare", "Hamlet"),
    102 to Book("Homer", "The Odyssey")
)

val server: Server by lazy {
    Server(adapter) {
        post("/books") {
            // Require fails if parameter does not exists
            val author = parameters.require("author").first()
            val title = parameters.require("title").first()
            val id = (books.keys.max() ?: 0) + 1
            books += id to Book(author, title)
            send(201, id)
        }

        get("/books/{id}") {
            // Path parameters *must* exist an error is thrown if they are not present
            val bookId = pathParameters["id"].toInt()
            val book = books[bookId]
            if (book != null)
                // ok() is a shortcut to send(200)
                ok("Title: ${book.title}, Author: ${book.author}")
            else
                send(404, "Book not found")
        }

        put("/books/{id}") {
            val bookId = pathParameters["id"].toInt()
            val book = books[bookId]
            if (book != null) {
                books += bookId to book.copy(
                    author = parameters["author"]?.first() ?: book.author,
                    title = parameters["title"]?.first() ?: book.title
                )

                ok("Book with id '$bookId' updated")
            }
            else {
                send(404, "Book not found")
            }
        }

        delete("/books/{id}") {
            val bookId = pathParameters["id"].toInt()
            val book = books[bookId]
            books -= bookId
            if (book != null)
                ok("Book with id '$bookId' deleted")
            else
                send(404, "Book not found")
        }

        // Matches path's requests with *any* HTTP method as a fallback (return 404 instead 405)
        any("/books/{id}") { send(405) }

        get("/books") { ok(books.keys.joinToString(" ", transform = Int::toString)) }
    }
}
// books

Session Example

Example showing how to use sessions. Here you can check the full test.

// session
val server: Server by lazy {
    Server(adapter) {
        path("/session") {
            get("/id") { ok(session.id ?: "null") }
            get("/access") { ok(session.lastAccessedTime?.toString() ?: "null") }
            get("/new") { ok(session.isNew()) }

            path("/inactive") {
                get { ok(session.maxInactiveInterval ?: "null") }
                put("/{time}") { session.maxInactiveInterval = pathParameters["time"].toInt() }
            }

            get("/creation") { ok(session.creationTime ?: "null") }
            post("/invalidate") { session.invalidate() }

            path("/{key}") {
                put("/{value}") { session.set(pathParameters["key"], pathParameters["value"]) }
                get { ok(session.get(pathParameters["key"]).toString()) }
                delete { session.remove(pathParameters["key"]) }
            }

            get {
                val attributes = session.attributes
                val attributeTexts = attributes.entries.map { it.key + " : " + it.value }

                response.setHeader("attributes", attributeTexts.joinToString(", "))
                response.setHeader("attribute values", attributes.values.joinToString(", "))
                response.setHeader("attribute names", attributes.keys.joinToString(", "))

                response.setHeader("creation", session.creationTime.toString())
                response.setHeader("id", session.id ?: "")
                response.setHeader("last access", session.lastAccessedTime.toString())

                response.status = 200
            }
        }
    }
}
// session

Cookies Example

Demo server to show the use of cookies. Here you can check the full test.

// cookies
val server: Server by lazy {
    Server(adapter) {
        post("/assertNoCookies") {
            if (!request.cookies.isEmpty())
                halt(500)
        }

        post("/addCookie") {
            val name = parameters["cookieName"]?.first()
            val value = parameters["cookieValue"]?.first()
            response.addCookie(HttpCookie(name, value))
        }

        post("/assertHasCookie") {
            val cookieName = parameters.require("cookieName").first()
            val cookieValue = request.cookies[cookieName]?.value
            if (parameters["cookieValue"]?.first() != cookieValue)
                halt(500)
        }

        post("/removeCookie") {
            response.removeCookie(parameters.require("cookieName").first())
        }
    }
}
// cookies

Error Handling Example

Code to show how to handle callback exceptions and HTTP error codes. Here you can check the full test.

// errors
class CustomException : IllegalArgumentException()

val server: Server by lazy {
    Server(adapter) {
        error(UnsupportedOperationException::class) {
            response.setHeader("error", it.message ?: it.javaClass.name)
            send(599, "Unsupported")
        }

        error(IllegalArgumentException::class) {
            response.setHeader("runtimeError", it.message ?: it.javaClass.name)
            send(598, "Runtime")
        }

        // Catching `Exception` handles any unhandled exception before (it has to be the last)
        error(Exception::class) { send(500, "Root handler") }

        // It is possible to execute a handler upon a given status code before returning
        error(588) { send(578, "588 -> 578") }

        get("/exception") { throw UnsupportedOperationException("error message") }
        get("/baseException") { throw CustomException() }
        get("/unhandledException") { error("error message") }

        get("/halt") { halt("halted") }
        get("/588") { halt(588) }
    }
}
// errors

Filters Example

This example shows how to add filters before and after route execution. Here you can check the full test.

// filters
private val users: Map<String, String> = mapOf(
    "Turing" to "London",
    "Dijkstra" to "Rotterdam"
)

private val server: Server by lazy {
    Server(adapter) {
        before { attributes["start"] = nanoTime() }

        before("/protected/*") {
            val authorization = request.headers["Authorization"] ?: halt(401, "Unauthorized")
            val credentials = authorization.first().removePrefix("Basic ")
            val userPassword = String(Base64.getDecoder().decode(credentials)).split(":")

            // Parameters set in call attributes are accessible in other filters and routes
            attributes["username"] = userPassword[0]
            attributes["password"] = userPassword[1]
        }

        // All matching filters are run in order unless call is halted
        before("/protected/*") {
            if(users[attributes["username"]] != attributes["password"])
                halt(403, "Forbidden")
        }

        get("/protected/hi") { ok("Hello ${attributes["username"]}!") }

        // After filters are ran even if request was halted before
        after { response.setHeader("time", nanoTime() - attributes["start"] as Long) }
    }
}
// filters

Files Example

The following code shows how to serve resources and receive files. Here you can check the full test.

// files
private val server: Server by lazy {
    Server(adapter) {
        assets("assets", "/html/*") // Serves `assets` resources on `/html/*`
        assets("public") // Serves `public` resources folder on `/*`
        post("/multipart") { ok(request.parts.keys.joinToString(":")) }
        post("/file") {
            val part = request.parts.values.first()
            val content = part.inputStream.reader().readText()
            ok(content)
        }
    }
}
// files

Status

DISCLAIMER: The project is not yet production ready. Use it at your own risk. There are some modules not finished yet (e.g: storage and HTTP client).

It is used in personal not released projects to develop APIs and Web applications.

Performance is not the primary goal, but it is taken seriously. You can check performance numbers in the TechEmpower Web Framework Benchmarks. You can also run the stress tests, to do so, read the Benchmark readme

Tests, of course, are taken into account. This is the coverage grid:

CoverageGrid

The code quality is checked by Codebeat:

codebeat badge

Contribute

If you like this project and want to support it, the easiest way is to give it a star ✌️.

If you feel like you can do more. You can contribute to the project in different ways:

To know what issues are currently open and be aware of the next features you can check the Project Board at Github.

You can ask any question, suggestion or complaint at the project's Slack channel. And be up to date of project's news following @hexagon_kt in Twitter.

Thanks to all project's contributors!

License

The project is licensed under the MIT License. This license lets you use the source for free or commercial purposes as long as you provide attribution and don’t hold any project member liable.

You can’t perform that action at this time.