• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala HttpServletRequest类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中javax.servlet.http.HttpServletRequest的典型用法代码示例。如果您正苦于以下问题:Scala HttpServletRequest类的具体用法?Scala HttpServletRequest怎么用?Scala HttpServletRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HttpServletRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
  }
} 
开发者ID:erickzanardo,项目名称:spammer,代码行数:26,代码来源:HttpUtil.scala


示例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
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:27,代码来源:RequestFacade.scala


示例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 = {}
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:50,代码来源:CORSFilter.scala


示例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)
      }
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:52,代码来源:SystemResource.scala


示例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"
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:52,代码来源:QueueResource.scala


示例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")
      }
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:47,代码来源:LeaderResource.scala


示例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
        )))
      }
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:60,代码来源:DeploymentsResource.scala


示例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))
    }
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:53,代码来源:AppVersionsResource.scala


示例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", "")
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:61,代码来源:HttpEventSSEHandleTest.scala


示例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]
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:51,代码来源:TestAuthFixture.scala


示例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")
      }
    }

  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:52,代码来源:LoginController.scala


示例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")

  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:61,代码来源:UsersController.scala


示例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)
  }

} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:23,代码来源:BaseController.scala


示例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
  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:35,代码来源:GZipServletFilter.scala


示例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)
  }

} 
开发者ID:arangodb,项目名称:arangodb-spark-example,代码行数:50,代码来源:Server.scala


示例16: AdminServlet

//设置package包名称以及导入依赖的类
package org.eck.servlets

import java.util.logging.Logger
import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}

import com.google.gson.JsonParser
import org.eck.entities.Settings

class AdminServlet extends HttpServlet {
  val logger = Logger.getLogger("AdminServlet")

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    if (req.getParameter("json") != null) {
      val json = new JsonParser().parse(req.getParameter("json")).getAsJsonObject
      logger.info("Updating settings data " + json.toString)
      Settings.fromJson(json)
    }

    printForm(resp)
  }

  def printForm(resp: HttpServletResponse) = {
    resp.setContentType("text/html")
    resp.getWriter.append("<form action=\"/admin\">")
    resp.getWriter.append(" <textarea name=\"json\" rows=\"30\">")
    resp.getWriter.append(Settings.asJson.toString)
    resp.getWriter.append(" </textarea>")
    resp.getWriter.append(" <br/>")
    resp.getWriter.append(" <button type=\"submit\">Save</button>")
  }
} 
开发者ID:erickzanardo,项目名称:spammer,代码行数:32,代码来源:AdminServlet.scala


示例17: CustomPage

//设置package包名称以及导入依赖的类
package org.apache.spark.ui

import javax.servlet.http.HttpServletRequest

import scala.xml.Node

abstract class CustomPage(val name: String) extends WebUIPage("") {

  private[ui] var tab: SparkUITab = _
  private[ui] var title: String = _
  private[ui] var ui: SparkUI = _

  def attachRedirectHandler(
    srcPath: String,
    destPath: String,
    beforeRedirect: HttpServletRequest => Unit = x => (),
    basePath: String = "",
    httpMethods: Set[String] = Set("GET")): Unit = {

    // Can't use Jetty interface as it is shaded to org.spark-project; use reflection instead
    val createRedirectHandler = JettyUtils.getClass.getMethods.filter(_.getName == "createRedirectHandler").head
    val handler = createRedirectHandler.invoke(JettyUtils, srcPath, destPath, beforeRedirect, basePath, httpMethods)

    val attachHandler = ui.getClass.getMethods.filter(_.getName == "attachHandler").head
    attachHandler.invoke(ui, handler)
  }

  def renderPage(request: HttpServletRequest): Seq[Node]

  final override def render(request: HttpServletRequest): Seq[Node] = {
    val content = renderPage(request)
    UIUtils.headerSparkPage(title, content, tab, Some(5000))
  }

} 
开发者ID:kakao,项目名称:cuesheet,代码行数:36,代码来源:CustomPage.scala


示例18: PlayerServlet

//设置package包名称以及导入依赖的类
package org.leanpoker.player

import javax.servlet.annotation.WebServlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import com.google.gson.JsonParser

@WebServlet(Array("/"))
class PlayerServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    resp.getWriter.print("Scala player is running")
  }

  @Override
  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) {
    req.getParameter("action") match {
      case "bet_request" =>
        val gameState = req.getParameter("game_state")
        resp.getWriter.print(Player.betRequest(new JsonParser().parse(gameState)))
      case "showdown" =>
        val gameState = req.getParameter("game_state")
        Player.showdown(new JsonParser().parse(gameState))
      case _ =>
        resp.getWriter.print(Player.VERSION)
    }
  }
} 
开发者ID:wlk,项目名称:poker-player-funny-chicken,代码行数:29,代码来源:PlayerServlet.scala


示例19: doGet

//设置package包名称以及导入依赖的类
package com.clay.web.servlets

import java.io._
import java.util.ResourceBundle
import javax.activation.MimetypesFileTypeMap
import javax.servlet.ServletConfig
import javax.servlet.annotation.WebServlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import org.springframework.util.StreamUtils



    override def doGet(req: HttpServletRequest, response: HttpServletResponse): Unit = {
        // We only support HTTP/1.0 and HTTP/1.1
        if (!req.getProtocol.endsWith("1.0") && !req.getProtocol.endsWith("1.1")) {
            throw new BadRequestServletErrorException()
        }

        val file = new File(resourcePath + "/" + req.getPathInfo)
        if (file.isDirectory) {
            throw new UnauthorizedServletErrorException()
        }

        if (!file.exists()) {
            throw new NotFoundServletErrorException()
        }

        var in: InputStream = null
        try {
            in = new FileInputStream(file)
            response.setContentType(mimeType.getContentType(file))
            response.setContentLength(in.available())
            StreamUtils.copy(in, response.getOutputStream.asInstanceOf[OutputStream])
        } finally {
            if (in != null) {
                try {
                    in.close()
                } catch {
                    case ex: Exception => // Ignore
                }
            }
        }

    }
} 
开发者ID:guynir,项目名称:clay,代码行数:47,代码来源:ResourcesServlet.scala


示例20: RackServer

//设置package包名称以及导入依赖的类
package coder36.rack

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import com.typesafe.scalalogging.LazyLogging
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ServletContextHandler, ServletHolder}

import scala.collection.mutable.Map

class RackServer extends LazyLogging {

  val port : Int = 8080
  var path : String = ""

  val apps = scala.collection.mutable.Map[String,RackServlet]()

  def map(path: String) : RackServer = {
    this.path = path
    this
  }

  def onto(rack: Rack) = {
    apps(path) = new RackServlet(rack, path)
  }

  def start() : RackServer = {
    val context = new ServletContextHandler(ServletContextHandler.SESSIONS)
    context.setContextPath("/")
    val server = new Server(port)
    server.setHandler(context)
    apps.foreach( app => context.addServlet(new ServletHolder(app._2), (app._1 + "/*").replaceAll("//", "/")) )
    println(s"\u001B[34mRack started... listening for HTTP on /0.0.0.0:${port}")
    server.start
    this
  }

}

class RackServlet(val rack: Rack, val path: String)  extends HttpServlet {

  override def service(request: HttpServletRequest, response: HttpServletResponse) {
    val res = Middleware.BaseRack( rack, request, response ).call(Map('base_path -> path))
    val status = res._1
    val headers = res._2
    val body = res._3
    response.setStatus(status)
    headers.foreach( (h) => response.addHeader(h._1, h._2))
    if( body != null ) response.getWriter().write(body)
  }
} 
开发者ID:coder36,项目名称:scalarack,代码行数:52,代码来源:Rackup.scala



注:本文中的javax.servlet.http.HttpServletRequest类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala RegexParsers类代码示例发布时间:2022-05-23
下一篇:
Scala JValue类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap