- 浏览: 2542872 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Playframework(10)Scala Project and Database
Using the Parser API
The most easiest parser is to parse a value to Scala Long
val rowParser = scalar[Long]
val rsParser = scalar[Long].single
This kind of simple parser API is useful to produce the result by a simple select count query:
val count: Long = SQL("select count(*) from Country").as(scalar[Long].single)
A complex one with str("name") ~ int("population")
val populations:List[String~Int] = {
SQL("select * from Country").as( str("name") ~ int("population") * )
}
Alternatively, we can write like this:
val result:List[String~Int] = {
SQL("select * from Country").as(get[String]("name")~get[Int]("population")* )
}
…snip…
8.3 Integrating with other database access libraries
Integrating with ScalaQuery
…snip..
Exposing the datasource through JNDI
…snip...
9. Using the Cache
It is based on Ehcache.
Accessing the Cache API
Using this simple API to store data in cache:
Cache.set("item.key", connectedUser)
retrieve it later:
val maybeUser: Option[User] = Cache.getAs[User]("item.key")
Caching HTTP responses
Play provides a default built-in helper for standard cases:
def index = Cached("homePage"){
Action{
Ok("Hello world")
}
}
10. Calling WebServices
10.1 The Play WS API
Any calls made by play.api.libs.ws.WS should return a Promise[play.api.libs.ws.Response] which we can later handle with Paly's asynchronous mechanisms.
Making an HTTP call
The simple way is to use ws.url().
val homePage: Promise[ws.Response] = WS.url("http://mysite.com").get();
Or:
val result: Promise[ws.Response] = {
WS.url("http://localhost:9001/post").post("content")
}
Post url-form-encoded data
…snip…
10.2 Connecting to OpenID services
The OpenID flow in a nutshell
1. The user gives you his OpenID(a URL).
2. Your server inspects the content behind the URL to produce a URL where you need to redirect the user.
3. The user confirms the authorization on his OpenID provider, and get redirected back to your server.
4. Your server receives information from that redirect, and checks with the provider that the information is correct.
OpenID in Play
The openID API has 2 import functions:
OpenID.redirectURL. It returns a Promise[String] rather than a String. If the OpenID is invalid, the returned Promise will be a Thrown.
OpenID.verifiedId. It will do a call to the OpenID server to check the authenticity of the information, this is why it returns a Promise[UserInfo] rather than just UserInfo. If the information is not correct or if the server check is false, the returned Promise will be a Thrown.
Here is an example of usage:
def login = Action {
Ok(views.html.login())
}
def loginPost = Action { implicit request =>
Form(single(
"openid" -> nonEmptyText
)).bindFromRequest.fold(
error => {
Logger.info("bad request " + error.toString)
BadRequest(error.toString)
},
{
case (openid) => AsyncResult(OpenID.redirectURL(openid, routes.Application.openIDCallback.absoluteURL()).extend( _.value match{
case Redeemed(url) => Redirect(url)
case Throw(t) => Redirect(routes.Application.login)
}))
}
)
}
def openIDCallback = Action { implicit request =>
AsyncResult(
OpenID.verifiedId.extend( _.value match {
case Redeemed(info) => Ok(info.id + "\n" + info.attributes)
case Thrown(t) => {
Redirect(routes.Application.login)
}
}
)
}
Extended Attributes
The OpenID of a user gives you his identity. The protocol also supports getting extended attributes such as the e-mail address, the first name, or the last name.
OpenID.redirectURL(
openid,
routes.Application.openIDCallback.absoluteURL(),
Seq("email" -> "http://schema.openid.net/contact/email")
)
10.3 Accessing resources protected by OAuth
There are 2 very different versions of OAuth: OAuth1.0 and OAuth2.0. Version 2 is simple enough to be implemented easily without library or helpers. Play only provides support for OAuth 1.0.
…snip...
11. Integrating with Akka
…snip…
12. Internationlization
…snip...
13 The application Global object
13.1 Application global settings
The Global object
object Global extends GlobalSettings{
}
Hooking into application start and stop events
Override the onStart and onStop methods to be notified of the events in the application life-cycle:
object Global extends GlobalSettings{
override def onStart(app: Application) {
Logger.info("Application has started")
}
override def onStop(app: Application) {
Logger.info("Application shutdown...")
}
}
Providing an application error page
When an exception occurs in your application, the onError operation will be called.
object Global extends GlobalSettings{
override def onError(request: RequestHeader, ex: Throwable) = {
InternalServerError(
views.html.errorPage(ex)
)
}
}
Handling missing actions and binding errors
If the framework doesn't find an Action for a request, the onHandlerNotFound operation will be called:
object Global extends GlobalSettings {
override def onHandlerNotFound( request: RequestHeader): Result = {
NotFound(
views.html.notFoundPage(request.path)
)
}
}
onBadRequest is for that if a route was found, but it was not possible to bind the request parameters.
13.2 Intercepting requests
Overriding onRouteRequest
object Global extends GlobalSettings {
def onRouteRequest( request: RequestHeader): Option[Handler] = {
println("executed before every request: " + request.toString)
super.onRouteRequest(request)
}
}
14 Testing your application
14.1 Writing tests
Using specs2
Unit specifications extend the org.specs2.mutable.Specification trait and are using the should/in format:
class HelloWorldSpec extends Specification{
"The 'Hello world' string" should {
"contain 11 characters" in {
"Hello world" must have size(11)
}
"start with 'Hello'" in {
"Hello world" must startWith("Hello")
}
"end with 'world'" in {
"Hello world" must endWith("world")
}
}
}
Running in a fake application
…snip...
References:
http://www.playframework.org/documentation/2.0.4/ScalaHome
http://www.playframework.org/documentation/2.0.4/ScalaAnorm
Using the Parser API
The most easiest parser is to parse a value to Scala Long
val rowParser = scalar[Long]
val rsParser = scalar[Long].single
This kind of simple parser API is useful to produce the result by a simple select count query:
val count: Long = SQL("select count(*) from Country").as(scalar[Long].single)
A complex one with str("name") ~ int("population")
val populations:List[String~Int] = {
SQL("select * from Country").as( str("name") ~ int("population") * )
}
Alternatively, we can write like this:
val result:List[String~Int] = {
SQL("select * from Country").as(get[String]("name")~get[Int]("population")* )
}
…snip…
8.3 Integrating with other database access libraries
Integrating with ScalaQuery
…snip..
Exposing the datasource through JNDI
…snip...
9. Using the Cache
It is based on Ehcache.
Accessing the Cache API
Using this simple API to store data in cache:
Cache.set("item.key", connectedUser)
retrieve it later:
val maybeUser: Option[User] = Cache.getAs[User]("item.key")
Caching HTTP responses
Play provides a default built-in helper for standard cases:
def index = Cached("homePage"){
Action{
Ok("Hello world")
}
}
10. Calling WebServices
10.1 The Play WS API
Any calls made by play.api.libs.ws.WS should return a Promise[play.api.libs.ws.Response] which we can later handle with Paly's asynchronous mechanisms.
Making an HTTP call
The simple way is to use ws.url().
val homePage: Promise[ws.Response] = WS.url("http://mysite.com").get();
Or:
val result: Promise[ws.Response] = {
WS.url("http://localhost:9001/post").post("content")
}
Post url-form-encoded data
…snip…
10.2 Connecting to OpenID services
The OpenID flow in a nutshell
1. The user gives you his OpenID(a URL).
2. Your server inspects the content behind the URL to produce a URL where you need to redirect the user.
3. The user confirms the authorization on his OpenID provider, and get redirected back to your server.
4. Your server receives information from that redirect, and checks with the provider that the information is correct.
OpenID in Play
The openID API has 2 import functions:
OpenID.redirectURL. It returns a Promise[String] rather than a String. If the OpenID is invalid, the returned Promise will be a Thrown.
OpenID.verifiedId. It will do a call to the OpenID server to check the authenticity of the information, this is why it returns a Promise[UserInfo] rather than just UserInfo. If the information is not correct or if the server check is false, the returned Promise will be a Thrown.
Here is an example of usage:
def login = Action {
Ok(views.html.login())
}
def loginPost = Action { implicit request =>
Form(single(
"openid" -> nonEmptyText
)).bindFromRequest.fold(
error => {
Logger.info("bad request " + error.toString)
BadRequest(error.toString)
},
{
case (openid) => AsyncResult(OpenID.redirectURL(openid, routes.Application.openIDCallback.absoluteURL()).extend( _.value match{
case Redeemed(url) => Redirect(url)
case Throw(t) => Redirect(routes.Application.login)
}))
}
)
}
def openIDCallback = Action { implicit request =>
AsyncResult(
OpenID.verifiedId.extend( _.value match {
case Redeemed(info) => Ok(info.id + "\n" + info.attributes)
case Thrown(t) => {
Redirect(routes.Application.login)
}
}
)
}
Extended Attributes
The OpenID of a user gives you his identity. The protocol also supports getting extended attributes such as the e-mail address, the first name, or the last name.
OpenID.redirectURL(
openid,
routes.Application.openIDCallback.absoluteURL(),
Seq("email" -> "http://schema.openid.net/contact/email")
)
10.3 Accessing resources protected by OAuth
There are 2 very different versions of OAuth: OAuth1.0 and OAuth2.0. Version 2 is simple enough to be implemented easily without library or helpers. Play only provides support for OAuth 1.0.
…snip...
11. Integrating with Akka
…snip…
12. Internationlization
…snip...
13 The application Global object
13.1 Application global settings
The Global object
object Global extends GlobalSettings{
}
Hooking into application start and stop events
Override the onStart and onStop methods to be notified of the events in the application life-cycle:
object Global extends GlobalSettings{
override def onStart(app: Application) {
Logger.info("Application has started")
}
override def onStop(app: Application) {
Logger.info("Application shutdown...")
}
}
Providing an application error page
When an exception occurs in your application, the onError operation will be called.
object Global extends GlobalSettings{
override def onError(request: RequestHeader, ex: Throwable) = {
InternalServerError(
views.html.errorPage(ex)
)
}
}
Handling missing actions and binding errors
If the framework doesn't find an Action for a request, the onHandlerNotFound operation will be called:
object Global extends GlobalSettings {
override def onHandlerNotFound( request: RequestHeader): Result = {
NotFound(
views.html.notFoundPage(request.path)
)
}
}
onBadRequest is for that if a route was found, but it was not possible to bind the request parameters.
13.2 Intercepting requests
Overriding onRouteRequest
object Global extends GlobalSettings {
def onRouteRequest( request: RequestHeader): Option[Handler] = {
println("executed before every request: " + request.toString)
super.onRouteRequest(request)
}
}
14 Testing your application
14.1 Writing tests
Using specs2
Unit specifications extend the org.specs2.mutable.Specification trait and are using the should/in format:
class HelloWorldSpec extends Specification{
"The 'Hello world' string" should {
"contain 11 characters" in {
"Hello world" must have size(11)
}
"start with 'Hello'" in {
"Hello world" must startWith("Hello")
}
"end with 'world'" in {
"Hello world" must endWith("world")
}
}
}
Running in a fake application
…snip...
References:
http://www.playframework.org/documentation/2.0.4/ScalaHome
http://www.playframework.org/documentation/2.0.4/ScalaAnorm
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 468NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 330Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 377Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 468NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 414Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 332Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 243GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 445GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 321GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 307Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 286Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 303Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 282NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 257Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 565NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 257Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 362Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 366Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
Mastering Play Framework for Scala
Leverage the awesome features of Play Framework to build scalable, resilient, and responsive applications First published: May 2015 274page
Mastering Play Framework for Scala 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开
Mastering Play Framework for Scala 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Mastering Play Framework for Scala 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
《精通Scala的Play框架》是一本专为Scala开发者设计的深度学习指南,旨在帮助读者全面理解和熟练运用Play框架。Play框架是构建Web应用程序的一个强大工具,尤其在Scala语言的支持下,它提供了高度的灵活性和效率。这...
This book is intended for those developers who are keen to master the internal workings of Play Framework to effectively build and deploy web-related apps.
Play Framework 是一个基于Java和Scala的高性能Web应用框架,它提供了快速开发、可测试和敏捷迭代的能力。在Play Framework中,安全模块是一个重要的组件,它帮助开发者实现基本的认证(Authentication)和授权...
Play Framework是一種用Scala編寫的Web應用框架,其遵循模型-視圖-控制器建築模式。Play Framework使用Scala編寫,並可以被編譯成Java虛擬機器位元組碼中的其他編程語言使用;例如Java語言。
Play Framework 是一个开源的Web应用框架,主要针对Java和Scala开发者设计,它的核心理念是简化开发流程,提高开发效率,并且特别强调了RESTful架构风格。这个“playframework中文教程.zip”压缩包很可能是为了帮助...
- **框架简介**:Play Framework 是一个开源的 Web 开发框架,基于 Java 和 Scala 编程语言。它采用轻量级、非阻塞的服务端架构,特别适合开发高性能、可扩展的应用程序。Play Framework 通过其独特的设计理念简化了...
10. **元编程**:Scala的反射和类型系统支持元编程,即在运行时检查和操作类型信息,甚至修改程序的行为。 11. ** Scalactic和ScalaTest**:Scala社区广泛使用的测试库,帮助开发者编写单元测试和集成测试,确保...
Play Framework 是一个开源的Web应用框架,用于构建现代、高性能的Java和Scala应用程序。它采用模型-视图-控制器(MVC)架构模式,并且强调简洁的代码和开发的即时反馈。Play Framework API 是开发者使用该框架进行...
Play Framework DDD示例Play框架的DDD示例播放框架:2.6.x Scala(Scala):2.12.6用例文章:创建并显示文章详细信息帐户:创建帐户并登录draw.io上的设计域:/ designs 给我一颗星星 :glowing_star: 如果你喜欢他们...
- **定义与背景**:Play Framework 是一款基于 Java 和 Scala 的高性能、轻量级 Web 开发框架。它采用 RESTful 架构设计,支持热重载功能,能够显著提高开发效率。本书(《Play Framework Cookbook》)提供了超过 60...
Play Frmaework for Scala 完整电子书300页
PlayFramework是一个高性能的Java和Scala框架,它支持Web应用的快速开发,并且主要面向RESTful应用程序。在PlayFramework中,为了确保数据的准确性和合法性,通常会在数据保存到数据库之前,对HTTP请求中的参数进行...
Play Framework 2.0 是一个开源的Web应用框架,它基于Scala和Java语言,遵循“模式-动作”(Action)架构,提供了一种轻量级、敏捷开发的方式。本篇文章将引导你通过创建一个简单的待办事项(Todo List)应用来了解...