2. Agenda
· Introduction to Scala Play
· Key Features
· Anatomy of Scala Play Application
· Architecture of Scala play
· MVC Architecture in Scala play
· Developing Rest API in Play Framework
· Adding Dependency In Play Framework
· Request URL Mapping in play
· Reading Configuration File
· Concurrent Programming in Scala
· Packing for Production – Commonly used Commands
3. Introduction to Play Framework
· Is based on a lightweight, stateless, web-friendly, non blocking architecture.
· Built on Akka, provides predictable and minimal resources consumption (CPU, memory, threads)
for highly-scalable applications.
· Lots of built in features for fast development.
· Follows MVC architecture
4. Features of Play Framework
· Strong focus on productivity. Fast turnaround.
· Hot reloading: Fix the bug and hit reload!
· Type safe all the way, even templates and route files!
· Use Scala or Java: Your choice. You can even mix them!
· Predefined module for heavy lifting. Mail Service, Authentication
· Play Provides full stack
· Websocket support
· Template Engine for views
· Testing engine
5. Installation of Play Framework
· Dependencies
· Java 1.8
· Sbt 1.1.0
· Intellji or Eclipse
· Creating New Application
· Using Play Starter Projects
· Download Play Starter
· Create a new application using SBT
· Requires giter8
6. Steps to Initialize Play
Framework
· Unzip the package and place in the desired location
· Open the package in the IntelliJ editor File->Open
· Open the terminal inside the IntelliJ editor
· Run $sbt run - Process will take more time, please wait patiently
· Application will be opened at port 9000
13. Playing Around Play Framework
· Accessing the End Point
· GET http://localhost:9000 - HTML View Page
· GET http://localhost:9000/count - Count gets incremented for each page refresh or request
· GET http://localhost:9000/message - Displays Hi! Message
· Important File to Remember in Play Framework
· build.sbt – Adding third party dependency from Maven
· Conf/applicaton.conf – Contains the Play framework settings
· Conf/routes – Contains the Url Mapping
· App folder holds the controllers, views, filters etc
15. Hello World using Play
· Go to conf/routes
· GET /greetings controllers.HelloWorldController.index
· HelloWorldController – name of the controller class file
· Index is the function name inside the controller class file
· Create a controller called HelloWorldController.scala in app/controller
package controllers
import javax.inject._
import play.api.mvc._
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
@Singleton
class HelloWorldController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
/**
Returns hello world
*/
def index = Action {
Ok("Hello World")
}
}
17. Adding Dependency in Play
· Using build.sbt
· // https://mvnrepository.com/artifact/org.apache.opennlp/opennlp-tools
libraryDependencies += "org.apache.opennlp" % "opennlp-tools" % "1.8.3"
· Using custom build jar
· Placing the custom build jar or jar which are not available in the Maven repository. We
should place those files inside lib in root location
18. Play Terminology
· Actions
· A Action is basically a function that handles a request and generates a result to be sent to
the client.
· Controllers
· A controller in Play is nothing more than an object that generates Action values. Controllers
are typically defined as classes to take advantage of Dependency Injection.
· Modules
· Play uses public modules to augment built-in functionality.
19. Returning Different Result Type
· val textResult = Ok("Hello World!")
· By default returns text/plain
· val xmlResult = Ok(<message>Hello World!</message>)
· Returns the result application/xml
· val htmlResult2 = Ok(<h1>Hello World!</h1>).as(HTML)
· Renders the HTML page
21. HTTP routing
· The built-in HTTP router
· The router is the component in charge of translating each incoming HTTP request to an
Action.
· An HTTP request is seen as an event by the MVC framework. This event contains two major
pieces of information:
· The request path (e.g. /clients/1542, /photos/list), including the query string
· The HTTP method (e.g. GET, POST)
· URI Pattern
· Static Path
· GET /clients/all controllers.Clients.list()
· Dynamic Parts
· GET /clients/:id controllers.Clients.show(id: Long)
· Router Feature
· What if I say you can do regex validation in route file itself !
23. Configuration File
· Play uses the Typesafe config library, but Play also provides a nice Scala wrapper called
Configuration with more advanced Scala features.
class MyController @Inject() (config: Configuration, c: ControllerComponents) extends
AbstractController(c) {
def getFoo = Action {
Ok(config.get[String]("name"))
}
}
24. Scala Concepts
· Writing Future Method
· A Future gives you a simple way to run an algorithm concurrently. A future starts running
concurrently when you create it and returns a result at some point, well, in the future.
val f = Future {
ComplexOperation // takes 100 sec approx
42
}
· Case class
· Case classes are like regular classes with a few key differences which we will go over. Case
classes are good for modeling immutable data
case class Book(isbn: String)
val frankenstein = Book("978-0486282114")
25. Creating Part of Speech Tagger
def convertPos(data:String) = Future {
var result:String = ""
if(data.isEmpty)
Future.successful(BadRequest("Data is empty"))
try {
// converting option[x] to x
// val sentence = data.get
// tokenize the sentence
val projectPath = Play.application().path();
var tokenModelIn = new FileInputStream(projectPath+"/conf/resource/en-token.bin")
val tokenModel = new TokenizerModel(tokenModelIn)
val tokenizer = new TokenizerME(tokenModel)
val tokens = tokenizer.tokenize(data)
// Parts-Of-Speech Tagging
// reading parts-of-speech model to a stream
var posModelIn = new FileInputStream(projectPath+ "/conf/resource/en-pos-maxent.bin")
// loading the parts-of-speech model from stream
val posModel = new POSModel(posModelIn)
// initializing the parts-of-speech tagger with model
val posTagger = new POSTaggerME(posModel)
// Tagger tagging the tokens
val tags = posTagger.tag(tokens)
// Getting the probabilities of the tags given to the tokens
val probs = posTagger.probs
// Iterates the token, tag and probability score
// Flattening to list makes into string
result++= (0 until tokens.length).map(i => tokens(i) + "t:t" + tags(i) + "t:t" + probs(i) + "n").flatten.toList
} catch {
case e: IOException =>
// Model loading failed, handle the error
e.printStackTrace()
}
result.toString
}
27. References
· Scala Programming Language (Wikipedia Article)
· Scala official site
· Typesafe
· Programming in Scala Book on Amazon
· Functional Programming Principles in Scala on Coursera
· Principles of Reactive Programming on Coursera
· Play Framework Official Website
· Play Framework (Wikipedia Article)
· Typesafe Activator