Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering play framework for scala
Mastering play framework for scala

Mastering play framework for scala: Leverage the awesome features of Play Framework to build scalable, resilient, and responsive applications

eBook
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Mastering play framework for scala

Chapter 2. Defining Actions

If you're reading this, you've either survived the first chapter or skipped it. Either way, I am assuming you know the structure of a simple Play application. A controller in Play generates Action values and, to do so, it uses several objects and methods internally. In this chapter, we will see what goes on behind the scenes and how we can leverage these actions when we build our application.

In this chapter, we will be covering the following topics:

  • Defining Actions
  • Request body parsers
  • Action composition and troubleshooting

A dummy Artist model

In the following sections, we will give make reference to an artist model. It is a simple class with a companion object, defined as follows:

case class Artist(name: String, country: String)

object Artist {
  val availableArtist = Seq(Artist("Wolfgang Amadeus Mozart", "Austria"), 
    Artist("Ludwig van Beethoven", "Germany"), 
    Artist("Johann Sebastian Bach", "Germany"), 
    Artist("Frédéric François Chopin", "Poland"), 
    Artist("Joseph Haydn", "Austria"), 
    Artist("Antonio Lucio Vivaldi", "Italy"), 
    Artist("Franz Peter Schubert", "Austria"), 
    Artist("Franz Liszt", "Austria"), 
    Artist("Giuseppe Fortunino Francesco Verdi", "Austria")) 

  def fetch: Seq[Artist] = {
    availableArtist 
  } 

  def fetchByName(name: String): Seq[Artist] = {
    availableArtist...

Actions

An Action in Play defines how a server should respond to a request. The methods, which define an Action, are mapped to a request in the routes file. For example, let's define an Action which displays the information of all the artists as a response:

def listArtist = Action {
  Ok(views.html.home(Artist.fetch))
}

Now, to use this Action, we should map it to a request in the routes file.

GET     /api/artist       controllers.Application.listArtist

In this example, we fetch all the artists and send them with the view, as the response to the request.

Note

The term api used in the route file is just a URL prefix and is not mandatory.

Run the application and access http://localhost:9000/api/artist from the browser. A table with the available artist is visible.

Action takes a request and yields a result. It is an implementation of the EssentialAction trait. It is defined as:

trait EssentialAction extends (RequestHeader => Iteratee[Array[Byte], Result]) with Handler {
 
  def apply() = this...

Request body parsers

Consider the most common POST request in any application—the request sent for logins. Will it be sufficient if the request body has the user's credentials in, say, a JSON or XML format? Will the request handler be able to extract this data and process it directly? No, since the data in the request has to be understood by the application code, it must be translated into a compatible type. For example, XML sent in a request must be translated to Scala XML for a Scala application.

There are several libraries, such as Jackson, XStream, and so on, which can be used to achieve this task, but we wouldn't need them as Play supports this internally. Play provides request body parsers to transform the request body into equivalent Scala objects for some of the frequently used content types. In addition to this, we can extend existing parsers or define new ones.

Every Action has a parser. How do I know this ? Well, the Action object, which we used to define how our...

Extending a parser

Let's extend the JSON parser so that we get a subscription model. We will assume that the Subscription model is defined as follows:

case class Subscription(emailId: String, interval: String) 

Now, let's write a parser that transforms the request body into a subscription object. The following code should be written in a controller:

val parseAsSubscription = parse.using {
    request => 
      parse.json.map {
        body => 
          val emailId:String = (body \ "emailId").as[String] 
          val fromDate:Long = (body \ "fromDate").as[Long] 
          Subscription(emailId, fromDate)
      }
  }

  implicit val subWrites = Json.writes[Subscription]
  def getSub = Action(parseAsSubscription) {
    request => 
      val subscription: Subscription = request.body
      Ok(Json.toJson(subscription))
   } 

There are also tolerant parsers. By tolerant, we mean that errors in a format are not ignored. This simply means that it ignores the...

Exploring the results

In Play, the response to a request is a result. A result has two components: the response header and the response body. Let's look at a simple example of this:

def plainResult = Action {
  Result( 
    header = ResponseHeader(200, Map(CONTENT_TYPE -> "text/plain")), 
    body = Enumerator("This is the response from plainResult method".getBytes())
  )
}

Notice that we used an enumerator for the response body. An enumerator is a means to provide data to an iteratee. We will discuss these in detail in Chapter 6, Reactive Data Streams.

Apart from this, a result has additional functions that equips us with better means to handle response headers, sessions, cookies, and so on.

A result can send JSON, XML, and images as a response, apart from a String content. An easier way of generating a result is to use the result helpers. A result helper is used for most of the HTTP response status. As an example, let's see how the TODO Action that comes built...

A dummy Artist model


In the following sections, we will give make reference to an artist model. It is a simple class with a companion object, defined as follows:

case class Artist(name: String, country: String)

object Artist {
  val availableArtist = Seq(Artist("Wolfgang Amadeus Mozart", "Austria"), 
    Artist("Ludwig van Beethoven", "Germany"), 
    Artist("Johann Sebastian Bach", "Germany"), 
    Artist("Frédéric François Chopin", "Poland"), 
    Artist("Joseph Haydn", "Austria"), 
    Artist("Antonio Lucio Vivaldi", "Italy"), 
    Artist("Franz Peter Schubert", "Austria"), 
    Artist("Franz Liszt", "Austria"), 
    Artist("Giuseppe Fortunino Francesco Verdi", "Austria")) 

  def fetch: Seq[Artist] = {
    availableArtist 
  } 

  def fetchByName(name: String): Seq[Artist] = {
    availableArtist.filter(a => a.name.contains(name)) 
  } 

  def fetchByCountry(country: String): Seq[Artist] = {
    availableArtist.filter(a => a.country == country) 
  } 

  def fetchByNameOrCountry...

Actions


An Action in Play defines how a server should respond to a request. The methods, which define an Action, are mapped to a request in the routes file. For example, let's define an Action which displays the information of all the artists as a response:

def listArtist = Action {
  Ok(views.html.home(Artist.fetch))
}

Now, to use this Action, we should map it to a request in the routes file.

GET     /api/artist       controllers.Application.listArtist

In this example, we fetch all the artists and send them with the view, as the response to the request.

Note

The term api used in the route file is just a URL prefix and is not mandatory.

Run the application and access http://localhost:9000/api/artist from the browser. A table with the available artist is visible.

Action takes a request and yields a result. It is an implementation of the EssentialAction trait. It is defined as:

trait EssentialAction extends (RequestHeader => Iteratee[Array[Byte], Result]) with Handler {
 
  def apply() = this

...

Request body parsers


Consider the most common POST request in any application—the request sent for logins. Will it be sufficient if the request body has the user's credentials in, say, a JSON or XML format? Will the request handler be able to extract this data and process it directly? No, since the data in the request has to be understood by the application code, it must be translated into a compatible type. For example, XML sent in a request must be translated to Scala XML for a Scala application.

There are several libraries, such as Jackson, XStream, and so on, which can be used to achieve this task, but we wouldn't need them as Play supports this internally. Play provides request body parsers to transform the request body into equivalent Scala objects for some of the frequently used content types. In addition to this, we can extend existing parsers or define new ones.

Every Action has a parser. How do I know this ? Well, the Action object, which we used to define how our app should respond...

Extending a parser


Let's extend the JSON parser so that we get a subscription model. We will assume that the Subscription model is defined as follows:

case class Subscription(emailId: String, interval: String) 

Now, let's write a parser that transforms the request body into a subscription object. The following code should be written in a controller:

val parseAsSubscription = parse.using {
    request => 
      parse.json.map {
        body => 
          val emailId:String = (body \ "emailId").as[String] 
          val fromDate:Long = (body \ "fromDate").as[Long] 
          Subscription(emailId, fromDate)
      }
  }

  implicit val subWrites = Json.writes[Subscription]
  def getSub = Action(parseAsSubscription) {
    request => 
      val subscription: Subscription = request.body
      Ok(Json.toJson(subscription))
   } 

There are also tolerant parsers. By tolerant, we mean that errors in a format are not ignored. This simply means that it ignores the content type header in the request...

Exploring the results


In Play, the response to a request is a result. A result has two components: the response header and the response body. Let's look at a simple example of this:

def plainResult = Action {
  Result( 
    header = ResponseHeader(200, Map(CONTENT_TYPE -> "text/plain")), 
    body = Enumerator("This is the response from plainResult method".getBytes())
  )
}

Notice that we used an enumerator for the response body. An enumerator is a means to provide data to an iteratee. We will discuss these in detail in Chapter 6, Reactive Data Streams.

Apart from this, a result has additional functions that equips us with better means to handle response headers, sessions, cookies, and so on.

A result can send JSON, XML, and images as a response, apart from a String content. An easier way of generating a result is to use the result helpers. A result helper is used for most of the HTTP response status. As an example, let's see how the TODO Action that comes built in with Play is implemented...

Asynchronous Actions


Suppose that we are at a food court and place an order to eat something at a kiosk, we are given a token and a bill. Later, when the order is ready, the kiosk flashes the token number, and upon noticing it, we collect the order.

This is similar to a request with an asynchronous response cycle, where the kiosk acts like the server, the order acts similar to a request, and the token as a promise, which gets resolved when the order is ready.

Most operations are better handled asynchronously. This is also mostly preferred since it does not block server resources until the operation is completed.

Play Action is a helper object, which extends the ActionBuilder trait. The apply method of the ActionBuilder trait implements the Action trait, which we saw earlier. Let's take a look at the relevant code from the ActionBuilder trait:

trait ActionBuilder[+R[_]] extends ActionFunction[Request, R] { 
  self => 

  final def apply[A](bodyParser: BodyParser[A])(block: R[A] => 
   ...
Left arrow icon Right arrow icon

Description

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.

Who is this book for?

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.

What you will learn

  • Customize your framework to accommodate the specific requirements of an application
  • Develop responsive, reliable, and highly scalable applications using Play Framework
  • Build and customize Play Framework plugins that can be used in multiple Play applications
  • Familiarize yourself with thirdparty APIs to avoid rewriting existing code
  • Gain an insight into the various aspects of testing and debugging in Play to successfully test your apps
  • Get to know all about the concepts of WebSockets and Actors to process messages based on events

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 29, 2015
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781783983810
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 29, 2015
Length: 274 pages
Edition : 1st
Language : English
ISBN-13 : 9781783983810
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
Mastering play framework for scala
€41.99
Learning Concurrent Programming in Scala
€36.99
Play Framework essentials
€24.99
Total 103.97 Stars icon

Table of Contents

14 Chapters
1. Getting Started with Play Chevron down icon Chevron up icon
2. Defining Actions Chevron down icon Chevron up icon
3. Building Routes Chevron down icon Chevron up icon
4. Exploring Views Chevron down icon Chevron up icon
5. Working with Data Chevron down icon Chevron up icon
6. Reactive Data Streams Chevron down icon Chevron up icon
7. Playing with Globals Chevron down icon Chevron up icon
8. WebSockets and Actors Chevron down icon Chevron up icon
9. Testing Chevron down icon Chevron up icon
10. Debugging and Logging Chevron down icon Chevron up icon
11. Web Services and Authentication Chevron down icon Chevron up icon
12. Play in Production Chevron down icon Chevron up icon
13. Writing Play Plugins Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2
(10 Ratings)
5 star 30%
4 star 20%
3 star 10%
2 star 20%
1 star 20%
Filter icon Filter
Top Reviews

Filter reviews by




adnan baloch Jun 21, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are a beginner or intermediate level Scala developer interested in dabbling in web development, this is the book for you. Concepts are presented in a very easy to understand manner that will appeal to readers of all skill levels. The author discusses how to leverage the power of the Play framework to get the benefits of REST and MVC pattern without worrying about the nitty gritty details since the framework is designed to make everything manageable. Whether the readers are interested in connectivity with relational databases or NoSQL databases, this book has them covered. Additionally, entire chapters dedicated to websockets, testing, logging, debugging, web services and authentication serve to empower the users with all the knowledge they need to design and develop rock solid web applications. Finally, readers will see how to deploy their Play applications in production using popular web servers and writing their own custom Play plugins to take care of any functionality not offered by the framework.
Amazon Verified review Amazon
Kevshouse Jun 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Many books either assume the reader is already an expert of difficult sums and bombard one with complexity from page 1 or miss out important development steps such as Unit Testing and Debugging.Shiti Saxena follows a different and refreshing approach leading the student in the basics of Play right through to Development, Deployment and the Packaging of applications.
Amazon Verified review Amazon
Amazon Customer Nov 26, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am new to Scala and Play, so I did need a book to give me overall picture as well as detailed examples. Luckily, I bought the book and found it very useful for me. The book also explains quite well what is the implementation of Play in each subject, which I like too.Really good book and highly recommended (especially for beginners)!
Amazon Verified review Amazon
Piotr Zalewski Jun 17, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The book is well structured and will be useful for understanding the basic principles of developing with Play Framework. You start learning from very simple example, and chapter after chapter you are more familiar with many aspects of Play. Its great book for beginners, but also a more advanced Play developers will find many interesting things. Ill expected a few more practical tips for a bigger applications, as Play is used in many places (from small to very complex), maybe some examples from real life (especially in chapter about Play in production). But it's good enough, and everyone could find something useful.
Amazon Verified review Amazon
Ryblov Alexandr Jun 16, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book provides the necessary information to start developing with Play Framework. Although the some information is brief (chapters about Aktors, Working with Data), author covers all the major issues. As for me, chapter 10 (Debugging and Logging) and chapter 12 (production) contain a lot of useful information. The book is well structured and will be useful for understanding the basic principles of developing with Play Framework
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.