- 浏览: 2477499 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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 422NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 287Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 368Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 329Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 408NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 348Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 283Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 202GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 384GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 270GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 255Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 253Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 245Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 230Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 228NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 216Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 507NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 223Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 316Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 316Supervisor 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 英文原版数据和代码
Mastering Play Framework for Scala 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开
Play Framework is an open source web application framework that is written in Java and Scala. It follows the Model-View-Controller architectural pattern and enables the user to employ Scala for ...
Mastering Play Framework for Scala 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Mastering Play Framework for Scala 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
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.
PlayFramework框架安全模块.pdf
Play Framework是一種用Scala編寫的Web應用框架,其遵循模型-視圖-控制器建築模式。Play Framework使用Scala編寫,並可以被編譯成Java虛擬機器位元組碼中的其他編程語言使用;例如Java語言。
scala学习-project.zip
Play Framework DDD示例Play框架的DDD示例播放框架:2.6.x Scala(Scala):2.12.6用例文章:创建并显示文章详细信息帐户:创建帐户并登录draw.io上的设计域:/ designs 给我一颗星星 :glowing_star: 如果你喜欢他们...
Play Frmaework for Scala 完整电子书300页
After that, the Scala web framework will be discussed in brief. Then, we will provide a comparative analysis of Java and Scala. Finally, we will dive into Scala programming to get started with Scala....
Play for Scala.Play.2.pdf, 完整版英文文档。 Play 框架关注于开发者的效率和 RESTful 风格的架构。Play 是敏捷软件开发的完美伴侣,它的目标是让基于 Java 的 web 应用开发变得更加容易。同时它也支持使用基于 ...
playframework-java-过滤器 关于如何将 play 的 Scala API 适配到 Java 的示例
Play for Scala shows you how to build Scala-based web applications using the Play 2 framework. This book starts by introducing Play through a comprehensive overview example. Then, you'll look at each ...
Scala and Spark for Big Data Analytics by Md. Rezaul Karim English | 25 July 2017 | ISBN: 1785280848 | ASIN: B072J4L8FQ | 898 Pages | AZW3 | 20.56 MB Harness the power of Scala to program Spark and ...
play2-war-plugin, 用于 Play Framework 2.x的WAR插件 用于 Play Framework 2.x的 WAR插件Current versions: Play 2.2.x : 1.2.1 Play 2.3.0 -> 2.3.1 : 1.3-beta1 (Scala 2.1