SlideShare a Scribd company logo
Play ! Framework 
Introduction & Highlights 
Malti Yadav 
malti@knoldus.com
Quick Overview 
 Stateless framework 
 Integration of JSON 
 Full stack web framework 
 Compilation and Exact Error 
 Lots of build in feature for fast developement 
 Urls are entry poin to application 
 RESTful by default
Architecture
Setup play project
Standard Application Layout 
app → Application sources 
└ assets → Compiled asset sources 
└ stylesheets → Typically LESS CSS sources 
└ javascripts → Typically CoffeeScript sources 
└ controllers → Application controllers 
└ models → Application business layer 
└ views → Templates 
build.sbt → Application build script 
conf → Configurations files and other non-compiled resources (on classpath) 
└ application.conf → Main configuration file 
└ routes → Routes definition 
public → Public assets 
└ stylesheets → CSS files 
└ javascripts → Javascript files 
└ images → Image files 
project → sbt configuration files 
└ build.properties → Marker for sbt project 
└ plugins.sbt → sbt plugins including the declaration for Play itself 
lib → Unmanaged libraries dependencies 
logs → Standard logs folder 
└ application.log → Default log file 
target → Generated stuff 
└ scala-2.10.0 
└ cache 
└ classes → Compiled class files 
└ classes_managed → Managed class files (templates, ...) 
└ resource_managed → Managed resources (less, ...) 
└ src_managed → Generated sources (templates, ...) 
test → source folder for unit or functional tests
The conf/routes file 
# Routes 
# This file defines all application routes (Higher priority routes first) 
# ~~~~ 
# Home page 
GET / controllers.Application.index 
# Registration page 
GET /registration controllers.Application.registration 
# Login page 
GET /login controllers.Application.login 
# logout 
GET /logout controllers.Application.logout 
#save userdata 
POST /registration controllers.Application.createUser 
# loginAuthentication 
POST /login controllers.Application.loginAuthentication 
# Dashboard page 
GET /dashboard controllers.Application.dashboard 
# Map static resources from the /public folder to the /assets URL path 
GET /assets/*file controllers.Assets.at(path="/public", file)
The conf/application file 
 Configure database access 
 mongodb.servers=[“localhost:27017”] 
 mongodb.db=”test” 
 Logger 
 Router 
 Specific modules
Designing a domain models 
package models 
import java.util.Date 
object Domains { 
/* 
* Case class for UserForm 
*/ 
case class UserForm(name:String,email:String,password: 
(String,String),joinDate: Date) 
/* 
* Case class for LoginForm 
*/ 
case class LoginForm(email:String,password: String) 
}
Designing a QueryBuilder models 
package models 
import play.api._ 
import play.api.mvc._ 
import play.api.libs.functional.syntax._ 
import play.api.libs.json._ 
import play.api.libs.concurrent.Execution.Implicits.defaultContext 
import scala.concurrent.Future 
import reactivemongo.api._ 
import play.modules.reactivemongo.MongoController 
import play.modules.reactivemongo.json.collection.JSONCollection 
object QueryBuilder extends Controller with MongoController { 
/* 
* Get a JSONCollection (a Collection implementation that is designed to work 
* with JsObject, Reads and Writes.) 
* Note that the `collection` is not a `val`, but a `def`. We do _not_ store 
* the collection reference to avoid potential problems in development with 
* Play hot-reloading. 
*/ 
def collection(collectionname: String): JSONCollection = 
db.collection[JSONCollection](collectionname)
Cont... 
def getDocumentsByQuery(collectionname: String, query: JsObject): 
Future[List[JsObject]] = { 
val cursor: Cursor[JsObject] = 
collection(collectionname).find(query).cursor[JsObject] 
val futureresult: Future[List[JsObject]] = cursor.collect[List]() 
futureresult 
} 
def insertDocuments(collectionname: String, documents: JsObject) { 
collection(collectionname).insert(documents) 
} 
}
Designing a helper class 
package utils 
import play.api.mvc.RequestHeader 
object Helper { 
/* 
* find URI 
* @param request 
*/ 
def findUri(request: RequestHeader): String = { 
request.uri 
}
Cont... 
/* 
* find session values 
* @param request 
* @param element - find session value stored in element 
*/ 
def findSession(request: RequestHeader, element: String): String = { 
request.session.get(element).map { sessionvalue => 
sessionvalue 
}.getOrElse { 
" " 
} 
}
Cont... 
/* 
* find flash values 
* @param request - HTTP request 
* @param element - find flash value stored in element 
*/ 
def findFlash(request: RequestHeader, element: String): String = { 
request.flash.get(element).getOrElse { 
" " 
} 
} 
}
Designing a constants class 
package utils 
object Constants { 
val USER_COLLECTION_NAME = "user" 
val MIN_LENGTH_OF_PASSWORD = 6 
val PASSWORD_NOT_MATCHED = "Password must be matched" 
val HOME_PAGE_TITLE = "Welcome to home page" 
val WRONG_LOGIN_DETAILS = "The email or password you entered is incorrect" 
val DASHBOARD_TITLE = "Welcome to dashboard" 
val ENTERED_EMAIL_EXISTS = "Entered email id already exist in database" 
val DEFAULT_PROFILE_IMAGE = "profile.jpeg" 
}
Calling business logic (Controller) 
package controllers 
import models.Domains._ 
import models.QueryBuilder._ 
import utils.Helper._ 
import utils.Constants._ 
import play.api._ 
import play.api.mvc._ 
import play.api.data.Form 
import play.api.data.Forms._ 
import play.api.libs.concurrent.Execution.Implicits.defaultContext 
import play.api.libs.functional.syntax._ 
import play.api.libs.json._ 
import java.util.Date 
import scala.concurrent.Future 
import views.html 
object Application extends Controller {
Cont... 
/* 
* userForm 
*/ 
val userForm = Form( 
mapping( 
"name" -> nonEmptyText, "email" -> email, "password" -> tuple("main" -> 
nonEmptyText(MIN_LENGTH_OF_PASSWORD), "confirm" -> nonEmptyText). 
verifying(PASSWORD_NOT_MATCHED, passwords => passwords._1 == 
passwords._2), "joinDate" -> date("yyyy-MM-dd"))(UserForm.apply) 
(UserForm.unapply)) 
/* 
* Login Form 
*/ 
val loginForm = Form( 
mapping( 
"email" -> email, 
"password" -> nonEmptyText)(LoginForm.apply)(LoginForm.unapply))
Cont..... 
/* 
* Redirect Home Page 
*/ 
def index = Action { request => 
Ok(html.index(HOME_PAGE_TITLE, findUri(request))) 
} 
/* 
* Redirect Registration Page 
*/ 
def registration = Action { implicit request => 
val name = findFlash(request, "name") 
val email = findFlash(request, "email") 
if (email != " ") { 
val userForm = Application.userForm.fill(UserForm(name, email, (" ", " 
"), new Date)) 
} 
Ok(html.registration(userForm, findUri(request))) 
}
Cont... 
/* 
* Redirect Login Page 
*/ 
def login = Action { implicit request => 
val email = findFlash(request, "email") 
if (email != " ") { 
val loginForm = Application.loginForm.fill(LoginForm(email, " ")) 
} 
Ok(html.login(loginForm, findUri(request))) 
} 
/* 
* Logout and clean the session. 
*/ 
def logout = Action { implicit request => 
Redirect(routes.Application.login).withNewSession 
}
Cont... 
/* 
* Handle UserForm Submission 
*/ 
def createUser = Action.async { implicit request => 
userForm.bindFromRequest.fold( 
error => Future(BadRequest(html.registration(error, findUri(request)))), 
userForm => { 
val name = userForm.name 
val email = userForm.email 
val (password, _) = userForm.password 
val joinDate = userForm.joinDate 
val saveRecord = Json.obj("name" -> name, "email" -> email, "password" -> password, 
"joinDate" -> joinDate) 
val jsonuserdata = Json.obj("email" -> email) 
val futureUserdetails = getDocumentsByQuery(USER_COLLECTION_NAME, jsonuserdata) 
futureUserdetails.map { result => 
if (result.size > 0) { 
Redirect(routes.Application.registration).flashing( 
"message" -> ENTERED_EMAIL_EXISTS, "name" -> name, "email" -> email) 
} else { 
val futuresaveUser = insertDocuments(USER_COLLECTION_NAME, saveRecord) 
Redirect(routes.Application.dashboard).withSession( 
"email" -> email) 
} 
} 
}) 
}
Cont... 
/* 
* Login Authentication 
*/ 
def loginAuthentication = Action.async { implicit request => 
loginForm.bindFromRequest.fold( 
error => Future(BadRequest(html.login(error, findUri(request)))), 
loginForm => { 
val email = loginForm.email 
val password = loginForm.password 
val jsonuserdata = Json.obj("email" -> email, "password" -> password) 
val futureUserdetails = getDocumentsByQuery(USER_COLLECTION_NAME, 
jsonuserdata) 
futureUserdetails.map { result => 
if (result.size > 0) { 
Redirect(routes.Application.dashboard).withSession( 
"email" -> email) 
} else { 
Redirect(routes.Application.login).flashing( 
"message" -> WRONG_LOGIN_DETAILS, "email" -> email) 
} 
} 
}) 
}
Cont... 
/* 
* Redirect Dashboard 
*/ 
def dashboard = Action.async { implicit request => 
if (findSession(request, "email") == " ") { 
Future(Redirect(routes.Application.login)) 
} else { 
val jsonuserdata = Json.obj("email" -> findSession(request, "email")) 
val userfutureresult = getDocumentsByQuery(USER_COLLECTION_NAME, 
jsonuserdata) 
userfutureresult.map { result => 
Ok(html.dashboard(DASHBOARD_TITLE, findUri(request),result)) 
} 
} 
} 
}
The templating system 
(main.scala.html) 
@(title:String)(content:Html) 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<title>@title</title> 
<meta charset="utf-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" media="screen" 
href="@routes.Assets.at("Bootstrap/css/bootstrap.min.css")"> 
<link rel="stylesheet" media="screen" 
href="@routes.Assets.at("Bootstrap/css/bootstrap-theme.min.css")"> 
<link rel="stylesheet" media="screen" 
href="@routes.Assets.at("css/custom.css")"> 
<script src="@routes.Assets.at("jquery/jquery-1.11.1.min.js")" 
type="text/javascript"></script> 
<script src="@routes.Assets.at("Bootstrap/js/bootstrap.min.js")" 
type="text/javascript"></script> 
<script src="@routes.Assets.at("Bootstrap/js/bootstrap.js")" 
type="text/javascript"></script> 
</head> 
<body>@content 
</body> 
</html>
Cont... 
registration.scala.html 
@import models.Domains._ 
@(userForm:Form[UserForm],path:String)(implicit flash: Flash) 
@import helper._ 
@main("Welcome to Registration Page"){ 
<div class="container"> 
@header(path) 
<div class="jumbotron"> 
@form(routes.Application.createUser){ 
@registrationformElements(userForm) 
<div class="registration-error">@flash.get("message")</div> 
<input type="submit" name="submit" value="Submit" class="btn btn-primary"> 
} 
</div> 
@footer() 
</div> 
}
Cont... 
registrationformElements.scala.html 
@import models.Domains._ 
@(userForm: Form[UserForm]) 
@import helper._ 
@implicitField = @{ helper.FieldConstructor(BootstrapInput.f) } 
@inputText(userForm("name"),'_label -> "Name", '_showConstraints -> false,'class 
-> "form-control") 
@inputText(userForm("email"),'_label -> "Email", '_showConstraints -> 
false,'class -> "form-control") 
@inputPassword(userForm("password.main"),'_label -> "Password", '_help 
->"Password should be minimum 6 character",'class -> "form-control") 
@inputPassword(userForm("password.confirm"),'_error 
->userForm.error("password"), '_label -> "Confirm Password", '_showConstraints 
-> false,'class -> "form-control") 
@inputText(userForm("joinDate"),'_label -> "Joining Date", '_showConstraints -> 
false,'class -> "form-control")
Questions ?
THANK YOU

More Related Content

What's hot

Web2py
Web2pyWeb2py
Web2py
Lucas D
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code LabColin Su
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.fRui Apps
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
Benjamin Eberlei
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Benjamin Eberlei
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
Maurizio Pelizzone
 
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Francois Marier
 
Mule esb – connecting to ms sql db
Mule esb – connecting to ms sql dbMule esb – connecting to ms sql db
Mule esb – connecting to ms sql db
Gunjan Deshmukh
 
Jquery
JqueryJquery
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
Mark Rackley
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
Paul Bearne
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testing
smontanari
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
ghnash
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Rabble .
 

What's hot (18)

Web2py
Web2pyWeb2py
Web2py
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
 
Mule esb – connecting to ms sql db
Mule esb – connecting to ms sql dbMule esb – connecting to ms sql db
Mule esb – connecting to ms sql db
 
Jquery
JqueryJquery
Jquery
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testing
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 

Viewers also liked

Play Framework 2.5
Play Framework 2.5Play Framework 2.5
Play Framework 2.5
m-kurz
 
Apache Cassandra overview
Apache Cassandra overviewApache Cassandra overview
Apache Cassandra overview
ElifTech
 
Scala, Apache Spark, The PlayFramework and Docker in IBM Platform As A Service
Scala, Apache Spark, The PlayFramework and Docker in IBM Platform As A ServiceScala, Apache Spark, The PlayFramework and Docker in IBM Platform As A Service
Scala, Apache Spark, The PlayFramework and Docker in IBM Platform As A Service
Romeo Kienzler
 
Overview of DataStax OpsCenter
Overview of DataStax OpsCenterOverview of DataStax OpsCenter
Overview of DataStax OpsCenter
DataStax
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
What is play
What is playWhat is play
What is play
Takafumi Ikeda
 

Viewers also liked (6)

Play Framework 2.5
Play Framework 2.5Play Framework 2.5
Play Framework 2.5
 
Apache Cassandra overview
Apache Cassandra overviewApache Cassandra overview
Apache Cassandra overview
 
Scala, Apache Spark, The PlayFramework and Docker in IBM Platform As A Service
Scala, Apache Spark, The PlayFramework and Docker in IBM Platform As A ServiceScala, Apache Spark, The PlayFramework and Docker in IBM Platform As A Service
Scala, Apache Spark, The PlayFramework and Docker in IBM Platform As A Service
 
Overview of DataStax OpsCenter
Overview of DataStax OpsCenterOverview of DataStax OpsCenter
Overview of DataStax OpsCenter
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
What is play
What is playWhat is play
What is play
 

Similar to Intoduction on Playframework

“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
AvitoTech
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
John Wilker
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
Hugo Hamon
 
Knockoutjs UG meeting presentation
Knockoutjs UG meeting presentationKnockoutjs UG meeting presentation
Knockoutjs UG meeting presentation
Valdis Iljuconoks
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
Siarzh Miadzvedzeu
 
ABCD firebase
ABCD firebaseABCD firebase
ABCD firebase
옥현 도
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
Shumpei Shiraishi
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps OfflinePedro Morais
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
Jonathan Wage
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
Boris Nadion
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QAFest
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
joaopmaia
 

Similar to Intoduction on Playframework (20)

“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Knockoutjs UG meeting presentation
Knockoutjs UG meeting presentationKnockoutjs UG meeting presentation
Knockoutjs UG meeting presentation
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
ABCD firebase
ABCD firebaseABCD firebase
ABCD firebase
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 

More from Knoldus Inc.

Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
Knoldus Inc.
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
Knoldus Inc.
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
Knoldus Inc.
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
Knoldus Inc.
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
Knoldus Inc.
 

More from Knoldus Inc. (20)

Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 

Recently uploaded

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 

Recently uploaded (20)

Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 

Intoduction on Playframework

  • 1. Play ! Framework Introduction & Highlights Malti Yadav malti@knoldus.com
  • 2. Quick Overview  Stateless framework  Integration of JSON  Full stack web framework  Compilation and Exact Error  Lots of build in feature for fast developement  Urls are entry poin to application  RESTful by default
  • 5. Standard Application Layout app → Application sources └ assets → Compiled asset sources └ stylesheets → Typically LESS CSS sources └ javascripts → Typically CoffeeScript sources └ controllers → Application controllers └ models → Application business layer └ views → Templates build.sbt → Application build script conf → Configurations files and other non-compiled resources (on classpath) └ application.conf → Main configuration file └ routes → Routes definition public → Public assets └ stylesheets → CSS files └ javascripts → Javascript files └ images → Image files project → sbt configuration files └ build.properties → Marker for sbt project └ plugins.sbt → sbt plugins including the declaration for Play itself lib → Unmanaged libraries dependencies logs → Standard logs folder └ application.log → Default log file target → Generated stuff └ scala-2.10.0 └ cache └ classes → Compiled class files └ classes_managed → Managed class files (templates, ...) └ resource_managed → Managed resources (less, ...) └ src_managed → Generated sources (templates, ...) test → source folder for unit or functional tests
  • 6. The conf/routes file # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET / controllers.Application.index # Registration page GET /registration controllers.Application.registration # Login page GET /login controllers.Application.login # logout GET /logout controllers.Application.logout #save userdata POST /registration controllers.Application.createUser # loginAuthentication POST /login controllers.Application.loginAuthentication # Dashboard page GET /dashboard controllers.Application.dashboard # Map static resources from the /public folder to the /assets URL path GET /assets/*file controllers.Assets.at(path="/public", file)
  • 7. The conf/application file  Configure database access  mongodb.servers=[“localhost:27017”]  mongodb.db=”test”  Logger  Router  Specific modules
  • 8. Designing a domain models package models import java.util.Date object Domains { /* * Case class for UserForm */ case class UserForm(name:String,email:String,password: (String,String),joinDate: Date) /* * Case class for LoginForm */ case class LoginForm(email:String,password: String) }
  • 9. Designing a QueryBuilder models package models import play.api._ import play.api.mvc._ import play.api.libs.functional.syntax._ import play.api.libs.json._ import play.api.libs.concurrent.Execution.Implicits.defaultContext import scala.concurrent.Future import reactivemongo.api._ import play.modules.reactivemongo.MongoController import play.modules.reactivemongo.json.collection.JSONCollection object QueryBuilder extends Controller with MongoController { /* * Get a JSONCollection (a Collection implementation that is designed to work * with JsObject, Reads and Writes.) * Note that the `collection` is not a `val`, but a `def`. We do _not_ store * the collection reference to avoid potential problems in development with * Play hot-reloading. */ def collection(collectionname: String): JSONCollection = db.collection[JSONCollection](collectionname)
  • 10. Cont... def getDocumentsByQuery(collectionname: String, query: JsObject): Future[List[JsObject]] = { val cursor: Cursor[JsObject] = collection(collectionname).find(query).cursor[JsObject] val futureresult: Future[List[JsObject]] = cursor.collect[List]() futureresult } def insertDocuments(collectionname: String, documents: JsObject) { collection(collectionname).insert(documents) } }
  • 11. Designing a helper class package utils import play.api.mvc.RequestHeader object Helper { /* * find URI * @param request */ def findUri(request: RequestHeader): String = { request.uri }
  • 12. Cont... /* * find session values * @param request * @param element - find session value stored in element */ def findSession(request: RequestHeader, element: String): String = { request.session.get(element).map { sessionvalue => sessionvalue }.getOrElse { " " } }
  • 13. Cont... /* * find flash values * @param request - HTTP request * @param element - find flash value stored in element */ def findFlash(request: RequestHeader, element: String): String = { request.flash.get(element).getOrElse { " " } } }
  • 14. Designing a constants class package utils object Constants { val USER_COLLECTION_NAME = "user" val MIN_LENGTH_OF_PASSWORD = 6 val PASSWORD_NOT_MATCHED = "Password must be matched" val HOME_PAGE_TITLE = "Welcome to home page" val WRONG_LOGIN_DETAILS = "The email or password you entered is incorrect" val DASHBOARD_TITLE = "Welcome to dashboard" val ENTERED_EMAIL_EXISTS = "Entered email id already exist in database" val DEFAULT_PROFILE_IMAGE = "profile.jpeg" }
  • 15. Calling business logic (Controller) package controllers import models.Domains._ import models.QueryBuilder._ import utils.Helper._ import utils.Constants._ import play.api._ import play.api.mvc._ import play.api.data.Form import play.api.data.Forms._ import play.api.libs.concurrent.Execution.Implicits.defaultContext import play.api.libs.functional.syntax._ import play.api.libs.json._ import java.util.Date import scala.concurrent.Future import views.html object Application extends Controller {
  • 16. Cont... /* * userForm */ val userForm = Form( mapping( "name" -> nonEmptyText, "email" -> email, "password" -> tuple("main" -> nonEmptyText(MIN_LENGTH_OF_PASSWORD), "confirm" -> nonEmptyText). verifying(PASSWORD_NOT_MATCHED, passwords => passwords._1 == passwords._2), "joinDate" -> date("yyyy-MM-dd"))(UserForm.apply) (UserForm.unapply)) /* * Login Form */ val loginForm = Form( mapping( "email" -> email, "password" -> nonEmptyText)(LoginForm.apply)(LoginForm.unapply))
  • 17. Cont..... /* * Redirect Home Page */ def index = Action { request => Ok(html.index(HOME_PAGE_TITLE, findUri(request))) } /* * Redirect Registration Page */ def registration = Action { implicit request => val name = findFlash(request, "name") val email = findFlash(request, "email") if (email != " ") { val userForm = Application.userForm.fill(UserForm(name, email, (" ", " "), new Date)) } Ok(html.registration(userForm, findUri(request))) }
  • 18. Cont... /* * Redirect Login Page */ def login = Action { implicit request => val email = findFlash(request, "email") if (email != " ") { val loginForm = Application.loginForm.fill(LoginForm(email, " ")) } Ok(html.login(loginForm, findUri(request))) } /* * Logout and clean the session. */ def logout = Action { implicit request => Redirect(routes.Application.login).withNewSession }
  • 19. Cont... /* * Handle UserForm Submission */ def createUser = Action.async { implicit request => userForm.bindFromRequest.fold( error => Future(BadRequest(html.registration(error, findUri(request)))), userForm => { val name = userForm.name val email = userForm.email val (password, _) = userForm.password val joinDate = userForm.joinDate val saveRecord = Json.obj("name" -> name, "email" -> email, "password" -> password, "joinDate" -> joinDate) val jsonuserdata = Json.obj("email" -> email) val futureUserdetails = getDocumentsByQuery(USER_COLLECTION_NAME, jsonuserdata) futureUserdetails.map { result => if (result.size > 0) { Redirect(routes.Application.registration).flashing( "message" -> ENTERED_EMAIL_EXISTS, "name" -> name, "email" -> email) } else { val futuresaveUser = insertDocuments(USER_COLLECTION_NAME, saveRecord) Redirect(routes.Application.dashboard).withSession( "email" -> email) } } }) }
  • 20. Cont... /* * Login Authentication */ def loginAuthentication = Action.async { implicit request => loginForm.bindFromRequest.fold( error => Future(BadRequest(html.login(error, findUri(request)))), loginForm => { val email = loginForm.email val password = loginForm.password val jsonuserdata = Json.obj("email" -> email, "password" -> password) val futureUserdetails = getDocumentsByQuery(USER_COLLECTION_NAME, jsonuserdata) futureUserdetails.map { result => if (result.size > 0) { Redirect(routes.Application.dashboard).withSession( "email" -> email) } else { Redirect(routes.Application.login).flashing( "message" -> WRONG_LOGIN_DETAILS, "email" -> email) } } }) }
  • 21. Cont... /* * Redirect Dashboard */ def dashboard = Action.async { implicit request => if (findSession(request, "email") == " ") { Future(Redirect(routes.Application.login)) } else { val jsonuserdata = Json.obj("email" -> findSession(request, "email")) val userfutureresult = getDocumentsByQuery(USER_COLLECTION_NAME, jsonuserdata) userfutureresult.map { result => Ok(html.dashboard(DASHBOARD_TITLE, findUri(request),result)) } } } }
  • 22. The templating system (main.scala.html) @(title:String)(content:Html) <!DOCTYPE html> <html lang="en"> <head> <title>@title</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" media="screen" href="@routes.Assets.at("Bootstrap/css/bootstrap.min.css")"> <link rel="stylesheet" media="screen" href="@routes.Assets.at("Bootstrap/css/bootstrap-theme.min.css")"> <link rel="stylesheet" media="screen" href="@routes.Assets.at("css/custom.css")"> <script src="@routes.Assets.at("jquery/jquery-1.11.1.min.js")" type="text/javascript"></script> <script src="@routes.Assets.at("Bootstrap/js/bootstrap.min.js")" type="text/javascript"></script> <script src="@routes.Assets.at("Bootstrap/js/bootstrap.js")" type="text/javascript"></script> </head> <body>@content </body> </html>
  • 23. Cont... registration.scala.html @import models.Domains._ @(userForm:Form[UserForm],path:String)(implicit flash: Flash) @import helper._ @main("Welcome to Registration Page"){ <div class="container"> @header(path) <div class="jumbotron"> @form(routes.Application.createUser){ @registrationformElements(userForm) <div class="registration-error">@flash.get("message")</div> <input type="submit" name="submit" value="Submit" class="btn btn-primary"> } </div> @footer() </div> }
  • 24. Cont... registrationformElements.scala.html @import models.Domains._ @(userForm: Form[UserForm]) @import helper._ @implicitField = @{ helper.FieldConstructor(BootstrapInput.f) } @inputText(userForm("name"),'_label -> "Name", '_showConstraints -> false,'class -> "form-control") @inputText(userForm("email"),'_label -> "Email", '_showConstraints -> false,'class -> "form-control") @inputPassword(userForm("password.main"),'_label -> "Password", '_help ->"Password should be minimum 6 character",'class -> "form-control") @inputPassword(userForm("password.confirm"),'_error ->userForm.error("password"), '_label -> "Confirm Password", '_showConstraints -> false,'class -> "form-control") @inputText(userForm("joinDate"),'_label -> "Joining Date", '_showConstraints -> false,'class -> "form-control")