SlideShare une entreprise Scribd logo
1  sur  20
LOGO SPEAKER‘S COMPANY
Scala for Sling
Building RESTful Web Applications with Scala for Sling
http://people.apache.org/~mduerig/scala4sling/
Michael Dürig
Day Software AG
10080
2
Introduction
> Michael Dürig
– Developer for Day Software
– http://michid.wordpress.com/
> Michael Marth
– Technology Evangelist for Day Software
– http://dev.day.com/
3
Overview
> What to expect
– Proof of concept
– Experimental code
> What not to expect
– Product showcase, tutorial
– Live coding (demo code available from
http://people.apache.org/~mduerig/scala4sling/)
> Prerequisites
– Basic understanding of Java content repositories (JCR)
– Prior exposure to Scala a plus
4
AGENDA
> Introduction
> What is Apache Sling?
> What is Scala?
> Scala for Sling
> Summary and questions
5
Sling builds on JCR
> Web application framework for JCR
– JCR (JSR-170/JSR-283): Apache Jackrabbit
– OSGi-based: Apache Felix
– http://incubator.apache.org/sling/
> Scriptable application layer for JCR
– JSR-223: Scripting for the Java platform
> REST over JCR
– Content resolution for mapping request URLs to JCR nodes
– Servlet resolution for mapping JCR nodes to request handlers (i.e. scripts)
6
URL decomposition
GET /forum/scala4sling.thread.html
Repository
Repository path Script selection
Application selection
7
AGENDA
> Introduction
> What is Apache Sling?
> What is Scala?
> Scala for Sling
> Summary and questions
8
Scala builds on the JVM
> Multi-paradigm language for the JVM
– Conceived by Martin Odersky and his group (EPFL, Lausanne)
– Fully interoperable with Java
– IDE plugins for Eclipse and IntelliJ IDEA
– http://www.scala-lang.org/
> Concise, elegant, and type safe
– Touch and feel of a genuine scripting language
– Smoothly integrates object oriented and functional features
– Ideal for creating internal DSLs
> Values
> Type parameters
9
Type inference: the scripting touch
val x = 42 // x has type Int
val s = x.toString // s has type String
val q = s.substring(s) // type mismatch; found String, required Int
class Pair[S, T](s: S, t: T)
def makePair[S, T](s: S, t: T) = new Pair(s, t)
val p = makePair(42.0, "Scala") // p has type Pair[Double, String]
class Pair<S, T> {
public final S s;
public final T t;
public Pair(S s, T t) {
super();
this.s = s;
this.t = t;
}
}
public <S, T> Pair<S, T> makePair(S s, T t) {
return new Pair<S, T>(s, t);
}
public final Pair<Double, String> p = makePair(42.0, "Scala");
10
XML <pre>literals</pre>
> HTML? Scala!
val title = "Hello Jazoon 09"
println {
Elem(null, "html", Null, TopScope,
Elem(null, "body", Null, TopScope,
Elem(null, "h1", Null, TopScope,
Text(title)
),
Text(
(for (c <- title) yield c)
.mkString(" ")
)
)
)
}
val title = "Hello Jazoon 09"
println {
<html>
<body>
<h1>{ title }</h1>
{
(for (c <- title) yield c)
.mkString(" ")
}
</body>
</html>
}
<html>
<body>
<h1>Hello Jazoon 09</h1>
H e l l o J a z o o n 0 9
</body>
</html>
11
Implicits: pimp my library
> Implicit conversion
> Déjà vu?
– Similar to extension methods in C#
– Similar to conversion constructors in C++
– Equivalent to type classes in Haskell
implicit def translate(s: String) = new {
def toGerman = s match {
case "Example" => "Beispiel"
// ...
case _ => throw new Exception("No translation for " + s)
}
}
val german = "Example".toGerman
12
AGENDA
> Introduction
> What is Apache Sling?
> What is Scala?
> Scala for Sling
> Summary and questions
13
Demo application: Forum
package forum {
object html {
import html_Bindings._
// ...
println {
<html>
<body>
Welcome to the { currentNode("name") } forum
&mdash; { Calendar.getInstance.getTime }
{ ThreadNewForm.render }
{ ThreadOverview.render(currentNode) }
</body>
</html>
}
}
GET /forum.html
Put Sling variables into scope
(currentNode, request, response, etc.)/**
* Print out an object followed by a new line character.
* @param x the object to print.
*/
def println(x: Any): Unit = out.println(x)
14
Forum: html.scala
implicit def rich(node: Node) = new {
def apply(property: String) = node.getProperty(property).getString
...
}
object ThreadNewForm {
def render = {
<h1>start a new thread</h1>
<form action="/content/forum/*" method="POST"
enctype="multipart/form-data">
subject <input name="subject" type="text" />
<textarea name="body"></textarea>
logo <input name="logo“ type="file" />
<input type="submit" value="save" />
<input name=":redirect" value="/content/forum.html" type="hidden" />
</form>
}
}
15
Forum: form data
POST should add new child node to
/content/forum/
Redirect to forum.html on success
... with properties subject and body of
type String,
... and a child node logo of type nt:file.
16
Forum: custom POST request handler
package forum {
object POST {
import POST_Bindings._
// ...
val node = addNodes(session.root, newPath)
node.setProperty("body", request("body"))
node.setProperty(“subject", request(“subject"))
if (request("logo") != "") {
val logoNode = node.addNode("logo", "nt:file")
val contentNode = logoNode.addNode("jcr:content", "nt:resource")
val logo = request.getRequestParameter("logo")
contentNode.setProperty("jcr:lastModified", Calendar.getInstance)
contentNode.setProperty("jcr:mimeType", logo.getContentType)
contentNode.setProperty("jcr:data", logo.getInputStream)
}
session.save
response.sendRedirect(request(":redirect"))
}
}
POST /forum.html
Add node for this post
Set properties for body and subject
If the request contains a logo
... add a child node logo of type nt:file
... and set properties jcr:lastModified,
jcr:mimeType and jcr:data
Save changes and send redirect
object html_Bindings extends MockBindings {
override def currentNode = new MockNode
with MockItem
override def request = new MockSlingHttpServletRequest
with MockHttpServletRequest
with MockServletRequest
}
object Test extends Application {
forum.html
}
17
Forum: unit testing
<html>
<head>
<link href="/apps/forum/static/blue.css" rel="stylesheet"></link>
</head>
<body>
<div id="Header">
Welcome to the forum
&mdash; Wed Jun 17 17:12:48 CEST 2009
</div>
<div id="Menu">
<p>search all threads:
<form action="/content/forum.search.html"
enctype="multipart/form-data" method="GET">
<input value="" type="text" size="10" name="query"></input>
<input value="search" type="submit"></input>
</form>
</p>
</div>
<div id="Content">
<h1>start a new thread</h1>
<span id="inp">
<form action="/content/forum/*" enctype="multipart/form-data" method="POST">
<p>subject</p>
<p><input type="text" name="subject"></input></p>
<p><textarea name="body"></textarea></p>
<p>logo</p>
<p><input type="file" name="logo"></input></p>
<p><input value="save" type="submit"></input></p>
<input value="/content/forum.html" type="hidden" name=":redirect"></input>
</form>
</span>
</div>
</body>
</html>
18
AGENDA
> Introduction
> What is Apache Sling?
> What is Scala?
> Scala for Sling
> Summary and questions
19
Conclusion
> Advantages
– Scala!
– No language boundary: «on the
fly» templates through XML
literals
– Tool support (i.e. IDE, ScalaDoc,
safe refactoring, unit testing)
> Disadvantages
– IDE support shaky, improves
quickly though
– Not much refactoring support as
of today
object html_Bindings {
def currentNode = new MockNode
...
}
object Test extends Application {
forum.html
}
<p>Welcome to { currentNode("name") } forum</p>
&mdash; { Calendar.getInstance.getTime }
{ ThreadNewForm.render }
{ ThreadOverview.render(currentNode) }
LOGO SPEAKER‘S COMPANY
Michael Dürig michael.duerig@day.com
Michael Marth michael.marth@day.com
Day Software AG http://www.day.com/
References:
• Scala for Sling: http://people.apache.org/~mduerig/scala4sling/
• The Scala programming language: http://www.scala-lang.org/
• Apache Sling: http://incubator.apache.org/sling/

Contenu connexe

Similaire à Scala & sling

Scala4sling
Scala4slingScala4sling
Scala4slingday
 
Big Data processing with Spark, Scala or Java?
Big Data processing with Spark, Scala or Java?Big Data processing with Spark, Scala or Java?
Big Data processing with Spark, Scala or Java?Erik-Berndt Scheper
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your AppLuca Mearelli
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingmichid
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesScala Italy
 
Diseño y Desarrollo de APIs
Diseño y Desarrollo de APIsDiseño y Desarrollo de APIs
Diseño y Desarrollo de APIsRaúl Neis
 
Abusing text/template for data transformation
Abusing text/template for data transformationAbusing text/template for data transformation
Abusing text/template for data transformationArnaud Porterie
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Andrey Volobuev
 
A Blueprint for Scala Microservices
A Blueprint for Scala MicroservicesA Blueprint for Scala Microservices
A Blueprint for Scala MicroservicesFederico Feroldi
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingday
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQLjeykottalam
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibElasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibJen Aman
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)MongoDB
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scalarostislav
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 

Similaire à Scala & sling (20)

Scala4sling
Scala4slingScala4sling
Scala4sling
 
Big Data processing with Spark, Scala or Java?
Big Data processing with Spark, Scala or Java?Big Data processing with Spark, Scala or Java?
Big Data processing with Spark, Scala or Java?
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservices
 
Diseño y Desarrollo de APIs
Diseño y Desarrollo de APIsDiseño y Desarrollo de APIs
Diseño y Desarrollo de APIs
 
Abusing text/template for data transformation
Abusing text/template for data transformationAbusing text/template for data transformation
Abusing text/template for data transformation
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)
 
A Blueprint for Scala Microservices
A Blueprint for Scala MicroservicesA Blueprint for Scala Microservices
A Blueprint for Scala Microservices
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlibElasticsearch And Apache Lucene For Apache Spark And MLlib
Elasticsearch And Apache Lucene For Apache Spark And MLlib
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scala
 
03 form-data
03 form-data03 form-data
03 form-data
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 

Dernier

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 

Dernier (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

Scala & sling

  • 1. LOGO SPEAKER‘S COMPANY Scala for Sling Building RESTful Web Applications with Scala for Sling http://people.apache.org/~mduerig/scala4sling/ Michael Dürig Day Software AG 10080
  • 2. 2 Introduction > Michael Dürig – Developer for Day Software – http://michid.wordpress.com/ > Michael Marth – Technology Evangelist for Day Software – http://dev.day.com/
  • 3. 3 Overview > What to expect – Proof of concept – Experimental code > What not to expect – Product showcase, tutorial – Live coding (demo code available from http://people.apache.org/~mduerig/scala4sling/) > Prerequisites – Basic understanding of Java content repositories (JCR) – Prior exposure to Scala a plus
  • 4. 4 AGENDA > Introduction > What is Apache Sling? > What is Scala? > Scala for Sling > Summary and questions
  • 5. 5 Sling builds on JCR > Web application framework for JCR – JCR (JSR-170/JSR-283): Apache Jackrabbit – OSGi-based: Apache Felix – http://incubator.apache.org/sling/ > Scriptable application layer for JCR – JSR-223: Scripting for the Java platform > REST over JCR – Content resolution for mapping request URLs to JCR nodes – Servlet resolution for mapping JCR nodes to request handlers (i.e. scripts)
  • 7. 7 AGENDA > Introduction > What is Apache Sling? > What is Scala? > Scala for Sling > Summary and questions
  • 8. 8 Scala builds on the JVM > Multi-paradigm language for the JVM – Conceived by Martin Odersky and his group (EPFL, Lausanne) – Fully interoperable with Java – IDE plugins for Eclipse and IntelliJ IDEA – http://www.scala-lang.org/ > Concise, elegant, and type safe – Touch and feel of a genuine scripting language – Smoothly integrates object oriented and functional features – Ideal for creating internal DSLs
  • 9. > Values > Type parameters 9 Type inference: the scripting touch val x = 42 // x has type Int val s = x.toString // s has type String val q = s.substring(s) // type mismatch; found String, required Int class Pair[S, T](s: S, t: T) def makePair[S, T](s: S, t: T) = new Pair(s, t) val p = makePair(42.0, "Scala") // p has type Pair[Double, String] class Pair<S, T> { public final S s; public final T t; public Pair(S s, T t) { super(); this.s = s; this.t = t; } } public <S, T> Pair<S, T> makePair(S s, T t) { return new Pair<S, T>(s, t); } public final Pair<Double, String> p = makePair(42.0, "Scala");
  • 10. 10 XML <pre>literals</pre> > HTML? Scala! val title = "Hello Jazoon 09" println { Elem(null, "html", Null, TopScope, Elem(null, "body", Null, TopScope, Elem(null, "h1", Null, TopScope, Text(title) ), Text( (for (c <- title) yield c) .mkString(" ") ) ) ) } val title = "Hello Jazoon 09" println { <html> <body> <h1>{ title }</h1> { (for (c <- title) yield c) .mkString(" ") } </body> </html> } <html> <body> <h1>Hello Jazoon 09</h1> H e l l o J a z o o n 0 9 </body> </html>
  • 11. 11 Implicits: pimp my library > Implicit conversion > Déjà vu? – Similar to extension methods in C# – Similar to conversion constructors in C++ – Equivalent to type classes in Haskell implicit def translate(s: String) = new { def toGerman = s match { case "Example" => "Beispiel" // ... case _ => throw new Exception("No translation for " + s) } } val german = "Example".toGerman
  • 12. 12 AGENDA > Introduction > What is Apache Sling? > What is Scala? > Scala for Sling > Summary and questions
  • 14. package forum { object html { import html_Bindings._ // ... println { <html> <body> Welcome to the { currentNode("name") } forum &mdash; { Calendar.getInstance.getTime } { ThreadNewForm.render } { ThreadOverview.render(currentNode) } </body> </html> } } GET /forum.html Put Sling variables into scope (currentNode, request, response, etc.)/** * Print out an object followed by a new line character. * @param x the object to print. */ def println(x: Any): Unit = out.println(x) 14 Forum: html.scala implicit def rich(node: Node) = new { def apply(property: String) = node.getProperty(property).getString ... }
  • 15. object ThreadNewForm { def render = { <h1>start a new thread</h1> <form action="/content/forum/*" method="POST" enctype="multipart/form-data"> subject <input name="subject" type="text" /> <textarea name="body"></textarea> logo <input name="logo“ type="file" /> <input type="submit" value="save" /> <input name=":redirect" value="/content/forum.html" type="hidden" /> </form> } } 15 Forum: form data POST should add new child node to /content/forum/ Redirect to forum.html on success ... with properties subject and body of type String, ... and a child node logo of type nt:file.
  • 16. 16 Forum: custom POST request handler package forum { object POST { import POST_Bindings._ // ... val node = addNodes(session.root, newPath) node.setProperty("body", request("body")) node.setProperty(“subject", request(“subject")) if (request("logo") != "") { val logoNode = node.addNode("logo", "nt:file") val contentNode = logoNode.addNode("jcr:content", "nt:resource") val logo = request.getRequestParameter("logo") contentNode.setProperty("jcr:lastModified", Calendar.getInstance) contentNode.setProperty("jcr:mimeType", logo.getContentType) contentNode.setProperty("jcr:data", logo.getInputStream) } session.save response.sendRedirect(request(":redirect")) } } POST /forum.html Add node for this post Set properties for body and subject If the request contains a logo ... add a child node logo of type nt:file ... and set properties jcr:lastModified, jcr:mimeType and jcr:data Save changes and send redirect
  • 17. object html_Bindings extends MockBindings { override def currentNode = new MockNode with MockItem override def request = new MockSlingHttpServletRequest with MockHttpServletRequest with MockServletRequest } object Test extends Application { forum.html } 17 Forum: unit testing <html> <head> <link href="/apps/forum/static/blue.css" rel="stylesheet"></link> </head> <body> <div id="Header"> Welcome to the forum &mdash; Wed Jun 17 17:12:48 CEST 2009 </div> <div id="Menu"> <p>search all threads: <form action="/content/forum.search.html" enctype="multipart/form-data" method="GET"> <input value="" type="text" size="10" name="query"></input> <input value="search" type="submit"></input> </form> </p> </div> <div id="Content"> <h1>start a new thread</h1> <span id="inp"> <form action="/content/forum/*" enctype="multipart/form-data" method="POST"> <p>subject</p> <p><input type="text" name="subject"></input></p> <p><textarea name="body"></textarea></p> <p>logo</p> <p><input type="file" name="logo"></input></p> <p><input value="save" type="submit"></input></p> <input value="/content/forum.html" type="hidden" name=":redirect"></input> </form> </span> </div> </body> </html>
  • 18. 18 AGENDA > Introduction > What is Apache Sling? > What is Scala? > Scala for Sling > Summary and questions
  • 19. 19 Conclusion > Advantages – Scala! – No language boundary: «on the fly» templates through XML literals – Tool support (i.e. IDE, ScalaDoc, safe refactoring, unit testing) > Disadvantages – IDE support shaky, improves quickly though – Not much refactoring support as of today object html_Bindings { def currentNode = new MockNode ... } object Test extends Application { forum.html } <p>Welcome to { currentNode("name") } forum</p> &mdash; { Calendar.getInstance.getTime } { ThreadNewForm.render } { ThreadOverview.render(currentNode) }
  • 20. LOGO SPEAKER‘S COMPANY Michael Dürig michael.duerig@day.com Michael Marth michael.marth@day.com Day Software AG http://www.day.com/ References: • Scala for Sling: http://people.apache.org/~mduerig/scala4sling/ • The Scala programming language: http://www.scala-lang.org/ • Apache Sling: http://incubator.apache.org/sling/