== Responses

This chapter covers some special response types, like `raw responses`, `streaming`, `file download`, `non-blocking`, etc...

=== Raw

Raw responses are NOT processed by a <<context-response-body-message-encoder, message encoder>>. These response types are considered `raw`:

- String/CharSequence
- byte[]
- java.nio.ByteBuffer/io.netty.buffer.ByteBuf
- java.io.File/java.io.InputStream/java.nio.file.Path/java.nio.channels.FileChannel

.Generate a JSON String from handler
[source,java,role="primary"]
----
{
  get("/json", ctx -> {
    ctx.setContentType(MediaType.json);
    return "{\"message\": \"Hello Raw Response\"}";
  });
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/json") {
    ctx.contentType = MediaType.json
    """
      "message": "Hello Raw Response"
    """
  }
}
----

No matter if there is a JSON encoder installed, a raw response is always send directly to client.

=== Streaming / Chunked

Streaming/chunked API is available via:

- javadoc:Context[responseStream]: blocking API that provides an `OutputStream`
- javadoc:Context[responseWriter]: blocking API that provides a `PrintWriter`
- javadoc:Context[responseSender]: non-blocking API that provides a javadoc:Sender[]

Only one of these methods must be call it per request. At the time you call one of these methods Jooby
automatically adds the `Transfer-Encoding: chunked` header when `Content-Length` is missing.

All the three APIs have a `close` method. You must call it once you finish.

.Writer example
[source,java,role="primary"]
----
{
  get("/chunk", ctx -> {
    try(Writer writer = ctx.responseWriter()) { // <1>
      writer.write("chunk1");                   // <2>
      ...
      writer.write("chunkN");
    }

    return ctx;                                 // <3>
  });
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/chunk") {
    ctx.responseWriter().use {                  // <1>
      writer.write("chunk1")                    // <2>
      ...
      writer.write("chunkN")
    }
    ctx                                         // <3>
  }
}
----

<1> Get the `Writer` inside a try-with-resources statement, so close it automatically. 
<2> Write chunks
<3> Return the `Context`

There is an overloaded version (for Java mainly) that let you skip the try-with-resources and
automatically close the writer/stream:

.Writer example
[source,java,role="primary"]
----
{
  get("/chunk", ctx -> {
    return ctx.responseWriter(writer -> { // <1>
      writer.write("chunk1");             // <2>
      ...
      writer.write("chunkN");
    });
  });
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/chunk") {
    ctx.responseWriter {                  // <1>
      writer.write("chunk1")              // <2>
      ...
      writer.write("chunkN")
    }
  }
}
----

=== File download

The javadoc:AttachedFile[] is used to generate file downloads, i.e. responses with 
`Content-Disposition` header.

.File download example
[source,java,role="primary"]
----
{
  get("/download-file", ctx -> {
    Path source = Paths.get("logo.png");
    return new AttachedFile(source);               // <1>
  });
  
  get("/download-stream", ctx -> {
    InputStream source = ...;
    return new AttachedFile("myfile.txt", source); // <2>
  });
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/download-file") {
    val source = Paths.get("logo.png")
    AttachedFile(source)                // <1>
  }

  get("/download-stream") {
    val source = ...
    AttachedFile("myfile.txt", source)  // <2>
  }
}
----

<1> Send a download from an `InputStream`
<2> Send a download from a `File`

=== NonBlocking

Non-blocking responses are a new feature of Jooby 2.x.

From user point of view there is nothing special about them, you just write your route handler as 
usually do with blocking types.

In Jooby 1.x we were forced to produces directly/indirectly a `Deferred` result. All that is gone now, 
we don't need a custom type to do the integration.

Before we jump to each of the supported types, we need to learn what occurs in the pipeline when
there is a non-blocking route handler.

.In event loop
[source,java,role="primary"]
----
{
  mode(EVENT_LOOP);                 // <1>

  get("/non-blocking", ctx -> {

    ...                             // <2>

    return CompletableFuture        // <3>
        .supplyAsync(() -> {
          ...                       // <4>
        });
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  mode(EVENT_LOOP)                  // <1>

  get("/non-blocking") {

    ...                             // <2>

    CompletableFuture               // <3>
        .supplyAsync {
          ...                       // <4>
        }
  }
}
----

<1> App run in *event loop*
<2> Route block run in *event loop*. No blocking code is permitted
<3> Value is provided from *event loop*. No blocking code is permitted
<4> Value is computed/produces from completable future context

Running your `App` in *worker* mode works identically, except for we are able to do blocking calls:

.In worker mode
[source,java,role="primary"]
----
{
  mode(WORKER);                     // <1>

  get("/blocking", ctx -> {

    ...                             // <2>

    return CompletableFuture        // <3>
        .supplyAsync(() -> {
          ...                       // <4>
        });
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  mode(WORKER)                      // <1>

  get("/blocking") {

    ...                             // <2>

    CompletableFuture               // <3>
        .supplyAsync {
          ...                       // <4>
        }
  }
}
----

<1> App run in *worker mode*
<2> Route block run in *worker mode*. Blocking code is permitted
<3> Value is provided from *worker mode*. Blocking code is permitted
<4> Value is computed/produces from completable future context

Running your `App` in *default* mode works identically to running in the *event loop* mode:

.In default mode
[source,java,role="primary"]
----
{
  mode(DEFAULT);                    // <1>

  get("/non-blocking", ctx -> {

    ...                             // <2>

    return CompletableFuture        // <3>
        .supplyAsync(() -> {
          ...                       // <4>
        });
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  mode(DEFAULT)                     // <1>

  get("/non-blocking") {

    ...                             // <2>

    CompletableFuture               // <3>
        .supplyAsync {
          ...                       // <4>
        }
  }
}
----

<1> App run in *event loop*
<2> Route block run in *event loop*. No blocking code is permitted
<3> Value is provided from *event loop*. No blocking code is permitted
<4> Value is computed/produces from completable future context

The *default* mode mimics the *event loop* mode execution when route produces a *non-blocking* type.

==== Limitations

While writing non-blocking/reactive responses we should *avoid the use of Jooby filters*: <<router-handler-before, before>> and <<router-handler-after, after>>.

In most use cases they won't work, so it is preferred to avoid them while programming
non-blocking/reactive responses.

On non-blocking/reactive responses there is always a "dispatch call". This call moves execution to
somewhere else (usually a different thread). Because of this is almost impossible to ensure the
execution of pipeline.

[quote]
If you have a non-blocking route handler, it is better to not have any type of filter in the pipeline

The alternative option is to write cross-cutting concerns we usually put inside a filter using the
non-blocking API.

==== CompletableFuture

CompletableFuture is considered a non-blocking type which is able to produces a single result:

.Java
[source,java, role="primary"]
----
{
  get("/non-blocking", ctx -> {
    return CompletableFuture
        .supplyAsync(() -> "Completable Future!")
        .thenApply(it -> "Hello " + it);
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/non-blocking") {
    CompletableFuture
        .supplyAsync { "Completable Future!" }
        .thenApply { "Hello $it" }
  }
}
----

==== RxJava

1) Add the https://github.com/ReactiveX/RxJava[RxJava] dependency:

[dependency, artifactId="rxjava"]
.

2) Write code:

===== Single

.Java
[source,java, role="primary"]
----
{
  get("/non-blocking", ctx -> {
    return Single
        .fromCallable(() -> "Single")
        .map(it -> "Hello " + it);
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/non-blocking") {
    Single
        .fromCallable { "Single" }
        .map { "Hello $it" }
  }
}
----

===== Flowable

.Java
[source,java, role="primary"]
----
{
  get("/non-blocking", ctx -> {
    return Flowable.range(1, 10)
        .map(it -> it + ", ");
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/non-blocking") {
    Flowable.range(1, 10)
        .map{ "$it, " }
  }
}
----

For Flowable, Jooby builds a `chunked` response. That:

. Set the `Transfer-Encoding: chunked` header
. Each item means new `chunk` send it to client 

==== Reactor

1) Add the https://projectreactor.io/[Reactor] dependency:

[dependency, artifactId="reactor-core"]
.

2) Write code:

===== Mono

.Java
[source,java, role="primary"]
----
{
  get("/non-blocking", ctx -> {
    return Mono
        .fromCallable(() -> "Mono")
        .map(it -> "Hello " + it);
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/non-blocking") {
    Mono
        .fromCallable { "Mono" }
        .map { "Hello $it" }
  }
}
----

===== Flux

.Java
[source,java, role="primary"]
----
{
  get("/non-blocking", ctx -> {
    return Flux.range(1, 10)
        .map(it -> it + ", ");
  })
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/non-blocking") {
    Flux.range(1, 10)
        .map{ "$it, " }
  }
}
----

For Flux, Jooby builds a `chunked` response. That:

. Set the `Transfer-Encoding: chunked` header
. Each item means new `chunk` send it to client

==== Kotlin Coroutines

Probably one of most exciting new features of Jooby 2.x is the builtin integration with https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html[Kotlin Coroutines]:

.Coroutine handler:
[source, kotlin, role="primary"]
----
{
  coroutine {
    get("/") {         // <1>
      ctx.getRequestPath() 
    }
  }
}
----

.Normal handler:
[source, kotlin, role="secondary"]
----
{
  get("/") {           // <2>
    ctx.getRequestPath() 
  }
}
----

<1> Coroutine route
<2> Normal route


Also, if you try to call a suspending function from normal handler, Kotlin complains about:

.Not allowed it:
[source, kotlin]
----
{
  get("/") {
    delay(100)      // <1>
    "..."
  }
}
----

<1> Suspend function 'delay' should be called only from a coroutine or another suspend function

Now, if we wrap the route with the `coroutine` router:

.Hello Coroutines
[source, kotlin]
----
{
  coroutine {
    get("/") {
      delay(100)           // <1>
      "Hello Coroutines!"  // <2>
    }
  }
}
----

<1> Call a suspending function
<2> Send response to client

.Here is another example with an extension and suspending function:
[source, kotlin]
----
{
  coroutine {
    get("/") {
      ctx.doSomething()         // <1>
    }
  }
}

suspend fun Context.doSomething(): String {
  delay(100)                  // <2>
  return "Hello Coroutines!"  // <3>
}
----

<1> Call extension suspending function
<2> Call a suspending function or do a blocking call
<3> Send response to client

A coroutine works like any of the other non-blocking types. You start Jooby using the **event loop**
or **default mode**, Jooby detects we produce a coroutine and creates a coroutine context to execute
it.

Jooby uses the *worker executor* to creates a coroutine context. As described in <<worker-executor, worker executor section>>
this is provided by the web server implementation unless you provided your own.

.Coroutines with custom executor:
[source, kotlin]
----
{
  worker(Executors.newCachedThreadPool())

  coroutine {
    get("/") {
      val n = 5 * 5        // <1>
      delay(100)           // <2>
      "Hello Coroutines!"  // <3>
    }
  }
}
----

<1> Statement run in the *worker executor* (cached thread pool)
<2> Call a suspending function
<3> Produces a response

Coroutines always run in the <<worker-executor, worker executor>>. There is an experimental API where
coroutines run in the *caller thread*(event loop in this case) until a suspending function is found.

Jooby allows you to use this experimental API by setting the `coroutineStart` option:

.UNDISPATCHED
[source, kotlin]
----
{
  coroutine (CoroutineStart.UNDISPATCHED) {
    get("/") {
      val n = 5 * 5        // <1>
      delay(100)           // <2>
      "Hello Coroutines!"  // <3>
    }
  }
}
----

<1> Statement run in the *event loop* (caller thread)
<2> Call a suspending function and dispatch to *worker executor*
<3> Produces a response from *worker executor*

{love} {love}!

=== Send methods

Jooby provides a family of `send()` methods that produces a response via side effects.

.send text
[source,java,role="primary"]
----
{
  get("/", ctx -> {
    return ctx.send("Hello World!");
  });
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
{
  get("/") {
    ctx.send("Hello World!")
  }
}
----

Beside we operate via side effects, the route still returns something. This is required because a route
handler is a function which always produces a result.

All the send methods returns the current `Context`, this signal Jooby that we want to operate via
side effects ignoring the output of the route handler.

Family of send methods include:

- javadoc:Context[send, byte[\]]
- javadoc:Route[consumes, io.jooby.MediaType...]
- javadoc:Context[send, java.nio.Buffer]
- javadoc:Context[send, java.lang.String]
- javadoc:Context[send, java.nio.file.Path]
- javadoc:Context[send, java.io.File]
- javadoc:Context[send, java.nio.channels.FileChannel]
- javadoc:Context[send, io.jooby.AttachedFile]
- javadoc:Context[send, io.jooby.StatusCode]
