本文整理汇总了Scala中javax.servlet.http.HttpServletRequest类的典型用法代码示例。如果您正苦于以下问题:Scala HttpServletRequest类的具体用法?Scala HttpServletRequest怎么用?Scala HttpServletRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpServletRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: HttpUtil
//设置package包名称以及导入依赖的类
package org.eck.utils
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import com.google.gson.{JsonElement, JsonParser, JsonObject}
object HttpUtil {
def readBody(request: HttpServletRequest): String = {
val reader = request.getReader
val sb = new StringBuilder
var line = ""
while({line = reader.readLine(); line != null}) sb.append(line)
sb.toString
}
def readBodyAsJson(request: HttpServletRequest): JsonObject = {
val parser = new JsonParser
parser.parse(readBody(request)).getAsJsonObject
}
def writeJson(response: HttpServletResponse, json: JsonElement) = {
response.addHeader("Content-Type", "application/json")
response.getWriter.print(json.toString)
}
}
示例2: RequestFacade
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package api
import javax.servlet.http.HttpServletRequest
import mesosphere.marathon.plugin.http.HttpRequest
import mesosphere.marathon.stream._
class RequestFacade(request: HttpServletRequest, path: String) extends HttpRequest {
def this(request: HttpServletRequest) = this(request, request.getRequestURI)
// Jersey will not allow calls to the request object from another thread
// To circumvent that, we have to copy all data during creation
val headers: Map[String, Seq[String]] = request.getHeaderNames.seq.map(header =>
header.toLowerCase -> request.getHeaders(header).seq)(collection.breakOut)
val cookies = request.getCookies
val params = request.getParameterMap
val remoteAddr = request.getRemoteAddr
val remotePort = request.getRemotePort
val localAddr = request.getLocalAddr
val localPort = request.getLocalPort
override def header(name: String): Seq[String] = headers.getOrElse(name.toLowerCase, Seq.empty)
override def requestPath: String = path
override def cookie(name: String): Option[String] = cookies.find(_.getName == name).map(_.getValue)
override def queryParam(name: String): Seq[String] = Option(params.get(name)).map(_.to[Seq]).getOrElse(Seq.empty)
override def method: String = request.getMethod
}
示例3: CORSFilter
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package api
import javax.inject.Inject
import javax.servlet._
import javax.servlet.http.{ HttpServletRequest, HttpServletResponse }
import mesosphere.marathon.stream._
class CORSFilter @Inject() (config: MarathonConf) extends Filter {
// Map access_control_allow_origin flag into separate headers
lazy val maybeOrigins: Option[Seq[String]] =
config.accessControlAllowOrigin.get.map { configValue =>
configValue.split(",").map(_.trim)(collection.breakOut)
}
override def init(filterConfig: FilterConfig): Unit = {}
override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
response match {
case httpResponse: HttpServletResponse if maybeOrigins.isDefined =>
request match {
case httpRequest: HttpServletRequest =>
maybeOrigins.foreach { origins =>
origins.foreach { origin =>
httpResponse.setHeader("Access-Control-Allow-Origin", origin)
}
}
// Add all headers from request as accepted headers
// Unclear why `toTraversableOnce` isn't being applied implicitly here.
val accessControlRequestHeaders =
toTraversableOnce(httpRequest.getHeaders("Access-Control-Request-Headers")).flatMap(_.split(","))
httpResponse.setHeader("Access-Control-Allow-Headers", accessControlRequestHeaders.mkString(", "))
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
httpResponse.setHeader("Access-Control-Max-Age", "86400")
case _ =>
}
case _ => // Ignore other responses
}
chain.doFilter(request, response)
}
override def destroy(): Unit = {}
}
示例4: SystemResource
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api
import java.io.StringWriter
import java.util.concurrent.TimeUnit
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.{ Context, MediaType, Response }
import com.codahale.metrics.{ MetricFilter, MetricRegistry }
import com.codahale.metrics.annotation.Timed
import com.codahale.metrics.json.MetricsModule
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.inject.Inject
import mesosphere.marathon.MarathonConf
import mesosphere.marathon.io.IO
import mesosphere.marathon.plugin.auth.AuthorizedResource.SystemConfig
import mesosphere.marathon.plugin.auth.{ Authenticator, Authorizer, ViewResource }
@Path("")
@Consumes(Array(MediaType.APPLICATION_JSON))
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
class SystemResource @Inject() (metrics: MetricRegistry, val config: MarathonConf)(implicit
val authenticator: Authenticator,
val authorizer: Authorizer) extends RestResource with AuthResource {
private[this] lazy val mapper = new ObjectMapper().registerModule(
new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL)
)
@GET
@Path("ping")
@Timed
def ping(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
withAuthorization(ViewResource, SystemConfig){
ok("pong")
}
}
@GET
@Path("metrics")
@Timed
def metrics(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
withAuthorization(ViewResource, SystemConfig){
IO.using(new StringWriter()) { writer =>
mapper.writer().writeValue(writer, metrics)
ok(writer.toString)
}
}
}
}
示例5: QueueResource
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2
import javax.inject.Inject
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.{ Context, MediaType, Response }
import com.codahale.metrics.annotation.Timed
import mesosphere.marathon.MarathonConf
import mesosphere.marathon.api.{ AuthResource, MarathonMediaType }
import mesosphere.marathon.core.base.Clock
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.plugin.auth.{ Authenticator, Authorizer, UpdateRunSpec, ViewRunSpec }
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.raml.Raml
@Path("v2/queue")
@Consumes(Array(MediaType.APPLICATION_JSON))
class QueueResource @Inject() (
clock: Clock,
launchQueue: LaunchQueue,
val authenticator: Authenticator,
val authorizer: Authorizer,
val config: MarathonConf) extends AuthResource {
@GET
@Timed
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
def index(@Context req: HttpServletRequest, @QueryParam("embed") embed: java.util.Set[String]): Response = authenticated(req) { implicit identity =>
val embedLastUnusedOffers = embed.contains(QueueResource.EmbedLastUnusedOffers)
val infos = launchQueue.listWithStatistics.filter(t => t.inProgress && isAuthorized(ViewRunSpec, t.runSpec))
ok(Raml.toRaml((infos, embedLastUnusedOffers, clock)))
}
@DELETE
@Path("""{appId:.+}/delay""")
def resetDelay(
@PathParam("appId") id: String,
@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
val appId = id.toRootPath
val maybeApp = launchQueue.list.find(_.runSpec.id == appId).map(_.runSpec)
withAuthorization(UpdateRunSpec, maybeApp, notFound(s"Application $appId not found in tasks queue.")) { app =>
launchQueue.resetDelay(app)
noContent
}
}
}
object QueueResource {
val EmbedLastUnusedOffers = "lastUnusedOffers"
}
示例6: LeaderResource
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2
import javax.servlet.http.HttpServletRequest
import javax.ws.rs.core.{ Context, Response }
import javax.ws.rs.{ DELETE, GET, Path, Produces }
import com.google.inject.Inject
import mesosphere.chaos.http.HttpConf
import mesosphere.marathon.MarathonConf
import mesosphere.marathon.api.{ AuthResource, MarathonMediaType, RestResource }
import mesosphere.marathon.core.election.ElectionService
import mesosphere.marathon.plugin.auth._
@Path("v2/leader")
class LeaderResource @Inject() (
electionService: ElectionService,
val config: MarathonConf with HttpConf,
val authenticator: Authenticator,
val authorizer: Authorizer)
extends RestResource with AuthResource {
@GET
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
def index(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
withAuthorization(ViewResource, AuthorizedResource.Leader) {
electionService.leaderHostPort match {
case None => notFound("There is no leader")
case Some(leader) =>
ok(jsonObjString("leader" -> leader))
}
}
}
@DELETE
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
def delete(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
withAuthorization(UpdateResource, AuthorizedResource.Leader) {
if (electionService.isLeader) {
electionService.abdicateLeadership()
ok(jsonObjString("message" -> "Leadership abdicated"))
} else {
notFound("There is no leader")
}
}
}
}
示例7: DeploymentsResource
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2
import javax.inject.Inject
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.Response.Status._
import javax.ws.rs.core.{ Context, MediaType, Response }
import mesosphere.marathon.api.v2.json.Formats._
import mesosphere.marathon.api.{ AuthResource, MarathonMediaType }
import mesosphere.marathon.core.group.GroupManager
import mesosphere.marathon.plugin.auth._
import mesosphere.marathon.{ MarathonConf, MarathonSchedulerService }
import mesosphere.util.Logging
@Path("v2/deployments")
@Consumes(Array(MediaType.APPLICATION_JSON))
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
class DeploymentsResource @Inject() (
service: MarathonSchedulerService,
groupManager: GroupManager,
val authenticator: Authenticator,
val authorizer: Authorizer,
val config: MarathonConf)
extends AuthResource
with Logging {
@GET
def running(@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
val infos = result(service.listRunningDeployments())
.filter(_.plan.affectedRunSpecs.exists(isAuthorized(ViewRunSpec, _)))
ok(infos)
}
@DELETE
@Path("{id}")
def cancel(
@PathParam("id") id: String,
@DefaultValue("false")@QueryParam("force") force: Boolean,
@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
val plan = result(service.listRunningDeployments()).find(_.plan.id == id).map(_.plan)
plan.fold(notFound(s"DeploymentPlan $id does not exist")) { deployment =>
deployment.affectedRunSpecs.foreach(checkAuthorization(UpdateRunSpec, _))
if (force) {
// do not create a new deployment to return to the previous state
log.info(s"Canceling deployment [$id]")
service.cancelDeployment(id)
status(ACCEPTED) // 202: Accepted
} else {
// create a new deployment to return to the previous state
deploymentResult(result(groupManager.updateRoot(
deployment.revert,
force = true
)))
}
}
}
}
示例8: AppVersionsResource
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api.v2
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.{ Context, MediaType, Response }
import com.codahale.metrics.annotation.Timed
import mesosphere.marathon.api.v2.json.Formats._
import mesosphere.marathon.api.{ AuthResource, MarathonMediaType }
import mesosphere.marathon.core.group.GroupManager
import mesosphere.marathon.plugin.auth.{ Authenticator, Authorizer, ViewRunSpec }
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.state.Timestamp
import mesosphere.marathon.{ MarathonConf, MarathonSchedulerService }
import org.slf4j.LoggerFactory
@Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
@Consumes(Array(MediaType.APPLICATION_JSON))
class AppVersionsResource(
service: MarathonSchedulerService,
groupManager: GroupManager,
val authenticator: Authenticator,
val authorizer: Authorizer,
val config: MarathonConf) extends AuthResource {
val log = LoggerFactory.getLogger(getClass.getName)
@GET
@Timed
def index(
@PathParam("appId") appId: String,
@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
val id = appId.toRootPath
withAuthorization(ViewRunSpec, result(groupManager.app(id)), unknownApp(id)) { _ =>
ok(jsonObjString("versions" -> service.listAppVersions(id)))
}
}
@GET
@Timed
@Path("{version}")
def show(
@PathParam("appId") appId: String,
@PathParam("version") version: String,
@Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
val id = appId.toRootPath
val timestamp = Timestamp(version)
withAuthorization(ViewRunSpec, service.getApp(id, timestamp), unknownApp(id, Some(timestamp))) { app =>
ok(jsonString(app))
}
}
}
示例9: HttpEventSSEHandleTest
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package core.event.impl.stream
import java.util.Collections
import javax.servlet.http.HttpServletRequest
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.eclipse.jetty.servlets.EventSource.Emitter
import org.scalatest.{ GivenWhenThen, Matchers }
import mesosphere.marathon.stream._
class HttpEventSSEHandleTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {
test("events should be filtered") {
Given("An emiter")
val emitter = mock[Emitter]
Given("An request with params")
val req = mock[HttpServletRequest]
req.getParameterMap returns Map("event_type" -> Array("xyz"))
Given("handler for request is created")
val handle = new HttpEventSSEHandle(req, emitter)
When("Want to sent unwanted event")
handle.sendEvent("any event", "")
Then("event should NOT be sent")
verify(emitter, never).event("any event", "")
When("Want to sent subscribed event")
handle.sendEvent("xyz", "")
Then("event should be sent")
verify(emitter).event("xyz", "")
}
test("events should NOT be filtered") {
Given("An emiter")
val emitter = mock[Emitter]
Given("An request without params")
val req = mock[HttpServletRequest]
req.getParameterMap returns Collections.emptyMap()
Given("handler for request is created")
val handle = new HttpEventSSEHandle(req, emitter)
When("Want to sent event")
handle.sendEvent("any event", "")
Then("event should NOT be sent")
verify(emitter).event("any event", "")
When("Want to sent event")
handle.sendEvent("xyz", "")
Then("event should be sent")
verify(emitter).event("xyz", "")
}
}
示例10: TestAuthFixture
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api
import java.util.Collections
import javax.servlet.http.{ HttpServletRequest, HttpServletResponse }
import mesosphere.marathon.plugin.auth.{ Authenticator, AuthorizedAction, Authorizer, Identity }
import mesosphere.marathon.plugin.http.{ HttpRequest, HttpResponse }
import mesosphere.marathon.test.Mockito
import scala.concurrent.Future
class TestAuthFixture() extends Mockito {
type Auth = Authenticator with Authorizer
var identity: Identity = new Identity {}
var authenticated: Boolean = true
var authorized: Boolean = true
var authFn: Any => Boolean = { _ => true }
val UnauthorizedStatus = 401
val NotAuthenticatedStatus = 403
def auth: Auth = new Authorizer with Authenticator {
override def authenticate(request: HttpRequest): Future[Option[Identity]] = {
Future.successful(if (authenticated) Some(identity) else None)
}
override def handleNotAuthenticated(request: HttpRequest, response: HttpResponse): Unit = {
response.status(NotAuthenticatedStatus)
}
override def handleNotAuthorized(principal: Identity, response: HttpResponse): Unit = {
response.status(UnauthorizedStatus)
}
override def isAuthorized[Resource](
principal: Identity,
action: AuthorizedAction[Resource],
resource: Resource): Boolean = {
authorized && authFn(resource)
}
}
var request: HttpServletRequest = {
val req = mock[HttpServletRequest]
req.getHeaderNames returns Collections.emptyEnumeration()
req.getHeaders(any) returns Collections.emptyEnumeration()
req
}
var response: HttpServletResponse = mock[HttpServletResponse]
}
示例11: LoginController
//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import co.informatica.mvc.models.User
import co.informatica.mvc.views.LoginFormTemplate
class LoginController extends BaseController {
override lazy val template = LoginFormTemplate
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
super.doGet(req, resp)
resp.setCharacterEncoding("UTF-8")
resp.getWriter().print("<!DOCTYPE html>" + template.message())
}
override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
super.doPost(req, resp)
val id = ""
val name = req.getParameter("name")
val email = req.getParameter("email")
val user = new User(id, name, email)
val findUser = User.find(user)
findUser match {
case Some(findUser) => {
val user = findUser
val session = req.getSession()
session.setAttribute("id", user.id)
session.setAttribute("name", user.name)
session.setAttribute("email", user.email)
println("Logged User:")
println(user.name)
println(user.email)
resp.sendRedirect("/")
}
case None => {
resp.sendRedirect("/login")
}
}
}
}
示例12: UsersController
//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers
import javax.servlet.http.{HttpServletRequest, HttpServletResponse, HttpSession}
import co.informatica.mvc.models.User
import co.informatica.mvc.views.{UserFormTemplate, UsersTemplate}
class UsersController extends BaseController {
override lazy val template = UsersTemplate
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
super.doGet(req, resp)
val session: HttpSession = req.getSession(false)
if (session != null) {
val name = session.getAttribute("name").toString()
resp.setCharacterEncoding("UTF-8")
if (req.getPathInfo == null) {
val users = User.getAll
template.entities = Option(users)
resp.getWriter().print("<!DOCTYPE html>" + template.message(name))
} else if (req.getPathInfo() == "/create") {
resp.getWriter().print("<!DOCTYPE html>" + UserFormTemplate.message(name))
} else if (req.getPathInfo() contains "delete") {
val oid = req.getPathInfo().substring(req.getPathInfo().lastIndexOf("/") + 1)
User.delete(oid)
resp.sendRedirect("/users")
} else {
resp.sendRedirect("/users")
}
} else {
resp.sendRedirect("/login")
}
}
override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
super.doPost(req, resp)
val id = ""
val name = req.getParameter("name")
val email = req.getParameter("email")
val user = new User(id, name, email)
val createdUser = User.create(user)
println("Created User:")
println(createdUser.id)
println(createdUser.name)
println(createdUser.email)
resp.sendRedirect("/users")
}
}
示例13: doGet
//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import co.informatica.mvc.models.Model
import co.informatica.mvc.views.BaseTemplate
trait BaseController extends HttpServlet {
lazy val model: Model = null
lazy val template: BaseTemplate = null
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
println("GET: " + this.getClass.getName)
println("getPathInfo:")
println(req.getPathInfo())
}
override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
println("POST: " + this.getClass.getName)
}
}
示例14: GZipServletFilter
//设置package包名称以及导入依赖的类
package co.informatica.mvc.filters
import java.io.IOException
import javax.servlet._
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
class GZipServletFilter extends Filter {
@throws[ServletException]
override def init(filterConfig: FilterConfig): Unit = {
}
override def destroy(): Unit = {
}
@throws[IOException]
@throws[ServletException]
override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
val httpRequest = request.asInstanceOf[HttpServletRequest]
val httpResponse = response.asInstanceOf[HttpServletResponse]
if (acceptsGZipEncoding(httpRequest)) {
httpResponse.addHeader("Content-Encoding", "gzip")
val gzipResponse = new GZipServletResponseWrapper(httpResponse)
chain.doFilter(request, gzipResponse)
gzipResponse.close
}
else chain.doFilter(request, response)
}
private def acceptsGZipEncoding(httpRequest: HttpServletRequest) = {
val acceptEncoding = httpRequest.getHeader("Accept-Encoding")
acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1
}
}
示例15: Server
//设置package包名称以及导入依赖的类
package com.arangodb
import scala.beans.BeanProperty
import org.eclipse.jetty.server.Request
import org.eclipse.jetty.server.handler.AbstractHandler
import com.arangodb.Server.Movie
import com.arangodb.util.MapBuilder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
object Server {
private val COLLECTION_NAME = "ring_movies"
class Handler(arangoDB: ArangoDB) extends AbstractHandler {
override def handle(target: String,
req: Request,
httpReq: HttpServletRequest,
httpRes: HttpServletResponse) = {
httpRes.setContentType("text/html")
httpRes.setStatus(HttpServletResponse.SC_OK)
httpRes.getWriter().println("<h1>all movies that have \"Lord.*Rings\" in their title</h1>")
val cursor = getMovies(arangoDB)
while (cursor.hasNext()) {
httpRes.getWriter().println(cursor.next().title + "<br />")
}
req.setHandled(true)
}
}
def main(args: Array[String]): Unit = {
val arangoDB = new ArangoDB.Builder().host("arangodb-proxy.marathon.mesos").user("root").build();
val server = new org.eclipse.jetty.server.Server(8080)
server.setHandler(new Handler(arangoDB))
server.start
}
def getMovies(arangoDB: ArangoDB): ArangoCursor[Movie] = {
arangoDB.db().query("for doc in @@col return doc", new MapBuilder().put("@col", COLLECTION_NAME).get(), null, classOf[Movie])
}
case class Movie(@BeanProperty title: String) {
def this() = this(title = null)
}
}