Main : Split handler to separate models.

This commit is contained in:
Dmitry Voronin 2024-09-23 15:40:08 +03:00
parent e74dbb0bec
commit 359d4af5ca
Signed by: voronind
SSH key fingerprint: SHA256:3kBb4iV2ahufEBNq+vFbUe4QYfHt98DHQjN7QaptY9k
3 changed files with 49 additions and 39 deletions

View file

@ -1,52 +1,17 @@
package com.voronind.doublegis.test
import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}
import java.io.{InputStream, OutputStream}
import model.handler.TitleCrawlerHandler
import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import scala.language.postfixOps
@main def main(): Unit = {
println("Hello world!")
val server = HttpServer.create(new InetSocketAddress(8000), 0)
server.createContext("/", new RootHandler())
server.createContext(TitleCrawlerHandler.context, new TitleCrawlerHandler())
server.setExecutor(null)
server.start()
println("Hit any key to exit...")
println("Server started! Input any key to exit.")
System.in.read()
server.stop(0)
}
class RootHandler extends HttpHandler {
def handle(t: HttpExchange): Unit = {
displayPayload(t.getRequestBody)
sendResponse(t)
}
private def displayPayload(body: InputStream): Unit = {
println()
println("**** Start ****")
println()
copyStream(body, System.out)
println()
println("**** End ****")
println()
}
private def copyStream(in: InputStream, out: OutputStream): Unit = {
Iterator
.continually(in.read)
.takeWhile(-1 !=)
.foreach(out.write)
}
private def sendResponse(t: HttpExchange): Unit = {
val response = "Ack!"
t.sendResponseHeaders(200, response.length())
val os = t.getResponseBody
os.write(response.getBytes)
os.close()
}
}

View file

@ -0,0 +1,31 @@
package com.voronind.doublegis.test
package model.handler
import model.lib.StreamUtil
import com.sun.net.httpserver.{HttpExchange, HttpHandler}
import java.io.InputStream
class TitleCrawlerHandler extends HttpHandler {
def handle(t: HttpExchange): Unit = {
log(t.getRequestBody)
sendResponse(t)
}
private def log(body: InputStream): Unit = {
println(f"${TitleCrawlerHandler.context}%s : Got payload.")
StreamUtil.copyStream(body, System.out)
println()
}
private def sendResponse(t: HttpExchange): Unit = {
val response = "Ack!"
t.sendResponseHeaders(200, response.length())
val os = t.getResponseBody
os.write(response.getBytes)
os.close()
}
}
object TitleCrawlerHandler {
val context = "/crawl_title"
}

View file

@ -0,0 +1,14 @@
package com.voronind.doublegis.test
package model.lib
import java.io.{InputStream, OutputStream}
import scala.language.postfixOps
object StreamUtil {
def copyStream(in: InputStream, out: OutputStream): Unit = {
Iterator
.continually(in.read)
.takeWhile(-1 !=)
.foreach(out.write)
}
}