The document describes a presentation by Massimiliano Dessì and Alberto Quario for the Google Technology User Group Sardegna on Scala web frameworks Play, Scalatra, and Spray. The agenda includes an overview of Scalatra, Play Framework, and Spray as well as REST, JSON, routing, templates, actors, sessions, deployment, and testing.
Come hear about the highly available and massively scalable cloud storage service that is provided by Windows Azure. Learn how to create and access the different types of Windows Azure storage available, including blobs, tables, and queues.
By the sum of PHPUnit assertion power and Symfony2 functional testing tools the developer can obtain a deep control on the developed application.
Here you can find some suggestions on how to leverage that power.
Come hear about the highly available and massively scalable cloud storage service that is provided by Windows Azure. Learn how to create and access the different types of Windows Azure storage available, including blobs, tables, and queues.
By the sum of PHPUnit assertion power and Symfony2 functional testing tools the developer can obtain a deep control on the developed application.
Here you can find some suggestions on how to leverage that power.
Node.js has given JavaScript a new resurgence as a server-side language. No longer just for image rollovers and AJAX, JS is now available as a platform for creating lightning-fast, lightweight, networked applications. In this session, we will move beyond Node’s base web servers and Twitter applications, and into module development: those small, reusable components that are the foundation for every business application on every platform. Learn how to create a module within Node.js, how to test your module and validate functionality, and how to get your creation distributed into the wild. With this knowledge, you can make the next great Node package and become famous.
Scala meetup - Milan, 25 May 2013
Dopo anni di sviluppo Web in Java con le Servlet come base, vediamo come poter sviluppare usando le stesse solide fondamenta con Scala. Scalatra è un toolkit minimale che ci permette di iniziare ad approcciare Scala sul web attraverso le Servlet permettendoci di integrare Scala (o di migrare) in delle WebApp già esistenti. Vedremo in questo quickie come delle funzionalità generiche ed avanzate, implementate con SpringMVC, possono essere implementate con Scalatra.
Overview of The Scala Based Lift Web FrameworkIndicThreads
All of us having experience with other web frameworks such as Struts,Tapestry, Rails, etc would ask “Why another framework? Does Lift really solve problems any differently or more effectively than the ones we’ve used before? The Lift Web Framework provides an advanced set of tools for quickly and easily building real-time, multi-users, interactive web applications. Lift has a unique advantage that no other web framework currently shares: the Scala programming language. Scala is a relatively new language developed by Martin Odersky and his group at EPFL Switzerland. Scala is a hybrid Object Oriented and Functional language that runs at native speeds on the JVM and fully interoperates with Java code. Lift is a hybrid web framework built on Scala. Lift derives its features and idioms from the best of existing web frameworks as well as the functional and OO features in Scala. It compiles to Java bytecode and runs on the JVM, which means that we can leverage the vast ecosystem of Java libraries just as we would with any other java web framework. This presentation details the advantages of this Scala based Web framework over all the existing frameworks that we have used uptil now and shows a small sample application built with Lift. We will create a basic application with a model that maps to RDBMS, web pages that correspond to back end logic and bind dynamically created content to elements on the webpage.
Is your web app drowning in a sea of JavaScript? Has your client-side codebase grown from "a snippet here and there" to "more JavaScript than HTML"? Do you find yourself writing one-off snippets instead of generalized components? You're not the only one. Learn about a handful of strategies you can use to keep your JavaScript codebase lean, modular, and flexible. We'll cover all the major pain points — MVC, templates, persisting state, namespacing, graceful error handling, client/server communication, and separation of concerns. And we'll cover how to do all this incrementally so that you don't have to redo everything from scratch.
Node.js has given JavaScript a new resurgence as a server-side language. No longer just for image rollovers and AJAX, JS is now available as a platform for creating lightning-fast, lightweight, networked applications. In this session, we will move beyond Node’s base web servers and Twitter applications, and into module development: those small, reusable components that are the foundation for every business application on every platform. Learn how to create a module within Node.js, how to test your module and validate functionality, and how to get your creation distributed into the wild. With this knowledge, you can make the next great Node package and become famous.
Scala meetup - Milan, 25 May 2013
Dopo anni di sviluppo Web in Java con le Servlet come base, vediamo come poter sviluppare usando le stesse solide fondamenta con Scala. Scalatra è un toolkit minimale che ci permette di iniziare ad approcciare Scala sul web attraverso le Servlet permettendoci di integrare Scala (o di migrare) in delle WebApp già esistenti. Vedremo in questo quickie come delle funzionalità generiche ed avanzate, implementate con SpringMVC, possono essere implementate con Scalatra.
Overview of The Scala Based Lift Web FrameworkIndicThreads
All of us having experience with other web frameworks such as Struts,Tapestry, Rails, etc would ask “Why another framework? Does Lift really solve problems any differently or more effectively than the ones we’ve used before? The Lift Web Framework provides an advanced set of tools for quickly and easily building real-time, multi-users, interactive web applications. Lift has a unique advantage that no other web framework currently shares: the Scala programming language. Scala is a relatively new language developed by Martin Odersky and his group at EPFL Switzerland. Scala is a hybrid Object Oriented and Functional language that runs at native speeds on the JVM and fully interoperates with Java code. Lift is a hybrid web framework built on Scala. Lift derives its features and idioms from the best of existing web frameworks as well as the functional and OO features in Scala. It compiles to Java bytecode and runs on the JVM, which means that we can leverage the vast ecosystem of Java libraries just as we would with any other java web framework. This presentation details the advantages of this Scala based Web framework over all the existing frameworks that we have used uptil now and shows a small sample application built with Lift. We will create a basic application with a model that maps to RDBMS, web pages that correspond to back end logic and bind dynamically created content to elements on the webpage.
Is your web app drowning in a sea of JavaScript? Has your client-side codebase grown from "a snippet here and there" to "more JavaScript than HTML"? Do you find yourself writing one-off snippets instead of generalized components? You're not the only one. Learn about a handful of strategies you can use to keep your JavaScript codebase lean, modular, and flexible. We'll cover all the major pain points — MVC, templates, persisting state, namespacing, graceful error handling, client/server communication, and separation of concerns. And we'll cover how to do all this incrementally so that you don't have to redo everything from scratch.
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
Android is a fast-growing mobile operating system with millions of users worldwide.
Scala is a modern programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Why not combine both of them?
How to replace rails asset pipeline with webpack?Tomasz Bak
How to replace rails asset pipeline with webpack?
How to structure webpack.config.js?
What is NPM equivalent of ".ruby-version"?
What is NPM equivalent of "Gamefile.lock"?
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsSimo Ahava
Here's my list of 10 JavaScript (related) concepts that I think all web analysts should understand at least on a basic level. A solid grasp of JavaScript is a base requirement for anyone working with the web browser.
Similar to Codemotion 2013 scalatra play spray (20)
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
1. Massimiliano Dessì
&
Alberto Quario
Scala On Web
Play - Scalatra - Spray
Google Technology User Group Sardegna
1
2. Speakers
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Max has more than 13 years of experience in
programming. He’s a proud father of three.
Manager of GTUG Sardegna, Founder of
SpringFramework IT, co-founder of Jug Sardegna.
Author of Spring 2.5 AOP. He works in Energeya and
lives in Cagliari, Italy.
Alberto has more than 15 years experience in
developing software, he wrote his first programs on a
TI-99/4A and hasn't stopped since. Other than
languages and development, Alberto's passions
include squash, cooking and Monet paintings. He
lives and works in Milano, Italy.
2
3. Agenda
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Scalatra -Playframework -Spray
REST
JSON
Routing
Template
Actors
Sessions
Deploy
Hot Reloading
Test
3
4. Massimiliano Dessì & Alberto Quario GTUG Sardegna
Scalatra
is a web microframework
written in Scala
inspired to Sinatra
a Ruby DSL to build webapp
http://www.scalatra.org
the BBC, LinkedIn,
the Guardian,
games website IGN,
UK government
rely on Scalatra.
4
5. REST
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class JellyBeans extends ScalatraServlet {
get("/jellybs/:id") { ... }
post("/jellybs") { ... }
put("/jellybs/:id") { ... }
delete("/jellybs/:id") { ... }
}
For browser add PUT & DELETE support client side
X-HTTP-METHOD-OVERRIDE or _method=put _method=delete in the post body
class JellyBeansBrowser extends ScalatraFilter with MethodOverride
5
7. Filter
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class JellyBeans extends ScalatraServlet {
before() {
db.acquireConnecion
contentType="text/html" Like Servlet Filter
} (or Aspect Oriented Programming)
You can add logic before or the
get("/") { routes
val menu = db.findWelcome()
templateEngine.layout("index.ssp", menu)
}
after() {
db.releaseConnection
}
}
7
9. Handlers
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Handlers are top level methods for http routines
class JellyBeans extends ScalatraServlet {
notFound {
<h1>Not found</h1>
}
halt(status = 301, headers =
Map("Location" -> "http://www.codemotion.com/"))
get("/jellybs/names/*") {
"Name not found!"
}
}
9
10. Handlers
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class JellyBeans extends ScalatraServlet {
get("/jellybs/names/:who") {
params("who") match {
case "Cherry" => "Found Cherry!"
case _ => pass() /* call the next matching route route, routes are
matched from bottom up*/
}
}
get("/jellybs/download/:id") {
jellyBeanService.find(params("id")) match {
case Some(jellybean) => Ok(jellybean)
case None => NotFound("Sorry, jellybean not found")
}
}
}
10
11. Request Response & Friends
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class JellyBeans extends ScalatraServlet {
get("/jellybs/shows/:id") {
//access to request,response, session and params
request.body //request body as a string
request.cookies // cookie map
request.isAjax // is ajaxRequest
request.getSession // HttpServletSession
request.locale // user locale
response.getOutputStream //response outputstream
servletContext.get("myIntParam") //servlet context
val idString = params("id")
val id = params.getAs[Int]("id")
//val id = params.getOrElse("id", halt(500)) //another way
....
}
}
11
13. Binding
Massimiliano Dessì & Alberto Quario GTUG Sardegna
To avoid manual binding from http and our Object Scalatra provide a binding module
case class MyClass(id: Integer, name: String)
post("/myroute") {
val cmd = command[CreateMyClassCommand]
...
}
13
14. Binding
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Under the hood
abstract class MyClassCommand[S](implicit mf: Manifest[S])
extends ModelCommand[S] with JsonCommand {
implicit def todoStringValidators(b: FieldDescriptor[String]) =
new MyClassStringValidations(b)
}
class CreateMyClassCommand extends MyClassCommand[MyClass] {
protected implicit val jsonFormats = DefaultFormats
val name: Field[String] = asType[String]("name").notBlank.minLength(3)
}
14
15. Binding
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Under the hood
class MyClassStringValidations(b: FieldDescriptor[String]) {
def startsWithCap(message: String = "%s must start with a capital letter.") =
b.validateWith(_ =>
_ flatMap {
new PredicateValidator[String](
b.name,
"""^[A-Z,0-9]""".r.findFirstIn(_).isDefined,
message).validate(_)
)
}
)
}
15
16. Gzip
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class GzipJellyBeans extends ScalatraServlet with GZipSupport{
get("/") {
<html>
<body>
<h1>This is
<a href="http://en.wikipedia.org/wiki/Sparta">
http/gzip
</a>!
</h1>
</body>
</html>
}
}
16
17. Flash message
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class FlashServlet extends ScalatraServlet with FlashMapSupport{
post("/jellybs/create") {
flash("notice") = "jellybean created successfully"
redirect("/home")
}
get("/home") {
ssp("/home") //Scala Server Pages
}
17
18. JSON
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Automatic Serialization and deserialization of any Case class
object JSONServlet extends ScalatraServlet with JacksonJsonSupport{
case class JellyBean(id: Int, name: String, flavor:String)
protected implicit val jsonFormats: Formats = DefaultFormats
before() {
contentType = formats("json")
}
....
18
19. JSON
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Automatic Serialization and deserialization of any Case class
object JSONServlet extends ScalatraServlet with JacksonJsonSupport{
...
get("/jellybs/all"){
jellyBeanRepo.all //from class to json
}
post("/jellybs/create") {
val jb = parsedBody.extract[JellyBean] //from json to class
...
}
}
19
20. Template
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Html inline,
Scalate
Twirl (Play2 template)
Scalate
mean
SSP (Scala Server Page)
Scaml
Mustache
Jade
20
21. Template
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class ScalateServlet extends ScalatraServlet with ScalateSupport{
get("/"jellybeans/ssp) {
contentType="text/html"
ssp("/index", "foo" -> "uno", "bar" -> "two")
// the layout used it’s WEB-INF/layouts/default.ssp
}
get("/jellybeans/jade") {
jade("/index", "layout" -> "", "foo" -> "one", "bar" -> "two")
// render without a layout.
}
get("/jellybeans/direct") {
templateEngine.layout("/jellybeans/index.ssp")
//direct invoking of scalate
}
21
22. Template
Massimiliano Dessì & Alberto Quario GTUG Sardegna
SSP
<%@ var body: String %>
<%@ var title: String = "Some Default Title" %>
<%@ var head: String = "" %>
<html>
<head>
<title>${title}</title>
<%-- page specific head goes here --%>
${unescape(head)}
</head>
<body>
<p>layout header goes here...</p>
${unescape(body)}
<p>layout footer goes here...</p>
</body>
</html>
22
23. Template
Massimiliano Dessì & Alberto Quario GTUG Sardegna
JADE
!!! 5
html(lang="en")
head
title= pageTitle
:javascript
if (foo) {
bar()
}
body
h1 Jade - node template engine
#container
- if (youAreUsingJade)
p You are amazing
- else
p Get on it!
:coffeescript
alert "Hello, Coffee!"
23
24. Template
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Mustache
Hello {{name}}
You have just won ${{value}}!
{{#in_ca}}
Well, ${{taxed_value}}, after taxes.
{{/in_ca}}
24
25. Template
Massimiliano Dessì & Alberto Quario GTUG Sardegna
SCAML
!!! XML
!!!
%html
%head
%title Myspace
%body
%h1 I am the international space station
%p Sign my guestbook
25
26. Actors
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Non Blocking and Async
with
Akka and Actors
26
27. Actors
Massimiliano Dessì & Alberto Quario GTUG Sardegna
The routes can returns a Future
class MyActorServlet(system:ActorSystem, myActor:ActorRef)
extends ScalatraServlet with FutureSupport {
import _root_.akka.pattern.ask
implicit val timeout = Timeout(10)
protected implicit def executor: ExecutionContext = system.dispatcher
get("/async") {
myActor ? "Do stuff and give me an answer"
}
get("/fire-forget") {
myActor ! "Hey, you know what?"
Accepted() //if you do not want return a future
}
}
27
28. Actors
Massimiliano Dessì & Alberto Quario GTUG Sardegna
get("/async") {
myActor ? "Do stuff and give me an answer"
}
get("/fire-forget") {
myActor ! "Hey, you know what?"
Accepted() //if you don’t want return a future
}
class CodemotionActor extends Actor {
def receive = {
case "Do stuff and give me an answer" => sender ! "The answer is 42"
case "Hey, you know what?" => println("Yeah I know...")
}
}
}
28
29. Actors
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Akka start in the Bootstrap of Scalatra
class ScalatraBootstrap extends LifeCycle {
val system = ActorSystem()
val codemotionActor = system.actorOf(Props[CodemotionActor])
override def init(context: ServletContext) {
context.mount(new JSONServlet, "/jellybs/*")
context.mount(new FrontServlet, "/template/*")
context.mount(new MyActorServlet(system, codemotionActor), "/actors/*")
}
override def destroy(context:ServletContext) {
system.shutdown()
}
}
29
30. Authentication & Security
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Scalatra uses Scentry a porting of Ruby Warden authentication
class OurAuthStrategy(protected override val app: ScalatraBase, realm: String)
extends BasicAuthStrategy[User](app, realm) {
protected def validate(userName: String, password: String): Option[User] = {
if(userName == "myusername" && password == "secret") Some(User("myusername"))
else None
}
protected def getUserId(user: User): String = user.id
}
case class User(id: String)
30
31. Authentication & Security
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Now we need to combine our strategy and ScentrySupport
trait AuthenticationSupport extends ScentrySupport[User] with BasicAuthSupport[User] {
self: ScalatraBase =>
val realm = "Scalatra Basic Auth Example"
protected def fromSession = { case id: String => User(id) }
protected def toSession = { case usr: User => usr.id }
protected val scentryConfig = (new ScentryConfig {}).asInstanceOf[ScentryConfiguration]
}
31
32. Authentication & Security
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Now we need to combine our strategy and ScentrySupport
trait AuthenticationSupport extends ScentrySupport[User] with BasicAuthSupport[User] {
....
override protected def configureScentry = {
scentry.unauthenticated {
scentry.strategies("Basic").unauthenticated()
scentry.strategies("")
}
}
override protected def registerAuthStrategies = {
scentry.register("Basic", app => new OurBasicAuthStrategy(app, realm))
}
protected def validate(userName: String, password: String): Option[User] = {
if(userName == "scalatra" && password == "scalatra") Some(User("scalatra"))
else None
}
}
32
33. Authentication & Security
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Now we can use the Authentication for all routes defined in our Authenticated Servlets
class AuthenticatedServlet extends ScalatraServlet with AuthenticationSupport{
//every route goes under authentication
}
Unauthenticated user will see a browser prompt login
33
34. Deployment
Massimiliano Dessì & Alberto Quario GTUG Sardegna
The simplest way to deploy
your Scalatra application
is as a
Web application ARchive file
34
35. Deployment
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Scalatra is based on regular Java Servlet 3.0
it can start from:
Standalone from jetty embedded
From Servlet container
Heroku
Jelastic
CloudBees
GAE (not out of the box )
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.scalatra.servlet.ScalatraListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/img/*</url-pattern>
<url-pattern>/css/*</url-pattern>
<url-pattern>/js/*</url-pattern>
<url-pattern>/assets/*</url-pattern>
</servlet-mapping>
</web-app>
35
36. Test
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Test with Specs2
class FrontServletSpec extends ScalatraSpec {
def is =
"GET / on FrontServlet" ^
"should return status 200" ! root200 ^
end
addServlet(classOf[FrontServlet], "/*")
def root200 = get("/") {
status must_== 200
}
}
36
37. Hot reloading
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Thanks JRebel for free Scala plan !
37
40. Routing
Massimiliano Dessì & Alberto Quario GTUG Sardegna
conf/routes
GET /clients/all controllers.Clients.list()
GET /clients/:id controllers.Clients.show(id: Long)
GET /clients/$id<[0-9]+> controllers.Clients.show(id: Long)
GET /clients controllers.Clients.list(page: Int ?= 1)
GET /api/list-all controllers.Api.list(Option[version])
40
41. Session
Massimiliano Dessì & Alberto Quario GTUG Sardegna
def index = Action { implicit request =>
session.get("connected").map { user =>
Ok("Hello " + user)
}.getOrElse {
Unauthorized("Oops, you are not connected")
}
}
Ok("Welcome!").withSession(
"connected" -> "user@gmail.com"
)
Ok("Welcome!").withSession(
session + ("saidHello" -> "yes") - "theme"
)
41
48. Non-blocking IO /2
Massimiliano Dessì & Alberto Quario GTUG Sardegna
def race() = Action {
Async {
val start = System.currentTimeMillis()
def getLatency(r: Any): Long = System.currentTimeMillis() - start
val googleTime = WS.url("http://www.google.com").get().map(getLatency)
val yahooTime = WS.url("http://www.yahoo.com").get().map(getLatency)
val bingTime = WS.url("http://www.bing.com").get().map(getLatency)
Future.sequence(Seq(googleTime, yahooTime, bingTime)).map {
case times =>
Ok(Json.toJson(Map(
"google" -> times(0),
"yahoo" -> times(1),
"bing" -> times(2),
"total" -> getLatency(0))))
}
}
}
{"google":343,"yahoo":3043,"bing":1608,"total":3048}
48
49. Test
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class ApplicationSpec extends Specification {
"Application" should {
"send 404 on a bad request" in {
running(FakeApplication()) {
route(FakeRequest(GET, "/boum")) must beNone
}
}
"render the index page" in {
running(FakeApplication()) {
val home = route(FakeRequest(GET, "/")).get
status(home) must equalTo(OK)
contentType(home) must beSome.which(_ == "text/html")
contentAsString(home) must contain ("Your new application is ready.")
}
}
}
}
49
50. Test /2
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class IntegrationSpec extends Specification {
"Application" should {
"work in a server" in {
running(TestServer(3333)) {
await(WS.url("http://localhost:3333").get).status must equalTo(OK)
}
}
"work from within a browser" in {
running(TestServer(3333), HTMLUNIT) { browser =>
browser.goTo("http://localhost:3333/")
browser.pageSource must contain("Your new application is ready.")
}
}
}
}
50
52. Deploy /2
Massimiliano Dessì & Alberto Quario GTUG Sardegna
Welcome to Play 2.1.0!
These commands are available:
-----------------------------
classpath Display the project classpath.
clean Clean all generated files.
compile Compile the current application.
console Launch the interactive Scala console (use :quit to exit).
dependencies Display the dependencies summary.
dist Construct standalone application package.
exit Exit the console.
h2-browser Launch the H2 Web browser.
license Display licensing informations.
package Package your application as a JAR.
play-version Display the Play version.
publish Publish your application in a remote repository.
publish-local Publish your application in the local repository.
reload Reload the current application build file.
run <port> Run the current application in DEV mode.
test Run Junit tests and/or Specs from the command line
eclipse generate eclipse project file
idea generate Intellij IDEA project file
sh <command to run> execute a shell command
start <port> Start the current application in another JVM in PROD mode.
update Update application dependencies.
52
53. Massimiliano Dessì & Alberto Quario GTUG Sardegna
spray is an open-source toolkit for REST/HTTP
and
low-level network IO on top of Scala and Akka.
aka Scala -IKEA
VMWare and Ebay use spray
for some internal projects
53
54. Routing
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class PingServiceActor extends Actor {
def receive = {
case HttpRequest(GET, "/ping", _, _, _) =>
sender ! HttpResponse(200, "PONG")
}
}
54
55. Routing
Massimiliano Dessì & Alberto Quario GTUG Sardegna
path with name order => directive route
get and put => are inner route
~ =>route concatenation
class MyServiceActor extends Actor with Routing {
def receive = receiveFromRoute {
path("order" / HexIntNumber) { id =>
get {
completeWith {
"Received GET for order " + id
}
} ~
put {
completeWith { "Received PUT for order " + id
}
}
}
}
}
55
56. Routing
Massimiliano Dessì & Alberto Quario GTUG Sardegna
trait LongerService extends HttpService with MyApp {
val simpleCache = routeCache(maxCapacity = 1000, timeToIdle = Duration("30 min"))
val route = {
path("orders") {
authenticate(BasicAuth(realm = "admin area")) { user =>
get {
cache(simpleCache) {
encodeResponse(Deflate) {
complete {
getOrdersFromDB
}
}
}
} ~
post {
(decodeRequest(Gzip) | decodeRequest(NoEncoding)) {
entity(as[Order]) { order =>
detachTo(singleRequestServiceActor) {
complete {
// ... write order to DB
"Order received"
}
}
}
}
}
}
} ~
56
57. Routing
Massimiliano Dessì & Alberto Quario GTUG Sardegna
pathPrefix("order" / IntNumber) { orderId =>
path("") {
// method tunneling via query param
(put | parameter('method ! "put")) {
// form extraction from multipart or www-url-encoded forms
formFields('email, 'total.as[Money]).as(Order) { order =>
complete {
// complete with serialized Future result
(myDbActor ? Update(order)).mapTo[TransactionResult]
}
}
} ~
get {
jsonpWithParameter("callback") {
produce(instanceOf[Order]) { complete => ctx =>
processOrderRequest(orderId, complete)
}
}
}
} ~
57
58. Non-blocking IO
Massimiliano Dessì & Alberto Quario GTUG Sardegna
def race() {
val start = System.currentTimeMillis()
def getLatency(r: Any): Long = System.currentTimeMillis() - start
val googleFuture = httpClient.ask(Get("http://www.google.com"))
.mapTo[HttpResponse].map(getLatency)
val yahooFuture = httpClient.ask(Get("http://www.yahoo.com"))
.mapTo[HttpResponse].map(getLatency)
val bingFuture = httpClient.ask(Get("http://www.example.com"))
.mapTo[HttpResponse].map(getLatency)
Future.sequence(Seq(googleFuture, yahooFuture, bingFuture)).map {
case times =>
log.info(
"google" + times(0) +
" yahoo" + times(1) +
" bing" + times(2) +
" total: "+getLatency(0))
system.shutdown() // stops all actors
}
}
58
59. Test
Massimiliano Dessì & Alberto Quario GTUG Sardegna
class DemoServiceSpec extends Specification with Specs2RouteTest with DemoService {
def actorRefFactory = system
"The DemoService" should {
"return a greeting for GET requests to the root path" in {
Get() ~> demoRoute ~> check { entityAs[String] must contain("Say hello") }
}
"return a 'PONG!' response for GET requests to /ping" in {
Get("/ping") ~> demoRoute ~> check { entityAs[String] === "PONG!" }
}
"leave GET requests to other paths unhandled" in {
Get("/kermit") ~> demoRoute ~> check { handled must beFalse }
}
"return a MethodNotAllowed error for PUT requests to the root path" in {
Put() ~> sealRoute(demoRoute) ~> check {
status === MethodNotAllowed
entityAs[String] === "HTTP method not allowed, supported methods: GET"
}
}
}
}
59