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

Scala Logger类代码示例

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

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



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

示例1: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:sarathraj-coder,项目名称:play2_6curd_rest,代码行数:27,代码来源:ApplicationTimer.scala


示例2: injectorModules

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

import actors.ChadashSystem
import com.google.inject.{Guice, Module}
import play.api.mvc.{EssentialAction, Filters}
import play.api.{Application, GlobalSettings, Logger, Mode}
import play.filters.gzip.GzipFilter
import play.filters.headers.SecurityHeadersFilter

trait AppGlobalSettings extends GlobalSettings {

  private var INJECTOR: Option[com.google.inject.Injector] = None

  def injectorModules(): Seq[Module]

  override def onStart(app: Application) {
    INJECTOR = Some(Guice.createInjector(injectorModules(): _*))
  }

  override def onStop(app: Application) {
    Logger.info("Application shutdown...")
    if(app.mode != Mode.Test)
      ChadashSystem.system.shutdown()
  }

  override def doFilter(next: EssentialAction): EssentialAction = {
    Filters(super.doFilter(next), new GzipFilter(), SecurityHeadersFilter())
  }

  override def getControllerInstance[A](controllerClass: Class[A]): A = {
    INJECTOR match {
      case Some(x) => x.getInstance(controllerClass)
      case None => throw new UnsupportedOperationException("The DI framework has not been setup yet!")
    }
  }
} 
开发者ID:lifeway,项目名称:Chadash,代码行数:37,代码来源:AppGlobalSettings.scala


示例3: FilmController

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

import javax.inject._

import models.film.{Film, FilmRepository, Isbn}
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}

class FilmController @Inject()(filmRepository: FilmRepository)(implicit exec: ExecutionContext) extends Controller {

  def createFilm = Action.async(parse.json) { implicit request =>
    request.body.validate[Film].map { film =>
      Logger.debug(s"Creating film using isbn: ${film.isbn}")
      filmRepository.create(film)
        .map { f =>
          Logger.info("Successfully created a film")
          Created(Json.toJson(f))
        }
        .recover {
          case e: Throwable =>
            Logger.error("Error creating film", e)
            InternalServerError(Json.obj("error" -> "Error creating film"))
        }
    }.recoverTotal { e =>
      Logger.warn(s"Unable to create a film: ${JsError.toJson(e)}")
      Future.successful(BadRequest(Json.obj("error" -> s"unable to create film. Cause ${e}")))
    }
  }

  def findFilmBy(isbn: Isbn) = Action.async { implicit request =>
    filmRepository.get(isbn).map { maybeFilm =>
      maybeFilm.fold(NotFound(Json.obj("error" -> s"${isbn.value} not found")))(f => Ok(Json.toJson(f)))
    }.recover {
      case e: Throwable =>
        Logger.error(s"Error finding film using isbn: $isbn", e)
        InternalServerError(Json.obj("error" -> "Error finding films"))
    }
  }

} 
开发者ID:fagossa,项目名称:play-reactive-couchbase,代码行数:44,代码来源:FilmController.scala


示例4: onServerError

//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.play

import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.http.HttpVerbs.{ GET, POST }
import play.api.http.Status.INTERNAL_SERVER_ERROR
import play.api.mvc.Results._
import play.api.mvc.{ Call, RequestHeader, Result }
import org.danielnixon.progressive.play.extensions.{ RequestHeaderWrapper, ResultWrapper }
import org.danielnixon.progressive.play.Results.redirectToRefererOrElse
import org.danielnixon.progressive.shared.api.AjaxResponse
import play.twirl.api.HtmlFormat

import scalaz.Scalaz._
import scala.concurrent.Future


  def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    val errorMessage = serverErrorToErrorMessage(request, exception)
    Logger.error(errorMessage, exception)
    errorResponse(request, errorMessage, INTERNAL_SERVER_ERROR)
  }

  private def errorResponse(request: RequestHeader, errorMessage: String, statusCode: Int): Future[Result] = {
    val status = Status(statusCode)

    Future.successful {
      request.isAjax match {
        case true => status(AjaxResponse.asJson(AjaxResponse(Some(errorMessage), None, None)))
        case false if request.method === POST => redirectToRefererOrElse(errorRoute)(request).flashingError(errorMessage)
        case _ => status(errorPage(request, statusCode, errorMessage))
      }
    }
  }
} 
开发者ID:danielnixon,项目名称:progressive,代码行数:36,代码来源:ProgressiveErrorHandler.scala


示例5: ArtistController

//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import model.Artist
import play.api.mvc._
import play.api.libs.json.Json
import services.{ArtistServices}
import play.api.Logger

@Singleton
class ArtistController @Inject() (service : ArtistServices) extends Controller {

  def getArtist(name: String) = Action {
    val response = service.findAllByType(name)
    Logger.debug("Attempting risky calculation.")
    Ok(Json.toJson(response))

  }

  def addArtist = Action { request =>
    val json = request.body.asJson.get
    val stock = Json.fromJson[Artist](json)
    println(stock)
    stock.isSuccess match {
      case true => {
        service.add(stock.get);
        Ok("The Artist has been added !!!")
      }
      case _ => Ok("The Artist Didnt get Added!!")
    }
  }
} 
开发者ID:ralekar,项目名称:play-scala-casbah,代码行数:32,代码来源:ArtistController.scala


示例6: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:wfhartford,项目名称:javadoc-server,代码行数:27,代码来源:ApplicationTimer.scala


示例7: stringPersister

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

import javax.inject.{Inject, Singleton}

import akka.NotUsed
import akka.stream._
import akka.stream.scaladsl.{Broadcast, Flow, GraphDSL, Sink}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits._

import scala.concurrent.Future
import scala.util.{Failure, Success}


  def stringPersister(pf: String => Future[Unit]): Flow[String, String, NotUsed] =
    Flow.fromGraph(GraphDSL.create() { implicit builder =>
      import GraphDSL.Implicits._

      val persistenceSink = Sink.foreach[String] { content =>
        val f = pf(content)
        f.onComplete {
          case Success(u) => Logger.debug(s"Persisted content: '$content'")
          case Failure(t) => Logger.error(s"Failed to persist content: '$content", t)
        }
      }

      val bcast = builder.add(Broadcast[String](2))
      bcast.out(1) ~> persistenceSink

      FlowShape(bcast.in, bcast.out(0))
    })
} 
开发者ID:snackCake,项目名称:TweetStreamChallenge,代码行数:33,代码来源:PersistenceService.scala


示例8: Schema

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

import jdub.async.Database
import models.queries.ddl._
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import scala.concurrent.Future

object Schema {
  val tables = Seq(
    "users" -> CreateUsersTable,

    "user_profiles" -> CreateUserProfilesTable,
    "password_info" -> CreatePasswordInfoTable,
    "oauth1_info" -> CreateOAuth1InfoTable,
    "oauth2_info" -> CreateOAuth2InfoTable,
    "openid_info" -> CreateOpenIdInfoTable,
    "session_info" -> CreateSessionInfoTable
  )

  def update() = {
    Future.sequence(tables.map { t =>
      Database.query(DdlQueries.DoesTableExist(t._1)).flatMap { exists =>
        if (exists) {
          Future.successful(Unit)
        } else {
          Logger.info(s"Creating missing table [${t._1}].")
          val name = s"CreateTable-${t._1}"
          Database.raw(name, t._2.sql).map(x => Unit)
        }
      }
    })
  }
} 
开发者ID:laurinka,项目名称:golfmit,代码行数:36,代码来源:Schema.scala


示例9: PlaceController

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

import javax.inject._

import models._
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection._
import utils.Errors
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}



@Singleton
class PlaceController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {

  def placeFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("place"))

  def create(name: String, location: Location, residents: Seq[Resident] ) = Action.async {
    for {
      places <- placeFuture
      lastError <- places.insert(Place(name, location, residents))
    } yield
      Ok("Mongo LastError: %s".format(lastError))
  }

  def createFromJson = Action.async(parse.json) { request =>
    Json.fromJson[Place](request.body) match {
      case JsSuccess(place, _) =>
        for {
          places <- placeFuture
          lastError <- places.insert(place)
        } yield {
          Logger.debug(s"Successfully inserted with LastError: $lastError")
          Created("Created 1 place")
        }
      case JsError(errors) =>
        Future.successful(BadRequest("Could not build a place from the json provided. " + Errors.show(errors)))
    }
  }

  def findPlace(name: String) = Action.async {
    val futurePlacesList: Future[List[Place]] = placeFuture.flatMap{
        _.find(Json.obj("name" -> name)).
          cursor[Place](ReadPreference.primary).
          collect[List]()
    }
    futurePlacesList.map { places =>
      Ok(Json.prettyPrint(Json.toJson(places))) }
  }


} 
开发者ID:Yashar78,项目名称:play,代码行数:58,代码来源:PlaceController.scala


示例10: LocationController

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

import javax.inject._

//import models.City
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.play.json.collection._
import utils.Errors
import models._
import scala.concurrent.{ExecutionContext, Future}
import play.modules.reactivemongo.json._


@Singleton
class LocationController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {

  def locationFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("location"))

  def create(lat: Double, long: Double) = Action.async {
    for {
      locations <- locationFuture
      lastError <- locations.insert(Location(lat, long))
    } yield
      Ok("Mongo LastError: %s".format(lastError))
  }

  def createFromJson = Action.async(parse.json) { request =>
    Json.fromJson[Location](request.body) match {
      case JsSuccess(location, _) =>
        for {
          locations <- locationFuture
          lastError <- locations.insert(location)
        } yield {
          Logger.debug(s"Successfully inserted with LastError: $lastError")
          Created("Created 1 location")
        }
      case JsError(errors) =>
        Future.successful(BadRequest("Could not build a location from the json provided. " + Errors.show(errors)))
    }
  }


} 
开发者ID:Yashar78,项目名称:play,代码行数:47,代码来源:LocationController.scala


示例11: Forms

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

import java.util

import Models.Room
import play.api.Logger
import play.api.data._
import play.api.data.Forms._
import scala.collection.JavaConversions._

object Forms {

  case class RoomFull(name:String,number:Int,cost:BigDecimal,items:Option[String]){
    def getRoom = {
      val room = Room(name,number,cost)
      this.items match {
        case Some(x) =>var arr = new util.ArrayList[String]()
          arr.appendAll(x.split(",").map(_.trim))
//          Logger.info(arr.toString)
          room.items = arr
//          Logger.info(room.items.toString)
        case _ => 
      }
//      Logger.info(room.toString)
      room
    }
  }

  val editForm = Form(
    mapping(
      "name" -> text,
      "number" -> number,
      "cost" -> bigDecimal,
      "items" -> optional(text)
    )(RoomFull.apply)(RoomFull.unapply)
  )

} 
开发者ID:amitkrs,项目名称:pmr,代码行数:39,代码来源:Forms.scala


示例12:

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

import akka.actor._
import play.api.Logger
import shared.ChatTypes.{Channel, User}
import shared._



    case CLoginRequest(requestedUsername) =>
      allUsers.get(requestedUsername) match {
        case None =>
          //we escape the name from html related characters
          val saveName = Utils.escape(requestedUsername)
          allUsers += User(saveName) -> sender
          sender ! SLoginSuccessFul(saveName)
        case Some(x) =>
          sender ! SLoginFailed("Username taken")
      }

    case [email protected](channelName, partner) =>
      ifLoggedIn(user => {
        allUsers.get(partner) match {
          case Some(ref) => ref    ! SInviteToRoom(channelName)
          case None      => sender ! SNotAuthorized(s"# Can't create custom room with '$partner' for the following reason: User is not logged in!")
        }
      })

    case [email protected]() =>
      ifLoggedIn(user => {
        for ((name, ref) <- allChannels){
          ref forward AuthedMessage(user, m)
        }
      })

    case [email protected](channelName, potMod) =>
      ifLoggedIn(user => {
        if(user.toString == potMod.toString)
          sender ! SNotAuthorized("You can't give or remove moderator rights for yourself")
        else
          allUsers.get(potMod) match {
            case Some(_) => forwardOrCreateChannel(channelName, user, m)
            case None    => sender ! SNotAuthorized(s"The user $potMod can't be given moderator rights as he's not online")
          }
      })

    case m:AuthedRequiredMessage =>
      ifLoggedIn(user => {
        forwardOrCreateChannel(m.channelName, user, m)
      })

    case _ => Logger.warn("Unknown packet in MainServerActor")
  }
} 
开发者ID:Starofall,项目名称:Chakka,代码行数:55,代码来源:ServerActor.scala


示例13: Application

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

import actors.{ServerConnectionActor, ServerActor}
import javax.inject._
import com.google.inject.Inject
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc._
import play.api.libs.iteratee._
import play.api.Logger
import akka.actor._
import scala.concurrent.Future
import scala.util.{Success, Failure}
import shared._
import prickle._

@Singleton
class Application @Inject()(system: ActorSystem) extends Controller {

  
    implicit val messagePickler = ChatPickler.messagePickler

    //here we create a connection between the webSocket and the serverConnectionActor
    val (out, channel) = Concurrent.broadcast[String]
    val connectionHandler = system.actorOf(ServerConnectionActor.props(channel, serverActor))

    //for each incoming message try to unpickle it and handle it to the ServerConnectionActor
    val in = Iteratee.foreach[String] { msg =>
      Unpickle[NetworkMessage].fromString(msg) match {
        case Failure(exception) => Logger.error("UNKNOWN PACKET FORMAT")
        case Success(value) => connectionHandler ! value
      }
    }
    //return the webSocketHandle
    Future(Right(in, out))
  }
} 
开发者ID:Starofall,项目名称:Chakka,代码行数:37,代码来源:Application.scala


示例14: ProjectRetriever

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

import akka.actor.{Actor, Props}
import messages.ProjectManagerMessages._
import play.api.Logger

class ProjectRetriever extends Actor {
  override def receive = {
    case GetProjectDetails(projectID) =>
      Logger.info(s"actor ${self.path} - received msg : ${GetProjectDetails(projectID)} ")

      val projectDetailsRetriever = context.actorOf(ProjectDetailsRetriever.props(sender()), "projectDetailsRetriever")
      projectDetailsRetriever forward GetProjectDetails(projectID)

    case GetProjectDetailsWithTemplateBody(projectID) =>
      Logger.info(s"actor ${self.path} - received msg : ${GetProjectDetailsWithTemplateBody(projectID)} ")

      val projectDetailsWithTemplateBodyRetriever = context.actorOf(ProjectDetailsWithTemplateBodyRetriever.props(sender()), "projectDetailsWithTemplateBodyRetriever")
      projectDetailsWithTemplateBodyRetriever forward GetProjectDetailsWithTemplateBody(projectID)

    case ListProjects(filter, offset, limit) =>
      Logger.info(s"actor ${self.path} - received msg : ${ListProjects(filter, offset, limit)} ")

      val bulkProjectsRetriever = context.actorOf(BulkProjectsRetriever.props(sender()), "bulkProjectsRetriever")
      bulkProjectsRetriever forward ListProjects(filter, offset, limit)

    case SearchProjects(keyword, offset, limit) =>
      Logger.info(s"actor ${self.path} - received msg : ${SearchProjects(keyword, offset, limit)} ")

      val projectsSearchRetriever = context.actorOf(ProjectsSearchRetriever.props(sender()), "projectsSearchRetriever")
      projectsSearchRetriever forward SearchProjects(keyword, offset, limit)

    case GetProjectStats(projectID) =>
      Logger.info(s"actor ${self.path} - received msg : ${GetProjectStats(projectID)} ")

      val projectStatsRetriever = context.actorOf(ProjectStatsRetriever.props(sender()), "projectStatsRetriever")
      projectStatsRetriever forward GetProjectStats(projectID)

    case GetProjectResults(projectID, offset, limit) =>
      Logger.info(s"actor ${self.path} - received msg : ${GetProjectResults(projectID, offset, limit)} ")

      val projectResultsRetriever = context.actorOf(ProjectResultsRetriever.props(sender()), "projectResultsRetriever")
      projectResultsRetriever forward GetProjectResults(projectID, offset, limit)
  }
}

object ProjectRetriever {
  def props(): Props = Props(new ProjectRetriever)
} 
开发者ID:Sengab-platform,项目名称:backend,代码行数:50,代码来源:ProjectRetriever.scala


示例15: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at ${start}.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:mendelmiranda,项目名称:play-scala-crud,代码行数:27,代码来源:ApplicationTimer.scala


示例16: VisitService

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

import com.sksamuel.elastic4s.{ HitAs, RichSearchHit }
import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.source.Indexable
import javax.inject.{ Inject, Singleton }
import play.api.Logger
import play.api.libs.json.Json
import scala.concurrent.{ Future, ExecutionContext }
import storage.ES

@Singleton
class VisitService @Inject() (implicit val es: ES, val ctx: ExecutionContext) {
  
  implicit object VisitIndexable extends Indexable[Visit] {
    override def json(v: Visit): String = Json.stringify(Json.toJson(v))
  }

  implicit object VisitHitAs extends HitAs[Visit] {
    override def as(hit: RichSearchHit): Visit =
      Json.fromJson[Visit](Json.parse(hit.sourceAsString)).get
  }
  
  def insertVisit(visit: Visit): Future[Unit] =
    es.client execute {
      index into ES.RECOGITO / ES.VISIT source visit
    } map { _ => 
    } recover { case t: Throwable =>
      Logger.error("Error logging visit event")
      val foo = t.printStackTrace
    }
    
  def countTotal(): Future[Long] =
    es.client execute {
      search in ES.RECOGITO / ES.VISIT limit 0
    } map { _.totalHits }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:39,代码来源:VisitService.scala


示例17: DumpImporter

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

import java.io.{ InputStream, File, FileInputStream }
import java.util.zip.GZIPInputStream
import models.place.{ GazetteerRecord, PlaceService }
import play.api.Logger
import scala.concurrent.{ Await, ExecutionContext }
import scala.concurrent.duration._

class DumpImporter {
  
  private def getStream(file: File, filename: String) =
    if (filename.endsWith(".gz"))
      new GZIPInputStream(new FileInputStream(file))
    else
      new FileInputStream(file)
  
  def importDump(file: File, filename: String, crosswalk: InputStream => Seq[GazetteerRecord])(implicit places: PlaceService, ctx: ExecutionContext) = {
    val records = crosswalk(getStream(file, filename))
    Logger.info("Importing " + records.size + " records")
    Await.result(places.importRecords(records), 60.minute)   
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:25,代码来源:DumpImporter.scala


示例18: GazetteerAdminController

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

import akka.stream.Materializer
import controllers.{ BaseAuthController, WebJarAssets }
import javax.inject.{ Inject, Singleton }
import models.document.DocumentService
import models.place.PlaceService
import models.user.UserService
import models.user.Roles._
import play.api.{ Configuration, Logger }
import scala.concurrent.{ ExecutionContext, Future }
import java.io.FileInputStream
import models.place.crosswalks.PleiadesCrosswalk
import models.place.crosswalks.GeoNamesCrosswalk
import models.place.crosswalks.PelagiosRDFCrosswalk
import models.place.crosswalks.PelagiosGeoJSONCrosswalk

@Singleton
class GazetteerAdminController @Inject() (
    val config: Configuration,
    val documents: DocumentService,
    val places: PlaceService,
    val users: UserService,
    implicit val materializer: Materializer,
    implicit val ctx: ExecutionContext,
    implicit val webjars: WebJarAssets
  ) extends BaseAuthController(config, documents, users) {
  
  def index = AsyncStack(AuthorityKey -> Admin) { implicit request =>
    places.listGazetteers().map { gazetteers => 
      Ok(views.html.admin.gazetteers.index(gazetteers))
    }
  }
  
  def importGazetteer = StackAction(AuthorityKey -> Admin) { implicit request =>
    request.body.asMultipartFormData.flatMap(_.file("gazetteer-file")) match {
      case Some(formData) => {
        
        Logger.info("Importing gazetteer from " + formData.filename)
  
        
        
        
          
          
          
        Redirect(routes.GazetteerAdminController.index)
      }
        
      case None => BadRequest
        
    }
  }
  
  def deleteGazetteer(name: String) = AsyncStack(AuthorityKey -> Admin) { implicit request =>
    places.deleteByGazetteer(name).map { _ =>
      Status(200)
    }
  }

} 
开发者ID:pelagios,项目名称:recogito2,代码行数:62,代码来源:GazetteerAdminController.scala


示例19: PersonController

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

import javax.inject._

import models.Person
import org.joda.time.DateTime
import play.api.Logger
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.json.Json._
import play.api.libs.json._
import play.api.mvc._
import services.PersonService
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class PersonController @Inject()(personService: PersonService) extends Controller {
  private val logger = Logger(this.getClass)

  case class WritePerson(name: String, age: Int) {
    def toPerson = new Person(id = None, name = name, age = age, createdAt = DateTime.now)
  }

  val form = Form(
    mapping(
      "name" -> text,
      "age" -> number
    )(WritePerson.apply)(WritePerson.unapply)
  )

  def create = Action.async { implicit request =>
    form.bindFromRequest.fold(
      formWithErrors => Future.successful(BadRequest("Error")),
      writePerson =>
        personService.insert(writePerson.toPerson).map(person =>
          Ok(Json.toJson(person))
        )
    )
  }

  def findByName(name: String) = Action.async {
    personService.findOne(Json.obj("name" -> name)).map{
      case Some(person) => Ok(Json.toJson(person))
      case _            => NotFound
    }
  }
} 
开发者ID:deusz,项目名称:play-rest-embeded-mongo,代码行数:49,代码来源:PersonController.scala


示例20: badRequest

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

import play.api.Logger
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.{Result, Controller}

trait BaseController extends Controller {

  def badRequest(msg: String): Result = {
    Logger.debug(s"BadRequest: error '$msg'")
    BadRequest(Json.obj("error" -> true, "message" -> msg))
  }

  def error(msg: String): Result = {
    Logger.debug(s"Error: '$msg'")
    InternalServerError(Json.obj("error" -> true, "message" -> msg))
  }

  def ok(json: JsValue): Result = {
    Ok(Json.obj("error" -> false, "message" -> "", "content" -> json))
  }

  def ok(message: String): Result = {
    Ok(Json.obj("error" -> false, "message" -> message))
  }

  def redirect(redirectLink: String): Result = {
    Ok(Json.obj("error" -> false, "message" -> "", "type" -> "redirect", "redirect" -> redirectLink))
  }

} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:32,代码来源:BaseController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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