SlideShare a Scribd company logo
1 of 36
Download to read offline
<Insert Picture Here>
Turtle Graphics in Groovy
Jim Driscoll
2
My Background
• ADFm
– Part of Oracle's ADF Framework
– Provides data binding and database access
– Provides ways to customize data views via Groovy
– Groovy uses have basic DSL customizations
• Wanted to Learn JavaFX (after last year's GR8 Conf)
• Have 5 year old daughter
• Napili – named after the Maui bay
3
Logo
• An early programming language (1960's)
• Popular in the 80's as a teaching tool
– Which is how I first heard about it
• A dialect of Lisp (but much more approachable)
• Currently (per Wikipedia) 197 different dialects
• Most famous for it's use of Turtle Graphics
4
Turtle Graphics
• Vector based graphics using a relative cursor
– The “Turtle”
– Represented in early work as a triangle
• Turtles have three attributes
– A location
– An orientation
– A “pen” (which has on/off state, color, width, etc)
5
Turtle Commands
• home
• left / right (takes int arg, degrees)
• forward / back (takes int arg, #pixels)
• penup / pendown
• pencolor (takes Color arg)
• show / hide
• speed (takes int arg)
6
Language Style
• Commands without parens
– left 90, home, hide, etc
• Chained Commands
– left 90 forward 100 hide (as one line)
• Use with an explicit turtle, or with an implicit turtle
• Use Groovy language constructs
– Define variables
– Define methods
– Closures
7
Language Decisions – DSL vs GPL
• DSL (Domain Specific Language)
– A limited language, designed to be useful for a specific task
– HTML, SQL, stuff you can build with Groovy Builders
• GPL (General Purpose Language)
– A general language, designed to be useful for any task
– Java, Groovy, Assembler, etc
• I went the GPLish route, full Groovy + DSL extensions
– But there's not necessarily a one right answer
8
Demo
9
First, Create a Framework
• Created a Turtle class, with supporting classes
– Methods like #home(), #hide(), #forward(int), etc.
• Allows drawing on a canvas via a turtle
• Used JavaFX, including animations
– This isn't a JavaFX talk...
• Once that's all working, add the control language
10
Executing Programs In Memory
• Object GroovyShell#evaluate(String)
– Can be slow (10ms)
• Cacheing Scripts
– Script GroovyShell#parse(String) ← slow part (10ms)
– Object Script#run() ← fast part (<1ms)
GroovyShell shell = new GroovyShell();
Script script = shell.parse("println 'hello world'");
script.run();
11
Bindings – the Nouns
• A Binding is a way to pass values in/out of a script
– Used as unqualified variables (“println name”)
– Declared varaibles (def) go into a separate space
• Groovy provides a default Binding
– But you can provide one of your own
• Use it to provide
– Constant values
– Default values
– Error checked values
test = 1
println test
def test = 0
println test
binding.test
12
Bindings in Napili
• Little used
– But could be used much more
• Just two variables, turtle and out
• out
– Special variable to redirect println output
• turtle
– Used for direct calls on the turtle
• turtle.penup(), turtle.forward(100) will now work
13
Initialize Bindings in Napili
static class BasicBinding extends Binding {
Turtle turtle
public BasicBinding() {
super();
turtle = new Turtle()
}
14
Getting Binding Values
public Object getVariable(String name) {
if (name == 'out') {
return NapiliOutput.getPrintWriter();
}
if (name == 'turtle') {
return turtle;
}
return super.getVariable(name)
}
15
Setting Binding Values
public void setVariable(String name, Object value) {
if ("turtle".equals(name)) {
NapiliOutput.println('Unable to set "turtle" to value' + value)
return;
}
super.setVariable(name, value);
}
16
Using the Binding
GroovyShell shell = new GroovyShell(config)
Script script = shell.parse(scriptStr)
script.setBinding(new BasicBinding())
script.run()
17
Adding Imports
• Can add imports and static imports to scripts
• Allows easy usage of existing classes
• Added via CompilerConfiguration
– An optional parameter to GroovyShell
• Static imports can let you define variables
– import static java.lang.Math.PI lets “println PI” work
18
Adding Imports in Napili
CompilerConfiguration config = new CompilerConfiguration()
ImportCustomizer ic = new ImportCustomizer();
ic.addImports('javafx.scene.paint.Color')
config.addCompilationCustomizers(ic)
GroovyShell shell = new GroovyShell(config)
• Adds an automatic import for JavaFX's Color so...
• turtle.pencolor(Color.Purple) now works
• If we instead do a static import, we could just say Purple
– ImportCustomizer#addStarImports(String)
19
ScriptBaseClass – the Verbs
• Dynamically assign a new base class
• Allows you to declare top level functions
• Inserted as part of the CompilerConfiguration
• Has access to Binding variables
– Can be used for implicit parameter passing
20
ScriptBaseClass – example
abstract class BaseScript extends Script {
def forward(int i) {
turtle.forward(i)
}
def right(int i) {
turtle.right(i)
}
}
21
InvokeMethod
• Allows you to dynamically route method calls
– Lets you use a context object
– GroovyInterceptable interface
• Just add a #invokeMethod(String,args) function
def invokeMethod(String name, args) {
println name
}
def test() {println “hey”}
hello()
test()
22
MethodMissing
• Allows you to specify new behavior if a method isn't
found
• Just add a #methodMissing(String,args) function
• Combined with a ScriptBaseClass...
23
ScriptBaseClass in Napili
abstract class TurtleDelegateBaseScript extends Script {
// if we can't find the method, look for it on the turtle binding object
def methodMissing(String name, args) {
binding.turtle."$name"(* args)
}
}
• Abstract class
• Effectively reroutes all calls through Turtle
24
ScriptBaseClass in Napili
CompilerConfiguration config = new CompilerConfiguration()
config.setScriptBaseClass("fullpath.TurtleDelegateBaseScript")
GroovyShell shell = new GroovyShell(config)
• Now, “forward(100)” works
• Because of optional parens, “forward 100” works too
• But “home()” is required, “home” won't work...
25
No arg Methods
• But what about “home” or “penup”?
• They're seen as Binding variables
• So, use the Binding to execute them:
public Object getVariable(String name) {
...
// treat all no-arg methods on Turtle as binding variables with side effects
if (turtle.metaClass.respondsTo(turtle,name)) {
return turtle.metaClass.invokeMethod(turtle, name)
}
return super.getVariable(name)
}
26
No arg Methods as Properties
• Use #propertyMissing(String) on Turtle
• Allows turtle.hide instead of turtle.hide()
def propertyMissing(String name) {
// treat all no-arg methods as properties
if (this.metaClass.respondsTo(this, name)) {
return this.metaClass.invokeMethod(this, name)
}
throw new MissingPropertyException("No property on Turtle named '$name'")
}
27
Timeout protection
• What about while (true) {}?
• groovy.transform.TimedInterrupt
CompilerConfiguration config = new CompilerConfiguration()
config.setScriptBaseClass("org.netdance.napili.language.TurtleDelegateBaseScript")
ImportCustomizer ic = new ImportCustomizer();
ic.addImports('javafx.scene.paint.Color')
def ti = new ASTTransformationCustomizer([value: Napili.TIMEOUT],TimedInterrupt)
config.addCompilationCustomizers(ic, ti)
GroovyShell shell = new GroovyShell(config)
28
Recap
• Create a Turtle object
• Make it available to scripts via the Binding
• Use ScriptBaseClass to route all method calls through it
• ImportCustomizer to allow using JavaFX Color
• TimedInterrupt to stop runaway processes
29
Method Chaining
• You may have noticed....
– forward 100 back 100 hide
• It's harder than it looks
– first second third fourth == first(second).third(fourth)
– first second third fourth fifth == first(second).third(fourth).fifth
– GroovyConsole is great for understanding the parse rules
• No arg methods break that flow
– forward 100 hide home ← doesn't work
30
Removing Language Features
• SecureASTCustomizer
– Static Analysis
– def s = Shell; s.exit(0)
– (See my talk this afternoon for more on security)
• Can be used to remove language features
31
Removing Increment Operator (++)
def config = new CompilerConfiguration();
def customizer = new SecureASTCustomizer();
def tokens = []
tokens.add(Types.PLUS_PLUS);
customizer.setTokensBlacklist(tokens);
config.addCompilationCustomizers(customizer);
def shell = new GroovyShell(config);
32
Removing For Loops
def config = new CompilerConfiguration();
def customizer = new SecureASTCustomizer();
def statements = []
statements.add(ForStatement.class);
customizer.setStatementsBlacklist(statements);
config.addCompilationCustomizers(customizer);
def shell = new GroovyShell(config);
33
Q&A
34
Resources
• Napili Code
– https://github.com/netdance/Napili
• My Blog
– https://jamesgdriscoll.wordpress.com/
• Books
– Groovy in Action, 2nd
ed (still in early access, but worth getting)
– Groovy for Domain Specific Languages
– DSLs in Action (multiple language examples)
35
The preceding is intended to outline our general product
direction. It is intended for information purposes only,
and may not be incorporated into any contract. It is
not a commitment to deliver any material, code, or
functionality, and should not be relied upon in making
purchasing decisions.
The development, release, and timing of any features
or functionality described for Oracle’s products remains
at the sole discretion of Oracle.
36

More Related Content

What's hot

concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. ExperienceMike Fogus
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
tictactoe groovy
tictactoe groovytictactoe groovy
tictactoe groovyPaul King
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)Qiangning Hong
 
awesome groovy
awesome groovyawesome groovy
awesome groovyPaul King
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)Gagan Agrawal
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.Mike Fogus
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019Leonardo Borges
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startupsbmlever
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers輝 子安
 

What's hot (20)

concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
tictactoe groovy
tictactoe groovytictactoe groovy
tictactoe groovy
 
Python高级编程(二)
Python高级编程(二)Python高级编程(二)
Python高级编程(二)
 
awesome groovy
awesome groovyawesome groovy
awesome groovy
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 
Python lec4
Python lec4Python lec4
Python lec4
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Python lec5
Python lec5Python lec5
Python lec5
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
 
Groovy
GroovyGroovy
Groovy
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startups
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 

Viewers also liked

Cassandra thompson ignite slideshow1
Cassandra thompson ignite slideshow1Cassandra thompson ignite slideshow1
Cassandra thompson ignite slideshow1cassye28
 
20090324 Het Nieuwe Werken Media Plaza V7
20090324 Het Nieuwe Werken Media Plaza V720090324 Het Nieuwe Werken Media Plaza V7
20090324 Het Nieuwe Werken Media Plaza V7abos
 
LIS 5240 Library Design Project
LIS 5240   Library Design ProjectLIS 5240   Library Design Project
LIS 5240 Library Design Projecttrautweiler
 
Prezentace tianDe (lepší verze)
Prezentace tianDe (lepší verze)Prezentace tianDe (lepší verze)
Prezentace tianDe (lepší verze)Liza Alypova
 
Ekošampon tiande cz
Ekošampon tiande czEkošampon tiande cz
Ekošampon tiande czLiza Alypova
 
Bringing your brand to Romania !
Bringing your brand to Romania !Bringing your brand to Romania !
Bringing your brand to Romania !NEW ELITE
 
Nuclear Opportunities in the US and UK
Nuclear Opportunities in the US and UKNuclear Opportunities in the US and UK
Nuclear Opportunities in the US and UKSNC-Lavalin
 
Pre-checklist for Real Estate Brokers and Customer
Pre-checklist for Real Estate Brokers and Customer Pre-checklist for Real Estate Brokers and Customer
Pre-checklist for Real Estate Brokers and Customer RE/MAX Andhra Pradesh
 
Cmmaao resource-commitment-matrix-pmi-pmp
Cmmaao resource-commitment-matrix-pmi-pmpCmmaao resource-commitment-matrix-pmi-pmp
Cmmaao resource-commitment-matrix-pmi-pmpvishvasyadav45
 
Narrowed Horizons: the fiscal choices at Spending Review 2013 and beyond
Narrowed Horizons: the fiscal choices at Spending Review 2013 and beyondNarrowed Horizons: the fiscal choices at Spending Review 2013 and beyond
Narrowed Horizons: the fiscal choices at Spending Review 2013 and beyondResolutionFoundation
 
無題プレゼンテーション3
無題プレゼンテーション3無題プレゼンテーション3
無題プレゼンテーション3s1200017
 

Viewers also liked (16)

Cassandra thompson ignite slideshow1
Cassandra thompson ignite slideshow1Cassandra thompson ignite slideshow1
Cassandra thompson ignite slideshow1
 
20090324 Het Nieuwe Werken Media Plaza V7
20090324 Het Nieuwe Werken Media Plaza V720090324 Het Nieuwe Werken Media Plaza V7
20090324 Het Nieuwe Werken Media Plaza V7
 
Uitnodiging: "Een licht op visie"
Uitnodiging: "Een licht op visie"Uitnodiging: "Een licht op visie"
Uitnodiging: "Een licht op visie"
 
LIS 5240 Library Design Project
LIS 5240   Library Design ProjectLIS 5240   Library Design Project
LIS 5240 Library Design Project
 
Prezentace tianDe (lepší verze)
Prezentace tianDe (lepší verze)Prezentace tianDe (lepší verze)
Prezentace tianDe (lepší verze)
 
Ekošampon tiande cz
Ekošampon tiande czEkošampon tiande cz
Ekošampon tiande cz
 
Bringing your brand to Romania !
Bringing your brand to Romania !Bringing your brand to Romania !
Bringing your brand to Romania !
 
Nuclear Opportunities in the US and UK
Nuclear Opportunities in the US and UKNuclear Opportunities in the US and UK
Nuclear Opportunities in the US and UK
 
Pre-checklist for Real Estate Brokers and Customer
Pre-checklist for Real Estate Brokers and Customer Pre-checklist for Real Estate Brokers and Customer
Pre-checklist for Real Estate Brokers and Customer
 
Cmmaao resource-commitment-matrix-pmi-pmp
Cmmaao resource-commitment-matrix-pmi-pmpCmmaao resource-commitment-matrix-pmi-pmp
Cmmaao resource-commitment-matrix-pmi-pmp
 
A Look at Structural Claims
A Look at Structural ClaimsA Look at Structural Claims
A Look at Structural Claims
 
Mickey
MickeyMickey
Mickey
 
Esd project mcmc marcht 2016
Esd project mcmc marcht 2016Esd project mcmc marcht 2016
Esd project mcmc marcht 2016
 
Narrowed Horizons: the fiscal choices at Spending Review 2013 and beyond
Narrowed Horizons: the fiscal choices at Spending Review 2013 and beyondNarrowed Horizons: the fiscal choices at Spending Review 2013 and beyond
Narrowed Horizons: the fiscal choices at Spending Review 2013 and beyond
 
無題プレゼンテーション3
無題プレゼンテーション3無題プレゼンテーション3
無題プレゼンテーション3
 
Multilateral Newsletter - March 2016
Multilateral Newsletter - March 2016Multilateral Newsletter - March 2016
Multilateral Newsletter - March 2016
 

Similar to Turtle Graphics in Groovy

Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovyIsuru Samaraweera
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouAndres Almiray
 
Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Joachim Baumann
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubtersMax Klyga
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Jim Driscoll
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Bozhidar Batsov
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGuillaume Laforge
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoMatt Stine
 

Similar to Turtle Graphics in Groovy (20)

Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and You
 
Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)Introduction to Groovy (Serbian Developer Conference 2013)
Introduction to Groovy (Serbian Developer Conference 2013)
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubters
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Groovy.pptx
Groovy.pptxGroovy.pptx
Groovy.pptx
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 

Recently uploaded

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 

Recently uploaded (20)

Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 

Turtle Graphics in Groovy

  • 1. <Insert Picture Here> Turtle Graphics in Groovy Jim Driscoll
  • 2. 2 My Background • ADFm – Part of Oracle's ADF Framework – Provides data binding and database access – Provides ways to customize data views via Groovy – Groovy uses have basic DSL customizations • Wanted to Learn JavaFX (after last year's GR8 Conf) • Have 5 year old daughter • Napili – named after the Maui bay
  • 3. 3 Logo • An early programming language (1960's) • Popular in the 80's as a teaching tool – Which is how I first heard about it • A dialect of Lisp (but much more approachable) • Currently (per Wikipedia) 197 different dialects • Most famous for it's use of Turtle Graphics
  • 4. 4 Turtle Graphics • Vector based graphics using a relative cursor – The “Turtle” – Represented in early work as a triangle • Turtles have three attributes – A location – An orientation – A “pen” (which has on/off state, color, width, etc)
  • 5. 5 Turtle Commands • home • left / right (takes int arg, degrees) • forward / back (takes int arg, #pixels) • penup / pendown • pencolor (takes Color arg) • show / hide • speed (takes int arg)
  • 6. 6 Language Style • Commands without parens – left 90, home, hide, etc • Chained Commands – left 90 forward 100 hide (as one line) • Use with an explicit turtle, or with an implicit turtle • Use Groovy language constructs – Define variables – Define methods – Closures
  • 7. 7 Language Decisions – DSL vs GPL • DSL (Domain Specific Language) – A limited language, designed to be useful for a specific task – HTML, SQL, stuff you can build with Groovy Builders • GPL (General Purpose Language) – A general language, designed to be useful for any task – Java, Groovy, Assembler, etc • I went the GPLish route, full Groovy + DSL extensions – But there's not necessarily a one right answer
  • 9. 9 First, Create a Framework • Created a Turtle class, with supporting classes – Methods like #home(), #hide(), #forward(int), etc. • Allows drawing on a canvas via a turtle • Used JavaFX, including animations – This isn't a JavaFX talk... • Once that's all working, add the control language
  • 10. 10 Executing Programs In Memory • Object GroovyShell#evaluate(String) – Can be slow (10ms) • Cacheing Scripts – Script GroovyShell#parse(String) ← slow part (10ms) – Object Script#run() ← fast part (<1ms) GroovyShell shell = new GroovyShell(); Script script = shell.parse("println 'hello world'"); script.run();
  • 11. 11 Bindings – the Nouns • A Binding is a way to pass values in/out of a script – Used as unqualified variables (“println name”) – Declared varaibles (def) go into a separate space • Groovy provides a default Binding – But you can provide one of your own • Use it to provide – Constant values – Default values – Error checked values test = 1 println test def test = 0 println test binding.test
  • 12. 12 Bindings in Napili • Little used – But could be used much more • Just two variables, turtle and out • out – Special variable to redirect println output • turtle – Used for direct calls on the turtle • turtle.penup(), turtle.forward(100) will now work
  • 13. 13 Initialize Bindings in Napili static class BasicBinding extends Binding { Turtle turtle public BasicBinding() { super(); turtle = new Turtle() }
  • 14. 14 Getting Binding Values public Object getVariable(String name) { if (name == 'out') { return NapiliOutput.getPrintWriter(); } if (name == 'turtle') { return turtle; } return super.getVariable(name) }
  • 15. 15 Setting Binding Values public void setVariable(String name, Object value) { if ("turtle".equals(name)) { NapiliOutput.println('Unable to set "turtle" to value' + value) return; } super.setVariable(name, value); }
  • 16. 16 Using the Binding GroovyShell shell = new GroovyShell(config) Script script = shell.parse(scriptStr) script.setBinding(new BasicBinding()) script.run()
  • 17. 17 Adding Imports • Can add imports and static imports to scripts • Allows easy usage of existing classes • Added via CompilerConfiguration – An optional parameter to GroovyShell • Static imports can let you define variables – import static java.lang.Math.PI lets “println PI” work
  • 18. 18 Adding Imports in Napili CompilerConfiguration config = new CompilerConfiguration() ImportCustomizer ic = new ImportCustomizer(); ic.addImports('javafx.scene.paint.Color') config.addCompilationCustomizers(ic) GroovyShell shell = new GroovyShell(config) • Adds an automatic import for JavaFX's Color so... • turtle.pencolor(Color.Purple) now works • If we instead do a static import, we could just say Purple – ImportCustomizer#addStarImports(String)
  • 19. 19 ScriptBaseClass – the Verbs • Dynamically assign a new base class • Allows you to declare top level functions • Inserted as part of the CompilerConfiguration • Has access to Binding variables – Can be used for implicit parameter passing
  • 20. 20 ScriptBaseClass – example abstract class BaseScript extends Script { def forward(int i) { turtle.forward(i) } def right(int i) { turtle.right(i) } }
  • 21. 21 InvokeMethod • Allows you to dynamically route method calls – Lets you use a context object – GroovyInterceptable interface • Just add a #invokeMethod(String,args) function def invokeMethod(String name, args) { println name } def test() {println “hey”} hello() test()
  • 22. 22 MethodMissing • Allows you to specify new behavior if a method isn't found • Just add a #methodMissing(String,args) function • Combined with a ScriptBaseClass...
  • 23. 23 ScriptBaseClass in Napili abstract class TurtleDelegateBaseScript extends Script { // if we can't find the method, look for it on the turtle binding object def methodMissing(String name, args) { binding.turtle."$name"(* args) } } • Abstract class • Effectively reroutes all calls through Turtle
  • 24. 24 ScriptBaseClass in Napili CompilerConfiguration config = new CompilerConfiguration() config.setScriptBaseClass("fullpath.TurtleDelegateBaseScript") GroovyShell shell = new GroovyShell(config) • Now, “forward(100)” works • Because of optional parens, “forward 100” works too • But “home()” is required, “home” won't work...
  • 25. 25 No arg Methods • But what about “home” or “penup”? • They're seen as Binding variables • So, use the Binding to execute them: public Object getVariable(String name) { ... // treat all no-arg methods on Turtle as binding variables with side effects if (turtle.metaClass.respondsTo(turtle,name)) { return turtle.metaClass.invokeMethod(turtle, name) } return super.getVariable(name) }
  • 26. 26 No arg Methods as Properties • Use #propertyMissing(String) on Turtle • Allows turtle.hide instead of turtle.hide() def propertyMissing(String name) { // treat all no-arg methods as properties if (this.metaClass.respondsTo(this, name)) { return this.metaClass.invokeMethod(this, name) } throw new MissingPropertyException("No property on Turtle named '$name'") }
  • 27. 27 Timeout protection • What about while (true) {}? • groovy.transform.TimedInterrupt CompilerConfiguration config = new CompilerConfiguration() config.setScriptBaseClass("org.netdance.napili.language.TurtleDelegateBaseScript") ImportCustomizer ic = new ImportCustomizer(); ic.addImports('javafx.scene.paint.Color') def ti = new ASTTransformationCustomizer([value: Napili.TIMEOUT],TimedInterrupt) config.addCompilationCustomizers(ic, ti) GroovyShell shell = new GroovyShell(config)
  • 28. 28 Recap • Create a Turtle object • Make it available to scripts via the Binding • Use ScriptBaseClass to route all method calls through it • ImportCustomizer to allow using JavaFX Color • TimedInterrupt to stop runaway processes
  • 29. 29 Method Chaining • You may have noticed.... – forward 100 back 100 hide • It's harder than it looks – first second third fourth == first(second).third(fourth) – first second third fourth fifth == first(second).third(fourth).fifth – GroovyConsole is great for understanding the parse rules • No arg methods break that flow – forward 100 hide home ← doesn't work
  • 30. 30 Removing Language Features • SecureASTCustomizer – Static Analysis – def s = Shell; s.exit(0) – (See my talk this afternoon for more on security) • Can be used to remove language features
  • 31. 31 Removing Increment Operator (++) def config = new CompilerConfiguration(); def customizer = new SecureASTCustomizer(); def tokens = [] tokens.add(Types.PLUS_PLUS); customizer.setTokensBlacklist(tokens); config.addCompilationCustomizers(customizer); def shell = new GroovyShell(config);
  • 32. 32 Removing For Loops def config = new CompilerConfiguration(); def customizer = new SecureASTCustomizer(); def statements = [] statements.add(ForStatement.class); customizer.setStatementsBlacklist(statements); config.addCompilationCustomizers(customizer); def shell = new GroovyShell(config);
  • 34. 34 Resources • Napili Code – https://github.com/netdance/Napili • My Blog – https://jamesgdriscoll.wordpress.com/ • Books – Groovy in Action, 2nd ed (still in early access, but worth getting) – Groovy for Domain Specific Languages – DSLs in Action (multiple language examples)
  • 35. 35 The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
  • 36. 36