`
sillycat
  • 浏览: 2542771 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Playframework(10)Scala Project and Database

 
阅读更多
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


分享到:
评论

相关推荐

    Mastering Play Framework for Scala

    Mastering Play Framework for Scala

    Mastering Play Framework for Scala.pdf

    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 0分

    Mastering Play Framework for Scala 英文无水印pdf pdf使用FoxitReader和PDF-XChangeViewer测试可以打开

    Mastering Play Framework for Scala mobi

    Mastering Play Framework for Scala 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Mastering Play Framework for Scala epub

    Mastering Play Framework for Scala 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    mastering play framework for scala

    《精通Scala的Play框架》是一本专为Scala开发者设计的深度学习指南,旨在帮助读者全面理解和熟练运用Play框架。Play框架是构建Web应用程序的一个强大工具,尤其在Scala语言的支持下,它提供了高度的灵活性和效率。这...

    《mastering play framework for scala》 Shiti Saxena & 著

    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 是一个基于Java和Scala的高性能Web应用框架,它提供了快速开发、可测试和敏捷迭代的能力。在Play Framework中,安全模块是一个重要的组件,它帮助开发者实现基本的认证(Authentication)和授权...

    Play for Scala.pdf_several7zb_scala_play_play开发scalaweb_

    Play Framework是一種用Scala編寫的Web應用框架,其遵循模型-視圖-控制器建築模式。Play Framework使用Scala編寫,並可以被編譯成Java虛擬機器位元組碼中的其他編程語言使用;例如Java語言。

    playframework中文教程.zip

    Play Framework 是一个开源的Web应用框架,主要针对Java和Scala开发者设计,它的核心理念是简化开发流程,提高开发效率,并且特别强调了RESTful架构风格。这个“playframework中文教程.zip”压缩包很可能是为了帮助...

    Play Framework Cookbook.pdf

    - **框架简介**:Play Framework 是一个开源的 Web 开发框架,基于 Java 和 Scala 编程语言。它采用轻量级、非阻塞的服务端架构,特别适合开发高性能、可扩展的应用程序。Play Framework 通过其独特的设计理念简化了...

    scala学习-project.zip

    10. **元编程**:Scala的反射和类型系统支持元编程,即在运行时检查和操作类型信息,甚至修改程序的行为。 11. ** Scalactic和ScalaTest**:Scala社区广泛使用的测试库,帮助开发者编写单元测试和集成测试,确保...

    play framework api,play! framework api,play api

    Play Framework 是一个开源的Web应用框架,用于构建现代、高性能的Java和Scala应用程序。它采用模型-视图-控制器(MVC)架构模式,并且强调简洁的代码和开发的即时反馈。Play Framework API 是开发者使用该框架进行...

    ddd-playframework-scala:Play框架的DDD示例(域驱动设计)

    Play Framework DDD示例Play框架的DDD示例播放框架:2.6.x Scala(Scala):2.12.6用例文章:创建并显示文章详细信息帐户:创建帐户并登录draw.io上的设计域:/ designs 给我一颗星星 :glowing_star: 如果你喜欢他们...

    Play Framework Cookbook

    - **定义与背景**:Play Framework 是一款基于 Java 和 Scala 的高性能、轻量级 Web 开发框架。它采用 RESTful 架构设计,支持热重载功能,能够显著提高开发效率。本书(《Play Framework Cookbook》)提供了超过 60...

    Play Frmaework for Scala 完整电子书300页

    Play Frmaework for Scala 完整电子书300页

    PlayFramework框架验证.pdf

    PlayFramework是一个高性能的Java和Scala框架,它支持Web应用的快速开发,并且主要面向RESTful应用程序。在PlayFramework中,为了确保数据的准确性和合法性,通常会在数据保存到数据库之前,对HTTP请求中的参数进行...

    Play framework 2.0 -第一个应用程序

    Play Framework 2.0 是一个开源的Web应用框架,它基于Scala和Java语言,遵循“模式-动作”(Action)架构,提供了一种轻量级、敏捷开发的方式。本篇文章将引导你通过创建一个简单的待办事项(Todo List)应用来了解...

Global site tag (gtag.js) - Google Analytics