-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.scala
62 lines (53 loc) · 1.71 KB
/
App.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package msgpack_json
import java.io._
import msgpack4z._
import play.api.libs.json.Json
import unfiltered.request._
import unfiltered.response._
import scalaz.{-\/, \/-}
object App {
private val codec = Play2Msgpack.jsValueCodec(UndefinedHandler.ThrowSysError, PlayUnpackOptions.default)
def json2bytes(jsonString: String): Array[Byte] = {
val json = Json.parse(jsonString)
codec.toBytes(json, Msgpack06.defaultPacker)
}
def stream2bytes(in: InputStream): Array[Byte] = {
val out = new ByteArrayOutputStream
val ba = new Array[Byte](8192)
@annotation.tailrec
def loop(): Unit = {
val len = in.read(ba)
if (len > 0) out.write(ba, 0, len)
if (len >= 0) loop()
}
loop()
out.toByteArray
}
val main: unfiltered.filter.Plan.Intent = {
case req @ POST(Path("/json2msgpack")) =>
val str = scala.io.Source.fromInputStream(req.inputStream, "UTF-8").mkString
Ok ~> ResponseBytes(App.json2bytes(str))
case req @ POST(Path("/msgpack2json")) =>
val unpacker = Msgpack06.defaultUnpacker(stream2bytes(req.inputStream))
App.codec.unpackAndClose(unpacker) match {
case \/-(a) =>
Ok ~> JsonContent ~> ResponseString(a.toString)
case -\/(a) =>
BadRequest ~> ResponseString(a.toString)
}
}
}
final class App extends unfiltered.filter.Plan {
override def intent = {
case request if App.main.isDefinedAt(request) =>
try{
App.main(request)
}catch{
case e: Throwable =>
e.printStackTrace()
System.err.println(e)
System.err.println(e.getStackTrace.mkString("\n"))
ResponseString(e.toString + "\n\n" + e.getStackTrace.mkString("\n")) ~> InternalServerError
}
}
}