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

Scala HttpServletResponse类代码示例

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

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



在下文中一共展示了HttpServletResponse类的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: CacheDisablingFilter

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import javax.servlet._
import javax.servlet.http.HttpServletResponse

class CacheDisablingFilter extends Filter {
  override def init(filterConfig: FilterConfig): Unit = {}

  override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    response match {
      case httpResponse: HttpServletResponse =>
        httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1
        httpResponse.setHeader("Pragma", "no-cache") // HTTP 1.0
        httpResponse.setHeader("Expires", "0") // Proxies
      case _ => // ignore other responses
    }

    chain.doFilter(request, response)
  }

  override def destroy(): Unit = {}
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:23,代码来源:CacheDisablingFilter.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: LimitConcurrentRequestsFilter

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import java.util.concurrent.Semaphore
import javax.servlet._
import javax.servlet.http.HttpServletResponse


class LimitConcurrentRequestsFilter(concurrentOption: Option[Int]) extends Filter {

  val concurrent = concurrentOption.getOrElse(0)
  val semaphore = new Semaphore(concurrent)
  val filterFunction = concurrentOption.map(_ => withSemaphore _).getOrElse(pass _)

  def withSemaphore(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    if (semaphore.tryAcquire()) {
      try { chain.doFilter(request, response) }
      finally { semaphore.release() }
    } else {
      response match {
        case r: HttpServletResponse => r.sendError(503, s"Too many concurrent requests! Allowed: $concurrent.")
        case r: ServletResponse => throw new IllegalArgumentException(s"Expected http response but got $response")
      }
    }
  }

  def pass(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    chain.doFilter(request, response)
  }

  override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    filterFunction(request, response, chain)
  }

  override def init(filterConfig: FilterConfig): Unit = {}
  override def destroy(): Unit = {}
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:37,代码来源:LimitConcurrentRequestsFilter.scala


示例5: HttpEventStreamServletTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.event.impl.stream

import javax.servlet.http.HttpServletResponse

import akka.actor.ActorRef
import mesosphere.marathon._
import mesosphere.marathon.api.TestAuthFixture
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.scalatest.{ GivenWhenThen, Matchers }

class HttpEventStreamServletTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {

  test("access without authentication is denied") {
    Given("An unauthenticated request")
    val f = new Fixture
    val resource = f.streamServlet()
    val response = mock[HttpServletResponse]
    f.auth.authenticated = false

    When("we try to attach to the event stream")
    resource.doGet(f.auth.request, response)

    Then("we receive a NotAuthenticated response")
    verify(response).setStatus(f.auth.NotAuthenticatedStatus)
  }

  test("access without authorization is denied") {
    Given("An unauthorized request")
    val f = new Fixture
    val resource = f.streamServlet()
    val response = mock[HttpServletResponse]
    f.auth.authenticated = true
    f.auth.authorized = false

    When("we try to attach to the event stream")
    resource.doGet(f.auth.request, response)

    Then("we receive a Unauthorized response")
    verify(response).setStatus(f.auth.UnauthorizedStatus)
  }

  class Fixture {
    val actor = mock[ActorRef]
    val auth = new TestAuthFixture
    val config = AllConf.withTestConfig("--event_subscriber", "http_callback")
    def streamServlet() = new HttpEventStreamServlet(actor, config, auth.auth, auth.auth)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:49,代码来源:HttpEventStreamServletTest.scala


示例6: 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


示例7: 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


示例8: 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


示例9: 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


示例10: GZipServletResponseWrapper

//设置package包名称以及导入依赖的类
package co.informatica.mvc.filters

import java.io.{IOException, OutputStreamWriter, PrintWriter}
import javax.servlet.ServletOutputStream
import javax.servlet.http.{HttpServletResponse, HttpServletResponseWrapper}

class GZipServletResponseWrapper(val response: HttpServletResponse) extends HttpServletResponseWrapper(response) {
  private var gzipOutputStream: GZipServletOutputStream = null
  private var printWriter: PrintWriter = null

  def close(): Unit = { //PrintWriter.close does not throw exceptions.
    //Hence no try-catch block.
    if (this.printWriter != null) this.printWriter.close()
    if (this.gzipOutputStream != null) this.gzipOutputStream.close
  }

  override def flushBuffer(): Unit = { //PrintWriter.flush() does not throw exception
    if (this.printWriter != null) this.printWriter.flush()
    var exception1: IOException = null
    try
        if (this.gzipOutputStream != null) this.gzipOutputStream.flush
    catch {
      case e: IOException =>
        exception1 = e
    }
    var exception2: IOException = null
    try
      super.flushBuffer()
    catch {
      case e: IOException =>
        exception2 = e
    }
    if (exception1 != null) throw exception1
    if (exception2 != null) throw exception2
  }

  override def getOutputStream: ServletOutputStream = {
    if (this.printWriter != null) throw new IllegalStateException("PrintWriter obtained already - cannot get OutputStream")
    if (this.gzipOutputStream == null) this.gzipOutputStream = new GZipServletOutputStream(getResponse.getOutputStream)
    this.gzipOutputStream
  }

  override def getWriter: PrintWriter = {
    if (this.printWriter == null && this.gzipOutputStream != null) throw new IllegalStateException("OutputStream obtained already - cannot get PrintWriter")
    if (this.printWriter == null) {
      this.gzipOutputStream = new GZipServletOutputStream(getResponse.getOutputStream)
      this.printWriter = new PrintWriter(new OutputStreamWriter(this.gzipOutputStream, getResponse.getCharacterEncoding))
    }
    this.printWriter
  }

  override def setContentLength(len: Int): Unit = {
    //ignore, since content length of zipped content
    //does not match content length of unzipped content.
  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:57,代码来源:GZipServletResponseWrapper.scala


示例11: 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


示例12: 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


示例13: 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


示例14: 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


示例15: 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


示例16: 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


示例17: ExceptionHandlerAdvice

//设置package包名称以及导入依赖的类
package com.github.yingzhuo.springboot.scala.demo.controller

import javax.servlet.http.HttpServletResponse

import kushan.scala.error.BusinessException
import kushan.scala.logging.LazyLogging
import kushan.scala.web.{HttpStatus, Json}
import org.springframework.web.bind.annotation.{ExceptionHandler, RestControllerAdvice}

@RestControllerAdvice
class ExceptionHandlerAdvice extends LazyLogging {

    @ExceptionHandler
    def handle(ex: BusinessException, response: HttpServletResponse): Json = {
        slf.debug("???? {} => {}", ex.code.toString, ex.getMessage)
        response.setStatus(ex.code)
        Json(HttpStatus(ex.code), ex.getMessage)
    }

    @ExceptionHandler
    def handle(ex: RuntimeException, response: HttpServletResponse): Json = {
        slf.debug("???? {} => {}", ex.getClass.getName, ex.getMessage)
        response.setStatus(500)
        Json(HttpStatus.INTERNAL_SERVER_ERROR, null)
    }

} 
开发者ID:yingzhuo,项目名称:springboot-scala-demo,代码行数:28,代码来源:ExceptionHandlerAdvice.scala


示例18: ApiAuthenticationFilter

//设置package包名称以及导入依赖的类
package gitbucket.core.servlet

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

import gitbucket.core.model.Account
import gitbucket.core.service.SystemSettingsService.SystemSettings
import gitbucket.core.service.{AccessTokenService, AccountService, SystemSettingsService}
import gitbucket.core.util.{AuthUtil, Keys}


class ApiAuthenticationFilter extends Filter with AccessTokenService with AccountService with SystemSettingsService {

  override def init(filterConfig: FilterConfig): Unit = {}

  override def destroy(): Unit = {}

  override def doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain): Unit = {
    implicit val request = req.asInstanceOf[HttpServletRequest]
    implicit val session = req.getAttribute(Keys.Request.DBSession).asInstanceOf[slick.jdbc.JdbcBackend#Session]
    val response = res.asInstanceOf[HttpServletResponse]
    Option(request.getHeader("Authorization")).map{
      case auth if auth.startsWith("token ") => AccessTokenService.getAccountByAccessToken(auth.substring(6).trim).toRight(())
      case auth if auth.startsWith("Basic ") => doBasicAuth(auth, loadSystemSettings(), request).toRight(())
      case _ => Left(())
    }.orElse{
      Option(request.getSession.getAttribute(Keys.Session.LoginAccount).asInstanceOf[Account]).map(Right(_))
    } match {
      case Some(Right(account)) => request.setAttribute(Keys.Session.LoginAccount, account); chain.doFilter(req, res)
      case None => chain.doFilter(req, res)
      case Some(Left(_)) => {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED)
        response.setContentType("application/json; charset=utf-8")
        val w = response.getWriter()
        w.print("""{ "message": "Bad credentials" }""")
        w.close()
      }
    }
  }

  def doBasicAuth(auth: String, settings: SystemSettings, request: HttpServletRequest): Option[Account] = {
    implicit val session = request.getAttribute(Keys.Request.DBSession).asInstanceOf[slick.jdbc.JdbcBackend#Session]
    val Array(username, password) = AuthUtil.decodeAuthHeader(auth).split(":", 2)
    authenticate(settings, username, password)
  }
} 
开发者ID:piggymumu,项目名称:gitbucket,代码行数:47,代码来源:ApiAuthenticationFilter.scala


示例19: PluginAssetsServlet

//设置package包名称以及导入依赖的类
package gitbucket.core.servlet

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

import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.util.FileUtil
import org.apache.commons.io.IOUtils


class PluginAssetsServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse): Unit = {
    val assetsMappings = PluginRegistry().getAssetsMappings
    val path = req.getRequestURI.substring(req.getContextPath.length)

    assetsMappings
      .find    { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) }
      .flatMap { case (prefix, resourcePath, classLoader) =>
        val resourceName = path.substring(("/plugin-assets" + prefix).length)
        Option(classLoader.getResourceAsStream(resourcePath.replaceFirst("^/", "") + resourceName))
      }
      .map { in =>
        try {
          val bytes = IOUtils.toByteArray(in)
          resp.setContentLength(bytes.length)
          resp.setContentType(FileUtil.getContentType(path, bytes))
          resp.setHeader("Cache-Control", "max-age=3600")
          resp.getOutputStream.write(bytes)
        } finally {
          in.close()
        }
      }
      .getOrElse {
        resp.setStatus(404)
      }
  }

} 
开发者ID:piggymumu,项目名称:gitbucket,代码行数:39,代码来源:PluginAssetsServlet.scala


示例20: AuthUtil

//设置package包名称以及导入依赖的类
package gitbucket.core.util

import java.util.Base64
import javax.servlet.http.HttpServletResponse


object AuthUtil {
  def requireAuth(response: HttpServletResponse): Unit = {
    response.setHeader("WWW-Authenticate", "BASIC realm=\"GitBucket\"")
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED)
  }

  def decodeAuthHeader(header: String): String = {
    try {
      new String(Base64.getDecoder.decode(header.substring(6)))
    } catch {
      case _: Throwable => ""
    }
  }
} 
开发者ID:piggymumu,项目名称:gitbucket,代码行数:21,代码来源:AuthUtil.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala FilenameFilter类代码示例发布时间:2022-05-23
下一篇:
Scala DateFormat类代码示例发布时间: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