package ccf.transport.http

import java.io.IOException
import java.net.URL

import org.apache.http.params.HttpConnectionParams
import ccf.transport.json.{JsonFormatter, JsonParser}

import dispatch.{Request => HttpRequest, Http}
import dispatch.Http._

class HttpConnection(url: URL, timeoutMillis: Int, http: Http) extends Connection {
  private val formatter = JsonFormatter
  private val parser = JsonParser
  init
  def this(url: URL, timeoutMillis: Int) = this(url, timeoutMillis, new Http)
  def send(request: Request): Option[Response] = {
    val req = requestUrl(request).POST << formatter.format(request)
    http(req >- { parser.parse(_) })
  }
  private def requestUrl(request: Request) = url.toString / request.header("type").getOrElse(requestTypeMissing)
  private def requestTypeMissing = throw new InvalidRequestException("Request header \"type\" missing")
  private def init = {
    HttpConnectionParams.setConnectionTimeout(httpClientParams, timeoutMillis)
    HttpConnectionParams.setSoTimeout(httpClientParams, timeoutMillis)
  }
  private def httpClientParams = http.client.getParams
}

package ccf.transport.http

import java.io.IOException
import java.net.URL

import ccf.transport.json.{JsonFormatter, JsonParser}

class HttpConnection(url: URL, timeoutMillis: Int, http: Http) extends Connection {
  private val formatter = JsonFormatter
  private val parser = JsonParser
  def this(url: URL, timeoutMillis: Int) = this(url, timeoutMillis, new HttpImpl(timeoutMillis))
  def send(request: Request): Option[Response] = try {
    http.post(requestUrl(request), formatter.format(request)) { parser.parse }
  } catch {
    case e: IOException => throw new ConnectionException(e.toString)
  }
  private def requestUrl(request: Request) = new URL(url, request.header("type").getOrElse(requestTypeMissing))
  private def requestTypeMissing = throw new InvalidRequestException("Request header \"type\" missing")
}

Drop direct dep. from HTTP connection to Databinder Dispatch
transport: Drop direct dep. from HTTP connection to Databinder Dispatch

While at it, transform IO exceptions to ConnectionExceptions.

Signed-off-by: Karim Osman <94396faf6cc817be76165477038b3cfa832e89a4@reaktor.fi>
Acked-by: Harri Salokorpi <eefb23b8deb8c30dca252cd0ae751b67337dc69f@reaktor.fi>
