A Spark DSL in idiomatic kotlin.

Overview

spark-kotlin

A Spark DSL in idiomatic kotlin.

Authors:

  • Per Wendel, @perwendel
  • Love Löfdahl, @lallemupp

Dependency:

Maven:

<dependency>
    <groupId>com.sparkjavagroupId>
    <artifactId>spark-kotlinartifactId>
    <version>1.0.0-alphaversion>
dependency>

Gradle:

compile "com.sparkjava:spark-kotlin:1.0.0-alpha"

Documentation

Routes

") splat() status() status(404) queryParams(" ") queryMap() queryMap(" ") attribute(" ") attribute(" ", " ") attributes() session() session(create = true) contentType() uri() protocol() scheme() host() port() pathInfo() servletPath() contextPath() userAgent() requestMethod() type() type(contentType = "application/json") redirect(location = "/to") redirect(location = "/to", statusCode = 302) // has all above and some more request response } get("/nothing") { status(404) "Oops, we couldn't find what you're looking for" } get("/saymy/:name") { params(":name") } get("/redirect") { redirect("/hello") } // Instance API val http = ignite() http.get("/hello") { "Hello Spark Kotlin" } http.get("/nothing") { status(404) "Oops, we couldn't find what you're looking for" } http.get("/saymy/:name") { params(":name") } http.get("/redirect") { redirect("/hello") }">
// Static API
get("/hello") {
    "Hello Spark Kotlin"
}

get("/doc") {
    // available (same in instance API)
    params()
    params("
        
         "
        )
    splat()
    status()
    status(404)
    queryParams("
        
         "
        )
    queryMap()
    queryMap("
        
         "
        )
    attribute("
        
         "
        )
    attribute("
        
         "
        , "
        
         "
        )
    attributes()
    session()
    session(create = true)
    contentType()
    uri()
    protocol()
    scheme()
    host()
    port()
    pathInfo()
    servletPath()
    contextPath()
    userAgent()
    requestMethod()
    type()
    type(contentType = "application/json")
    redirect(location = "/to")
    redirect(location = "/to", statusCode = 302)
    
    // has all above and some more
    request 
    response
}

get("/nothing") {
    status(404)
    "Oops, we couldn't find what you're looking for"
}

get("/saymy/:name") {
    params(":name")
}

get("/redirect") {
    redirect("/hello")
}

// Instance API
val http = ignite()

http.get("/hello") {
    "Hello Spark Kotlin"
}

http.get("/nothing") {
    status(404)
    "Oops, we couldn't find what you're looking for"
}

http.get("/saymy/:name") {
    params(":name")
}

http.get("/redirect") {
    redirect("/hello")
}

Initialization DSL

// Static API
config {
    port = 5500
    ipAddress = "0.0.0.0"
    threadPool {
        maxThreads = 10
        minThreads = 5
        idleTimeoutMillis = 1000
    }
    secure {
        keystore {
            file = "/etc/secure/keystore"
            password = "hardtocrack"
        }
        truststore {
            file = "/etc/secure/truststore"
            password = "otherdifficultpassword"
        }
        needsClientCert = false
    }
    staticFiles {
        location = "/public"
        expiryTime = 36000.seconds
        headers(
                "description" to "static content",
                "licence" to "free to use"
        )
        mimeTypes(
                "cxt" to "text/html"
        )
    }
}

// Instance API
val http = ignite {
    port = 5500
    ipAddress = "0.0.0.0"
    threadPool {
        maxThreads = 10
        minThreads = 5
        idleTimeoutMillis = 1000
    }
    secure {
        keystore {
            file = "/etc/secure/keystore"
            password = "hardtocrack"
        }
        truststore {
            file = "/etc/secure/truststore"
            password = "otherdifficultpassword"
        }
        needsClientCert = false
    }
    staticFiles {
        location = "/public"
        expiryTime = 36000.seconds
        headers(
                "description" to "static content",
                "licence" to "free to use"
        )
        mimeTypes(
                "cxt" to "text/html"
        )
    }
}

Redirect DSL

// Static API
redirect {
    any(
            "/from" to "/hello",
            "/hi" to "/hello"
    )
    get(
            "/source" to "/target"
    )
    post(
            "/gone" to "/new"
    )
}

// Instance API
http.redirect {
    any(
            "/from" to "/hello",
            "/hi" to "/hello"
    )
    get(
            "/source" to "/target"
    )
    post(
            "/gone" to "/new"
    )
}


WebSocket DSL (design ongoing)

// Static API
webSocket("/echo") {
    opened {
        println("[Opened] remote address = " + session.remoteAddress)
    }
    received {
        println("[Received] message = $message")
    }
    closed {
        println("[Closed] code = $code, reason = $reason, session = $session")
    }
    error {
        println("[Error] cause = " + cause)
    }
}

// Instance API
http.webSocket("/echo") {
    opened {
        println("[Opened] remote address = " + session.remoteAddress)
    }
    received {
        println("[Received] message = $message")
    }
    closed {
        println("[Closed] code = $code, reason = $reason, session = $session")
    }
    error {
        println("[Error] cause = " + cause)
    }
}

class WebSocketSession
    val remote
    var idleTimeout
    val isOpen
    val localAddress
    val protocolVersion
    val upgradeResponse
    val upgradeRequest
    val policy
    val isSecure
    val remoteAddress
    
    fun disconnect()
    fun suspend(): Suspension 
    fun close()
    fun close(closeStatus: CloseStatus?)
    fun close(statusCode: Int, reason: String?)
    fun raw(): Session
Comments
  • Sources JAR in Maven

    Sources JAR in Maven

    Source JAR in Maven doesn't include the Kotlin sources:

    # unzip -l spark-kotlin-1.0.0-alpha-sources.jar
    Archive:  spark-kotlin-1.0.0-alpha-sources.jar
      Length      Date    Time    Name
    ---------  ---------- -----   ----
           93  05-30-2017 23:37   META-INF/MANIFEST.MF
            0  05-30-2017 23:37   META-INF/
            0  05-30-2017 23:36   dummy/
            0  05-30-2017 23:37   META-INF/maven/
            0  05-30-2017 23:37   META-INF/maven/com.sparkjava/
            0  05-30-2017 23:37   META-INF/maven/com.sparkjava/spark-kotlin/
          920  05-30-2017 23:36   dummy/JavadocDummy.java
         8372  05-30-2017 23:36   META-INF/maven/com.sparkjava/spark-kotlin/pom.xml
          124  05-30-2017 23:37   META-INF/maven/com.sparkjava/spark-kotlin/pom.properties
    ---------                     -------
         9509                     9 files
    
    opened by 0x3333 3
  • Possible to group request handlers into controllers?

    Possible to group request handlers into controllers?

    Question/Feature request: I tend to write apps where the code is grouped by feature/package (opposed to group-by-layer) in order to achieve cleaner code, especially when it comes to larger codebases. I'm a newbie to Kotlin and haven't figured a way how to group routes into controllers using spark-kotlin, sparkjava supports this pattern. Is this possible, and if so how? In case it isn't, would it be possible to add support for it to spark-kotlin?

    opened by pehagg 2
  • return value in places that use http transformer

    return value in places that use http transformer

    Hey,

    This is a bit contradictory to https://github.com/perwendel/spark-kotlin/issues/7, however I was using a response transformer to generate JSON and noticed that the Kotlin wrapper didn't pass through the return values of the routes.

    Cheers, Andreas

    opened by athurn 2
  • Too many arguments for public fun ignite()

    Too many arguments for public fun ignite()

    Hi! I try to run the basic example given on the project main page:

    val http = ignite {
        port = 8080
        ipAddress = "0.0.0.0"
        threadPool {
            maxThreads = 10
            minThreads = 5
            idleTimeoutMillis = 1000
        }
    }
    
    http.get("/") {
        "Hello Spark Kotlin!"
    }
    

    but it gives already errors without doing a compile/build step, saying "Too many arguments for public fun ignite()". I would appreciate a working example or some hint, what goes wrong.

    I added import spark.kotlin.* to the import section of my main.kt file and implementation "com.sparkjava:spark-kotlin:1.0.0-alpha" to my modules build.gradle dependencies section. And yes I triggered a gradle sync afterwards.

    opened by matths 1
  • Unable to serve static files

    Unable to serve static files

    I'm trying out spark with Kotlin for the first time so forgive me if this is a trivial error but it seems to be in line with the documentation. I have created a folder in src/main/resources/public that contains an index.html

    package com.divanvisagie.todo
    import spark.kotlin.*
    
    
    fun main(args: Array<String>) {
    
        val http: Http = ignite()
    
        staticFiles.location("/public")
    
        http.get("/hello") {
            "Hello Spark Kotlin!"
        }
    
    
        println("Hello Kotlin ?")
    }
    

    However browsing to the following url returns a 404.

    http://localhost:4567/index.html

    opened by divanvisagie 1
  • Add Banner support to the framework

    Add Banner support to the framework

    Hey ya, I like spark quite a bit and use it in multiple projects. I was wondering if framework can add banner functionality, just like Spring or Dropwizard?

    Thank you.

    opened by meirka 0
  • Instance API exception handling

    Instance API exception handling

    In Java version I can app.exception(Exception::class.java) { e, req, res -> /**/ }

    However, in this one the api seems to be unavailable, the IDE can't find any method with name exception. So how am I supposed to establish exception handling with instance API?

    opened by isaac-weisberg 0
  • Release or updated alpha?

    Release or updated alpha?

    Hello happy people,

    will there be a new(er) release any time soon? It seems that exception handlers (and maybe some other things I haven't touched yet) don't work in the latest release (from May, 2017) on maven central.

    Are there anything to do before a release is possible that one can help with maybe?

    Cheers, Alex

    opened by JimPanic 4
  • halt return type gets in the way

    halt return type gets in the way

    Since halt doesn't return, it should return Nothing. This can be accomplished by throwing the result of java's halt (it won't actually get thrown because java's halt will do it first).

    This will let us use halt inside of when and the like without affecting the type of the expression. (right now, since halt returns the exception, a when statement will change its type to Any for no good reason)

    opened by phrodo00 1
  • RouteHandler::queryParams can be null

    RouteHandler::queryParams can be null

    request.queryParams can return null, which throws a runtime error since the return type of RouteHandler.queryParams is set as a non-nullable String: fun queryParams(key: String): String { return request.queryParams(key) }

    There are probably other methods with the same problem (contentType?)

    opened by richardskg 1
  • Make things that are possibly null nullable

    Make things that are possibly null nullable

    Right now, certain things are nullable from the Java side of things and are declared as non-null on the Kotlin side of things, which would cause runtime crashes as they occur. I think I covered them all here, but these were the ones that I found could be null via the JavaDocs of the Java libraries.

    I also updated this to use the new java-library plugin which allows for more control over gradle dependencies.

    opened by Jawnnypoo 1
Owner
Per Wendel
Per Wendel
Kotter - aims to be a relatively thin, declarative, Kotlin-idiomatic API that provides useful functionality for writing delightful console applications.

Kotter (a KOTlin TERminal library) aims to be a relatively thin, declarative, Kotlin-idiomatic API that provides useful functionality for writing delightful console applications.

Varabyte 348 Dec 21, 2022
Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Mohammadali Rezaei 7 Nov 28, 2022
Nice and simple DSL for Espresso Compose UI testing in Kotlin

Kakao Compose Nice and simple DSL for Espresso Compose in Kotlin Benefits Readability Reusability Extensible DSL How to use it Create Screen Create yo

null 74 Dec 26, 2022
An Android template you can use to build your project with gradle kotlin dsl

Android Gradle KTS An Android template you can use to build your project with gradle kotlin dsl Build.gradle.kts You can use your project's build.grad

Deep 17 Sep 12, 2022
Gradle plugin which allows to use typed DSL for generating kubernetes/openshift YAML files

gr8s Gradle plugin which allows using typed DSL for generating kubernetes/openshift YAML files. Based on kuberig Usage import io.github.guai.gr8s.Gene

null 0 Jan 3, 2022
DSL for JPA Criteria API without generated metamodel and reflection.

Kotlin JDSL Kotlin JDSL is DSL for JPA Criteria API without generated metamodel and reflection. It helps you write a JPA query like writing an SQL sta

LINE 379 Jan 7, 2023
Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin_practice_problems Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Aman 0 Oct 14, 2021
Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Mockative 121 Dec 26, 2022
Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Marcos Felipe 1 Jan 5, 2022
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
Kotlin TodoMVC – full-stack Kotlin application demo

Kotlin full stack TodoMVC This project is an example implementation of the TodoMVC app written in Kotlin. More specifically, it's the Kotlin port of t

Gyula Voros 22 Oct 3, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
Small kotlin library for persisting _single instances_ of kotlin data classes

PerSista Small library for persisting single instances of kotlin data classes. NB: PerSista uses typeOf() internally which is marked as @ExperimentalS

Eric Donovan 5 Nov 13, 2022
Kotlin Leaning Notes from Udacity Course | Kotlin Bootcamp for Programmers by Google

Kotlin Beginners Notes These are all personal notes taken from the Udacity Course (ud9011) of Kotlin Bootcamp for Programmers by Google as well as oth

Süha Tanrıverdi 34 Dec 10, 2022
Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

Simon Vergauwen 50 Dec 30, 2022
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

Oguzhan 18 Apr 21, 2022
A sample skeleton backend app built using Spring Boot kotlin, Expedia Kotlin Graphql, Reactive Web that can be deployed to Google App Engine Flexible environmennt

spring-kotlin-gql-gae This is a sample skeleton of a backend app that was built using: Spring Boot(Kotlin) Reactive Web Sprinng Data R2DBC with MYSQL

Dario Mungoi 7 Sep 17, 2022
Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

Danilo Silva 0 Jan 7, 2022
Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.

Kotlin Academy Mis experimentos con Kotlin para JetBrains donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema. Acerca de

José Luis González Sánchez 1 Jan 10, 2022