SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
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




                                             X
Sling URL decomposition

  GET   /forum/scala4sling.html   HTTP/1.1




                                             X
Sling URL decomposition

    GET    /forum/scala4sling.html   HTTP/1.1

Repository path




                                                X
Sling URL decomposition

    GET    /forum/scala4sling.html   HTTP/1.1

Repository path




                  Application
                   selection




                                                X
Sling URL decomposition

    GET    /forum/scala4sling.html     HTTP/1.1

Repository path                      Script selection




                  Application
                   selection




                                                        X
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>
    }
}
                                                      6
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>
    }
}
                                                                        6
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>
    }
}
                                                                        6
Agenda
■ Introduction
■ Requirements and goals
  – JSR-223 compliance
  – OSGi tolerant
  – Further design goals
■ Challenges and solutions
■ Conclusion




                             7
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




                                                      8
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)




                                                                                9
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




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


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



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




                                   12
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

                                                13
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>
    }
}



                                                      14
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>
    }
}




                                                                                                        14
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>


                                                                                                        14
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()
}

                                                                         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)




                    Where are the types?

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


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

                                                                         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)




                    Where are the types?

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

                                                                         15
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.




                                                                         16
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)




                                                                         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)




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




                                                                             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)




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




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




                                                                  18
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


                                                      19
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




                                                                   X
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




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




                                                       20
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




                                                         21
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/
                                                       22

Mais conteúdo relacionado

Mais procurados

The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84Mahmoud Samir Fayed
 
POCO C++ Libraries Intro and Overview
POCO C++ Libraries Intro and OverviewPOCO C++ Libraries Intro and Overview
POCO C++ Libraries Intro and OverviewGünter Obiltschnig
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
Building Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::ClientBuilding Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::ClientMike Friedman
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringCary Millsap
 
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
 
Apache Hive Hook
Apache Hive HookApache Hive Hook
Apache Hive HookMinwoo Kim
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingJosé Paumard
 
What is the ServiceStack?
What is the ServiceStack?What is the ServiceStack?
What is the ServiceStack?Demis Bellot
 
The Ring programming language version 1.5.2 book - Part 10 of 181
The Ring programming language version 1.5.2 book - Part 10 of 181The Ring programming language version 1.5.2 book - Part 10 of 181
The Ring programming language version 1.5.2 book - Part 10 of 181Mahmoud Samir Fayed
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youSHRUG GIS
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented NetworkingMostafa Amer
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9Marcus Lagergren
 

Mais procurados (18)

The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84The Ring programming language version 1.2 book - Part 79 of 84
The Ring programming language version 1.2 book - Part 79 of 84
 
POCO C++ Libraries Intro and Overview
POCO C++ Libraries Intro and OverviewPOCO C++ Libraries Intro and Overview
POCO C++ Libraries Intro and Overview
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
Building Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::ClientBuilding Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::Client
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and Monitoring
 
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
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Nancy + rest mow2012
Nancy + rest   mow2012Nancy + rest   mow2012
Nancy + rest mow2012
 
Apache Hive Hook
Apache Hive HookApache Hive Hook
Apache Hive Hook
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
 
What's new in Liferay Mobile SDK 2.0 for Android
What's new in Liferay Mobile SDK 2.0 for AndroidWhat's new in Liferay Mobile SDK 2.0 for Android
What's new in Liferay Mobile SDK 2.0 for Android
 
What is the ServiceStack?
What is the ServiceStack?What is the ServiceStack?
What is the ServiceStack?
 
The Ring programming language version 1.5.2 book - Part 10 of 181
The Ring programming language version 1.5.2 book - Part 10 of 181The Ring programming language version 1.5.2 book - Part 10 of 181
The Ring programming language version 1.5.2 book - Part 10 of 181
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_youShrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Scala active record
Scala active recordScala active record
Scala active record
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9
 

Semelhante a Scala for scripting

Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingmichid
 
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
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsIndicThreads
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStackSeedStack
 
Revolution or Evolution in Page Object
Revolution or Evolution in Page ObjectRevolution or Evolution in Page Object
Revolution or Evolution in Page ObjectArtem Sokovets
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
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
 
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
 
Sparkling Water
Sparkling WaterSparkling Water
Sparkling Waterh2oworld
 
Apache spark undocumented extensions
Apache spark undocumented extensionsApache spark undocumented extensions
Apache spark undocumented extensionsSandeep Joshi
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Kevin Juma
 

Semelhante a Scala for scripting (20)

Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
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
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Gradle
GradleGradle
Gradle
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applications
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStack
 
Revolution or Evolution in Page Object
Revolution or Evolution in Page ObjectRevolution or Evolution in Page Object
Revolution or Evolution in Page Object
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
ERGroupware
ERGroupwareERGroupware
ERGroupware
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
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
 
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
 
Sparkling Water
Sparkling WaterSparkling Water
Sparkling Water
 
Apache spark undocumented extensions
Apache spark undocumented extensionsApache spark undocumented extensions
Apache spark undocumented extensions
 
Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03Groovygrailsnetbeans 12517452668498-phpapp03
Groovygrailsnetbeans 12517452668498-phpapp03
 

Mais de day

Performance Pack
Performance PackPerformance Pack
Performance Packday
 
Testing Zen
Testing ZenTesting Zen
Testing Zenday
 
Java Persistence Frameworks
Java Persistence FrameworksJava Persistence Frameworks
Java Persistence Frameworksday
 
Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009day
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3day
 
Tarpm Clustering
Tarpm ClusteringTarpm Clustering
Tarpm Clusteringday
 
Tech Summit 08 Support Initiative
Tech Summit 08 Support InitiativeTech Summit 08 Support Initiative
Tech Summit 08 Support Initiativeday
 
Non Cms For Web Apps
Non Cms For Web AppsNon Cms For Web Apps
Non Cms For Web Appsday
 
Getting Into The Flow With Cq Dam
Getting Into The Flow With Cq DamGetting Into The Flow With Cq Dam
Getting Into The Flow With Cq Damday
 
Dispatcher Oom
Dispatcher OomDispatcher Oom
Dispatcher Oomday
 
Advanced Collaboration And Beyond
Advanced Collaboration And BeyondAdvanced Collaboration And Beyond
Advanced Collaboration And Beyondday
 
Wc Mand Connectors2
Wc Mand Connectors2Wc Mand Connectors2
Wc Mand Connectors2day
 
Jackrabbit Roadmap
Jackrabbit RoadmapJackrabbit Roadmap
Jackrabbit Roadmapday
 
Doc Book Vs Dita
Doc Book Vs DitaDoc Book Vs Dita
Doc Book Vs Ditaday
 
Doc Book Vs Dita Teresa
Doc Book Vs Dita TeresaDoc Book Vs Dita Teresa
Doc Book Vs Dita Teresaday
 
862
862862
862day
 
Apache Con Us2007 Sanselan
Apache Con Us2007 SanselanApache Con Us2007 Sanselan
Apache Con Us2007 Sanselanday
 
Apache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In ActionApache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In Actionday
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batisday
 
Apache Con U S07 F F T Sling
Apache Con U S07  F F T  SlingApache Con U S07  F F T  Sling
Apache Con U S07 F F T Slingday
 

Mais de day (20)

Performance Pack
Performance PackPerformance Pack
Performance Pack
 
Testing Zen
Testing ZenTesting Zen
Testing Zen
 
Java Persistence Frameworks
Java Persistence FrameworksJava Persistence Frameworks
Java Persistence Frameworks
 
Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
 
Tarpm Clustering
Tarpm ClusteringTarpm Clustering
Tarpm Clustering
 
Tech Summit 08 Support Initiative
Tech Summit 08 Support InitiativeTech Summit 08 Support Initiative
Tech Summit 08 Support Initiative
 
Non Cms For Web Apps
Non Cms For Web AppsNon Cms For Web Apps
Non Cms For Web Apps
 
Getting Into The Flow With Cq Dam
Getting Into The Flow With Cq DamGetting Into The Flow With Cq Dam
Getting Into The Flow With Cq Dam
 
Dispatcher Oom
Dispatcher OomDispatcher Oom
Dispatcher Oom
 
Advanced Collaboration And Beyond
Advanced Collaboration And BeyondAdvanced Collaboration And Beyond
Advanced Collaboration And Beyond
 
Wc Mand Connectors2
Wc Mand Connectors2Wc Mand Connectors2
Wc Mand Connectors2
 
Jackrabbit Roadmap
Jackrabbit RoadmapJackrabbit Roadmap
Jackrabbit Roadmap
 
Doc Book Vs Dita
Doc Book Vs DitaDoc Book Vs Dita
Doc Book Vs Dita
 
Doc Book Vs Dita Teresa
Doc Book Vs Dita TeresaDoc Book Vs Dita Teresa
Doc Book Vs Dita Teresa
 
862
862862
862
 
Apache Con Us2007 Sanselan
Apache Con Us2007 SanselanApache Con Us2007 Sanselan
Apache Con Us2007 Sanselan
 
Apache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In ActionApache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In Action
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batis
 
Apache Con U S07 F F T Sling
Apache Con U S07  F F T  SlingApache Con U S07  F F T  Sling
Apache Con U S07 F F T Sling
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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
 

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 X
  • 7. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 X
  • 8. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 Repository path X
  • 9. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 Repository path Application selection X
  • 10. Sling URL decomposition GET /forum/scala4sling.html HTTP/1.1 Repository path Script selection Application selection X
  • 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> } } 6
  • 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> } } 6
  • 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> } } 6
  • 14. Agenda ■ Introduction ■ Requirements and goals – JSR-223 compliance – OSGi tolerant – Further design goals ■ Challenges and solutions ■ Conclusion 7
  • 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 8
  • 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) 9
  • 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 10
  • 18. Further design goals ■ Leverage existing tools – Compilers – IDEs – Test suites – Documentation and reporting tools ■ Independent from Sling and OSGi – Versatile – Configurable – Embeddable 11
  • 19. Agenda ■ Introduction ■ Requirements and goals ■ Challenges and solutions – Leverage existing tools – Passing arguments to scripts – Scalac and OSGi – Performance ■ Conclusion 12
  • 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 13
  • 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> } } 14
  • 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> } } 14
  • 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> 14
  • 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() } 15
  • 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() } 15
  • 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() } 15
  • 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. 16
  • 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) 17
  • 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] } 17
  • 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] } 17
  • 31. Bindings wrapper (cont.) ■ Limitations – Scala’s visibility modifiers not exposed through reflection – Not yet working with parametrized types – Ambiguities in generated implicit conversion 18
  • 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 19
  • 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 X
  • 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 X
  • 35. Performance ■ On the fly compilation is slow – Cache pre compiled scripts – Dependency on bindings: include bindings wrapper – Work in progress 20
  • 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 21
  • 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/ 22