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

Scala AnyContent类代码示例

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

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



在下文中一共展示了AnyContent类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: CoinController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import com.mohiva.play.silhouette.api.{Environment, Silhouette}
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import forms.CoinAddForm
import models.User
import models.coin.{Person, WorkEntry}
import models.common.Pagination
import play.api.i18n.MessagesApi
import play.api.mvc.{Action, AnyContent}

import scala.concurrent.Future


class CoinController @Inject()(
                                val messagesApi: MessagesApi,
                                val env: Environment[User, CookieAuthenticator]
                              ) extends Silhouette[User, CookieAuthenticator] {

  val itemsPerPage = 9

  
  def remove(id: Long): Action[AnyContent] = SecuredAction.async { implicit request =>
    WorkEntry.remove(id)
    Future.successful(Redirect(routes.CoinController.landing()))
  }
} 
开发者ID:wirvomgut,项目名称:curo,代码行数:30,代码来源:CoinController.scala


示例2: MenuController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import com.github.nscala_time.time.Imports._
import domain.MenuRepo.menuFormat
import domain._
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Controller}
import services.{MenuNotFound, MenuService, NoNewMenuContentFound}

class MenuController @Inject()(menuService: MenuService) extends Controller {

  def menu(fechaUltimaModificacionRef: Option[String]): Action[AnyContent] = Action {

    menuService.getLatestMenu(fechaUltimaModificacionRef) match {
      case Right(menu: Menu) => Ok(Json.toJson(menu))
      case Left(MenuNotFound()) => NotFound
      case Left(NoNewMenuContentFound()) => NoContent
      case _ => InternalServerError
    }
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:24,代码来源:MenuController.scala


示例3: ApplicationController

//设置package包名称以及导入依赖的类
package controllers

import domain.{Categoria, EstadoItemDePedido, EstadoPedido, EstadoSugerencia}
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Controller}

class ApplicationController extends Controller {

  def categorias() : Action[AnyContent] = Action {
    Ok(Json.arr(Categoria.values))
  }

  def estadosDePedido() : Action[AnyContent] = Action {
    Ok(Json.arr(EstadoPedido.values))
  }

  def estadosDeItemDePedido() : Action[AnyContent] = Action {
    Ok(Json.arr(EstadoItemDePedido.values))
  }

  def estadosDeSugerencia() : Action[AnyContent] = Action {
    Ok(Json.arr(EstadoSugerencia.values))
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:25,代码来源:ApplicationController.scala


示例4: Status2Controller

//设置package包名称以及导入依赖的类
package xyz.mattclifton.play.stringent.test

import play.api.mvc.{Request, AnyContent, Action, Controller}
import xyz.mattclifton.play.stringent.StringentActions
import xyz.mattclifton.play.stringent.test.helpers.FakeParsers._
import xyz.mattclifton.play.stringent.test.models.{TestResponse, TestContent}

import scala.concurrent.{ExecutionContext, Future}

class Status2Controller(implicit executionContext: ExecutionContext) extends Controller with StringentActions {
  def withBodyParser = Action.stringent.withContent[TestContent, OkResult, BadRequestResult](parse.json[TestContent]){ request =>
    Ok
  }

  def anyContent = Action.stringent.anyContent[OkResult, BadRequestResult]{ request =>
    Ok
  }

  def block = Action.stringent[OkResult, BadRequestResult]{
    Ok
  }

  def asyncBlock = Action.stringent.async[OkResult, BadRequestResult]{
    Future(Ok)
  }

  def asyncAnyContent = Action.stringent.anyContentAsync[OkResult, BadRequestResult]{ request =>
    Future(Ok)
  }

  def asyncBodyContent = Action.stringent.withContentAsync[TestContent, OkResult, BadRequestResult](parse.json[TestContent]){ request =>
    Future(Ok)
  }
} 
开发者ID:lynx44,项目名称:play-stringent,代码行数:35,代码来源:Status2Controller.scala


示例5: Route

//设置package包名称以及导入依赖的类
package com.viajobien.busy.models.routing

import com.viajobien.busy.dsl.condition.Condition
import com.viajobien.busy.models.Persistable
import play.api.mvc.{ AnyContent, Request }

abstract class Route(val path: String, endpoint: String,
    condition: Condition) extends Persistable with PathUtil {

  def satisfy(request: Request[AnyContent]): Boolean = {
    this.condition.eval(request)
  }

  def generateEndpoint(pathParameter: String): String = {
    val splittedPath = this.splitPath(this.path)
    val splittedPathParameter = this.splitPath(pathParameter, splittedPath.size)
    val zippedPath = splittedPath zip splittedPathParameter

    val wildcardsPath = zippedPath filter (z => z._1 == PATH_PART_WILDCARD || z._1 == PATH_WILDCARD)

    this.splittedEndpoint(wildcardsPath)
  }

  private def splittedEndpoint(wildcardsPath: List[(String, String)]): String = {
    def splitted(splittedEndpoint: List[String], wildcardsPath: List[(String, String)]): List[String] =
      splittedEndpoint match {
        case Nil                                        => Nil
        case (PATH_PART_WILDCARD | PATH_WILDCARD) :: es => wildcardsPath.head._2 :: splitted(es, wildcardsPath.tail)
        case e :: es                                    => e :: splitted(es, wildcardsPath)
      }

    splitted(this.splitPath(this.endpoint, dropChars = 0), wildcardsPath) mkString "/"
  }

} 
开发者ID:viajobien,项目名称:busy,代码行数:36,代码来源:Route.scala


示例6: MainController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import scala.concurrent.ExecutionContext

import domain.Id
import domain.wordcount.Model._
import parser.WordsBodyParsers
import play.api.Configuration
import play.api.libs.json._
import play.api.mvc.{Action, AnyContent, Controller}
import services.WordCountService
import services.WordCountService._

@Singleton
class MainController @Inject()(
  wordCountService: WordCountService,
  val configuration: Configuration,
  implicit val executionContext: ExecutionContext
) extends Controller with WordsBodyParsers {

  import json.WordCountJson._

  def index = Action {
    Ok("")
  }

  def countWords: Action[Map[String, Long]] = Action.async(parseWords.wordcount) { request =>
    wordCountService
      .createWordCount(CreateWordCountRequest(request.body))
      .map(res => Ok(Json.toJson(res.wordCount)))
  }

  def getWordCounts: Action[AnyContent] = Action.async { request =>
    wordCountService
      .findWordCounts(FindWordCountsRequest())
      .map(res => Ok(Json.toJson(res.wordCounts)))
  }

  def getWordCount(id: String): Action[AnyContent] = Action.async { request =>
    wordCountService
      .findWordCount(FindWordCountRequest(Id[WordCount](id)))
      .map(res =>
        if (res.wordCount.isDefined)
          Ok(Json.toJson(res.wordCount))
        else NotFound
      )
  }
} 
开发者ID:sebtomba,项目名称:wordcount-akka-streams,代码行数:51,代码来源:MainController.scala


示例7: DbPopulationController

//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api.controllers

import au.id.tmm.senatedb.api.services.DbPopulationService
import au.id.tmm.senatedb.api.services.exceptions.NoSuchElectionException
import com.google.inject.{Inject, Singleton}
import play.api.mvc.{Action, AnyContent, Controller}

import scala.concurrent.ExecutionContext

@Singleton
class DbPopulationController @Inject()(dbPopulationService: DbPopulationService)
                                      (implicit ec: ExecutionContext) extends Controller {

  def populateFor(electionId: String): Action[AnyContent] = Action.async {
    dbPopulationService.beginPopulationFor(electionId)
      .map(_ => Ok(s"Begun populating for $electionId"))
      .recover {
        case _: NoSuchElectionException => NotFound(electionId) // TODO handle this with an application level error handler
        case e: DbPopulationService.Exceptions.AnotherElectionCurrentlyPopulatingException => Ok(s"Already populating ${e.election}")
      }
  }

  def checkPopulationStatusFor(electionId: String): Action[AnyContent] = Action.async {
    dbPopulationService.isElectionPopulated(electionId)
      .map(electionIsPopulated => Ok(electionIsPopulated.toString))
      .recover {
        case _: NoSuchElectionException => NotFound(electionId) // TODO handle this with an application level error handler
      }
  }
} 
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:31,代码来源:DbPopulationController.scala


示例8: JSONCtrl

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

import javax.inject.Inject

import com.mohiva.play.silhouette.api.Environment
import com.mohiva.play.silhouette.impl.authenticators.CookieAuthenticator
import controllers.{ResultFormat, ViewContext}
import models.{PCMAPIUtils, User}
import org.opencompare.api.java.impl.io.KMFJSONExporter
import org.opencompare.formalizer.extractor.CellContentInterpreter
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.MessagesApi
import play.api.libs.json.Json
import play.api.mvc.{AnyContent, Request, Result}



class JSONCtrl @Inject() (
                           val messagesApi: MessagesApi,
                           val env: Environment[User, CookieAuthenticator],
                           val pcmAPIUtils : PCMAPIUtils) extends IOCtrl("json") {

  val jsonExporter = new KMFJSONExporter()
  val formalizer = new CellContentInterpreter

  val outputParametersForm = Form(
    mapping(
      "file" -> text
    )(JSONExportParameters.apply)(JSONExportParameters.unapply)
  )

  override def importPCMs(format: ResultFormat)(implicit request: Request[AnyContent], viewContext: ViewContext): Result = {
    NotFound("JSON import is not implemented yet")
  }

  override def exportPCM(implicit request: Request[AnyContent]): Result = {
    val parameters = outputParametersForm.bindFromRequest.get
    val pcmJSON = Json.parse(parameters.pcm)

    val container = pcmAPIUtils.parsePCMContainers(pcmJSON).head
    formalizer.interpretCells(container.getPcm)
    val json = jsonExporter.export(container)

    Ok(json)
  }

  case class JSONExportParameters(pcm : String)
} 
开发者ID:Bastcloa,项目名称:testJenkins,代码行数:50,代码来源:JSONCtrl.scala


示例9: index

//设置package包名称以及导入依赖的类
package controllers

import play.api.mvc.{Action, Controller, AnyContent}


  def index: Action[AnyContent] = Action { request =>
    if (request.session.get("customer").isDefined) {
      Redirect(routes.LoginController.loginUser())
    } else if (request.session.get("staff").isDefined) {
      Redirect(routes.LoginController.loginStaff())
    } else {
      Ok(views.html.index(controllers.LoginController.loginForm))
    }
  }
} 
开发者ID:ioaccept,项目名称:pizza,代码行数:16,代码来源:Application.scala


示例10: searchUser

//设置package包名称以及导入依赖的类
package controllers

import forms.LoginUserForm
import models.User
import play.api.mvc.{Action, AnyContent, Controller}
import play.api.data.Form
import play.api.data.Forms._
import services.{ExtrasService, ItemService, UserService}



  def searchUser: Action[AnyContent] = Action {
    implicit request =>
      loginForm.bindFromRequest.fold(
        formWithErrors => {
          BadRequest(views.html.index(formWithErrors))
        },
        userData => {
          val exists = UserService.registeredUsers.exists(_.name == userData.name)

          if (exists) {
            val user = UserService.registeredUsers.find {
              _.name == userData.name
            }.head

            if (user.password == userData.password && user.active) {
              if (!user.admin) {
                Redirect(routes.LoginController.loginUser()) withSession("id" -> user.id.toString, "user" -> user.name, "distance" -> user.distance.toString, "customer" -> "yes")
              } else {
                Redirect(routes.LoginController.loginStaff()) withSession("id" -> user.id.toString, "user" -> user.name, "staff" -> "yes")
              }
            } else Redirect(routes.Application.index())

          } else Redirect(routes.Application.index())

        }
      )
  }


} 
开发者ID:ioaccept,项目名称:pizza,代码行数:42,代码来源:LoginController.scala


示例11: changeGott

//设置package包名称以及导入依赖的类
package controllers

import forms.GottForm
import models.Gott
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, AnyContent, Controller}



  def changeGott: Action[AnyContent] = Action { implicit request =>
    gottForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.error("Fehler Gott"))
      },
      userData => {
        val gott = new Gott(userData.gottId, userData.userId, userData.gott, userData.passiv, userData.erweckt, userData.skill, userData.skillE,
          0)
        gott.getGesamt()
        services.GottService.changeGott(gott)
        Redirect(routes.DefController.showMemberDef(userData.userId.toString))
      })
  }
} 
开发者ID:ioaccept,项目名称:semperfidog,代码行数:25,代码来源:GottController.scala


示例12: Images

//设置package包名称以及导入依赖的类
package controllers

import java.io.File
import javax.inject.Inject

import com.smule.smg.SMGLogger
import play.Play
import play.api.mvc.{Action, AnyContent, Controller}


class Images  @Inject() () extends Controller {
  val log = SMGLogger

  def at(rootPath: String, file: String): Action[AnyContent] = Action { request =>
    if (file.contains(File.pathSeparator)) {
      log.error("Refusing to serve files outside my root: " + file)
      NotFound
    } else {
      val fileToServe = new File(Play.application.getFile(rootPath), file)
      if (fileToServe.exists) {
        Ok.sendFile(fileToServe, inline = true).withHeaders(CACHE_CONTROL -> "max-age=30")
      } else {
        NotFound
      }
    }
  }

} 
开发者ID:asen,项目名称:smg,代码行数:29,代码来源:Images.scala


示例13: ServiceHealthCheck

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, _}

import com.sharecare.lib.play.healthcheck.HealthCheckCriticality.High
import com.sharecare.lib.play.healthcheck.HealthCheckStatus.{Error, Healthy}
import com.sharecare.lib.play.healthcheck.controllers.HealthCheckController
import com.sharecare.lib.play.healthcheck.mongoDB.MongoReporterFactory
import com.sharecare.lib.play.healthcheck.{HealthCheck, HealthReporter}
import play.api.Configuration
import play.api.libs.ws.WSClient
import play.api.mvc.{Action, AnyContent, Controller}

import scala.concurrent.Await
import scala.concurrent.duration._



@Singleton
class ServiceHealthCheck @Inject() (mongoReporterFactory: MongoReporterFactory,
                                    careTeamReporter: CareTeamServiceReporter,
                                    config: Configuration,
                                    healthCheckController: HealthCheckController) extends Controller {

  lazy val mainCollection     = "collections.main"
  lazy val mongoReporters = mongoReporterFactory.report(mainCollection)

  val check: (Option[Boolean], Option[Boolean]) => Action[AnyContent] = healthCheckController.check (
    healthChecks = mongoReporters ++ Set(careTeamReporter),
    parentLabel  = config.getString("application.name"   ).getOrElse("<Specify name in conf>"   ),
    version      = config.getString("application.version").getOrElse("<Specify version in conf>")
  )
}

class CareTeamServiceReporter  @Inject() (config: Configuration, ws: WSClient) extends HealthReporter {
  val isInternal: Boolean = false

  def report: HealthCheck = {
    val careTeam = config.getConfig("application.healthchecks.careTeam")
    val url      = careTeam.flatMap(c => c.getString("url"))
    val timeout  = careTeam.flatMap(c => c.getInt("timeoutSeconds")).getOrElse(10)

    url match {
      case Some(u) => val response = Await.result(ws.url(u).get(), timeout.seconds)
        response.status match {
          case 200 => HealthCheck("CareTeamService", Healthy, High, "Ok")
          case _  => HealthCheck("CareTeamService", Error, High, response.body)
        }
      case None => HealthCheck("CareTeamService", Error, High, "careteam url has not been defined")
    }
  }
} 
开发者ID:Sharecare,项目名称:health-profile-social-history-play,代码行数:53,代码来源:ServiceHealthCheck.scala


示例14: MispCtrl

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import models.InvalidRequestError
import play.api.Logger
import play.api.libs.json.{ JsObject, JsValue }
import play.api.mvc.{ Action, AnyContent, Controller }
import services.MispSrv

import scala.concurrent.ExecutionContext

class MispCtrl @Inject() (mispSrv: MispSrv, implicit val ec: ExecutionContext) extends Controller {

  private[MispCtrl] lazy val logger = Logger(getClass)
  def modules: Action[AnyContent] = Action { _ ?
    Ok(mispSrv.moduleList)
  }

  def query: Action[JsValue] = Action.async(parse.json) { request ?
    val module = (request.body \ "module").asOpt[String].getOrElse(throw InvalidRequestError("Module parameter is not present in request"))
    val (mispType, dataJson) = request.body.as[JsObject].fields
      .collectFirst {
        case kv @ (k, _) if k != "module" ? kv
      }
      .getOrElse(throw InvalidRequestError("Request doesn't contain data to analyze"))
    val data = dataJson.asOpt[String].getOrElse(throw InvalidRequestError("Data has invalid type (expected string)"))
    mispSrv.query(module, mispType, data)
      .map(Ok(_))
  }
} 
开发者ID:CERT-BDF,项目名称:Cortex,代码行数:32,代码来源:MispCtrl.scala


示例15: get

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{ Inject, Singleton }

import play.api.Environment
import play.api.http.HttpErrorHandler
import play.api.mvc.{ Action, AnyContent }

trait AssetCtrl {
  def get(file: String): Action[AnyContent]
}

@Singleton
class AssetCtrlProd @Inject() (errorHandler: HttpErrorHandler) extends Assets(errorHandler) with AssetCtrl {
  def get(file: String): Action[AnyContent] = at("/ui", file)
}

@Singleton
class AssetCtrlDev @Inject() (environment: Environment) extends ExternalAssets(environment) with AssetCtrl {
  def get(file: String): Action[AnyContent] = {
    if (file.startsWith("bower_components/")) {
      at("ui", file)
    }
    else {
      at("ui/app", file)
    }
  }
} 
开发者ID:CERT-BDF,项目名称:Cortex,代码行数:29,代码来源:Asset.scala


示例16: JobCtrl

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import scala.annotation.implicitNotFound
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.Duration
import scala.util.{ Failure, Success }
import play.api.libs.json.{ JsString, Json }
import play.api.mvc.{ Action, AnyContent, Controller }
import models.JsonFormat._
import services.JobSrv

class JobCtrl @Inject() (
    jobSrv: JobSrv,
    implicit val ec: ExecutionContext) extends Controller {
  def list(dataTypeFilter: Option[String], dataFilter: Option[String], analyzerFilter: Option[String], start: Int, limit: Int): Action[AnyContent] = Action.async { request ?
    jobSrv.list(dataTypeFilter, dataFilter, analyzerFilter, start, limit).map {
      case (total, jobs) ? Ok(Json.toJson(jobs)).withHeaders("X-Total" ? total.toString)
    }
  }

  def get(jobId: String): Action[AnyContent] = Action.async { request ?
    jobSrv.get(jobId).map { job ?
      Ok(Json.toJson(job))
    }
  }

  def remove(jobId: String): Action[AnyContent] = Action.async { request ?
    jobSrv.remove(jobId).map(_ ? Ok(""))
  }

  def report(jobId: String): Action[AnyContent] = Action.async { request ?
    jobSrv
      .get(jobId)
      .map { job ?
        val report = job.report.value match {
          case Some(Success(r))     ? Json.toJson(r)
          case Some(Failure(error)) ? JsString(error.getMessage)
          case None                 ? JsString("Running")
        }
        Ok(jobWrites.writes(job) +
          ("status" ? jobStatusWrites.writes(job.status)) +
          ("report" ? report))
      }
  }

  def waitReport(jobId: String, atMost: String): Action[AnyContent] = Action.async { request ?
    jobSrv.waitReport(jobId, Duration(atMost))
      .map { job ? Ok(Json.toJson(job)) }
  }
} 
开发者ID:CERT-BDF,项目名称:Cortex,代码行数:53,代码来源:JobCtrl.scala


示例17: DemoController

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

import microtools.BusinessTry
import microtools.logging.LoggingContext
import microtools.models._
import play.api.mvc.{Action, AnyContent, Controller}

import scala.concurrent.{ExecutionContext, Future}

class DemoController(implicit ec: ExecutionContext) extends Controller with AuthActions {
  // This is something provided by a dao of some kind
  private def isOwnerOf(resourceId: String): ScopeRequirement.AccessCheck = {
    case (CustomerSubject(customer), _) => BusinessTry.success(resourceId.endsWith(customer))
  }

  // This is something that should be centralized in a trait
  implicit val serviceName: ServiceName = ServiceName("demo-service")

  private def isCustomerService: ScopeRequirement.AccessCheckWithLogging =
    new ScopeRequirement.AccessCheckWithLogging {
      override def check(subject: Subject, organization: Organization)(
          implicit loggingContext: LoggingContext,
          ec: ExecutionContext): BusinessTry[Boolean] = {
        val contextValues = loggingContext.contextValues.toMap
        log.info(s"Flow Id: ${contextValues.getOrElse("flowId", "unknown")}")
        (subject, organization) match {
          case (ServiceSubject("customer"), _) =>
            log.info(
              s"Customer Service check was successful for subject $subject and organization $organization")
            BusinessTry.success(true)
          case _ =>
            log.info(
              s"Customer Service check was unsuccessful for subject $subject and organization $organization")
            BusinessTry.success(false)
        }
      }
    }

  // Controller specific stuff

  private def readRequirements(resourceId: String) =
    StandardScopeRequirements.checkedReadWithLogging(isCustomerService) or
      StandardScopeRequirements.checkedSelf(isOwnerOf(resourceId))

  private def updateRequirements(resourceId: String) =
    StandardScopeRequirements.checkedWriteWithLogging(isCustomerService) or
      StandardScopeRequirements.checkedSelf(isOwnerOf(resourceId))

  def getProtectedResource(id: String): Action[AnyContent] =
    (AuthAction andThen ScopedAction(readRequirements(id))).async { implicit request =>
      Future.successful(Ok("Got it"))
    }

  def updateProtectedResource(id: String): Action[AnyContent] =
    (AuthAction andThen ScopedAction(updateRequirements(id))).async { implicit request =>
      Future.successful(Accepted("Updated it"))
    }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:59,代码来源:DemoController.scala


示例18: JsonHelper

//设置package包名称以及导入依赖的类
package helpers

import models.{FieldsForSSVal, User}
import play.api.libs.json.JsLookupResult
import play.api.mvc.{AnyContent, Request}

import scala.util.Try

object JsonHelper {

  def getLoginCreds(request: Request[AnyContent]) : (String, String) =
    request.body.asJson.get match{
      case json => {
        val uname = (json \ "username").as[String]
        val pass = (json \ "password").as[String]
        (uname, pass)
      }
    }

  def getRegistration(request: Request[AnyContent]) : User =
    request.body.asJson.get match{
      case json => {
        val email = (json \ "email").as[String]
        val uname = (json \ "username").as[String]
        val pass = (json \ "password").as[String]
        User(email, uname, pass, None)
      }
    }

  def getFieldsForSsVal(request: Request[AnyContent]) : FieldsForSSVal =
    request.body.asJson.map{
      case json => {
        val email = (json \ "email").asOptionString
        val nick = (json \ "username").asOptionString
        FieldsForSSVal(email, nick)
      }
    }.getOrElse(FieldsForSSVal(None, None))

  implicit class OptionWrapper(lookup: JsLookupResult){
    def asOptionString = Try(lookup.as[String]).toOption
  }
} 
开发者ID:rok21,项目名称:kc_web,代码行数:43,代码来源:JsonHelper.scala


示例19: LastUpdateController

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

import javax.inject.{ Inject, Singleton }

import com.typesafe.config.Config
import io.swagger.annotations.{ Api, ApiOperation, ApiResponse, ApiResponses }
import play.api.mvc.{ Action, AnyContent, Result }
import play.api.libs.json.Json
import controllers.BuildInfo

import scala.concurrent.Future
import com.outworkers.util.play._


@Api("Utils")
@Singleton
class LastUpdateController @Inject() (implicit val config: Config) extends ControllerUtils {

  @ApiOperation(
    value = "A Json list of dates representing dates of last changes made",
    notes = "Dates are typically for official releases (i.e. deployment not development level). Time is registered in system time millis.",
    httpMethod = "GET"
  )
  @ApiResponses(Array(
    new ApiResponse(code = 200, message = "Success - Displays json list of dates for official development.")
  ))
  def latestListings: Action[AnyContent] = Action.async {
    errAsResponse(
      generate
    )
  }

  def generate: Future[Result] = {
    val res = Ok(Json.obj("status" -> "OK", "bi-api-deployed-date" -> s"${BuildInfo.builtAtMillis}")).future
    res
  }

} 
开发者ID:ONSdigital,项目名称:sbr-pipeline-test,代码行数:39,代码来源:LastUpdateController.scala


示例20: TemplateController

//设置package包名称以及导入依赖的类
package de.frosner.broccoli.controllers

import javax.inject.Inject

import de.frosner.broccoli.models.Template
import de.frosner.broccoli.models.Template.templateApiWrites
import de.frosner.broccoli.services.{SecurityService, TemplateService}
import jp.t2v.lab.play2.auth.BroccoliSimpleAuthorization
import play.api.libs.json.Json
import play.api.mvc.{Action, AnyContent, Controller}

case class TemplateController @Inject()(templateService: TemplateService, override val securityService: SecurityService)
    extends Controller
    with BroccoliSimpleAuthorization {

  def list: Action[AnyContent] = StackAction { implicit request =>
    Ok(Json.toJson(TemplateController.list(templateService)))
  }

  def show(id: String): Action[AnyContent] = StackAction { implicit request =>
    templateService.template(id).map(template => Ok(Json.toJson(template))).getOrElse(NotFound)
  }

}

object TemplateController {

  def list(templateService: TemplateService): Seq[Template] =
    templateService.getTemplates

} 
开发者ID:FRosner,项目名称:cluster-broccoli,代码行数:32,代码来源:TemplateController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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