SlideShare une entreprise Scribd logo
1  sur  47
Télécharger pour lire hors ligne
Play Framework and Activator 
Getting started with the Play Framework with Activator
Topics, goals, context 
2 
• An introduction to Typesafe Activator 
• An introduction to the core features of Play 2.x 
• What is a Reactive application, and how do you build one with Play?
Introduction to Typesafe Activator
“Typesafe Activator is a browser-based or command-line tool that helps 
developers get started with the Typesafe Reactive Platform.”
Getting started with the Typesafe Activator UI 
5 
• Download Typesafe Activator 
• https://typesafe.com/platform/getstarted 
• Optional (Mac) 
• ~ $ rm -R .sbt 
• ~ $ rm -R .ivy 
• Unarchive and execute (Mac) 
• $ ./activator ui
Activator tutorials and seeds 
6
Activator Overview 
7 
• Learn — In depth tutorials 
• Develop — Code, compile, test, 
run, inspect 
• Deliver — Monitoring 
integration with AppDynamics 
and New Relic
Code view 
8 
• Activator 
• Browse code 
• Make small changes 
• IDE 
• Generate IDEA or Eclipse 
project files 
• Dig into the template in your 
favourite IDE
Development monitoring 
9 
• Incoming requests 
• Controller 
• HTTP verb (GET, POST, etc) 
• Response code 
• Invocation time
Inspect — Development monitoring 
10 
• Actor metrics 
• Throughput — messages/s 
• Max time — high watermark 
• Max size — mailbox
Monitoring and support 
11 
• Application monitoring 
• Need production caliber monitoring? 
• AppDynamics or New Relic integration 
• Support 
• Ready to take your application to the 
next level? 
• http://typesafe.com/how/subscription
Contributing a template — tutorials vs seeds 
12 
• Seed 
• Boilerplate code as a starting point 
• Tutorial 
• Teaching about a particular focused topic or integration 
• Components 
• Activator templates are just regular sbt projects with some additional components 
• Metadata (activator.properties), license, sbt build file, tutorial (tutorial/index.html) 
• Contribute! 
• https://typesafe.com/activator/template/contribute
The Typesafe Activator UI is a Play framework application. 
! 
Peek behind the covers… 
! 
https://github.com/typesafehub/activator/tree/master/ui
Play 2.3 overview 
14 
• Stateless MVC framework with routing, a template engine, REST support, etc 
• Dynamic class reloading 
• Support for Java 8 and Scala 2.1x 
• sbt-web to implement an asset pipeline 
• Akka interoperability for highly concurrent web applications 
• Built on Netty 3.9.x
Play application overview 
15 
View 
Controller 
JSON Model 
Slick JPA WS 
DB 
Akka 
Network
Creating your first view
17 
Simplified HTTP request 
1. mydomain.com/admin/settings 
renders views.html.admin HTML 
2. Browser fetches static assets served 
from outside of Play 
3. Ajax requests — Play serves JSON 
via a RESTful API 
Browser Play 
HTTP GET (mydomain.com/admin/settings) 
HTML for views.html.admin(...) 
CDN 
JS, CSS, images, etc 
HTTP GET (mydomain.com/ws/some/services) 
JSON
Example template with AngularJS 
18 
@(customer: Customer)! 
! 
<head>...</head>! 
<body>! 
<div class="wrapper">! 
<header>…</header>! 
<h1>Welcome @customer.name!</h1>! 
<section id="body" ng-app="ngAdmin">! 
<div ng-view></div>! 
</section>! 
<footer>...</footer>! 
</div>! 
</body>! 
</html> 
load async || fail whale 
• Scala template rendered by Twirl and returned by Play controller 
Header 
Play handles navigation 
Footer 
• HTML inserted into ng-view by Angular controller after initial page render 
load async || omit 
AngularJS
Creating your first routes and controllers
routes 
20 
GET !/admin!! ! ! ! controllers.AdminController.index! 
GET ! /admin/login! ! ! controllers.AdminController.login! 
GET ! /admin/*any! ! ! controllers.AdminController.angularWildcard(any: String)! 
GET ! /ws/some/service! ! controllers.ServiceController.service 
• Routes must be declared in order 
• /admin and /admin/login are used to render Scala view templates 
• /admin/*any will be intercepted by client-side routing in AngularJS 
• Client-side routes may hit the server if the URI has been bookmarked 
• Nothing special about web services aside from payload (JSON vs HTML)
Sample controller action 
21 
/**! 
* Renders the admin template.! 
*/! 
def index = Action.async {! 
implicit request =>! 
val account = loggedIn! 
Ok(views.html.admin()).withCookies(Cookie(“…”, …, httpOnly = false))! 
} 
• Controllers should stay thin and delegate the real work 
• Controllers actions should always be async 
• Controllers are stateless so context must be stored in cookies or cached
Asynchronous vs synchronous processing times 
22 
Asynchronous - 200ms 
Process 1 
Process 2 
75 ms 
Process 3 
200 ms 
150 ms 
0 ms 425 ms 
Synchronous - 425ms 
Process 1 Process 2 Process 3 
0 ms 425 ms 
• Staying async — and in the future — 
ensures that processing time is not 
bounded by IO 
• Async processing is limited by only 
the longest running process 
• Synchronous processing is limited by 
the combined processing times 
• Stay async!
Asset pipeline and sbt-web
An intro to sbt-web 
24 
• sbt-web brings the notion of a highly configurable asset pipeline to build files 
pipelineStages := Seq(rjs, digest, gzip)! 
• The above will order the RequireJs optimizer (sbt-rjs), the digester (sbt-digest) and 
then compression (sbt-gzip) 
• These tasks will execute in the order declared, one after the other
Asset pipelines 
25 
• Example asset pipeline 
• source file → 
• step 1: linting → 
• step 2: uglification/minification → 
• step 3: fingerprinting → 
• step 4: concatenation (optional)
Asset pipelines 
26 
• Linting 
• Inspect source code for suspicious language usage 
• Uglification/minification 
• Mangle and compress source files, e.g, remove whitespace, etc 
• Fingerprinting 
• Change the filename to reflect the contents of the file for cache busting 
• Concatenation 
• Combine multiple source files to reduce browser load times
sbt-web and asset fingerprinting 
27 
• Asset fingerprinting makes the name of a file dependent on the contents of the file 
• HTTP headers can be set to encourage caches to keep their own copy of the content 
• When the content is updated, the fingerprint will change 
• This will cause the remote clients to request a new copy of the content 
• Known as cache busting
Turning on asset fingerprinting 
28 
• Turning on asset fingerprinting only requires one additional route 
GET /assets/*file! controllers.Assets.versioned(path="/public", file: Asset) 
• Then request each asset as versioned 
<link rel="stylesheet" href=“@routes.Assets.versioned('assets/images/example.png')"> 
• A digest file and new file will be created based on MD5 
./target/web/digest/images/23dcc403b263f262692ac58437104acf-example.png! 
./target/web/digest/images/example.png.md5
sbt-web plugins 
29 
• sbt-coffeescript 
• sbt-concat 
• sbt-css-compress 
• sbt-digest 
• sbt-filter 
• sbt-gzip 
• sbt-handlebars 
• sbt-html-minifier 
• sbt-imagemin 
• sbt-jshint 
• sbt-jst 
• sbt-less 
• sbt-mocha 
• sbt-purescript 
• sbt-reactjs 
• sbt-rjs 
• sbt-stylus 
• sbt-uglify
Model-tier and data access
Model-tier considerations 
31 
Think in verbs rather than nouns… 
• save(model) 
• SRP — save is likely a simple function that does a single thing 
• model.save() 
• Violates SRP — tougher to test 
• Play makes it easy to implement your preferred solution to persistence 
• CRUD, CQRS (Command Query Responsibility Segregation), etc
Scala — Slick example 
32 
// This code:! 
coffees.filter(_.price < 10.0).map(_.name)! 
! 
// Will produce a query equivalent to the following SQL:! 
select COF_NAME from COFFEES where PRICE < 10.0 
• Slick is a Functional Relational Mapping (FRM) library for Scala where you work with 
relational data in a type-safe and functional way 
• Developers benefit from the type-safety and composability of FRM as well as being 
able to reuse the typical Scala collection APIs like filter, map, foreach, etc 
• Can also use plain SQL for insertions, complex joins, etc 
• http://typesafe.com/activator/template/hello-slick-2.1
Scala — JSON Writes example 
33 
• Simply define a Writes in 
implicit scope before invoking 
toJson 
implicit val locationWrites = new Writes[Location] {! 
def writes(location: Location) = Json.obj(! 
"lat" -> location.lat,! 
"long" -> location.long! 
)! 
}! 
! 
val json = Json.toJson(location)
Scala — JSON Reads example 
• Also elegantly handles Reads 
• Build in validate using standard 
types (e.g, Double, Int, etc) or 
define your own validators 
34 
implicit val locationReads: Reads[Location] = (! 
(JsPath  "lat").read[Double] and! 
(JsPath  "long").read[Double]! 
)(Location.apply _)! 
! 
val json = { ... }! 
! 
val locationResult: JsResult[Location] = ! 
! json.validate[Location]
Futures, Actors, and WebSockets
“If you want to parallelize a very deterministic algorithm, futures are the 
way to go.” 
- Derek Wyatt, Akka Concurrency
Futures 
37 
def index = Action.async {! 
! val futureInt = scala.concurrent.Future { intensiveComputation() }! 
! futureInt.map(i => Ok("Got result: " + i))! 
} 
• Great for handling immutable state 
• Intensive computations, reading from a database, pulling from web services, etc 
• Composition — futures guarantee order when chained 
• Parallelizing a deterministic algorithm
“Add behaviour to an algorithm by inserting actors into the message 
flow.” 
- Derek Wyatt, Akka Concurrency
Actors 
• Great for handling mutable state 
• Easy for imperative developers to dive 
into quickly 
• Don't guarantee order 
• Easy to change behaviour by inserting 
new actors into the message flow 
• Messages are directed to a specific actor, 
avoiding callback hell 
39 
package actors! 
! 
import akka.actor._! 
! 
object SomeActor {! 
! def props = Props(new GameActor)! 
}! 
! 
class SomeActor extends Actor {! 
! def receive = {! 
! ! case request: SomeRequest => {! 
! ! ! sender ! SomeResponse(...) ! 
! ! }! 
! }! 
}!
WebSockets 
def websocketAction = WebSocket.acceptWithActor[JsValue, JsValue] { request => channel =>! 
! SomeActor.props(channel)! 
}! 
40 
• Play provides two different built in mechanisms for handling WebSockets 
• Actors — better for discreet messages 
• Iteratees — better for streams 
• Both of these mechanisms can be accessed using the builders provided on WebSocket
Testing
Test framework comparison 
42 
• ScalaTest 
• Human readable output — in English 
• FeatureSpec 
• Matchers 
• http://www.artima.com/docs-scalatest-2.0.M8/#org.scalatest.Matchers 
• Great writeup by Gilt 
• http://tech.gilt.com/post/62430610230/which-scala-testing-tools-should-you-use
Test framework comparison 
43 
• Specs2 
• Enabled by default in Play 
• Good choice for international teams who gain less from English readability 
• Both Specs2 and ScalaTest are fantastic!
Coming soon to Play 2.4
Play 2.4 
45 
• Built-in dependency injection support 
• Experimental support for running Play on akka-http 
• Experimental support for handling IO in Java and Scala using Reactive Streams 
• Slick over anorm, JPA over ebean 
• Pull anorm/ebean support out into separate modules in GitHub playframework repo
Questions?
©Typesafe 2014 – All Rights Reserved

Contenu connexe

Tendances

Xitrum @ Scala Conference in Japan 2013
Xitrum @ Scala Conference in Japan 2013Xitrum @ Scala Conference in Japan 2013
Xitrum @ Scala Conference in Japan 2013
Ngoc Dao
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
DataArt
 

Tendances (20)

Designing a play framework application
Designing a play framework applicationDesigning a play framework application
Designing a play framework application
 
Play Framework 2.5
Play Framework 2.5Play Framework 2.5
Play Framework 2.5
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
 
Preparing for java 9 modules upload
Preparing for java 9 modules uploadPreparing for java 9 modules upload
Preparing for java 9 modules upload
 
Play framework
Play frameworkPlay framework
Play framework
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript Debugging
 
The Play Framework at LinkedIn
The Play Framework at LinkedInThe Play Framework at LinkedIn
The Play Framework at LinkedIn
 
Xitrum @ Scala Conference in Japan 2013
Xitrum @ Scala Conference in Japan 2013Xitrum @ Scala Conference in Japan 2013
Xitrum @ Scala Conference in Japan 2013
 
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Maven
Maven Maven
Maven
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
 
Introduction to CQ5
Introduction to CQ5Introduction to CQ5
Introduction to CQ5
 
50 features of Java EE 7 in 50 minutes at Geecon 2014
50 features of Java EE 7 in 50 minutes at Geecon 201450 features of Java EE 7 in 50 minutes at Geecon 2014
50 features of Java EE 7 in 50 minutes at Geecon 2014
 

Similaire à Play Framework and Activator

Architectures, Frameworks and Infrastructure
Architectures, Frameworks and InfrastructureArchitectures, Frameworks and Infrastructure
Architectures, Frameworks and Infrastructure
harendra_pathak
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
Ganesh Kondal
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
Avi Kedar
 

Similaire à Play Framework and Activator (20)

How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
Architectures, Frameworks and Infrastructure
Architectures, Frameworks and InfrastructureArchitectures, Frameworks and Infrastructure
Architectures, Frameworks and Infrastructure
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache Usergrid
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
Running Airflow Workflows as ETL Processes on Hadoop
Running Airflow Workflows as ETL Processes on HadoopRunning Airflow Workflows as ETL Processes on Hadoop
Running Airflow Workflows as ETL Processes on Hadoop
 
Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5Tech io spa_angularjs_20130814_v0.9.5
Tech io spa_angularjs_20130814_v0.9.5
 
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
Deep Dive: Alfresco Core Repository (... embedded in a micro-services style a...
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
 
Chef for OpenStack - OpenStack Fall 2012 Summit
Chef for OpenStack  - OpenStack Fall 2012 SummitChef for OpenStack  - OpenStack Fall 2012 Summit
Chef for OpenStack - OpenStack Fall 2012 Summit
 
Chef for OpenStack- Fall 2012.pdf
Chef for OpenStack- Fall 2012.pdfChef for OpenStack- Fall 2012.pdf
Chef for OpenStack- Fall 2012.pdf
 
OpenStack Deployments with Chef
OpenStack Deployments with ChefOpenStack Deployments with Chef
OpenStack Deployments with Chef
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScript
 
Where to save my data, for devs!
Where to save my data, for devs!Where to save my data, for devs!
Where to save my data, for devs!
 
Achieving Infrastructure Portability with Chef
Achieving Infrastructure Portability with ChefAchieving Infrastructure Portability with Chef
Achieving Infrastructure Portability with Chef
 

Dernier

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Dernier (20)

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 

Play Framework and Activator

  • 1. Play Framework and Activator Getting started with the Play Framework with Activator
  • 2. Topics, goals, context 2 • An introduction to Typesafe Activator • An introduction to the core features of Play 2.x • What is a Reactive application, and how do you build one with Play?
  • 4. “Typesafe Activator is a browser-based or command-line tool that helps developers get started with the Typesafe Reactive Platform.”
  • 5. Getting started with the Typesafe Activator UI 5 • Download Typesafe Activator • https://typesafe.com/platform/getstarted • Optional (Mac) • ~ $ rm -R .sbt • ~ $ rm -R .ivy • Unarchive and execute (Mac) • $ ./activator ui
  • 7. Activator Overview 7 • Learn — In depth tutorials • Develop — Code, compile, test, run, inspect • Deliver — Monitoring integration with AppDynamics and New Relic
  • 8. Code view 8 • Activator • Browse code • Make small changes • IDE • Generate IDEA or Eclipse project files • Dig into the template in your favourite IDE
  • 9. Development monitoring 9 • Incoming requests • Controller • HTTP verb (GET, POST, etc) • Response code • Invocation time
  • 10. Inspect — Development monitoring 10 • Actor metrics • Throughput — messages/s • Max time — high watermark • Max size — mailbox
  • 11. Monitoring and support 11 • Application monitoring • Need production caliber monitoring? • AppDynamics or New Relic integration • Support • Ready to take your application to the next level? • http://typesafe.com/how/subscription
  • 12. Contributing a template — tutorials vs seeds 12 • Seed • Boilerplate code as a starting point • Tutorial • Teaching about a particular focused topic or integration • Components • Activator templates are just regular sbt projects with some additional components • Metadata (activator.properties), license, sbt build file, tutorial (tutorial/index.html) • Contribute! • https://typesafe.com/activator/template/contribute
  • 13. The Typesafe Activator UI is a Play framework application. ! Peek behind the covers… ! https://github.com/typesafehub/activator/tree/master/ui
  • 14. Play 2.3 overview 14 • Stateless MVC framework with routing, a template engine, REST support, etc • Dynamic class reloading • Support for Java 8 and Scala 2.1x • sbt-web to implement an asset pipeline • Akka interoperability for highly concurrent web applications • Built on Netty 3.9.x
  • 15. Play application overview 15 View Controller JSON Model Slick JPA WS DB Akka Network
  • 17. 17 Simplified HTTP request 1. mydomain.com/admin/settings renders views.html.admin HTML 2. Browser fetches static assets served from outside of Play 3. Ajax requests — Play serves JSON via a RESTful API Browser Play HTTP GET (mydomain.com/admin/settings) HTML for views.html.admin(...) CDN JS, CSS, images, etc HTTP GET (mydomain.com/ws/some/services) JSON
  • 18. Example template with AngularJS 18 @(customer: Customer)! ! <head>...</head>! <body>! <div class="wrapper">! <header>…</header>! <h1>Welcome @customer.name!</h1>! <section id="body" ng-app="ngAdmin">! <div ng-view></div>! </section>! <footer>...</footer>! </div>! </body>! </html> load async || fail whale • Scala template rendered by Twirl and returned by Play controller Header Play handles navigation Footer • HTML inserted into ng-view by Angular controller after initial page render load async || omit AngularJS
  • 19. Creating your first routes and controllers
  • 20. routes 20 GET !/admin!! ! ! ! controllers.AdminController.index! GET ! /admin/login! ! ! controllers.AdminController.login! GET ! /admin/*any! ! ! controllers.AdminController.angularWildcard(any: String)! GET ! /ws/some/service! ! controllers.ServiceController.service • Routes must be declared in order • /admin and /admin/login are used to render Scala view templates • /admin/*any will be intercepted by client-side routing in AngularJS • Client-side routes may hit the server if the URI has been bookmarked • Nothing special about web services aside from payload (JSON vs HTML)
  • 21. Sample controller action 21 /**! * Renders the admin template.! */! def index = Action.async {! implicit request =>! val account = loggedIn! Ok(views.html.admin()).withCookies(Cookie(“…”, …, httpOnly = false))! } • Controllers should stay thin and delegate the real work • Controllers actions should always be async • Controllers are stateless so context must be stored in cookies or cached
  • 22. Asynchronous vs synchronous processing times 22 Asynchronous - 200ms Process 1 Process 2 75 ms Process 3 200 ms 150 ms 0 ms 425 ms Synchronous - 425ms Process 1 Process 2 Process 3 0 ms 425 ms • Staying async — and in the future — ensures that processing time is not bounded by IO • Async processing is limited by only the longest running process • Synchronous processing is limited by the combined processing times • Stay async!
  • 24. An intro to sbt-web 24 • sbt-web brings the notion of a highly configurable asset pipeline to build files pipelineStages := Seq(rjs, digest, gzip)! • The above will order the RequireJs optimizer (sbt-rjs), the digester (sbt-digest) and then compression (sbt-gzip) • These tasks will execute in the order declared, one after the other
  • 25. Asset pipelines 25 • Example asset pipeline • source file → • step 1: linting → • step 2: uglification/minification → • step 3: fingerprinting → • step 4: concatenation (optional)
  • 26. Asset pipelines 26 • Linting • Inspect source code for suspicious language usage • Uglification/minification • Mangle and compress source files, e.g, remove whitespace, etc • Fingerprinting • Change the filename to reflect the contents of the file for cache busting • Concatenation • Combine multiple source files to reduce browser load times
  • 27. sbt-web and asset fingerprinting 27 • Asset fingerprinting makes the name of a file dependent on the contents of the file • HTTP headers can be set to encourage caches to keep their own copy of the content • When the content is updated, the fingerprint will change • This will cause the remote clients to request a new copy of the content • Known as cache busting
  • 28. Turning on asset fingerprinting 28 • Turning on asset fingerprinting only requires one additional route GET /assets/*file! controllers.Assets.versioned(path="/public", file: Asset) • Then request each asset as versioned <link rel="stylesheet" href=“@routes.Assets.versioned('assets/images/example.png')"> • A digest file and new file will be created based on MD5 ./target/web/digest/images/23dcc403b263f262692ac58437104acf-example.png! ./target/web/digest/images/example.png.md5
  • 29. sbt-web plugins 29 • sbt-coffeescript • sbt-concat • sbt-css-compress • sbt-digest • sbt-filter • sbt-gzip • sbt-handlebars • sbt-html-minifier • sbt-imagemin • sbt-jshint • sbt-jst • sbt-less • sbt-mocha • sbt-purescript • sbt-reactjs • sbt-rjs • sbt-stylus • sbt-uglify
  • 31. Model-tier considerations 31 Think in verbs rather than nouns… • save(model) • SRP — save is likely a simple function that does a single thing • model.save() • Violates SRP — tougher to test • Play makes it easy to implement your preferred solution to persistence • CRUD, CQRS (Command Query Responsibility Segregation), etc
  • 32. Scala — Slick example 32 // This code:! coffees.filter(_.price < 10.0).map(_.name)! ! // Will produce a query equivalent to the following SQL:! select COF_NAME from COFFEES where PRICE < 10.0 • Slick is a Functional Relational Mapping (FRM) library for Scala where you work with relational data in a type-safe and functional way • Developers benefit from the type-safety and composability of FRM as well as being able to reuse the typical Scala collection APIs like filter, map, foreach, etc • Can also use plain SQL for insertions, complex joins, etc • http://typesafe.com/activator/template/hello-slick-2.1
  • 33. Scala — JSON Writes example 33 • Simply define a Writes in implicit scope before invoking toJson implicit val locationWrites = new Writes[Location] {! def writes(location: Location) = Json.obj(! "lat" -> location.lat,! "long" -> location.long! )! }! ! val json = Json.toJson(location)
  • 34. Scala — JSON Reads example • Also elegantly handles Reads • Build in validate using standard types (e.g, Double, Int, etc) or define your own validators 34 implicit val locationReads: Reads[Location] = (! (JsPath "lat").read[Double] and! (JsPath "long").read[Double]! )(Location.apply _)! ! val json = { ... }! ! val locationResult: JsResult[Location] = ! ! json.validate[Location]
  • 35. Futures, Actors, and WebSockets
  • 36. “If you want to parallelize a very deterministic algorithm, futures are the way to go.” - Derek Wyatt, Akka Concurrency
  • 37. Futures 37 def index = Action.async {! ! val futureInt = scala.concurrent.Future { intensiveComputation() }! ! futureInt.map(i => Ok("Got result: " + i))! } • Great for handling immutable state • Intensive computations, reading from a database, pulling from web services, etc • Composition — futures guarantee order when chained • Parallelizing a deterministic algorithm
  • 38. “Add behaviour to an algorithm by inserting actors into the message flow.” - Derek Wyatt, Akka Concurrency
  • 39. Actors • Great for handling mutable state • Easy for imperative developers to dive into quickly • Don't guarantee order • Easy to change behaviour by inserting new actors into the message flow • Messages are directed to a specific actor, avoiding callback hell 39 package actors! ! import akka.actor._! ! object SomeActor {! ! def props = Props(new GameActor)! }! ! class SomeActor extends Actor {! ! def receive = {! ! ! case request: SomeRequest => {! ! ! ! sender ! SomeResponse(...) ! ! ! }! ! }! }!
  • 40. WebSockets def websocketAction = WebSocket.acceptWithActor[JsValue, JsValue] { request => channel =>! ! SomeActor.props(channel)! }! 40 • Play provides two different built in mechanisms for handling WebSockets • Actors — better for discreet messages • Iteratees — better for streams • Both of these mechanisms can be accessed using the builders provided on WebSocket
  • 42. Test framework comparison 42 • ScalaTest • Human readable output — in English • FeatureSpec • Matchers • http://www.artima.com/docs-scalatest-2.0.M8/#org.scalatest.Matchers • Great writeup by Gilt • http://tech.gilt.com/post/62430610230/which-scala-testing-tools-should-you-use
  • 43. Test framework comparison 43 • Specs2 • Enabled by default in Play • Good choice for international teams who gain less from English readability • Both Specs2 and ScalaTest are fantastic!
  • 44. Coming soon to Play 2.4
  • 45. Play 2.4 45 • Built-in dependency injection support • Experimental support for running Play on akka-http • Experimental support for handling IO in Java and Scala using Reactive Streams • Slick over anorm, JPA over ebean • Pull anorm/ebean support out into separate modules in GitHub playframework repo
  • 47. ©Typesafe 2014 – All Rights Reserved