Presentation is loading. Please wait.

Presentation is loading. Please wait.

Richard Care Duncan McGregor

Similar presentations


Presentation on theme: "Richard Care Duncan McGregor"— Presentation transcript:

1 Richard Care Duncan McGregor
Java Scripting Richard Care Duncan McGregor RC – kick it off

2 Session Format Tutorial Worked examples in different languages
Runtime Java Evaluation in Beanshell Scripting an Application in JRuby Building a GUI in Jython Parsing Test Scripts in Jython Groovy for Application Development Try to pull together some threads at the end Questions at any time This is a big subject to cover in 75 minutes, so we’re only aiming to give a taste of some of the mainstream languages available, and to show what can be done with them. Questions at any time, but we’ll reserve the right to defer them to the end.

3 What Is Your Experience?
We might be able to tailor the session towards the mean We’re going to assume a Java background Show of hands - Do any of you have any experience with other languages on the Java VM Briefly - what experience?

4 What is Script? Scripting languages (commonly called scripting programming languages or script languages) are computer programming languages initially designed for "scripting" the operations of a computer. Early script languages were often called batch languages or job control languages. A script is more usually interpreted than compiled, but not always. en.wikipedia.org/wiki/Scripting_language Skipping lightly on, we’d better define what we mean by a scripting language But that’s a little dry, and misses our target

5 For Our Purposes Interpreted or compiled, but at runtime
eval(runtimeString) Running on the Java VM A scripting language may be interpreted or compiled, but this happens (or can happen) at runtime. This gives us the ability to evaluate code at runtime.

6 Runtime Java Evaluation
DMCG So lets look at the simple use of one of scripting languages best features, evaluation at runtime.

7 Runtime Java Evaluation
Goals We want fast turnaround of code deployed in a slow-startup system We don’t another language We want to compile to classes once we’ve got it ‘right’

8 Runtime Java Evaluation
Demo Run up beanshell console Capture in/out Type stuff

9 Runtime Java Evaluation
BSFManager scriptManager = new BSFManager(); scriptManager.declareBean("root", new File("/"), File.class); final Object[] result = new Object[1]; scriptManager.declareBean("result", result, result.getClass()); scriptManager.exec("beanshell", "script name", 0, 0, readFile(new File("src/java/com/example/dynamic/test.java"))); System.out.println(result[0]);

10 Runtime Java Evaluation
BeanShell “Small, free, embeddable, source level Java interpreter with object based scripting language features, written in Java.” JSR 274 Java syntax JSR means that there is a chance that it will become part of Java

11 Runtime Java Evaluation
BeanShell Good for rapid prototyping of systems which are going to end up as compiled Java Familiar syntax Can relax typing JDK 1.5 features on 1.4 VM Nice script bonuses this.variables - An array of Strings listing the variables defined in the current method context (namespace).・ this.methods - An array of Strings listing the methods defined the current method context (namespace).・ this.interpreter - A bsh.Interpreter reference to the currently executing BeanShell Interpreter object.・ this.namespace - A bsh.NameSpace reference to the BeanShell NameSpace object of the current method context. See "Advanced Topics".・ this.caller - A bsh.This reference to the calling BeanShell method context. See "Variables and Scope Modifiers".・ this.callstack - An array of bsh.NameSpace references representing the "call stack" up to the current method context. See "Advanced Topics".

12 Scripting an Application
ERAC

13 Scripting an Application
Goal Customising for site conditions Evolution without a new release Allow user control over some aspects We might usually deliver a command line app and script its invocation with shell

14 Scripting an Application
Demo Remember to introduce Utility

15 Scripting an Application
include_class "com.example.domain.Utility" include_class "com.example.domain.SpecialDomainFileFinder" fileFinder = SpecialDomainFileFinder.new files = fileFinder.find files.each do |item| Utility.new.run(item, true) end

16 Scripting an Application
JRuby “A compatible Ruby interpreter written in 100% pure Java. Most builtin Ruby classes provided. Support for interacting with and defining java classes from within ruby” Almost complete Ruby Lacks some os apis and continuations

17 Scripting an Application
JRuby More expressive than Java… Very little syntax Good metaprogramming support Good for implementing Domain Specific Languages

18 Building a Swing GUI DMCG

19 Building a Swing GUI Goal
Add a simple GUI to a command-line application

20 Building a Swing GUI Demo

21 Building a Swing GUI def run(event):
selection = fileChooser.selectedFile if selection: Utility().run(selection, checkBox.selected) def browse(event): fileChooser.showOpenDialog(frame) frame = JFrame("Utility") frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE fileChooser = JFileChooser() runButton = JButton("Run", actionPerformed = run) frame.contentPane.add(runButton, BorderLayout.SOUTH) browseButton = JButton("Browse", actionPerformed = browse) frame.contentPane.add(browseButton, BorderLayout.NORTH) checkBox = JCheckBox("Overwrite") frame.contentPane.add(checkBox, BorderLayout.CENTER) frame.pack() frame.show()

22 Building a Swing GUI Jython
“implementation of the high-level, dynamic, object-oriented language Python written in 100% Pure Java, and seamlessly integrated with the Java platform.” Stable (!) since 2000

23 Building a Swing GUI Jython Python, like it or loathe it
Nice bindings to Java Cute listener syntax

24 Parsing Test Scripts

25 Parsing Test Scripts Goals To allow the customer to write tests
We would like an extensible embedded language for future growth “You don’t need a testing framework, you need tests”

26 Parsing Test Scripts openApp("author", "author")
selectWindow("Ziris Create Development Version") selectCollection("My Collection") openMedia("Test Playlist") checkDragMediaToTrack("Test Text 2", "Layer 1") checkDragPlaylistEvent("Layer 1", "Test Text", Edge.WEST, "West Resize Cursor") rightClick("Layer 1") selectPopupItem("Pin all events") checkNoDragPlaylistEvent("Layer 1", "Test Text", Edge.WEST, "Default Cursor")

27 Parsing Test Scripts private void runTest(String[] lines) throws Throwable { runLine("from com.example.test.CustomerTestStartupSupport import *", 0); runLine("from com.example.test.StaticCustomerTestSupport import *", 0); runLine("from com.example.test import Edge", 0); for (int i = 0; i < lines.length; i++) { try { runLine(lines[i], i + 1); } catch (Throwable x) { throw new Exception("Running line " + (i + 1) + " of " + testFile + " : " + lines[i], x); }

28 Parsing Test Scripts Generic Swing Bindings
public static void selectPopupItem(String text) { JPopupMenuOperator menu = JPopupMenuOperator.waitJPopupMenu(text); menu.pushMenu(text); } public static void click(String name) { new JComponentOperator(currentWindow, new NameComponentChooser(name)). clickMouse();

29 Parsing Test Scripts Domain Bindings
public static void openMedia(int row) { JTableOperator table = new JTableOperator(currentWindow); table.clickOnCell(row, 1, 2); } public static void clickPlaylistEvent(String trackName, String eventName) { Rectangle bounds = findTimelineEvent(trackName, eventName); ComponentOperator operator = new ComponentOperator(findPlaylist()); operator.clickMouse(bounds.x + 10, bounds.y + 10, 1);

30 Parsing Test Scripts Jython Clean syntax Easy Java bindings

31 Application Development

32 Application Development
Goal Take advantage of a dynamic language Use existing Java APIs

33 Application Development
class Person { @Property firstName @Property lastName @Property dob @Property friends } jim = new Person(firstName: "Jim", lastName: "Smith", dob: "27/09/1967") jim.friends = [ new Person(firstName: "Bob", lastName: "Duggan"), new Person(firstName: "Alan", lastName: "Nutley") ] writer = new StringWriter() buildPerson(jim, new MarkupBuilder(writer)) println writer.toString() def buildPerson(person, builder) { builder.person() { name(surname:person.lastName, 'christian-name':person.firstName) birthday(person.dob) friends() { for (each in person.friends) { friend("${each.lastName}, ${each.firstName}") <person> <name surname='Smith' christian-name='Jim' /> <birthday>27/09/1967</birthday> <friends> <friend>Duggan, Bob</friend> <friend>Nutley, Alan</friend> </friends> </person>

34 Application Development
Groovy “Groovy is an agile dynamic language for the Java 2 Platform that has many of the features that people like so much in languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.” JSR-241 Relaxed Java syntax crossed with Ruby

35 Application Development
Groovy Nice extensions to Java syntax Blocks make light work of many problems Compiles to Java bytecode Compiler also compiles Java Troubled at the time of writing

36 Other Applications Configuration files Scripting a GUI Web flow …
Config as other languages far better than java at expressing data Web flow - cocoon and javascript

37 Summary Why Scripting Runtime evaluation Syntax Special features
Dynamic typing Expressiveness

38 Summary How to choose a language Syntax Features Expressiveness
Interaction with the Java API Efficiency Benchmarks are available and show up to 2 orders of magnitude difference

39 Resources Languages Other www.beanshell.org jruby.sourceforge.net
groovy.codehaus.org tcljava.sourceforge.net Other jakarta.apache.org/bsf IBM alt.lang.jre - java-source.net/open-source/scripting-languages


Download ppt "Richard Care Duncan McGregor"

Similar presentations


Ads by Google