play.api.http.HttpEntity Scala Examples

The following examples show how to use play.api.http.HttpEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: MetricsController.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers

import java.io.Writer
import javax.inject.Singleton

import akka.util.ByteString
import io.prometheus.client._
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports
import play.api.http.HttpEntity
import play.api.mvc._

@Singleton
class MetricsController extends Controller {
  //export default jvm metrics
  DefaultExports.initialize()

  def index = Action {
    val samples = new StringBuilder()
    val writer = new WriterAdapter(samples)

    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples())
    writer.close()

    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Strict(ByteString(samples.toString), Some(TextFormat.CONTENT_TYPE_004))
    )
  }
}

class WriterAdapter(buffer: StringBuilder) extends Writer {
  override def write(charArray: Array[Char], offset: Int, length: Int): Unit = {
    buffer ++= new String(new String(charArray, offset, length).getBytes("UTF-8"), "UTF-8")
  }
  override def flush(): Unit = {}
  override def close(): Unit = {}
} 
Example 2
Source File: MetricsController.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers
import java.io.Writer
import javax.inject.Singleton

import akka.util.ByteString
import io.prometheus.client._
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports
import play.api.http.HttpEntity
import play.api.mvc._


@Singleton
class MetricsController extends Controller {
  //export default jvm metrics
  DefaultExports.initialize()

  def index = Action {
    val samples = new StringBuilder()
    val writer = new WriterAdapter(samples)

    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples())
    writer.close()

    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Strict(ByteString(samples.toString), Some(TextFormat.CONTENT_TYPE_004))
    )
  }
}

class WriterAdapter(buffer: StringBuilder) extends Writer {
  override def write(charArray: Array[Char], offset: Int, length: Int): Unit = {
    val b = buffer.append(new String(new String(charArray, offset, length).getBytes("UTF-8"), "UTF-8"))
  }
  override def flush(): Unit = {}
  override def close(): Unit = {}
} 
Example 3
Source File: MetricsController.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers

import java.io.Writer
import javax.inject.Singleton

import akka.util.ByteString
import io.prometheus.client._
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports
import play.api.http.HttpEntity
import play.api.mvc._


@Singleton
class MetricsController extends Controller {
  //export default jvm metrics
  DefaultExports.initialize()

  def index = Action {
    val samples = new StringBuilder()
    val writer = new WriterAdapter(samples)

    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples())
    writer.close()

    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Strict(ByteString(samples.toString), Some(TextFormat.CONTENT_TYPE_004))
    )
  }
}

class WriterAdapter(buffer: StringBuilder) extends Writer {
  override def write(charArray: Array[Char], offset: Int, length: Int): Unit = {
    buffer ++= new String(new String(charArray, offset, length).getBytes("UTF-8"), "UTF-8")

  }
  override def flush(): Unit = {}
  override def close(): Unit = {}
} 
Example 4
Source File: MetricsController.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package controllers

import java.io.Writer
import javax.inject.Singleton

import akka.util.ByteString
import io.prometheus.client._
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports
import play.api.http.HttpEntity
import play.api.mvc._


@Singleton
class MetricsController extends Controller {
  //export default jvm metrics
  DefaultExports.initialize()

  def index = Action {
    val samples = new StringBuilder()
    val writer = new WriterAdapter(samples)

    TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples())
    writer.close()

    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Strict(ByteString(samples.toString), Some(TextFormat.CONTENT_TYPE_004))
    )
  }
}

class WriterAdapter(buffer: StringBuilder) extends Writer {
  override def write(charArray: Array[Char], offset: Int, length: Int): Unit = {
    buffer ++= new String(new String(charArray, offset, length).getBytes("UTF-8"), "UTF-8")
  }
  override def flush(): Unit = {}
  override def close(): Unit = {}
} 
Example 5
Source File: EmptyResponseFilter.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.filters

import akka.stream.Materializer
import javax.inject.Inject
import play.api.http.HttpEntity
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}

class EmptyResponseFilter @Inject()(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {

  val emptyHeader = "Gov-Empty-Response"

  def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = {
    f(rh) map { res =>
      if ((res.header.status == 201 || res.header.status == 409) && res.body.isKnownEmpty) {
        val headers = res.header.headers
          .updated("Content-Type", "application/json")
          .updated(emptyHeader, "true")
        res.copy(res.header.copy(headers = headers), HttpEntity.NoEntity)
      } else res
    }
  }

} 
Example 6
Source File: AttachmentCtrl.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.controllers

import java.net.URLEncoder
import java.nio.file.Files
import javax.inject.{Inject, Singleton}

import play.api.http.HttpEntity
import play.api.libs.Files.DefaultTemporaryFileCreator
import play.api.mvc._
import play.api.{mvc, Configuration}

import akka.stream.scaladsl.FileIO
import net.lingala.zip4j.core.ZipFile
import net.lingala.zip4j.model.ZipParameters
import net.lingala.zip4j.util.Zip4jConstants
import org.thp.cortex.models.Roles

import org.elastic4play.Timed
import org.elastic4play.controllers.{Authenticated, Renderer}
import org.elastic4play.models.AttachmentAttributeFormat
import org.elastic4play.services.AttachmentSrv


  @Timed("controllers.AttachmentCtrl.downloadZip")
  def downloadZip(hash: String, name: Option[String]): Action[AnyContent] = authenticated(Roles.read) { _ ⇒
    if (!name.getOrElse("").intersect(AttachmentAttributeFormat.forbiddenChar).isEmpty)
      BadRequest("File name is invalid")
    else {
      val f = tempFileCreator.create("zip", hash).path
      Files.delete(f)
      val zipFile   = new ZipFile(f.toFile)
      val zipParams = new ZipParameters
      zipParams.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FASTEST)
      zipParams.setEncryptFiles(true)
      zipParams.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD)
      zipParams.setPassword(password)
      zipParams.setFileNameInZip(name.getOrElse(hash))
      zipParams.setSourceExternalStream(true)
      zipFile.addStream(attachmentSrv.stream(hash), zipParams)

      Result(
        header = ResponseHeader(
          200,
          Map(
            "Content-Disposition"       → s"""attachment; filename="${URLEncoder.encode(name.getOrElse(hash), "utf-8")}.zip"""",
            "Content-Type"              → "application/zip",
            "Content-Transfer-Encoding" → "binary",
            "Content-Length"            → Files.size(f).toString
          )
        ),
        body = HttpEntity.Streamed(FileIO.fromPath(f), Some(Files.size(f)), Some("application/zip"))
      )
    }
  }
} 
Example 7
Source File: ChunkedEntities.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import akka.stream.scaladsl.Source
import akka.util.ByteString
import endpoints4s.algebra
import play.api.http.{ContentTypes, HttpChunk, HttpEntity}
import play.api.libs.streams.Accumulator
import play.api.mvc.BodyParser


trait ChunkedJsonEntities
    extends ChunkedEntities
    with algebra.ChunkedJsonEntities
    with JsonEntitiesFromCodecs {

  def jsonChunksRequest[A](implicit
      codec: JsonCodec[A]
  ): RequestEntity[Chunks[A]] = {
    val decoder = stringCodec(codec)
    chunkedRequestEntity { byteString =>
      val string = byteString.utf8String
      decoder
        .decode(string)
        .toEither
        .left
        .map(errors => new Throwable(errors.mkString(". ")))
    }
  }

  def jsonChunksResponse[A](implicit
      codec: JsonCodec[A]
  ): ResponseEntity[Chunks[A]] = {
    val encoder = stringCodec(codec)
    chunkedResponseEntity(ContentTypes.JSON, a => ByteString(encoder.encode(a)))
  }

} 
Example 8
Source File: ApplicationRequestProxy.scala    From HAT2.0   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.hatdex.hat.api.controllers

import com.mohiva.play.silhouette.api.Silhouette
import javax.inject.Inject
import org.hatdex.hat.api.json.ApplicationJsonProtocol
import org.hatdex.hat.api.models.applications.HatApplication
import org.hatdex.hat.api.models.{ ApplicationManage, ErrorMessage, Owner }
import org.hatdex.hat.api.service.RemoteExecutionContext
import org.hatdex.hat.api.service.applications.ApplicationsService
import org.hatdex.hat.authentication.{ ContainsApplicationRole, HatApiAuthEnvironment, HatApiController, WithRole }
import play.api.Logger
import play.api.http.HttpEntity
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import play.api.mvc.{ Action, AnyContent, ControllerComponents }

import scala.concurrent.Future

class ApplicationRequestProxy @Inject() (
    components: ControllerComponents,
    silhouette: Silhouette[HatApiAuthEnvironment],
    wsClient: WSClient)(
    implicit
    val ec: RemoteExecutionContext,
    applicationsService: ApplicationsService)
  extends HatApiController(components, silhouette) with ApplicationJsonProtocol {

  import org.hatdex.hat.api.json.HatJsonFormats.errorMessage

  val logger = Logger(this.getClass)

  def proxyRequest(id: String, path: String, method: String = "GET"): Action[AnyContent] = SecuredAction(ContainsApplicationRole(Owner(), ApplicationManage(id)) || WithRole(Owner())).async { implicit request =>
    logger.info(s"Proxy $method request for $id to $path with parameters: ${request.queryString}")
    applicationsService.applicationStatus(id).flatMap { maybeStatus ⇒
      maybeStatus map {
        case HatApplication(app, _, true, _, _, _) ⇒

          applicationsService.applicationToken(request.identity, app)
            .flatMap { token ⇒
              val baseRequest = wsClient.url(s"${app.kind.url}/$path")
                .withHttpHeaders("x-auth-token" → token.accessToken)
                .addQueryStringParameters(request.queryString.map(p ⇒ (p._1, p._2.head)).toSeq: _*)
                .withMethod(method)

              request.body.asJson.fold(baseRequest)(b ⇒ baseRequest.withBody(b))
                .stream()
                .map(r ⇒ new Status(r.status).sendEntity(HttpEntity.Strict(r.bodyAsBytes, Some("application/json"))))
            }

        case _ ⇒ Future.successful(BadRequest(Json.toJson(ErrorMessage(
          "Application not active",
          s"Application $id does not appear to be activated by the user"))))
      } getOrElse {
        Future.successful(NotFound(Json.toJson(ErrorMessage(
          "Application not Found",
          s"Application $id does not appear to be a valid application registered with the DEX"))))
      }
    }
  }
} 
Example 9
Source File: BaseApi.scala    From asura   with MIT License 5 votes vote down vote up
package asura.play.api

import akka.util.ByteString
import asura.common.model.ApiRes
import asura.common.util.JsonUtils
import org.pac4j.core.profile.{CommonProfile, ProfileManager}
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.play.PlayWebContext
import org.pac4j.play.scala.Security
import play.api.http.{ContentTypes, HttpEntity}
import play.api.mvc._

import scala.collection.JavaConverters.asScalaBuffer
import scala.concurrent.{ExecutionContext, Future}

trait BaseApi extends Security[CommonProfile] {

  import BaseApi._

  def getWsProfile(auth: JwtAuthenticator)(implicit request: RequestHeader): CommonProfile = {
    val token = request.getQueryString("token")
    if (token.nonEmpty) {
      auth.validateToken(token.get)
    } else {
      null
    }
  }

  def getProfiles()(implicit request: RequestHeader): List[CommonProfile] = {
    val webContext = new PlayWebContext(request, playSessionStore)
    val profileManager = new ProfileManager[CommonProfile](webContext)
    val profiles = profileManager.getAll(true)
    asScalaBuffer(profiles).toList
  }

  def getProfileId()(implicit request: RequestHeader): String = {
    getProfiles().head.getId
  }

  implicit class JsonToClass(req: Request[ByteString]) {
    def bodyAs[T <: AnyRef](c: Class[T]): T = JsonUtils.parse[T](req.body.decodeString("UTF-8"), c)
  }

  
  val responseNoCacheHeaders = Seq(
    ("Cache-Control", "no-cache"), ("X-Accel-Buffering", "no")
  )
  val DEFAULT_SOURCE_BUFFER_SIZE = 100
} 
Example 10
Source File: LeaderProxyFilter.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api.v1

import akka.util.ByteString
import dcos.metronome.api.ApiConfig
import mesosphere.marathon.core.election.ElectionService
import org.slf4j.LoggerFactory
import play.api.http.HttpEntity
import play.api.libs.streams.Accumulator
import play.api.libs.ws.WSClient
import play.api.mvc._

class LeaderProxyFilter(ws: WSClient, electionService: ElectionService, config: ApiConfig)
    extends EssentialFilter
    with Results {

  import LeaderProxyFilter._
  import scala.concurrent.ExecutionContext.Implicits.global
  val log = LoggerFactory.getLogger(getClass)

  val localHostPort = config.hostnameWithPort
  val localRoutes = Set("/ping", "/v1/metrics")

  override def apply(next: EssentialAction): EssentialAction =
    new EssentialAction {
      override def apply(request: RequestHeader): Accumulator[ByteString, Result] = {
        def isProxiedToSelf = request.headers.get(HEADER_VIA).contains(localHostPort)
        def doNotProxy() = localRoutes(request.path)
        if (electionService.isLeader || doNotProxy()) {
          next(request)
        } else if (isProxiedToSelf) {
          Accumulator.done(BadRequest("Prevent proxying already proxied request"))
        } else {
          electionService.leaderHostPort match {
            case Some(hostPort) => proxyRequest(request, hostPort)
            case None => Accumulator.done(ServiceUnavailable("No consistent leadership"))
          }
        }
      }
    }

  def proxyRequest(request: RequestHeader, leaderHostPort: String): Accumulator[ByteString, Result] = {
    log.info(s"Proxy request ${request.path} to $leaderHostPort")
    val headers = request.headers.headers ++ Seq(HEADER_LEADER -> leaderHostPort, HEADER_VIA -> localHostPort)
    val scheme = if (request.secure) "https" else "http"
    Accumulator.source[ByteString].mapFuture { source =>
      ws.url(s"$scheme://$leaderHostPort${request.path}?${request.rawQueryString}")
        .withMethod(request.method)
        .withHttpHeaders(headers: _*)
        .withRequestTimeout(config.leaderProxyTimeout)
        .withBody(source)
        .execute()
        .map { r =>
          val proxyHeaders = Map(HEADER_LEADER -> leaderHostPort, HEADER_VIA -> localHostPort)
          val responseHeaders = r.headers.map { case (k, v) => k -> v.mkString(", ") }
          val header = ResponseHeader(r.status, proxyHeaders ++ responseHeaders, Some(r.statusText))
          val body = HttpEntity.Strict(r.bodyAsBytes, None)
          Result(header, body)
        }
    }
  }
}

object LeaderProxyFilter {
  val HEADER_VIA = "X-VIA"
  val HEADER_LEADER = "X-LEADER"
} 
Example 11
Source File: PrometheusController.scala    From play-prometheus-filters   with MIT License 5 votes vote down vote up
package com.github.stijndehaes.playprometheusfilters.controllers

import akka.util.ByteString
import com.github.stijndehaes.playprometheusfilters.utils.WriterAdapter
import javax.inject._
import play.api.mvc._
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
import org.slf4j.LoggerFactory
import play.api.http.HttpEntity


class PrometheusController @Inject()(registry: CollectorRegistry, cc: ControllerComponents) extends AbstractController(cc) {

  private val logger = LoggerFactory.getLogger(classOf[PrometheusController])

  def getMetrics = Action {
    logger.trace("Metrics call received")
    val samples = new StringBuilder()
    val writer = new WriterAdapter(samples)
    TextFormat.write004(writer, registry.metricFamilySamples())
    writer.close()

    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Strict(ByteString(samples.toString), Some(TextFormat.CONTENT_TYPE_004))
    )
  }

} 
Example 12
Source File: BackupAdminController.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
package controllers.admin.backup

import akka.actor.ActorSystem
import akka.stream.scaladsl.FileIO
import com.mohiva.play.silhouette.api.Silhouette
import controllers.{BaseAuthController, Security}
import controllers.document.BackupReader
import javax.inject.{Inject, Singleton}
import services.ContentType
import services.annotation.AnnotationService
import services.document.DocumentService
import services.generated.tables.records.DocumentFilepartRecord
import services.user.UserService
import services.user.Roles._
import services.visit.VisitService
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.webjars.play.WebJarsUtil
import play.api.Configuration
import play.api.mvc.{ControllerComponents, ResponseHeader, Result}
import play.api.libs.Files.TemporaryFileCreator
import play.api.http.HttpEntity
import scala.concurrent.{ExecutionContext, Future}
import storage.db.DB
import storage.es.migration.AnnotationMigrationUtil
import transform.tiling.TilingService

@Singleton
class BackupAdminController @Inject() (
    val components: ControllerComponents,
    val config: Configuration,
    val migrationUtil: AnnotationMigrationUtil,
    val users: UserService,
    val visits: VisitService,
    val silhouette: Silhouette[Security.Env],
    implicit val db: DB,
    implicit val tilingService: TilingService,
    implicit val annotations: AnnotationService,
    implicit val documents: DocumentService,
    implicit val ctx: ExecutionContext,
    implicit val system: ActorSystem,
    implicit val tmpFileCreator: TemporaryFileCreator,
    implicit val webJarsUtil: WebJarsUtil
  ) extends BaseAuthController(components, config, documents, users) with BackupReader {

  

  def restore = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    request.body.asMultipartFormData.flatMap(_.file("backup")) match {
      case Some(formData) =>
        restoreBackup(formData.ref.path.toFile, runAsAdmin = true, forcedOwner = None).map { case (doc, fileparts) =>
          Ok
        }.recover { case t: Throwable =>
          t.printStackTrace()
          InternalServerError
        }

      case None =>
        Future.successful(BadRequest)
    }
  }

  def exportVisits = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    visits.scrollExport().map { path =>
      val fmt = DateTimeFormat.forPattern("yyyy-MM-dd")
      val source = FileIO.fromPath(path)
      val filename = s"visits-exported-${fmt.print(DateTime.now)}.csv"
      Result(
        header = ResponseHeader(200, Map("Content-Disposition" -> s"""attachment; filename="${filename}"""")),
        body = HttpEntity.Streamed(source, None, Some("text/csv"))
      )
    }
  }

  def deleteVisitsOlderThan(date: Option[String]) = silhouette.SecuredAction(Security.WithRole(Admin)).async { implicit request =>
    date match {
      case Some(_) =>
        Future.successful(BadRequest("User-provided dates not supported yet."))

      case _ =>
        val cutoffDate = DateTime.now minusMonths 6
        visits.deleteOlderThan(cutoffDate).map { success =>
          if (success) Ok("Done.")
          else InternalServerError("Something went wrong.")
        }
    }
  }

}