package dispatch.mime
import org.apache.http.entity.mime.{FormBodyPart, MultipartEntity}
import org.apache.http.entity.mime.content.{FileBody, StringBody, InputStreamBody, ContentBody}
import java.io.{File, InputStream}
object Mime {
implicit def Request2ExtendedRequest(r: Request) = new MimeRequest(r)
class MimeRequest(r: Request) {
def << (name: String, file: File) =
r next add(name, new FileBody(file))
def << (name: String, file: File, content_type: String) =
r next add(name, new FileBody(file, content_type))
def << (name: String, file_name: String, stream: () => InputStream, content_type: String) =
r next add(name, new InputStreamBody(stream(), content_type, file_name))
def << (name: String, file_name: String, stream: () => InputStream) =
r next add(name, new InputStreamBody(stream(), file_name))
private def add(name: String, content: => ContentBody): Request.Xf = {
case post: MultipartPost => post.add(name, content)
case p: Post[_] => Request.mimic(new MultipartPost)(p).add(p.values).add(name, content)
case req => Request.mimic(new MultipartPost)(req).add(name, content)
}
}
}
private [mime] class MultipartPost(val values: Map[String, Any], entity: MultipartEntity) extends Post[MultipartPost] {
def this() = this(Map.empty, new MultipartEntity)
def add(name: String, content: ContentBody) = {
entity.addPart(name, content)
this
}
setEntity(entity)
def add(more: collection.Map[String, Any]) = {
more.elements foreach { case (key, value) =>
entity.addPart(key, new StringBody(value.toString))
}
Request.mimic(new MultipartPost(values ++ more.elements, entity))(this)
}
}