SlideShare a Scribd company logo
1 of 37
Scala for Scripting
Implementing an OSGi enabled, JSR-223 compliant scripting engine for Scala
http://people.apache.org/~mduerig/scala4scripting/




Michael Dürig
michael.duerig@day.com

Day Software AG
http://www.day.com/

Scala Days 2010
April 15th




                                                                             1
Agenda
■ Introduction
  – Scripting with Scala
  – Scala for Apache Sling
■ Requirements and goals
■ Challenges and solutions
■ Conclusion




                             2
Scripting with Scala
■ (Illusion of) executing source code
■ Concise and versatile*
     var capitals = Map("Switzerland" -> "Bern", "Spain" -> "Madrid")
     capitals += ("France" -> "Paris")

     val c = capitals.find(_._1 == "France")
       .map(_._2)
       .getOrElse("NIL")


■ DSL capabilities
■ Type safe




*) Adapted from: Programming in Scala, Martin Odersky, Lex Spoon, Bill Venners. Artima, 2008.   3
Scripting with Scala (cont.)
■ XML literals: type safe templating
  <html>
    <head>
      <link rel="stylesheet" href="/apps/forum/static/blue.css" />
    </head>
    <body>
      <div id="Header">
        Welcome to the { node("name") } forum
        { Calendar.getInstance.getTime }
      </div>
      <div id="Content">
        { SearchBox.render(request) }
        { ThreadOverview.render(node) }
      </div>
    </body>
  </html>




                                                                     4
Apache Sling
■ Web application framework
  – Backed by a Java content repository (JSR-170/JSR-283):
    Apache Jackrabbit
  – Based on OSGi: Apache Felix
  – http://sling.apache.org/
■ RESTful
  – Content resolution for mapping request URLs to resources
    (i.e. JCR nodes)
  – Servlet resolution for mapping resources to request handlers
    (i.e. scripts)
■ Scriptable application layer
  – JSR-223: Scripting for the Java platform

                                                                   5
Sling URL decomposition

  GET   /forum/scala4sling.html   HTTP/1.1




                                             6
Sling URL decomposition

  GET   /forum/scala4sling.html   HTTP/1.1




                                             6
Sling URL decomposition

    GET    /forum/scala4sling.html   HTTP/1.1

Repository path




                                                6
Sling URL decomposition

    GET    /forum/scala4sling.html   HTTP/1.1

Repository path




                  Application
                   selection




                                                6
Sling URL decomposition

    GET    /forum/scala4sling.html     HTTP/1.1

Repository path                      Script selection




                  Application
                   selection




                                                        6
Scala for Sling
package forum


class html(args: htmlArgs) {
  import args._
    // further imports omitted


    println {
        <html>
          <body>
            <div id="Header">
             Welcome to the { node("name") } forum
             { Calendar.getInstance.getTime }
           </div>
           <div id="Content">
             { SearchBox.render(request) }
             { ThreadOverview.render(node) }
           </div>
         </body>
        </html>
    }
}
                                                     7
Scala for Sling
package forum


class html(args: htmlArgs) {
  import args._                                      Import bindings
    // further imports omitted


    println {
        <html>
          <body>
            <div id="Header">
             Welcome to the { node("name") } forum
             { Calendar.getInstance.getTime }
           </div>
           <div id="Content">
             { SearchBox.render(request) }
             { ThreadOverview.render(node) }
           </div>
         </body>
        </html>
    }
}
                                                                       7
Scala for Sling
package forum


class html(args: htmlArgs) {
  import args._                                      Import bindings
    // further imports omitted


    println {
        <html>
          <body>
            <div id="Header">
             Welcome to the { node("name") } forum
             { Calendar.getInstance.getTime }
           </div>
                                                     Use arguments
           <div id="Content">
             { SearchBox.render(request) }
             { ThreadOverview.render(node) }
           </div>
         </body>
        </html>
    }
}
                                                                       7
Agenda
■ Introduction
■ Requirements and goals
  – JSR-223 compliance
  – OSGi tolerant
  – Further design goals
■ Challenges and solutions
■ Conclusion




                             8
JSR-223
■ Scripting for the Java language
  – Allow scripts access to the Java Platform
  – Scripting for Java server-side applications
  – Executing scripts:
   javax.script.{ScriptEngine, ScriptEngineFactory}
  – Binding application objects into scripts:
   javax.script.Bindings




                                                      9
JSR-223: usage
val factories = ServiceRegistry.lookupProviders(classOf[ScriptEngineFactory])
val factory = factories.find(_.getEngineName == "Scala Scripting Engine")

val engine = factory.map(_.getScriptEngine).getOrElse {
  throw new Error("Cannot locate Scala scripting engine")
}

val bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE)
bindings.put("request", servletRequest)
engine.eval(script, bindings)




                                                                                10
OSGi
■ OSGi Service Platform
  – Runtime environment for Java applications (bundles)
  – Module system
  – Life cycle management
  – Service registry
■ Mostly transparent
  – Bundle information in manifest file
  – Relies on class loading




                                                          11
Further design goals
■ Leverage existing tools
  – Compilers
  – IDEs
  – Test suites
  – Documentation and reporting tools


■ Independent from Sling and OSGi
  – Versatile
  – Configurable
  – Embeddable



                                        12
Agenda
■ Introduction
■ Requirements and goals
■ Challenges and solutions
  – Leverage existing tools
  – Passing arguments to scripts
  – Scalac and OSGi
  – Performance
■ Conclusion




                                   13
Leverage existing tools
■ Scripts are valid Scala source entities
■ Tradeoff
  – ceremony
    package forum


    class html(args: htmlArgs) {
      import args._
        // ...
    }


■ Advantages
  – Write, refactor and debug with Scala IDEs
  – Compile with Scala compiler
  – Unit testing

                                                14
Unit testing
class html(args: htmlArgs) {
    import args._
    // further imports omitted


    println {
      <html>
        <body>
           <div id="Header">
             Welcome to the { node("name") } forum
             { Calendar.getInstance.getTime }
           </div>
           <div id="Content">
             { SearchBox.render(request) }
             { ThreadOverview.render(node) }
           </div>
          </body>
        </html>
    }
}



                                                     15
Unit testing
class html(args: htmlArgs) {
    import args._                                    class htmlArgs {
    // further imports omitted
                                                       val node = new {
    println {                                            def apply(name: String) = "Scala scripting"
      <html>
          <body>                                       }
           <div id="Header">                             val request = new { /* ... */ }
             Welcome to the { node("name") } forum
             { Calendar.getInstance.getTime }        }
           </div>
           <div id="Content">
             { SearchBox.render(request) }           new html(new htmlArgs)
             { ThreadOverview.render(node) }
           </div>
          </body>
        </html>
    }
}




                                                                                                       15
Unit testing
class html(args: htmlArgs) {
    import args._                                    class htmlArgs {
    // further imports omitted
                                                       val node = new {
    println {                                            def apply(name: String) = "Scala scripting"
      <html>
          <body>                                       }
           <div id="Header">                             val request = new { /* ... */ }
             Welcome to the { node("name") } forum
             { Calendar.getInstance.getTime }        }
           </div>
           <div id="Content">
             { SearchBox.render(request) }           new html(new htmlArgs)
             { ThreadOverview.render(node) }
           </div>
          </body>
        </html>
    }
                              <html>
}                               <body>
                                  <div id="Header">
                                     Welcome to the Scala scripting forum
                                     Tue Mar 16 19:46:38 CET 2010
                                  </div>
                                  <div id="Content">
                                     <!-- output omitted -->
                                  </div>
                                </body>
                              </html>


                                                                                                       15
Passing arguments to Scripts
class ResettableOutStream extends OutputStream implements Resettable {
  public void write(int b) throws IOException { /* ... */ }
  public void reset() { /* ... */ }
}

OutputStream getResetableOutputStream() { /* ... */ }


bindings.put("output", getResetableOutputStream)
engine.eval(script, bindings)




class html(args: htmlArgs) {
    import args._


    output.write(‘c’)
    output.reset()
}

                                                                         16
Passing arguments to Scripts
class ResettableOutStream extends OutputStream implements Resettable {
  public void write(int b) throws IOException { /* ... */ }
  public void reset() { /* ... */ }
}

OutputStream getResetableOutputStream() { /* ... */ }


bindings.put("output", getResetableOutputStream)
engine.eval(script, bindings)




                    Where are the types?

class html(args: htmlArgs) {
    import args._


    output.write(‘c’)
    output.reset()
}

                                                                         16
Passing arguments to Scripts
class ResettableOutStream extends OutputStream implements Resettable {
  public void write(int b) throws IOException { /* ... */ }
  public void reset() { /* ... */ }
}

OutputStream getResetableOutputStream() { /* ... */ }


bindings.put("output", getResetableOutputStream)
engine.eval(script, bindings)




                    Where are the types?

class html(args: htmlArgs) {
    import args._
                                     Bindings wrapper
    output.write(‘c’)
                                     provides static types
    output.reset()
}

                                                                         16
Bindings wrapper
■ No type information in javax.script.Bindings
  – Generate bindings wrapper exposing static types
  – Arguments appear to be of all accessible types
  – Implicit conversions to the rescue
■ Least accessible types
  – v: C, I1, ..., In
  – Expose v with static type D of least accessible super type of C
  – Expose v through implicit conversion to Ik if neither D nor any Im
    (m ≠ k) implements Ik.




                                                                         17
Bindings wrapper (cont.)
class ResettableOutStream extends OutputStream implements Resettable {
  public void write(int b) throws IOException { /* ... */ }
  public void reset() { /* ... */ }
}

OutputStream getResetableOutputStream() { /* ... */ }


bindings.put("output", new ResettableOutStream)
engine.eval(script, bindings)




                                                                         18
Bindings wrapper (cont.)
class ResettableOutStream extends OutputStream implements Resettable {
  public void write(int b) throws IOException { /* ... */ }
  public void reset() { /* ... */ }
}

OutputStream getResetableOutputStream() { /* ... */ }


bindings.put("output", new ResettableOutStream)
engine.eval(script, bindings)




Bindings wrapper
class htmlArgs(bindings: Bindings) {
  lazy val output = bindings.getValue("output").asInstanceOf[OutputStream]
  implicit def outputStream2Resettable(x: OutputStream): Resettable =
               x.asInstanceOf[Resettable]
}




                                                                             18
Bindings wrapper (cont.)
class ResettableOutStream extends OutputStream implements Resettable {
  public void write(int b) throws IOException { /* ... */ }
  public void reset() { /* ... */ }
}

OutputStream getResetableOutputStream() { /* ... */ }


bindings.put("output", new ResettableOutStream)
engine.eval(script, bindings)




Bindings wrapper
class htmlArgs(bindings: Bindings) {
  lazy val output = bindings.getValue("output").asInstanceOf[OutputStream]
  implicit def outputStream2Resettable(x: OutputStream): Resettable =
               x.asInstanceOf[Resettable]
}




                                                                             18
Bindings wrapper (cont.)
■ Limitations
  – Scala’s visibility modifiers not exposed through reflection
  – Not yet working with parametrized types
  – Ambiguities in generated implicit conversion




                                                                  19
Scalac and OSGi
■ Scalac
  – Requires compiler class path
  – File system based
■ OSGi
  – Provides class loaders
  – Bundle based
■ Bridging the gap
  – File system abstraction over OSGi bundles
  – Implement scala.tools.nsc.io.AbstractFile
  – Limitation: wiring probably not fully respected


                                                      20
Independent through configuration
■ Abstract implementation details into configuration class
  – Default implementation for standalone usage
  – Specialized implementations for Sling
  – Set through ScriptEngineFactory or injected via OSGi service
    lookup




                                                                   21
Configuration
■ Scala compiler
  – Per script engine
  – scripting.scala.SettingsProvider
  – Class and output paths: scala.tools.nsc.io.AbstractFile
  – Settings: scala.tools.nsc.Settings
  – Reporting: scala.tools.nsc.reporters.Reporter
■ Script entry point
  – Per invocation
  – scripting.scala.ScriptInfo




                                                              22
Performance
■ On the fly compilation is slow
  – Cache pre compiled scripts
  – Dependency on bindings: include bindings wrapper
  – Work in progress




                                                       23
Conclusion
■ Scala is attractive for scripting
  – Concise and versatile
  – DSL capabilities
  – Type safe
  – XML literals for type safe templating
■ Impedance mismatches
  – JSR-223: dynamic vs. static typing
  – OSGi: runtime environment vs. compile time utility
  – Performance: illusion of executing source code




                                                         24
References
■ Scala for Scripting
  http://people.apache.org/~mduerig/scala4scripting/
■ Apache Sling
  http://sling.apache.org/




■ Michael Dürig
  michael.duerig@day.com
■ Day Software AG
  http://www.day.com/
                                                       25

More Related Content

What's hot

Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsJustin Edelson
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David SzakallasDatabricks
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
 

What's hot (20)

scala
scalascala
scala
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala test
Scala testScala test
Scala test
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
All about scala
All about scalaAll about scala
All about scala
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Omnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the ThingsOmnisearch in AEM 6.2 - Search All the Things
Omnisearch in AEM 6.2 - Search All the Things
 
Spark Schema For Free with David Szakallas
 Spark Schema For Free with David Szakallas Spark Schema For Free with David Szakallas
Spark Schema For Free with David Szakallas
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 

Similar to Scala for scripting

Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingday
 
Scala4sling
Scala4slingScala4sling
Scala4slingday
 
Scala & sling
Scala & slingScala & sling
Scala & slingmichid
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about GradleEvgeny Goldin
 
Revolution or Evolution in Page Object
Revolution or Evolution in Page ObjectRevolution or Evolution in Page Object
Revolution or Evolution in Page ObjectArtem Sokovets
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStackSeedStack
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkIndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
OSMC 2009 | Icinga by Icinga Team
OSMC 2009 | Icinga by Icinga TeamOSMC 2009 | Icinga by Icinga Team
OSMC 2009 | Icinga by Icinga TeamNETWAYS
 

Similar to Scala for scripting (20)

Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Scala4sling
Scala4slingScala4sling
Scala4sling
 
Scala & sling
Scala & slingScala & sling
Scala & sling
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
GradleFX
GradleFXGradleFX
GradleFX
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
 
Revolution or Evolution in Page Object
Revolution or Evolution in Page ObjectRevolution or Evolution in Page Object
Revolution or Evolution in Page Object
 
Gradle
GradleGradle
Gradle
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStack
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
ERGroupware
ERGroupwareERGroupware
ERGroupware
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
OSMC 2009 | Icinga by Icinga Team
OSMC 2009 | Icinga by Icinga TeamOSMC 2009 | Icinga by Icinga Team
OSMC 2009 | Icinga by Icinga Team
 

Recently uploaded

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

Scala for scripting

  • 1. Scala for Scripting Implementing an OSGi enabled, JSR-223 compliant scripting engine for Scala http://people.apache.org/~mduerig/scala4scripting/ Michael Dürig michael.duerig@day.com Day Software AG http://www.day.com/ Scala Days 2010 April 15th 1
  • 2. Agenda ■ Introduction – Scripting with Scala – Scala for Apache Sling ■ Requirements and goals ■ Challenges and solutions ■ Conclusion 2
  • 3. Scripting with Scala ■ (Illusion of) executing source code ■ Concise and versatile* var capitals = Map("Switzerland" -> "Bern", "Spain" -> "Madrid") capitals += ("France" -> "Paris") val c = capitals.find(_._1 == "France") .map(_._2) .getOrElse("NIL") ■ DSL capabilities ■ Type safe *) Adapted from: Programming in Scala, Martin Odersky, Lex Spoon, Bill Venners. Artima, 2008. 3
  • 4. Scripting with Scala (cont.) ■ XML literals: type safe templating <html> <head> <link rel="stylesheet" href="/apps/forum/static/blue.css" /> </head> <body> <div id="Header"> Welcome to the { node("name") } forum { Calendar.getInstance.getTime } </div> <div id="Content"> { SearchBox.render(request) } { ThreadOverview.render(node) } </div> </body> </html> 4
  • 5. Apache Sling ■ Web application framework – Backed by a Java content repository (JSR-170/JSR-283): Apache Jackrabbit – Based on OSGi: Apache Felix – http://sling.apache.org/ ■ RESTful – Content resolution for mapping request URLs to resources (i.e. JCR nodes) – Servlet resolution for mapping resources to request handlers (i.e. scripts) ■ Scriptable application layer – JSR-223: Scripting for the Java platform 5
  • 6. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 6
  • 7. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 6
  • 8. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 Repository path 6
  • 9. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 Repository path Application selection 6
  • 10. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 Repository path Script selection Application selection 6
  • 11. Scala for Sling package forum class html(args: htmlArgs) { import args._ // further imports omitted println { <html> <body> <div id="Header"> Welcome to the { node("name") } forum { Calendar.getInstance.getTime } </div> <div id="Content"> { SearchBox.render(request) } { ThreadOverview.render(node) } </div> </body> </html> } } 7
  • 12. Scala for Sling package forum class html(args: htmlArgs) { import args._ Import bindings // further imports omitted println { <html> <body> <div id="Header"> Welcome to the { node("name") } forum { Calendar.getInstance.getTime } </div> <div id="Content"> { SearchBox.render(request) } { ThreadOverview.render(node) } </div> </body> </html> } } 7
  • 13. Scala for Sling package forum class html(args: htmlArgs) { import args._ Import bindings // further imports omitted println { <html> <body> <div id="Header"> Welcome to the { node("name") } forum { Calendar.getInstance.getTime } </div> Use arguments <div id="Content"> { SearchBox.render(request) } { ThreadOverview.render(node) } </div> </body> </html> } } 7
  • 14. Agenda ■ Introduction ■ Requirements and goals – JSR-223 compliance – OSGi tolerant – Further design goals ■ Challenges and solutions ■ Conclusion 8
  • 15. JSR-223 ■ Scripting for the Java language – Allow scripts access to the Java Platform – Scripting for Java server-side applications – Executing scripts: javax.script.{ScriptEngine, ScriptEngineFactory} – Binding application objects into scripts: javax.script.Bindings 9
  • 16. JSR-223: usage val factories = ServiceRegistry.lookupProviders(classOf[ScriptEngineFactory]) val factory = factories.find(_.getEngineName == "Scala Scripting Engine") val engine = factory.map(_.getScriptEngine).getOrElse { throw new Error("Cannot locate Scala scripting engine") } val bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE) bindings.put("request", servletRequest) engine.eval(script, bindings) 10
  • 17. OSGi ■ OSGi Service Platform – Runtime environment for Java applications (bundles) – Module system – Life cycle management – Service registry ■ Mostly transparent – Bundle information in manifest file – Relies on class loading 11
  • 18. Further design goals ■ Leverage existing tools – Compilers – IDEs – Test suites – Documentation and reporting tools ■ Independent from Sling and OSGi – Versatile – Configurable – Embeddable 12
  • 19. Agenda ■ Introduction ■ Requirements and goals ■ Challenges and solutions – Leverage existing tools – Passing arguments to scripts – Scalac and OSGi – Performance ■ Conclusion 13
  • 20. Leverage existing tools ■ Scripts are valid Scala source entities ■ Tradeoff – ceremony package forum class html(args: htmlArgs) { import args._ // ... } ■ Advantages – Write, refactor and debug with Scala IDEs – Compile with Scala compiler – Unit testing 14
  • 21. Unit testing class html(args: htmlArgs) { import args._ // further imports omitted println { <html> <body> <div id="Header"> Welcome to the { node("name") } forum { Calendar.getInstance.getTime } </div> <div id="Content"> { SearchBox.render(request) } { ThreadOverview.render(node) } </div> </body> </html> } } 15
  • 22. Unit testing class html(args: htmlArgs) { import args._ class htmlArgs { // further imports omitted val node = new { println { def apply(name: String) = "Scala scripting" <html> <body> } <div id="Header"> val request = new { /* ... */ } Welcome to the { node("name") } forum { Calendar.getInstance.getTime } } </div> <div id="Content"> { SearchBox.render(request) } new html(new htmlArgs) { ThreadOverview.render(node) } </div> </body> </html> } } 15
  • 23. Unit testing class html(args: htmlArgs) { import args._ class htmlArgs { // further imports omitted val node = new { println { def apply(name: String) = "Scala scripting" <html> <body> } <div id="Header"> val request = new { /* ... */ } Welcome to the { node("name") } forum { Calendar.getInstance.getTime } } </div> <div id="Content"> { SearchBox.render(request) } new html(new htmlArgs) { ThreadOverview.render(node) } </div> </body> </html> } <html> } <body> <div id="Header"> Welcome to the Scala scripting forum Tue Mar 16 19:46:38 CET 2010 </div> <div id="Content"> <!-- output omitted --> </div> </body> </html> 15
  • 24. Passing arguments to Scripts class ResettableOutStream extends OutputStream implements Resettable { public void write(int b) throws IOException { /* ... */ } public void reset() { /* ... */ } } OutputStream getResetableOutputStream() { /* ... */ } bindings.put("output", getResetableOutputStream) engine.eval(script, bindings) class html(args: htmlArgs) { import args._ output.write(‘c’) output.reset() } 16
  • 25. Passing arguments to Scripts class ResettableOutStream extends OutputStream implements Resettable { public void write(int b) throws IOException { /* ... */ } public void reset() { /* ... */ } } OutputStream getResetableOutputStream() { /* ... */ } bindings.put("output", getResetableOutputStream) engine.eval(script, bindings) Where are the types? class html(args: htmlArgs) { import args._ output.write(‘c’) output.reset() } 16
  • 26. Passing arguments to Scripts class ResettableOutStream extends OutputStream implements Resettable { public void write(int b) throws IOException { /* ... */ } public void reset() { /* ... */ } } OutputStream getResetableOutputStream() { /* ... */ } bindings.put("output", getResetableOutputStream) engine.eval(script, bindings) Where are the types? class html(args: htmlArgs) { import args._ Bindings wrapper output.write(‘c’) provides static types output.reset() } 16
  • 27. Bindings wrapper ■ No type information in javax.script.Bindings – Generate bindings wrapper exposing static types – Arguments appear to be of all accessible types – Implicit conversions to the rescue ■ Least accessible types – v: C, I1, ..., In – Expose v with static type D of least accessible super type of C – Expose v through implicit conversion to Ik if neither D nor any Im (m ≠ k) implements Ik. 17
  • 28. Bindings wrapper (cont.) class ResettableOutStream extends OutputStream implements Resettable { public void write(int b) throws IOException { /* ... */ } public void reset() { /* ... */ } } OutputStream getResetableOutputStream() { /* ... */ } bindings.put("output", new ResettableOutStream) engine.eval(script, bindings) 18
  • 29. Bindings wrapper (cont.) class ResettableOutStream extends OutputStream implements Resettable { public void write(int b) throws IOException { /* ... */ } public void reset() { /* ... */ } } OutputStream getResetableOutputStream() { /* ... */ } bindings.put("output", new ResettableOutStream) engine.eval(script, bindings) Bindings wrapper class htmlArgs(bindings: Bindings) { lazy val output = bindings.getValue("output").asInstanceOf[OutputStream] implicit def outputStream2Resettable(x: OutputStream): Resettable = x.asInstanceOf[Resettable] } 18
  • 30. Bindings wrapper (cont.) class ResettableOutStream extends OutputStream implements Resettable { public void write(int b) throws IOException { /* ... */ } public void reset() { /* ... */ } } OutputStream getResetableOutputStream() { /* ... */ } bindings.put("output", new ResettableOutStream) engine.eval(script, bindings) Bindings wrapper class htmlArgs(bindings: Bindings) { lazy val output = bindings.getValue("output").asInstanceOf[OutputStream] implicit def outputStream2Resettable(x: OutputStream): Resettable = x.asInstanceOf[Resettable] } 18
  • 31. Bindings wrapper (cont.) ■ Limitations – Scala’s visibility modifiers not exposed through reflection – Not yet working with parametrized types – Ambiguities in generated implicit conversion 19
  • 32. Scalac and OSGi ■ Scalac – Requires compiler class path – File system based ■ OSGi – Provides class loaders – Bundle based ■ Bridging the gap – File system abstraction over OSGi bundles – Implement scala.tools.nsc.io.AbstractFile – Limitation: wiring probably not fully respected 20
  • 33. Independent through configuration ■ Abstract implementation details into configuration class – Default implementation for standalone usage – Specialized implementations for Sling – Set through ScriptEngineFactory or injected via OSGi service lookup 21
  • 34. Configuration ■ Scala compiler – Per script engine – scripting.scala.SettingsProvider – Class and output paths: scala.tools.nsc.io.AbstractFile – Settings: scala.tools.nsc.Settings – Reporting: scala.tools.nsc.reporters.Reporter ■ Script entry point – Per invocation – scripting.scala.ScriptInfo 22
  • 35. Performance ■ On the fly compilation is slow – Cache pre compiled scripts – Dependency on bindings: include bindings wrapper – Work in progress 23
  • 36. Conclusion ■ Scala is attractive for scripting – Concise and versatile – DSL capabilities – Type safe – XML literals for type safe templating ■ Impedance mismatches – JSR-223: dynamic vs. static typing – OSGi: runtime environment vs. compile time utility – Performance: illusion of executing source code 24
  • 37. References ■ Scala for Scripting http://people.apache.org/~mduerig/scala4scripting/ ■ Apache Sling http://sling.apache.org/ ■ Michael Dürig michael.duerig@day.com ■ Day Software AG http://www.day.com/ 25

Editor's Notes

  1. Versatile: independent from file system (i.e. JCR), Reporting other then sysout
  2. Script compilation: fail fast behavior
  3. - Private modifier: 2.7: class file attributes, 2.8 annotations - Ambiguity issues: robuster when using a provider class as source for implicit conversion for each binding - Impedance mismatch: JSR-223 provides support for dynamically typed languages, Scala is statically typed
  4. - File system traversal operations somewhat problematic on top of OSGi bundles - Impedance mismatch: OSGi is a runtime environment, scalac a compile time utility
  5. - Pick up &amp;#x2018;illusion of...&amp;#x2019; from introduction
  6. Caching complicated: class files depend on generated type wrapper