Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Play Framework with Scala in Action

Play Framework with Scala in Action

Presented on Nov 9th, 2013 at the Desert Code Camp in Phoenix, AZ. Covers the basics of Scala, the Play Framework and builds a quick and simple RESTful example application.

Terry Drozdowski

November 09, 2013
Tweet

More Decks by Terry Drozdowski

Other Decks in Programming

Transcript

  1. Agenda • Technology Orientation • Scala in about 10 minutes

    (or so) • Play Framework Concepts & Features • Let's Build a Sample App! • Links to Gists are at: http://xymox.net
  2. General Overview • Play Framework is a web framework developed

    by web developers for web developers • Not JEE (zero reliance on JEE APIs/libs) • Focus on Developer Happiness/Productivity • Fully Asynchronous ('reactive') • Written in Scala • Backed by TypeSafe • Scala is a hybrid functional/OO language on the JVM • Originated in 2004 by Martin Odersky • Backed by TypeSafe
  3. General Overview - Cont. • Akka is a concurrency framework

    • Written in Scala • Implements the 'actor' concurrency model (very similar to Erlang's OTP) • Newly added ‘agent’ pattern inspired by agents from Clojure • Developers don't work with Threads directly • Highly scalable - 48 core machine can process up to 50 million messages per second • Backed by TypeSafe • MongoDB/ReactiveMongo • MongoDB is a document database that stores records in BSON (binary JSON) • ReactiveMongo is a fully asynchronous driver for MongoDB, built with Akka
  4. Scala - in about 10 minutes (or so) A (Very)

    Quick Introduction to the Scala Language
  5. Scala - Intro & Installation • Hybrid Language - Functional

    and Object Oriented • Created by Martin Odersky • Invented Java Generics and other Java Features • TypeSafe has James Gosling on board as an advisor • Used by many big companies and startups • Excellent Introduction: A Neophyte's Guide to Scala • Current Version 2.10.x • Install via zip file @ http://www.scala-lang.org • Homebrew on Mac: brew install scala • Requires JDK 1.6 or JDK 1.7 (JDK 8 may have some incompatibilities - use at your own risk)
  6. Who Uses Scala? • Used by a number of organizations/

    start ups in production today • Increased Developer Productivity • Scales Extremely Well • Twitter is best example • Number of Wall Street firms using Akka/Scala for stock trading • Easily Build Concurrent/Scalable Code • Case Studies: http://typesafe.com/ company/casestudies
  7. Scala - High Level Features • Modern Language Syntax •

    Type Safety and Type Inference • Concurrency • Monads • Traits & Case Classes • Option & Try • Pattern Matching • Higher Order Functions • REPL (read-eval-print-loop) • Java Interop
  8. Scala - Interactive Session • Live demo time… • Disclaimer

    - Scala is a very deep language with a steep learning curve. This overview is to simply demonstrate some basics; a lot of features/concepts are not touched on and there for you to explore on your own. :) • What You Need to Create a Foundation for Rest of Session • val vs var • working with collections • pattern matching • and much more… • To open REPL, from command-line simply type: scala • Follow samples via a gist: https://gist.github.com/tdrozdowski/7299177
  9. Intro to the Play Framework • A ‘full-stack’ Web Framework

    by Web Developers for Web Developers on the JVM platform • Was originally a Java Framework • Meant to enable productivity in building modern, ‘reactive’ web applications • Brings best ideas from various other frameworks such as Rails, Django
  10. Features • Declarative URL scheme declaration (routes) / URL Centric

    Design • Asset pipeline for compiling CoffeeScript, running LESS/Compass, etc. • Type-safe template system for generating HTML • Embraces HTML 5 (i.e. WebSockets) • Live code changes when you reload your browser page (compiles on the fly); compile/route errors shown in detail in your browser • Includes frameworks for: persistence, caching, security, internationalization, JSON handling, working with Web Services, WebSockets
  11. Architecture Comparison High Level Comparison between Facelets, Spring and Play

    Facelets JSF Servlet API JEE Container Play Framework NIO HTTP Server (Netty) Spring Framework Servlet API JEE Container
  12. Play Framework Architecture Integrated HTTP Server (Netty) Integrated Console and

    Build System HTTP Interface RESTful Web Services API Akka Datastore-agnostic Persistence Layer Template Engine Asset Pipeline HTML Form Validation Cache (EHCache) Asynchronou s I/O
  13. Console & Build System • Based on SBT • normal

    SBT console • sbt commands work • ~ compile - compiles code as you change files • ~ run - compile while server is running • ~ test - continually run tests as files change • Key commands • development day to day: • run, debug, clean, compile, test, console • deployment • dist, package, publish, publish-local
  14. Installation • http://www.playframework.com - download latest Zip (2.2.1) • Mac

    Homebrew: brew install play • Does not require Scala - will bring its own version (2.10.2) • Does require JDK (1.6 or 1.7) • IDE Optional: • IntelliJ EAP 13 Ultimate Edition • http://confluence.jetbrains.com/display/IDEADEV/IDEA+13+EAP • Build 132.947 • Scala Plugin • Play 2 Plugin
  15. Your First Play App • Create a folder to work

    in, ie. ‘sandbox’ • Type the following on command line: • play new hello • play run • http://localhost:9000 • optional: play idea / play eclipse
  16. Breaking Down A Play App • File system: • app

    - contains your Scala code • build.sbt - your build file • conf - contains your configuration files • project - sbt related folder (don’t touch this for now…) • public - your HTTP files (JS/CSS, etc) • test - your unit tests • lib - un-managed JARs • logs - application logs
  17. Controller • Controller is the interface between HTTP and Scala

    • A Scala object that is a subclass of play.api.mvc.Controller • Contains a series of methods for producing Actions • Action is a controller method that returns an instance of play.api.mvc.Action • Actions handle HTTP requests and provide a response • Defines a Request => Result function to handle the request • Actions can be composed of other Actions via the ActionBuilder • Let’s create a ping Action… User Controller all action get action create action update action GET /users/[email protected] HTTP Status 200 - { "email" : "[email protected]", ....}
  18. Action Composition • The ActionBuilder trait contains the methods for

    composing Actions • You can build your own • Why would you do this? • Add logging • Add Authentication • Add Authorization • etc.
  19. Routes • Links an HTTP method with a Controller method

    • Type-safe • File is compiled • Let’s add the ping route…
  20. Views • Provide the UI for a server side centric

    presentation architecture (legacy architecture) • Type-safe Scala Templates • Actions pass data into them for use via the Result • Templates can include other templates • Build links to your assets using @routes.Assets.at
  21. JSON • Play has a type-safe library for working with

    JSON : play.api.libs.json._ • Construct your own JSON objects • Does mapping from JSON -> case class • by hand with Readers/Writers • ‘JSON Inception’ using macros • Manipulate JSON w/o marshaling to a case class • add/remote attributes/branches • change values of specific nodes • transform attributes into new structures • Gist: https://gist.github.com/tdrozdowski/ 7348647
  22. WS - Web Service Client • Access any Web Service

    with the WS class • SOAP • REST • XMLRPC • play.api.libs.ws.WS • Can add in your own request signing • provides OAuth v1 signer • Results are asynchronous; will receive a Future with a Promise of the results of the HTTP call
  23. Logger • Play uses the Logback API for logging •

    a logger.xml is defined • can set log levels in applicaiton.conf • can override to use your own logger.xml via JVM arguments • -Dlogger.file=<path to logger.xml> • play.api.Logger
  24. Testing • Play uses specs2 unit/ integration test framework •

    Provides helpers so that you can mock certain aspects of the framework • Fairly straight forward way of writing tests (should match up to user stories fairly well) • play test
  25. Sample Application - Complaints • Application will be basic CRUD

    REST API for Complaints • User Story • “As a self-entitled user of the internet, I want to be able to post my complaints in a public forum so that I can stroke my ego.” • Service must be able to create, update, delete a complaint • Service will not have authentication (bad in real life - right?)
  26. Project Setup • Create new play project • play new

    complaints • Create new MongoDB @MongoHQ • http://mongohq.com • Choose Free 512MB Sandbox • Name database whatever you choose • Create a database user for your API
  27. Project Setup • Update build.sbt • Update resolvers to use

    the Sonatype Repository • Update dependencies to include play- reactivemongo • Update application.conf with mongodb.uri • Add play.plugins file to conf folder
  28. Project Setup - Final • From console type: play run

    • This will load all the dependencies for Play and the app - could take a few moments • Browser will load @ http://localhost:9000 when completed • Optional: play idea • Generates files for use with IntelliJ • Optional: Import Project into IntelliJ • File -> Import Project -> <directory> • May need to run play idea a second time
  29. Application Creation Steps • Live Demo! (What possibly could go

    wrong??) • Create new Scala object: ComplaintApi • Gist: https://gist.github.com/tdrozdowski/28fac40f7e8d24a15042 • We Will Add the following actions (and associated routes): • listForUser(user : String) • create • delete(id : String) • Test!
  30. Sample App - Bonus Time • Can you figure out

    how to add these actions? • list • update(id :String) • CORS Support • https://gist.github.com/tdrozdowski/7379656 • Basic Auth • https://gist.github.com/tdrozdowski/7379847
  31. The Future • Scala • 2.11.0 ; Theme: Fix Annoyances

    ; Release Target: Feb 2014 • Improve Performance (reflection, compiler times, distribution size) • Modularize • Remove 22 parameter limit on case classes • Play • 2.3 ; Theme: Extending into the Client ; Q1 2014 • Update to Scala 2.11.0 • Bring Slick into Play Project • Improve Mailer Plugin • JDK 8 Readiness • Client Side Support Improvements (WebJars support, JS Unit Test Runner, Update Asset Pipeline)
  32. Want to know more? Need Help? • Scala Language Resources

    • http://www.scala-lang.org • http://danielwestheide.com/scala/neophytes.html • Scala in Depth (covers 2.9 though!) - Manning Press • StackOverflow! • Use the source: https://github.com/scala/scala • Play Framework Resources • http://www.playframework.com/documentation/2.2.x/ScalaHome • Google Group • Play for Scala (covers 2.1) - Manning Press • StackOverflow! • Use the source: https://github.com/playframework/playframework