SlideShare a Scribd company logo
♥ △ ✿
Play Framework Nul ne sait qui nous sommes
Mélanie 2 janvier 2017
Kévin 4 décembre 2017
Développeurs Back-End
Play Framework Shh .. we have a plan !
La philosophie, le créateur, l’histoire
La structure d'un projet
Les configurations
Le cheminement d’une requête HTTP
Le routing
Les contrôleurs
La couche DAO avec Slick
Les tests
+ Bonus Où retrouve-t-on les
éléments du langage fonctionnel
chers à nos 💓 ?
Option / Either / Future
Play Framework Révisons sinon c’est la session 2
● Option
● Either
● Future
Option[T]
Some[T] None
Either[A, B]
Left[A, B] Right[A, B]
Future

Recommended for you

Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix

This document discusses embracing HTTP and changing approaches to web application development. It suggests flipping dependencies so that applications are built around HTTP rather than frameworks. It also recommends taking a more stateful approach by going CQRS/ES rather than relying on CRUD and resources. The document questions common patterns and promotes thinking beyond frameworks to more fundamental concepts.

elixirerlangcqrs
Scala active record
Scala active recordScala active record
Scala active record

This document provides an overview of Scala-ActiveRecord, a type-safe Active Record model library for Scala. It discusses features such as being type-safe, having Rails ActiveRecord-like functionality, automatic transaction control, and support for associations and validations. The document also covers getting started, defining schemas, CRUD operations, queries, caching queries, validations, callbacks, and relationships.

Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统

Facebook uses caching at multiple levels to improve performance and scalability. Caching is implemented globally, with APC, Memcached, and browser caches. Memcached is used to cache user profiles, photos, friends lists, and other frequently accessed data. Caching is optimized through techniques like caching serialization formats, priming APC, and caching parsed user agent strings. Dirty caching ensures cached data is invalidated when the source data changes.

Play Framework
open source → applications web en Java ou en Scala
φ
Play Framework C’est quoi les bails ?
2007: Guillaume Bort (Zengularity SA → Fabernovel Technologies)
Play 1.0: Mai 2008 - Octobre 2009
Play 2.0: Fin 2011 - Mars 2012 (+Sadek Drobi)
Play 2.5: Mars 2016 - Akka Streams
Play 2.6: 23 Juin 2017 - Akka HTTP serveur backend par défaut + Scala 2.12 [...]
Stateless Scala I/O asynchrones
Play Framework Family Tree
Play Framework Les configurations
sbt
● Outil de build
● Ajout des librairies, configuration version Scala/SBT, ajout de tâches
> run
> compile
> test
> test-only maClasseDeTesterCestDouter.scala
> testQuick <mesTestsUnitairesTasVu>
> doc

Recommended for you

Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング

Xitrum is an asynchronous and clustered Scala web framework and HTTP server built on top of Netty and Akka. It is feature-rich, easy to use, and high performance. Xitrum can scale to a cluster of servers using Akka Cluster and Hazelcast. It is used in production systems in various countries. The document provides information on Xitrum's architecture, features, annotations, and examples of actions and SockJS messaging.

programmingscala
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS Lambda

This document describes an immutable infrastructure approach using AWS Lambda and CloudFormation. Key points: - Infrastructure is defined as code using CloudFormation templates for reproducibility and versioning. - Lambda functions are used to provision resources, configure settings, run tests, and clean up resources to enforce immutability. - A pipeline handles building AMIs, deploying stacks, testing, updating DNS, and deleting old stacks in an automated and repeatable way.

 
by AOE
automationephemeralaws
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0

The document summarizes the new features and improvements in CodeIgniter 3.0. Key highlights include increased number of commits compared to previous versions, improved database features like query builder and failover connections, new features like output minification and pagination improvements, and a focus on unit testing.

frameworksphpcodeigniter
Play Framework Les configurations
/build.sbt
import Dependencies._
name := """poc-play"""
organization := "com.mrgueritte"
version := "1.0-SNAPSHOT"
scalaVersion := "2.12.6"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
libraryDependencies += "com.typesafe.play" %% "play-slick-evolutions"
% "3.0.3"
resolvers += Repositories.sonatypeOss
Play Framework Les configurations
application.conf
● Paramétrage divers : BD, Filtres, Taille buffers ...
● Format clé-valeur, HOCON
● Système héritage application.conf -> production.conf
● Injecté automatiquement dans le paramétrage de Play
● Possibilité de le charger en custom
Play Framework Les configurations
# Database configuration
# ~~~~~
include "db.conf"
# Evolutions
# ~~~~~
play.evolutions.db.default.autoApply=true
play.evolutions.db.default.autoApplyDowns=true
# Authentication
# ~~~~~
http.secure = false
Play Framework Workflow
l’internet
mondial
Route Action Service DAO DB
HTTP Response
HTTP Request
Routeurs
Route
Contrôleurs Services

Recommended for you

4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook

This document discusses techniques for improving caching performance at Facebook. It begins by explaining the benefits of caching for large sites and applications. It then describes the various caching layers Facebook uses, including globals caching, APC caching, memcached, and browser caching. It provides examples of how Facebook leverages these caches, such as caching parsed user agent strings, opcode caching with APC, and caching profile data in memcached. It also discusses challenges like cache invalidation between data centers and techniques for addressing them like caching proxies.

Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for

Gradle is the build system you have been waiting for or maybe the build system that has been waiting for you. The adoption rate is incredible from being the new Google Android development tools build system to most new Java opensource projects to JavaScript based front-end and back-end projects.

mavengradleant
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid

This document discusses using Backbone, Backgrid, and Symfony to build a datagrid application. It covers: 1) Setting up requirements including Symfony, Backbone dependencies, and FOSRestBundle. 2) Building Backbone models, collections, and associations to retrieve and represent ticket data. 3) Implementing a Backgrid grid with columns to display the ticket data. 4) Examples of extending Backgrid with features like select editors, toggle cells, and computed fields. 5) Testing the Backbone collections and API endpoints with sample test code.

php javascript symfony2 backgrid.js backbone.js si
Play Framework Painless HTTP Routing
Route = HTTP Verb + URI → Controller Method
# Routes
# This files defines all application routes (Higher priority routes first)
# https://www.playframwork.com/documentation/latest/ScalaRouting
# ~~~~
GET /api/cat/:id controllers.CatsController.get(id: CatId)
-> / order.Routes
-> / owner.Routes
Play Framework Les routeurs exemples
GET /clients/:id controllers.Clients.show(id: Long)
GET /api/list-all controllers.Api.list(version: Option[String])
GET /items/$id<[0-9]+> controllers.Items.show(id: Long)
GET / controllers.Application.show(page = "home")
GET /:page controllers.Application.show(page)
GET /clients controllers.Clients.list(page: Int ?= 1)
GET /api/cat/:id controllers.CatsController.get(id: CatId) ?
Play Framework Painless HTTP Routing
case class CatId(id: UUID)
Play Framework Router Tunning Custom
/build.sbt routesImport ++= "utils.RoutesParser._" :: "utils.CatId" :: Nil
/RoutesParser.scala
object RoutesParser {
implicit object parameterBindableCatId extends PathBindable[CatId] {
override def bind(key: String, catIdStr: String): Either[String, CatId] = {
Try(CatId(UUID.fromString(catIdStr))) match {
case Success(catId) => Right(catId)
case Failure(e) => Left(s"Cannot parse parameter $key as CatId: $e")
}
}
override def unbind(key: String, catId: CatId): String = catId.id.toString
}
}
Exemple d’UUID: 89a7df10-284f-415c-b52a-427acf4c31ae

Recommended for you

Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework

This document introduces the Flask micro web framework. It discusses that Flask provides URL routing, request and response objects, template engines and other features for web development. Flask is simple and extensible, using Werkzeug and Jinja2. It does not include an ORM or form validation, but supports extensions. The document provides examples of basic routing, using request objects, templates and the development server. It also discusses using SQLAlchemy, WTForms and common patterns like MVC with Flask projects.

You must know about CodeIgniter Popular Library
You must know about CodeIgniter Popular LibraryYou must know about CodeIgniter Popular Library
You must know about CodeIgniter Popular Library

This document discusses CodeIgniter PHP framework and web application security. It covers why frameworks are useful, CodeIgniter architecture and core components. It then focuses on common web security issues like exposed admin URLs, directory listings, error messages, temporary files and SQL injections. Methods to prevent each vulnerability are also provided, such as .htaccess rules, input validation and escaping. The document aims to help secure CodeIgniter applications and webservers.

codeigniterauthrestful
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEB

Testing Web Applications with GEB provides concise summaries in 3 sentences or less: GEB allows testing of web applications by driving browsers like Firefox using the Selenium WebDriver API. It integrates with jQuery-like content selection and supports features like page objects, modules, and JavaScript execution to simplify testing of Ajax applications. GEB uses Groovy for a more expressive and dynamic testing approach compared to other frameworks like Selenium.

integrationgoogle chromefirefox
Play Framework Workflow
Route Action Service DAO DB
HTTP Response
HTTP Request
Routeurs
Route
Contrôleurs Services
Play Framework Dans les contrôleurs y a de l’action
play.api.mvc.Request =>
play.api.mvc.Result
val echo = Action { request =>
Ok(s"Got request [$request]")
}
Play Framework Dans les contrôleurs y a de l’action
Action { Ok("Hello world") }
def hello(name: String) = Action {
Ok("Hello " + name)
}
def echo = Action { request =>
Ok("Got request [" + request + "]")
}
def createHouse() = Action(parse.json[House]) {request =>
Ok(request.body)//House
}
Play Framework Dans les contrôleurs y a de l’action
def createHouseAsync = Action().async { request =>
for {
design <- getPlans()
wood <- getMaterial()
} yield Ok(Json.obj("House plans" -> design, "material" -> wood))
}

Recommended for you

Pragmatic Browser Automation with Geb - GIDS 2015
Pragmatic Browser Automation with Geb - GIDS 2015Pragmatic Browser Automation with Geb - GIDS 2015
Pragmatic Browser Automation with Geb - GIDS 2015

This document discusses pragmatic browser automation using Geb. It introduces Geb and how it provides an elegant and expressive way to automate browsers using the power of WebDriver, jQuery style selector syntax, and page object modeling. Key features covered include navigating browsers, accessing and asserting page elements, using modules and page objects for organization, waiting capabilities, and integration with Spock for testing. Geb aims to provide the robustness of WebDriver with the simplicity of jQuery selectors and page objects for pragmatic browser automation.

groovyseleniumweb-driver
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015

Video presentation: https://www.youtube.com/watch?v=jLAFXQ1Av50 Most applications written in Ruby are great, but also exists evil code applying WOP techniques. There are many workarounds in several programming languages, but in Ruby, when it happens, the proportion is bigger. It's very easy to write Ruby code with collateral damage. You will see a collection of bad Ruby codes, with a description of how these codes affected negatively their applications and the solutions to fix and avoid them. Long classes, coupling, misapplication of OO, illegible code, tangled flows, naming issues and other things you can ever imagine are examples what you'll get.

rubysoftware developmentprodis
Redis for your boss
Redis for your bossRedis for your boss
Redis for your boss

“Use the right tool for the right job” is one of the first thing they teach you when you start out in these waters. I would make “Get to really know your tools” a second.  In this talk we’re going to work on the architecture of an app that showcases some common features/scenarios we all probably already have in the apps we’re working on: counters, leaderboards, queuing, timelines, caching. But this time we’ll implement them with Redis, making the apps much faster, your hardware (and you) much cooler, your boss (and the clients) much happier and hopefully your salary a bit higher.

redispridesphp
Play Framework Authentification
Support pour OAuth2
Guest
Member
OrganizationMember.(Read)
PlatformAdmin
Api(Scope)
[...]
def list() = OrganizationMember(READ)("cats.list").async { implicit request =>
catsService
.listByOrganization(request.organizationId)
.map(Ok(_))
}
=> Future[Result]
Play Framework Les resultats c’est pas du bois
Ok("Hello World!")
→ Content-Type header to text/plain
Ok(<message>Hello World!</message>)
→ application/xml
Ok(<h1>Hello World!</h1>)
→ application/html
Ok(Json.obj(”foo” -> “bar”)) -> application/json
val result = Ok("Hello World!").withHeaders(
CACHE_CONTROL -> "max-age=3600",
ETAG -> "xx")
Play Framework Les resultats c’est pas du bois
Play Framework Workflow
Route Action Service DAO DB
HTTP Response
HTTP Request
Routeurs
Route
Contrôleurs Services

Recommended for you

Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0

An exercise app that demonstrates the various uses of redis data structures. From queues, to leaderboards, lua scripts and redis modules.

redisredis moduleslua scripting
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207

Symfony is a PHP web framework that provides features like templating, caching, internationalization and MVC architecture out of the box. It uses the Model-View-Controller pattern and includes tools for scaffolding, routing, form generation and more. Symfony projects can be created via the command line and include an auto-generated directory structure for applications, modules and actions.

Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018

This document discusses using CommandBox and Docker to deploy real projects. It covers background on the development workflow and environments, benefits of Docker and CommandBox, code cleanup tools like CFLint and git hooks, serving apps with CommandBox, server monitoring with Prometheus, dynamic configuration, caching, session storage, logging with Elasticsearch and Kibana, load balancing with Kubernetes, data changes, scheduled tasks, and canary/blue-green deployments. The overall message is that CommandBox and tools can provide structure and simplify transitions to help teams succeed in deploying applications.

coldfusioncfmlortus solutions
Play Framework & Slick
Play Framework Les configurations de Slick
val slick = "com.typesafe.play” %% "play-slick" % Version.slickVersion
val slickEvolution = "com.typesafe.play" %% "play-slick-evolutions" % Version.slickVersion
/build.sbt
/application.conf
slick.dbs.default.profile = "slick.jdbc.H2Profile$"
slick.dbs.default.db.driver = "org.h2.Driver"
slick.dbs.default.db.url = "jdbc:h2:mem:play;DATABASE_TO_UPPER=false"
slick.dbs.default.profile = "slick.jdbc.PostgresProfile$"
slick.dbs.default.db.user = "user"
slick.dbs.default.db.password = "pswd"
Play Framework Les schémas
object Schemas extends EntityMappers {
class Cats(tag: Tag) extends Table[Cat](tag, "cats") {
def catId = column[CatId]("id")
def name = column[String]("name")
def pedigreeId = column[PedigreeId]("pedigree_id")
def gender = column[Gender]("gender")
def owner = column[Option[OwnerId]]("owner_id")
def dateOfBirth = column[Date]("date_of_birth")
def dateOfDeath = column[Option[Date]]("date_of_death")
override def * =
(catId, name, pedigreeId, gender, owner, dateOfBirth, dateOfDeath) <> (Cat.tupled, Cat.unapply)
}
...
val cats = TableQuery[Cats]
}
Play Framework Les requêtes : “tout est
collection”> SELECT * FROM cats WHERE id = ?
override def getById(id: CatId): DBIO[Option[Cat]] = Schemas.cats.filter(_.id === id).headOption
> INSERT INTO cats VALUES (?,?,? …)
override def create(cat: Cat): DBIO[Unit] = Schemas.cats += cat
> SELECT c.* FROM pedigrees p JOIN cat c ON c.pedigreeId = p.id WHERE p.name = ?
override def getByPedigreeName(name: String): DBIO[Seq[Cat]] = {
for {
cat <- Schemas.cats
pedigree <- Schemas.pedigrees
if pedigree.id === cat.pedigreeId && pedigree.pedigree === name
} yield cat
}

Recommended for you

Into The Box 2018 Going live with commandbox and docker
Into The Box 2018 Going live with commandbox and dockerInto The Box 2018 Going live with commandbox and docker
Into The Box 2018 Going live with commandbox and docker

This document discusses using CommandBox and Docker to deploy real projects. It covers background on the development workflow and environments, benefits of Docker and CommandBox, code cleanup tools like CFLint and git hooks, serving apps with CommandBox, server monitoring with Prometheus, dynamic configuration, caching, session storage, logging with Elasticsearch and Kibana, load balancing with Kubernetes, data changes, scheduled tasks, and canary/blue-green deployments. The overall message is that CommandBox and tools can provide structure and simplify transitions to help teams succeed in deploying applications.

ortus solutionscfmlcoldfusion
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web

Slides from a presentation that David Lopez (@lopezator) and me made for the students of the University of the Basque Country (UPV/EHU) where we talk about current technologies and methodologies used in professional web development. CSS3, jQuery, Composer, MVC, Clean Code, Git, etc. are different items we talked about. Some examples shown in the presentation available at: http://ojoven.es/labs/ehu2014/

developmentwebuniversity
Go Web Development
Go Web DevelopmentGo Web Development
Go Web Development

This document discusses Go web development using the Gin web framework. It provides an overview of Gin's features and file structure conventions. It also describes using Orator ORM for database migrations in Go applications. Benchmark results show the json-iterator library provides better JSON performance than the standard encoding/json package in Go. The document concludes with recommendations for Nginx SSL and security header parameters.

oratorgoweb
Play Framework Les DBIO
override def getByPedigreeName(name: String): Future[Seq[Cat]] = {
val transaction = (for {
cat <- catsDAO.getByPedigreeName(name)
_ <- DBIO.seq(cat.map(c => catsDAO.delete(c.catId)): _*)
} yield cat).transactionally
db.run(transaction)
}
> Les compositions de requêtes & les transactions
Play Framework Les évolutions
● Situé dans le dossier /conf/evolutions/<dbName>/
● Chaque script est composé de deux parties :
○ Ups! : SQL d’évolution de la BD (INSERT, CREATE …)
○ Downs! : Retour arrière de l’évolution (DROP, ALTER …)
● Une table `play_evolutions` est créée sur la DB => versionnage
# --- !Ups
CREATE TABLE pedigrees(
id UUID NOT NULL,
name VARCHAR(32) NOT NULL
);
…
# --- !Downs
DROP TABLE cats;
DROP TABLE owners;
DROP TABLE pedigrees;
Play Framework Les évolutions, “j’ai tout casséhéhé”
● Modification du script en question
● Marquer le script comme résolu => Application du `!Downs` puis du `!Ups`
Play Framework Injections de dépendances
● Guice est embarqué => utilisation à spécifier build.sbt
● Auto-gestion des dépendances avec @Inject() (java !)
● Runtime
“Use another compile time dependency injection!”

Recommended for you

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)

Video: http://www.nicovideo.jp/watch/1410857293 Here's the showdown you've been waiting for: Node.js vs Play Framework. Both are popular open source web frameworks that are built for developer productivity, asynchronous I/O, and the real time web. But which one is easier to learn, test, deploy, debug, and scale? Should you pick Javascript or Scala? The Google v8 engine or the JVM? NPM or Ivy? Grunt or SBT? Two frameworks enter, one framework leaves. This version of the presentation has Japanese subtitles. For the English only version, see http://www.slideshare.net/brikis98/nodejs-vs-play-framework

javaweb developmentjavascript
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js

Mathilde Lemée & Romain Maton La théorie, c’est bien, la pratique … aussi ! Venez nous rejoindre pour découvrir les profondeurs de Node.js ! Nous nous servirons d’un exemple pratique pour vous permettre d’avoir une premiere experience complete autour de Node.js et de vous permettre de vous forger un avis sur ce serveur Javascript qui fait parler de lui ! http://soft-shake.ch/2011/conference/sessions/incubator/2011/09/01/hands-on-nodejs.html

softshake2011softshake
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework

Video: https://www.youtube.com/watch?v=b6yLwvNSDck Here's the showdown you've been waiting for: Node.js vs Play Framework. Both are popular open source web frameworks that are built for developer productivity, asynchronous I/O, and the real time web. But which one is easier to learn, test, deploy, debug, and scale? Should you pick Javascript or Scala? The Google v8 engine or the JVM? NPM or Ivy? Grunt or SBT? Two frameworks enter, one framework leaves. This is the English version of the presentation. For the version with Japanese subtitles, see http://www.slideshare.net/brikis98/nodejs-vs-play-framework-with-japanese-subtitles

javascriptnode.jsplay framework
Play Framework Injections de dépendances
ApplicationLoader
● Point entrée unique facilement customisable => `application.conf`
● Chargement de toutes les “parties” de l’application => `Components`
class PocPlayApplicationLoader extends ApplicationLoader {
override def load(context: Context): Application = {
new PocPlayComponents(context).application
}
}
play.application.loader= "di.PocPlayApplicationLoader"
Play Framework Injections de dépendances
Components
class PocPlayComponents(context: Context) extends
BuiltInComponentsFromContext(context)
with HttpFiltersComponents // Add defaults HTTP Filters
with SlickComponents // Add Slick API (connect play to database)
with EvolutionsComponents { // Add Evolutions system
override lazy val dbApi: DBApi = SlickDBApi(slickApi)
applicationEvolutions.start()
...
}
PlayFramework On a parcouru le chemin, on a tenu la distance
class CatsController( catsService: CatsService [...]
def buy(catId: CatId, ownerId: OwnerId) = Action.async { implicit request =>
catsService.buy(catId, ownerId)[...] }
class CatsServiceImpl( catsDAO: CatsDAO, db: DbExecutor [...]
override def buy(catId: CatId, ownerId: OwnerId): Future[Either[ApiError, Void]] =
[...] db.run(catsDAO.updateOwner(catId, ownerId)) [...]
case class CatsDAOSlick()(implicit ec: ExecutionContext) extends CatsDAO {
override def updateOwner(catId: CatId, ownerId: OwnerId): DBIO[Void] = [...]
Play Framework Injections de dépendances
Components - Add dependency injection with macwire
class PocPlayComponents(context: Context) extends
BuiltInComponentsFromContext(context)
with HttpFiltersComponents // Add defaults HTTP Filters
with SlickComponents // Add Slick API (connect play to database)
with EvolutionsComponents { // Add Evolutions system
...
lazy val db: DbExecutor =
slickApi.dbConfig[JdbcProfile](DbName("default")).db
lazy val catsDAO: CatsDAO = new CatsDAOSlick()
lazy val catsService: CatsService = wire[CatsServiceImpl]
lazy val catsController: CatsController = wire[CatsController]
}

Recommended for you

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications

This document provides an introduction and overview of a Node.js tutorial presented by Tom Hughes-Croucher. The tutorial covers topics such as building scalable server-side code with JavaScript using Node.js, debugging Node.js applications, using frameworks like Express.js, and best practices for deploying Node.js applications in production environments. The tutorial includes exercises for hands-on learning and demonstrates tools and techniques like Socket.io, clustering, error handling and using Redis with Node.js applications.

node.jsfluentconfjavascript
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)

This document provides an overview and introduction to Node.js. It discusses that Node.js is a platform for building scalable network applications using JavaScript and uses non-blocking I/O and event-driven architecture. It was created by Ryan Dahl in 2009 and uses Google's V8 JavaScript engine. Node.js allows building web servers, networking tools and real-time applications easily and efficiently by handling concurrent connections without threads. Some popular frameworks and modules built on Node.js are also mentioned such as Express.js, Socket.IO and over 1600 modules in the npm registry.

nodejs javascript js
Wider than rails
Wider than railsWider than rails
Wider than rails

This document discusses ways to create lightweight Ruby solutions by simplifying frameworks and components. It suggests replacing ActiveRecord with the simpler and faster Sequel ORM. It also recommends using Zepto.js instead of jQuery for mobile apps, and Rack and Sinatra to build lightweight web apps instead of full Rails applications. Benchmarks show these lightweight approaches can significantly improve performance compared to default Rails. Tools mentioned that aid lightweight development include Pow for local web serving and rbenv for Ruby version management. The document concludes by reminding developers not to see Ruby as the only solution and to consider other languages like Erlang, Scala and C++ for certain problems.

Play Framework Tests
Scala Test - Flat Spec et d’autres WordSpec/FreeSpec etc.
class HelloWorldSpec extends Specification {
"The 'Hello world' string" should {
"contain 11 characters" in {
"Hello world" must have size(11)
}
"start with 'Hello'" in {
"Hello world" must startWith('Hello')
}
}
}
[info] HelloWorldSpec:
[info] The 'Hello world' string
[info] - should contain 11 characters
[info] - should start with 'Hello'
[info] ScalaTest
[info] Run completed in 2 seconds, 888 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 0, canceled 0,
ignored 0, pending 0
[info] All tests passed.
[info] Passed: Total 2, Failed 0, Errors 0, Passed 2
[success] Total time: 5 s, completed 3 juin 2018
22:13:54
Play Framework Tests
Mock API’s
import play.api.test.Helpers._
class CatsApiSpec extends PocPlayOneAppPerSuite {
…
def createCatApi(body: JsValue) = FakeRequest("POST", "/api/cats").withBody(body)
"Cats API" must {
"have a valid endpoint `create cat API`" in {
...
val Some(response) = route(app, createCatApi(catsBody))
status(response) == CREATED
val json = contentAsJson(response)
...
}
}
}
Play Framework Tests
Mock context
trait PocPlayOneAppPerSuite extends PlaySpec with GuiceOneAppPerSuite { self =>
override lazy val app = {
val context = ApplicationLoader.createContext(new Environment(new java.io.File("."),
ApplicationLoader.getClass.getClassLoader, Mode.Test))
new TestComponents(context).application
}
}
class TestComponents(context: Context) extends PocPlayComponents(context: Context) {
override lazy val configuration = {
val databseConfig = ConfigFactory.parseString(
"""slick.dbs.default.db.url = <database test>""".stripMargin)
context.initialConfiguration.copy(underlying = databseConfig)
}
}
Play Framework Fun with tests
Property-based testing - Scala Check
def catJsonGenerator: Gen[JsObject] = {
for {
name <- Gen.alphaStr.suchThat(_.size < 32)
gender <- Gen.oneOf(const(Gender.Female), const(Gender.Male))
pedigreeId <- const(PedigreeId(UUID.fromString("cc58095b-8d51-4a22-a110-7ace2d921c2c")))
ownerId <- option(const(OwnerId(UUID.fromString("76065e7d-8604-4995-a6ed-33fca30517aa"))))
dateOfBirth <- const(DateTime.now())
} yield buildCatJson(name, gender, pedigreeId, ownerId, dateOfBirth, None)
}
"have a valid endpoint `create cat API`" in {
check {
Prop.forAll(catJsonGenerator) { catsBody: JsObject =>
val Some(response) = route(app, createCatApi(catsBody))
status(response) == CREATED
}
}
}

Recommended for you

Express Presentation
Express PresentationExpress Presentation
Express Presentation

Express is a web application framework for Node.js that provides a robust set of features for building web applications and APIs. It is designed for building scalable and fast web applications and services. Some key features include being built on Node.js for asynchronous and event-driven capabilities, a simple routing system and middleware support, and support for template engines and plugins.

OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix

This document discusses Netflix's API ecosystem built using Scala, Scalatra, and Swagger. It summarizes Netflix's use of these technologies to build APIs that power their consumer electronics partner portal and enable certification of Netflix ready devices. It describes how the APIs provide a single source of truth for all device data at Netflix and correlate streaming quality metrics. It then discusses aspects of the architecture including the manager layer containing business logic, HTTP layer for handling requests/responses, and use of Scala, Scalatra, Swagger, and deployment process including immutable infrastructure.

restfulswaggernetflix
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile

This document summarizes a presentation about serverless and mobile applications. It includes: - An introduction focusing on startups, mobile apps, serverless computing, blockchain, and fintech. - Details about AWS AppSync and its Todo data model. - Information on request and response mapping templates in AWS Lambda. - An overview of delta sync using AppSync, base queries, subscriptions, and delta queries. - Notes on serverless technologies like AWS Lambda and its supported runtimes. - Resources on serverless best practices and architectures using Lambda, API Gateway, and other AWS services.

awsctonight
Play Framework Vous en profitez sans le savoir
Play Framework Merci d’être là, super sympa
https://github.com/kevin-margueritte/poc-playframework
Des questions ?
Vous êtes sûrs ? On va être coupés, y a un tunnel.

More Related Content

What's hot

Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
Siarzh Miadzvedzeu
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a boss
Francisco Ribeiro
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
Gabriele Lana
 
Scala active record
Scala active recordScala active record
Scala active record
鉄平 土佐
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
scalaconfjp
 
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS Lambda
AOE
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
Phil Sturgeon
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
guoqing75
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for
Corneil du Plessis
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
eugenio pombi
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
You must know about CodeIgniter Popular Library
You must know about CodeIgniter Popular LibraryYou must know about CodeIgniter Popular Library
You must know about CodeIgniter Popular Library
Bo-Yi Wu
 
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEB
Howard Lewis Ship
 
Pragmatic Browser Automation with Geb - GIDS 2015
Pragmatic Browser Automation with Geb - GIDS 2015Pragmatic Browser Automation with Geb - GIDS 2015
Pragmatic Browser Automation with Geb - GIDS 2015
Naresha K
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
Fernando Hamasaki de Amorim
 
Redis for your boss
Redis for your bossRedis for your boss
Redis for your boss
Elena Kolevska
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0
Elena Kolevska
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 

What's hot (20)

Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a boss
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
 
Scala active record
Scala active recordScala active record
Scala active record
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
Immutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS LambdaImmutable Deployments with AWS CloudFormation and AWS Lambda
Immutable Deployments with AWS CloudFormation and AWS Lambda
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
You must know about CodeIgniter Popular Library
You must know about CodeIgniter Popular LibraryYou must know about CodeIgniter Popular Library
You must know about CodeIgniter Popular Library
 
Testing Web Applications with GEB
Testing Web Applications with GEBTesting Web Applications with GEB
Testing Web Applications with GEB
 
Pragmatic Browser Automation with Geb - GIDS 2015
Pragmatic Browser Automation with Geb - GIDS 2015Pragmatic Browser Automation with Geb - GIDS 2015
Pragmatic Browser Automation with Geb - GIDS 2015
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
 
Redis for your boss
Redis for your bossRedis for your boss
Redis for your boss
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 

Similar to FP - Découverte de Play Framework Scala

Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018
Ortus Solutions, Corp
 
Into The Box 2018 Going live with commandbox and docker
Into The Box 2018 Going live with commandbox and dockerInto The Box 2018 Going live with commandbox and docker
Into The Box 2018 Going live with commandbox and docker
Ortus Solutions, Corp
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
Mikel Torres Ugarte
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web Development
Cheng-Yi Yu
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
Yevgeniy Brikman
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
Yevgeniy Brikman
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
Felix Geisendörfer
 
Wider than rails
Wider than railsWider than rails
Wider than rails
Alexey Nayden
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
aaronheckmann
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
Manish Pandit
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
Amazon Web Services Japan
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
Mike Brevoort
 
Play framework
Play frameworkPlay framework
Play framework
Andrew Skiba
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion
 
前端概述
前端概述前端概述
前端概述
Ethan Zhang
 
Sprockets
SprocketsSprockets
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
BradNeuberg
 
Evolution of Spark APIs
Evolution of Spark APIsEvolution of Spark APIs
Evolution of Spark APIs
Máté Szalay-Bekő
 

Similar to FP - Découverte de Play Framework Scala (20)

Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018Going live with BommandBox and docker Into The Box 2018
Going live with BommandBox and docker Into The Box 2018
 
Into The Box 2018 Going live with commandbox and docker
Into The Box 2018 Going live with commandbox and dockerInto The Box 2018 Going live with commandbox and docker
Into The Box 2018 Going live with commandbox and docker
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
Go Web Development
Go Web DevelopmentGo Web Development
Go Web Development
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at NetflixOSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
OSCON 2014 - API Ecosystem with Scala, Scalatra, and Swagger at Netflix
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Play framework
Play frameworkPlay framework
Play framework
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
前端概述
前端概述前端概述
前端概述
 
Sprockets
SprocketsSprockets
Sprockets
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Evolution of Spark APIs
Evolution of Spark APIsEvolution of Spark APIs
Evolution of Spark APIs
 

Recently uploaded

Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model SafePaharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
aarusi sexy model
 
Response & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITHResponse & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITH
IIIT Hyderabad
 
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.docCCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
Dss
 
Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies
maisnampibarel
 
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and PreventionUnderstanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Bert Blevins
 
LeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdfLeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdf
pavanaroshni1977
 
SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...
SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...
SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...
Jim Mimlitz, P.E.
 
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model SafeRohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
binna singh$A17
 
Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf
Kamal Acharya
 
Net Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK EmpireNet Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK Empire
Global Network for Zero
 
CONVEGNO DA IRETI 18 giugno 2024 | PASQUALE Donato
CONVEGNO DA IRETI 18 giugno 2024 | PASQUALE DonatoCONVEGNO DA IRETI 18 giugno 2024 | PASQUALE Donato
CONVEGNO DA IRETI 18 giugno 2024 | PASQUALE Donato
Servizi a rete
 
1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT
1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT
1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT
Mani Krishna Sarkar
 
Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.
Tool and Die Tech
 
Rotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptxRotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptx
surekha1287
 
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
PradeepKumarSK3
 
MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme
MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K SchemeMSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme
MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme
Anwar Patel
 
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
IJAEMSJORNAL
 
Chlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptxChlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptx
yadavsuyash008
 
IS Code SP 23: Handbook on concrete mixes
IS Code SP 23: Handbook  on concrete mixesIS Code SP 23: Handbook  on concrete mixes
IS Code SP 23: Handbook on concrete mixes
Mani Krishna Sarkar
 
kiln burning and kiln burner system for clinker
kiln burning and kiln burner system for clinkerkiln burning and kiln burner system for clinker
kiln burning and kiln burner system for clinker
hamedmustafa094
 

Recently uploaded (20)

Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model SafePaharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
 
Response & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITHResponse & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITH
 
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.docCCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
CCS367-STORAGE TECHNOLOGIES QUESTION BANK.doc
 
Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies
 
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and PreventionUnderstanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
 
LeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdfLeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdf
 
SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...
SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...
SCADAmetrics Instrumentation for Sensus Water Meters - Core and Main Training...
 
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model SafeRohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
Rohini @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Yogita Mehra Top Model Safe
 
Social media management system project report.pdf
Social media management system project report.pdfSocial media management system project report.pdf
Social media management system project report.pdf
 
Net Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK EmpireNet Zero Case Study: SRK House and SRK Empire
Net Zero Case Study: SRK House and SRK Empire
 
CONVEGNO DA IRETI 18 giugno 2024 | PASQUALE Donato
CONVEGNO DA IRETI 18 giugno 2024 | PASQUALE DonatoCONVEGNO DA IRETI 18 giugno 2024 | PASQUALE Donato
CONVEGNO DA IRETI 18 giugno 2024 | PASQUALE Donato
 
1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT
1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT
1239_2.pdf IS CODE FOR GI PIPE FOR PROCUREMENT
 
Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.Trends in Computer Aided Design and MFG.
Trends in Computer Aided Design and MFG.
 
Rotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptxRotary Intersection in traffic engineering.pptx
Rotary Intersection in traffic engineering.pptx
 
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
21EC63_Module1B.pptx VLSI design 21ec63 MOS TRANSISTOR THEORY
 
MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme
MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K SchemeMSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme
MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme MSBTE K Scheme
 
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
 
Chlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptxChlorine and Nitric Acid application, properties, impacts.pptx
Chlorine and Nitric Acid application, properties, impacts.pptx
 
IS Code SP 23: Handbook on concrete mixes
IS Code SP 23: Handbook  on concrete mixesIS Code SP 23: Handbook  on concrete mixes
IS Code SP 23: Handbook on concrete mixes
 
kiln burning and kiln burner system for clinker
kiln burning and kiln burner system for clinkerkiln burning and kiln burner system for clinker
kiln burning and kiln burner system for clinker
 

FP - Découverte de Play Framework Scala

  • 2. Play Framework Nul ne sait qui nous sommes Mélanie 2 janvier 2017 Kévin 4 décembre 2017 Développeurs Back-End
  • 3. Play Framework Shh .. we have a plan ! La philosophie, le créateur, l’histoire La structure d'un projet Les configurations Le cheminement d’une requête HTTP Le routing Les contrôleurs La couche DAO avec Slick Les tests + Bonus Où retrouve-t-on les éléments du langage fonctionnel chers à nos 💓 ? Option / Either / Future
  • 4. Play Framework Révisons sinon c’est la session 2 ● Option ● Either ● Future Option[T] Some[T] None Either[A, B] Left[A, B] Right[A, B] Future
  • 5. Play Framework open source → applications web en Java ou en Scala φ
  • 6. Play Framework C’est quoi les bails ? 2007: Guillaume Bort (Zengularity SA → Fabernovel Technologies) Play 1.0: Mai 2008 - Octobre 2009 Play 2.0: Fin 2011 - Mars 2012 (+Sadek Drobi) Play 2.5: Mars 2016 - Akka Streams Play 2.6: 23 Juin 2017 - Akka HTTP serveur backend par défaut + Scala 2.12 [...] Stateless Scala I/O asynchrones
  • 8. Play Framework Les configurations sbt ● Outil de build ● Ajout des librairies, configuration version Scala/SBT, ajout de tâches > run > compile > test > test-only maClasseDeTesterCestDouter.scala > testQuick <mesTestsUnitairesTasVu> > doc
  • 9. Play Framework Les configurations /build.sbt import Dependencies._ name := """poc-play""" organization := "com.mrgueritte" version := "1.0-SNAPSHOT" scalaVersion := "2.12.6" lazy val root = (project in file(".")).enablePlugins(PlayScala) libraryDependencies += "com.typesafe.play" %% "play-slick-evolutions" % "3.0.3" resolvers += Repositories.sonatypeOss
  • 10. Play Framework Les configurations application.conf ● Paramétrage divers : BD, Filtres, Taille buffers ... ● Format clé-valeur, HOCON ● Système héritage application.conf -> production.conf ● Injecté automatiquement dans le paramétrage de Play ● Possibilité de le charger en custom
  • 11. Play Framework Les configurations # Database configuration # ~~~~~ include "db.conf" # Evolutions # ~~~~~ play.evolutions.db.default.autoApply=true play.evolutions.db.default.autoApplyDowns=true # Authentication # ~~~~~ http.secure = false
  • 12. Play Framework Workflow l’internet mondial Route Action Service DAO DB HTTP Response HTTP Request Routeurs Route Contrôleurs Services
  • 13. Play Framework Painless HTTP Routing Route = HTTP Verb + URI → Controller Method # Routes # This files defines all application routes (Higher priority routes first) # https://www.playframwork.com/documentation/latest/ScalaRouting # ~~~~ GET /api/cat/:id controllers.CatsController.get(id: CatId) -> / order.Routes -> / owner.Routes
  • 14. Play Framework Les routeurs exemples GET /clients/:id controllers.Clients.show(id: Long) GET /api/list-all controllers.Api.list(version: Option[String]) GET /items/$id<[0-9]+> controllers.Items.show(id: Long) GET / controllers.Application.show(page = "home") GET /:page controllers.Application.show(page) GET /clients controllers.Clients.list(page: Int ?= 1) GET /api/cat/:id controllers.CatsController.get(id: CatId) ?
  • 15. Play Framework Painless HTTP Routing case class CatId(id: UUID)
  • 16. Play Framework Router Tunning Custom /build.sbt routesImport ++= "utils.RoutesParser._" :: "utils.CatId" :: Nil /RoutesParser.scala object RoutesParser { implicit object parameterBindableCatId extends PathBindable[CatId] { override def bind(key: String, catIdStr: String): Either[String, CatId] = { Try(CatId(UUID.fromString(catIdStr))) match { case Success(catId) => Right(catId) case Failure(e) => Left(s"Cannot parse parameter $key as CatId: $e") } } override def unbind(key: String, catId: CatId): String = catId.id.toString } } Exemple d’UUID: 89a7df10-284f-415c-b52a-427acf4c31ae
  • 17. Play Framework Workflow Route Action Service DAO DB HTTP Response HTTP Request Routeurs Route Contrôleurs Services
  • 18. Play Framework Dans les contrôleurs y a de l’action play.api.mvc.Request => play.api.mvc.Result val echo = Action { request => Ok(s"Got request [$request]") }
  • 19. Play Framework Dans les contrôleurs y a de l’action Action { Ok("Hello world") } def hello(name: String) = Action { Ok("Hello " + name) } def echo = Action { request => Ok("Got request [" + request + "]") } def createHouse() = Action(parse.json[House]) {request => Ok(request.body)//House }
  • 20. Play Framework Dans les contrôleurs y a de l’action def createHouseAsync = Action().async { request => for { design <- getPlans() wood <- getMaterial() } yield Ok(Json.obj("House plans" -> design, "material" -> wood)) }
  • 21. Play Framework Authentification Support pour OAuth2 Guest Member OrganizationMember.(Read) PlatformAdmin Api(Scope) [...] def list() = OrganizationMember(READ)("cats.list").async { implicit request => catsService .listByOrganization(request.organizationId) .map(Ok(_)) } => Future[Result]
  • 22. Play Framework Les resultats c’est pas du bois Ok("Hello World!") → Content-Type header to text/plain Ok(<message>Hello World!</message>) → application/xml Ok(<h1>Hello World!</h1>) → application/html Ok(Json.obj(”foo” -> “bar”)) -> application/json val result = Ok("Hello World!").withHeaders( CACHE_CONTROL -> "max-age=3600", ETAG -> "xx")
  • 23. Play Framework Les resultats c’est pas du bois
  • 24. Play Framework Workflow Route Action Service DAO DB HTTP Response HTTP Request Routeurs Route Contrôleurs Services
  • 26. Play Framework Les configurations de Slick val slick = "com.typesafe.play” %% "play-slick" % Version.slickVersion val slickEvolution = "com.typesafe.play" %% "play-slick-evolutions" % Version.slickVersion /build.sbt /application.conf slick.dbs.default.profile = "slick.jdbc.H2Profile$" slick.dbs.default.db.driver = "org.h2.Driver" slick.dbs.default.db.url = "jdbc:h2:mem:play;DATABASE_TO_UPPER=false" slick.dbs.default.profile = "slick.jdbc.PostgresProfile$" slick.dbs.default.db.user = "user" slick.dbs.default.db.password = "pswd"
  • 27. Play Framework Les schémas object Schemas extends EntityMappers { class Cats(tag: Tag) extends Table[Cat](tag, "cats") { def catId = column[CatId]("id") def name = column[String]("name") def pedigreeId = column[PedigreeId]("pedigree_id") def gender = column[Gender]("gender") def owner = column[Option[OwnerId]]("owner_id") def dateOfBirth = column[Date]("date_of_birth") def dateOfDeath = column[Option[Date]]("date_of_death") override def * = (catId, name, pedigreeId, gender, owner, dateOfBirth, dateOfDeath) <> (Cat.tupled, Cat.unapply) } ... val cats = TableQuery[Cats] }
  • 28. Play Framework Les requêtes : “tout est collection”> SELECT * FROM cats WHERE id = ? override def getById(id: CatId): DBIO[Option[Cat]] = Schemas.cats.filter(_.id === id).headOption > INSERT INTO cats VALUES (?,?,? …) override def create(cat: Cat): DBIO[Unit] = Schemas.cats += cat > SELECT c.* FROM pedigrees p JOIN cat c ON c.pedigreeId = p.id WHERE p.name = ? override def getByPedigreeName(name: String): DBIO[Seq[Cat]] = { for { cat <- Schemas.cats pedigree <- Schemas.pedigrees if pedigree.id === cat.pedigreeId && pedigree.pedigree === name } yield cat }
  • 29. Play Framework Les DBIO override def getByPedigreeName(name: String): Future[Seq[Cat]] = { val transaction = (for { cat <- catsDAO.getByPedigreeName(name) _ <- DBIO.seq(cat.map(c => catsDAO.delete(c.catId)): _*) } yield cat).transactionally db.run(transaction) } > Les compositions de requêtes & les transactions
  • 30. Play Framework Les évolutions ● Situé dans le dossier /conf/evolutions/<dbName>/ ● Chaque script est composé de deux parties : ○ Ups! : SQL d’évolution de la BD (INSERT, CREATE …) ○ Downs! : Retour arrière de l’évolution (DROP, ALTER …) ● Une table `play_evolutions` est créée sur la DB => versionnage # --- !Ups CREATE TABLE pedigrees( id UUID NOT NULL, name VARCHAR(32) NOT NULL ); … # --- !Downs DROP TABLE cats; DROP TABLE owners; DROP TABLE pedigrees;
  • 31. Play Framework Les évolutions, “j’ai tout casséhéhé” ● Modification du script en question ● Marquer le script comme résolu => Application du `!Downs` puis du `!Ups`
  • 32. Play Framework Injections de dépendances ● Guice est embarqué => utilisation à spécifier build.sbt ● Auto-gestion des dépendances avec @Inject() (java !) ● Runtime “Use another compile time dependency injection!”
  • 33. Play Framework Injections de dépendances ApplicationLoader ● Point entrée unique facilement customisable => `application.conf` ● Chargement de toutes les “parties” de l’application => `Components` class PocPlayApplicationLoader extends ApplicationLoader { override def load(context: Context): Application = { new PocPlayComponents(context).application } } play.application.loader= "di.PocPlayApplicationLoader"
  • 34. Play Framework Injections de dépendances Components class PocPlayComponents(context: Context) extends BuiltInComponentsFromContext(context) with HttpFiltersComponents // Add defaults HTTP Filters with SlickComponents // Add Slick API (connect play to database) with EvolutionsComponents { // Add Evolutions system override lazy val dbApi: DBApi = SlickDBApi(slickApi) applicationEvolutions.start() ... }
  • 35. PlayFramework On a parcouru le chemin, on a tenu la distance class CatsController( catsService: CatsService [...] def buy(catId: CatId, ownerId: OwnerId) = Action.async { implicit request => catsService.buy(catId, ownerId)[...] } class CatsServiceImpl( catsDAO: CatsDAO, db: DbExecutor [...] override def buy(catId: CatId, ownerId: OwnerId): Future[Either[ApiError, Void]] = [...] db.run(catsDAO.updateOwner(catId, ownerId)) [...] case class CatsDAOSlick()(implicit ec: ExecutionContext) extends CatsDAO { override def updateOwner(catId: CatId, ownerId: OwnerId): DBIO[Void] = [...]
  • 36. Play Framework Injections de dépendances Components - Add dependency injection with macwire class PocPlayComponents(context: Context) extends BuiltInComponentsFromContext(context) with HttpFiltersComponents // Add defaults HTTP Filters with SlickComponents // Add Slick API (connect play to database) with EvolutionsComponents { // Add Evolutions system ... lazy val db: DbExecutor = slickApi.dbConfig[JdbcProfile](DbName("default")).db lazy val catsDAO: CatsDAO = new CatsDAOSlick() lazy val catsService: CatsService = wire[CatsServiceImpl] lazy val catsController: CatsController = wire[CatsController] }
  • 37. Play Framework Tests Scala Test - Flat Spec et d’autres WordSpec/FreeSpec etc. class HelloWorldSpec extends Specification { "The 'Hello world' string" should { "contain 11 characters" in { "Hello world" must have size(11) } "start with 'Hello'" in { "Hello world" must startWith('Hello') } } } [info] HelloWorldSpec: [info] The 'Hello world' string [info] - should contain 11 characters [info] - should start with 'Hello' [info] ScalaTest [info] Run completed in 2 seconds, 888 milliseconds. [info] Total number of tests run: 2 [info] Suites: completed 1, aborted 0 [info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0 [info] All tests passed. [info] Passed: Total 2, Failed 0, Errors 0, Passed 2 [success] Total time: 5 s, completed 3 juin 2018 22:13:54
  • 38. Play Framework Tests Mock API’s import play.api.test.Helpers._ class CatsApiSpec extends PocPlayOneAppPerSuite { … def createCatApi(body: JsValue) = FakeRequest("POST", "/api/cats").withBody(body) "Cats API" must { "have a valid endpoint `create cat API`" in { ... val Some(response) = route(app, createCatApi(catsBody)) status(response) == CREATED val json = contentAsJson(response) ... } } }
  • 39. Play Framework Tests Mock context trait PocPlayOneAppPerSuite extends PlaySpec with GuiceOneAppPerSuite { self => override lazy val app = { val context = ApplicationLoader.createContext(new Environment(new java.io.File("."), ApplicationLoader.getClass.getClassLoader, Mode.Test)) new TestComponents(context).application } } class TestComponents(context: Context) extends PocPlayComponents(context: Context) { override lazy val configuration = { val databseConfig = ConfigFactory.parseString( """slick.dbs.default.db.url = <database test>""".stripMargin) context.initialConfiguration.copy(underlying = databseConfig) } }
  • 40. Play Framework Fun with tests Property-based testing - Scala Check def catJsonGenerator: Gen[JsObject] = { for { name <- Gen.alphaStr.suchThat(_.size < 32) gender <- Gen.oneOf(const(Gender.Female), const(Gender.Male)) pedigreeId <- const(PedigreeId(UUID.fromString("cc58095b-8d51-4a22-a110-7ace2d921c2c"))) ownerId <- option(const(OwnerId(UUID.fromString("76065e7d-8604-4995-a6ed-33fca30517aa")))) dateOfBirth <- const(DateTime.now()) } yield buildCatJson(name, gender, pedigreeId, ownerId, dateOfBirth, None) } "have a valid endpoint `create cat API`" in { check { Prop.forAll(catJsonGenerator) { catsBody: JsObject => val Some(response) = route(app, createCatApi(catsBody)) status(response) == CREATED } } }
  • 41. Play Framework Vous en profitez sans le savoir
  • 42. Play Framework Merci d’être là, super sympa https://github.com/kevin-margueritte/poc-playframework Des questions ? Vous êtes sûrs ? On va être coupés, y a un tunnel.

Editor's Notes

  1. Support code -> https://github.com/kevin-margueritte/poc-playframework
  2. Mélou
  3. Mélou
  4. Mélou
  5. Mélou + Kevin
  6. Kévin
  7. Mélou
  8. Mélou
  9. def Hello(name: String) = Action { request => } def createTruc() = Action(parse.json[House]) { request => println(request.body) // House } def createAsync = Action().async { request => for { res1 <- getWS1() res2 <- getWS2() } yield Ok(Json.obj("res1" -> res1, "res" -> res2)) }
  10. def Hello(name: String) = Action { request => } def createTruc() = Action(parse.json[House]) { request => println(request.body) // House } def createAsync = Action().async { request => for { res1 <- getWS1() res2 <- getWS2() } yield Ok(Json.obj("res1" -> res1, "res" -> res2)) }
  11. Etaler les exemples
  12. Kévin
  13. Kevinou
  14. Kevinou
  15. Kevinou
  16. Kevin override def create(cat: Cat): DBIO[Unit] = (Schemas.cats += cat).map(_ => Unit) Request Join à revoir
  17. Kevin override def create(cat: Cat): DBIO[Unit] = (Schemas.cats += cat).map(_ => Unit) Request Join à revoir
  18. Mélanie
  19. Mélanie
  20. Mélou