Skip to content

Instantly share code, notes, and snippets.

@no-longer-on-githu-b
Last active August 29, 2015 14:16
Show Gist options
  • Save no-longer-on-githu-b/4d672d1017ae6521d4ce to your computer and use it in GitHub Desktop.
Save no-longer-on-githu-b/4d672d1017ae6521d4ce to your computer and use it in GitHub Desktop.
import java.io.InputStream
import java.util.Locale
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import org.apache.commons.io.IOUtils
import scala.collection.JavaConverters._
case class ConnectionInfo(localAddress: String,
localHost: String,
localPort: Int,
remoteAddress: String,
remoteHost: String,
remotePort: Int)
object ConnectionInfo {
def fromHttpServletRequest(hsr: HttpServletRequest): ConnectionInfo = {
val localAddress = hsr.getLocalAddr
val localHost = hsr.getLocalName
val localPort = hsr.getLocalPort
val remoteAddress = hsr.getRemoteAddr
val remoteHost = hsr.getRemoteHost
val remotePort = hsr.getRemotePort
ConnectionInfo(localAddress, localHost, localPort, remoteAddress, remoteHost, remotePort)
}
}
case class HTTPRequest(protocol: String,
method: String,
requestURI: String,
headers: Map[String, String],
body: InputStream)
object HTTPRequest {
def fromHttpServletRequest(hsr: HttpServletRequest): HTTPRequest = {
val protocol = hsr.getProtocol
val method = hsr.getMethod
val requestURI = hsr.getRequestURI
val headers =
hsr.getHeaderNames.asScala
.map{header => header.toLowerCase(Locale.ENGLISH) -> hsr.getHeaders(header).asScala.mkString(",")}
.toMap
val body = hsr.getInputStream
HTTPRequest(protocol, method, requestURI, headers, body)
}
}
case class HTTPResponse(protocol: String,
status: (Int, String),
headers: Map[String, String],
body: InputStream)
object HTTPResponse {
def applyToHttpServletResponse(httpResponse: HTTPResponse, hsr: HttpServletResponse): Unit = {
hsr.setStatus(httpResponse.status._1)
httpResponse.headers.foreach(hsr.setHeader.tupled)
IOUtils.copy(httpResponse.body, hsr.getOutputStream)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment