本文整理汇总了Scala中javax.ws.rs.core.Response类的典型用法代码示例。如果您正苦于以下问题:Scala Response类的具体用法?Scala Response怎么用?Scala Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: DataResourceService
//设置package包名称以及导入依赖的类
package com.martinsnyder.service
import com.martinsnyder.api.DataResourceApi.AnyDataResourceApi
import com.martinsnyder.api._
import javax.ws.rs.{ GET, Path, PathParam, Produces }
import javax.ws.rs.core.{ MediaType, Response }
abstract class DataResourceService(api: AnyDataResourceApi) extends Service {
@GET
@Produces(Array(MediaType.APPLICATION_JSON))
def query(): Response =
toResponseBuilder(api.query()).build()
@GET
@Path("/{id}")
@Produces(Array(MediaType.APPLICATION_JSON))
def retrieve(@PathParam("id") id: ResourceId): Response =
toResponseBuilder(api.retrieve(id)).build()
@GET
@Path("/{id}/pointer")
@Produces(Array(MediaType.APPLICATION_JSON))
def resourcePointer(@PathParam("id") id: ResourceId): Response =
toResponseBuilder(api.resourcePointer(id)).build()
}
示例2: CertificateResponse
//设置package包名称以及导入依赖的类
// Copyright (C) 2016 Grier Forensics. All Rights Reserved.
package com.grierforensics.greatdane
import javax.ws.rs._
import javax.ws.rs.core.{MediaType, Response}
case class CertificateResponse(certificates: Seq[CertificateDetails])
case class ZoneLineResponse(zoneLines: Seq[String])
@Path("/")
@Produces(Array(MediaType.APPLICATION_JSON))
class Resource(engine: Engine) {
val genson = GensonConfig.genson
@POST
@Path("{email}/dnsZoneLineForCert")
def dnsZoneLine(@PathParam("email") email: String, pemEncodedCertificate: String): String = {
val zoneLine = engine.dnsZoneLine(email, pemEncodedCertificate)
genson.serialize(zoneLine)
}
}
示例3: 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)
}
}
}
}
示例4: 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"
}
示例5: 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")
}
}
}
}
示例6: 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
)))
}
}
}
}
示例7: 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))
}
}
}
示例8: ResponseFacade
//设置package包名称以及导入依赖的类
package mesosphere.marathon.api
import java.net.URI
import javax.ws.rs.core.Response.Status
import javax.ws.rs.core.{ NewCookie, Response }
import mesosphere.marathon.plugin.http.HttpResponse
class ResponseFacade extends HttpResponse {
private[this] var builder = Response.status(Status.UNAUTHORIZED)
override def header(name: String, value: String): Unit = builder.header(name, value)
override def status(code: Int): Unit = builder = builder.status(code)
override def sendRedirect(location: String): Unit = {
builder.status(Status.TEMPORARY_REDIRECT).location(new URI(location))
}
override def cookie(name: String, value: String, maxAge: Int, secure: Boolean): Unit = {
builder.cookie(new NewCookie(name, value, null, null, null, maxAge, secure))
}
override def body(mediaType: String, bytes: Array[Byte]): Unit = {
builder.`type`(mediaType)
builder.entity(bytes)
}
def response: Response = builder.build()
}
示例9: lookupHex
//设置package包名称以及导入依赖的类
// Copyright (C) 2016 Grier Forensics. All Rights Reserved.
package com.grierforensics.danesmimeatoolset.rest
import java.security.cert.X509Certificate
import javax.ws.rs._
import javax.ws.rs.core.{MediaType, Response}
import com.grierforensics.danesmimeatoolset.service.{BadCertificateException, Context, GensonConfig}
import org.bouncycastle.cert.dane.DANEEntry
import org.bouncycastle.util.encoders.{DecoderException, Hex}
@GET
@Path("{email}/hex/{index}")
def lookupHex(@PathParam("email") email: String, @PathParam("index") index: Int): String = {
val result = lookupHex(email) match {
case results if results.isDefinedAt(index) => results(index)
case otherwise => throw new WebApplicationException(Response.status(404).entity("DANE not found for email address").build())
}
GensonConfig.genson.serialize(result)
}
// // // lookupDnsZoneLine
@GET
@Path("{email}/dnsZoneLine")
def lookupDnsZoneLine(@PathParam("email") email: String): Seq[String] = {
daneSmimeaService.fetchDaneEntries(email).map(daneSmimeaService.getDnsZoneLineForDaneEntry(_)) match {
case Nil => throw new WebApplicationException(Response.status(404).build())
case nonempty => nonempty
}
}
@GET
@Path("{email}/dnsZoneLine/{index}")
def lookupDnsZoneLine(@PathParam("email") email: String, @PathParam("index") index: Int): String = {
val result = lookupDnsZoneLine(email) match {
case results if results.isDefinedAt(index) => results(index)
case otherwise => throw new WebApplicationException(Response.status(404).entity("DANE not found for email address").build())
}
GensonConfig.genson.serialize(result)
}
// // // createDnsZoneLineAsText
@POST
@Path("{email}/dnsZoneLineForCert")
@Consumes(Array(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN))
def createDnsZoneLineAsText(@PathParam("email") email: String, certPem: String): String = {
try {
val cert: X509Certificate = daneSmimeaService.fromPem(certPem)
val de2: DANEEntry = daneSmimeaService.createDANEEntry(email, cert)
val result = daneSmimeaService.getDnsZoneLineForDaneEntry(de2)
GensonConfig.genson.serialize(result)
}
catch {
case [email protected](_: BadCertificateException | _: DecoderException) => throw new WebApplicationException(Response.status(400).entity(e.getMessage).build())
}
}
}
示例10: IllegalArgumentExceptionMapper
//设置package包名称以及导入依赖的类
package pl.scalare.main.exceptionmapper
import javax.ws.rs.core.Response.Status
import javax.ws.rs.core.{MediaType, Response}
import javax.ws.rs.ext.ExceptionMapper
import com.codahale.metrics.{Meter, MetricRegistry}
import io.dropwizard.jersey.errors.ErrorMessage
class IllegalArgumentExceptionMapper(val exceptions: Meter) extends ExceptionMapper[IllegalArgumentException] {
def this(metrics: MetricRegistry) = this(metrics.meter(getClass() + "exceptions"))
override def toResponse(exception: IllegalArgumentException): Response = {
exceptions.mark();
return Response.status(Status.BAD_REQUEST)
.header("X-YOU-SILLY", "true")
.`type`(MediaType.APPLICATION_JSON_TYPE)
.entity(new ErrorMessage(Status.BAD_REQUEST.getStatusCode(),
"You passed an illegal argument!"))
.build();
}
}
示例11: BookResource
//设置package包名称以及导入依赖的类
package org.littlewings.wildflyswarm.datasource
import javax.enterprise.context.ApplicationScoped
import javax.persistence.{EntityManager, PersistenceContext}
import javax.transaction.Transactional
import javax.ws.rs._
import javax.ws.rs.core.{Context, MediaType, Response, UriInfo}
@Path("book")
@ApplicationScoped
@Transactional
class BookResource {
@PersistenceContext
private[datasource] var entityManager: EntityManager = _
@GET
@Path("{isbn}")
@Produces(Array(MediaType.APPLICATION_JSON))
def find(@PathParam("isbn") isbn: String): Book =
entityManager.find(classOf[Book], isbn)
@PUT
@Consumes(Array(MediaType.APPLICATION_JSON))
@Produces(Array(MediaType.APPLICATION_JSON))
def register(book: Book, @Context uriInfo: UriInfo): Response = {
entityManager.persist(book)
Response.created(uriInfo.getRequestUriBuilder.path(book.isbn).build()).build
}
}
示例12: RestResource
//设置package包名称以及导入依赖的类
package com.mbesida.synchronizer.rest
import java.util.concurrent.TimeUnit
import javax.ws.rs._
import javax.ws.rs.container.{AsyncResponse, Suspended}
import javax.ws.rs.core.Response.Status
import javax.ws.rs.core.{MediaType, Response}
import akka.pattern._
import akka.util.Timeout
import com.mbesida.synchronizer.ServiceActor.{Get, Put}
import com.mbesida.synchronizer.cake.{ConfigProvider, ServiceProvider}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
@Path("/service")
class RestResource extends ServiceProvider with ConfigProvider {
implicit val requestTimeout: Timeout = conf.getDuration("timeout", TimeUnit.MILLISECONDS)
@GET
@Path("/{v1}")
@Produces(Array(MediaType.APPLICATION_XML))
def asyncGet(@PathParam("v1") v1: Int, @Suspended asyncResponse: AsyncResponse): Unit = {
asyncResponse.setTimeout(requestTimeout.duration.toSeconds, TimeUnit.SECONDS)
(service ? Get(v1)).mapTo[Option[Double]] onComplete {
case Success(Some(r)) =>
asyncResponse.resume(GetResult(r))
case Success(None) =>
asyncResponse.resume(Response.status(Status.NOT_FOUND).build)
case Failure(e) => asyncResponse.resume(Response.status(Status.INTERNAL_SERVER_ERROR).build)
}
}
@POST
@Consumes(Array(MediaType.APPLICATION_XML))
@Produces(Array(MediaType.APPLICATION_XML))
def asyncPost(input: InputData, @Suspended asyncResponse: AsyncResponse): Unit = {
asyncResponse.setTimeout(requestTimeout.duration.toSeconds, TimeUnit.SECONDS)
(service ? Put(input.v2, input.v3, input.v4)).mapTo[Int] onComplete {
case Success(v) =>
asyncResponse.resume(PostResult(v))
case Failure(e) =>
asyncResponse.resume(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build)
}
}
}