GithubHelp home page GithubHelp logo

perwendel / spark-kotlin Goto Github PK

View Code? Open in Web Editor NEW
985.0 985.0 43.0 118 KB

A Spark DSL in idiomatic kotlin // dependency: com.sparkjava:spark-kotlin:1.0.0-alpha

License: Apache License 2.0

Kotlin 97.63% HTML 0.12% Java 2.25%

spark-kotlin's People

Contributors

lallemupp avatar mg6maciej avatar perwendel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spark-kotlin's Issues

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?)

Websocket DSL/method

Is there a kotlin dsl for defining websocket routes? Spark java has spark.Spark.webSocket.

Coroutines support. Non Blocking?

What do you think about using/support Kotlin? Would it give us async operations?
I made a test project with AsyncRoute implementation. It's only scratch for testing.

class AsyncRoute(path: String, val handler: suspend RouteHandler.() -> Any) : RouteImpl(path) {
    override fun handle(request: Request, response: Response): Any = runBlocking {
        kotlin.run {
            handler(RouteHandler(request, response))
        }
    }
}

and use it like this

http.service.addRoute(HttpMethod.get, AsyncRoute("/nonblocking") {
        val jobs = (0..10).map {
            async(CommonPool) {
                longComputationAwait(it)
            }
        }
        val total =  jobs.sumBy { it.await() }
        total.toString()
    })

where longComputationAwait is

suspend fun longComputationAwait(x: Int): Int {
    println("Compute started in: ${System.currentTimeMillis()}")
    delay(1000)
    return x * x
}

and blocking analog of this route

http.get("/blocking") {
        val total = List(10){ longComputation(it) }.sum()
        total.toString()
    }

where longComputation is

fun longComputation(x: Int): Int {
            Thread.sleep(1000)
            return x * x
        }

as result "/blocking" page recived respons in 10 seconds as expected
"/nonblocking" page recived it in 1 second recived with same total value

Have this idea reason for live? Can we get more complex coroutine support?

Push a new version in maven repo

The version in the maven repos is not up to date, it would be nice to have the current version in maven central. This would allow me to extend RouteHandler, which is now open but is final in the maven repo

Support SparkJava's path groups for routes

It would be useful to support path groups. I've split my code into separate controllers, like so:

class UserController : AbstractController() {
	val users: MutableList<User> = mutableListOf()
	init {
		get("/users") {
                        val model: MutableMap<String,List<User>> = hashMapOf<String,List<User>>()
			model.put("users",users)
			engine.render(ModelAndView(model,"users"))
                }
                post("/users/add-submit") {
			val u:User = User(request.queryParams("name"),request.queryParams("age").toInt())
			users.add(u)
			redirect("/users")
		}
         }
}

Being able to use paths could reduce code duplication:

init {
  path("/users") {
    get("/") {  // e.g. /users/ }
    get("/add") { // e.g. /users/add }
    post("/submit") { // e.g. /users/submit }
  }
}

Implementing CORS

Hi, I'm sorry if this is not the right place to ask this but I was having a hard time trying to figure out how to implement CORS (Cross Origin Resource Sharing) for a RESTful API. I needed it for testing purposes (difference in port).

I did find this but couldn't seem to make out a Kotlin version out of it. Thanks before!

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

redirect.post("oldURL", "new URL") is not working

Hi Team,

am using redirect.post("/variable", "/:region/variable"); to redirect variable to new variable endpoint. but getting below error. Even the new url is there which is POST endpoint is working.

6894 [qtp1340842603-23] INFO spa.htt.mat.MatcherFilter - The requested route [/:region/variable] has not been mapped in Spark for Accept: [*/*]

Found that redirect internal assigned HTTP method to GET instead of POST due to which the new URL is not being found

21316 [qtp79709097-29] INFO Received request with region: path=http://localhost:4567/:region/variable, method=GET, region=:region attributes =null

Please help me which is the issue and why HTTP GET is used instead of POST when am trying to redirect POST endpoint.

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

HTTP#secure(...) doesn't allow null for truststore parameters

Spark for Java allows passing nulls for truststoreFile and truststorePassword, while Spark for Kotlin for some reason doesn't, because these parameters are specified as non-nullable.

Possible solutions:

  1. Just specify them as nullable
  2. Specify them as nullable and add a default value
  3. Add an overloading function which doesn't take truststore parameters at all

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?

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.

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?

initExceptionHandler doesn't appear to be working

Using initExceptionHandler{ /* handle the exception here */} doesn't seem to be working in spark-kotlin. This should trigger when the port is already in use. Current behavior is that the entire program just exits with no exception and no way to catch the problem and reassign a new port.

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

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)

How to apply filters on static files?

It seems that static content
staticFiles.location("/public")
will not be matched by filters:
before("/*") { req, res -> .... }

I need to do authentication/authorization in a filter.

Is the pattern wrong?
How can I achieve this?

(using spark 2.6.0)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.