Object-Oriented Programming with Java Lecture Notes

1 May 2008 • Scripting Java


Outline

  • Review and basics.

  • New JVM-based languages.

    • Groovy, pnuts, BeanShell

    • JavaFX

  • Existing languages, JVM-adapted.

nested dolls

Simple Interaction

import java.util.Scanner;

class ip1 {
  public static void
  main(String args[]) {
    final Scanner in = new Scanner(System.in);

    while (true) {
      System.out.print("? ");
      System.out.flush();
      if (!in.hasNextLine())
        break;
      System.out.println(
        "You typed \"" + in.nextLine() + "\".\n");
      }
    }
  }

Interaction Example

$ javac ip1.java

$ java ip1
? hello
You typed "hello".

? good bye
You typed "good bye".

? ^D

$ 

More Interesting Interaction

Calculating

import java.util.Scanner;

class ip1 {
  public static void
  main(String args[]) {
    final Scanner in = new Scanner(System.in);

    while (true) {
      System.out.print("? ");
      System.out.flush();
      if (!in.hasNextLine())
        break;
      System.out.println(eval(in.nextLine()));
      }
    }
  }

Evaluating

private static double
eval(String line) {

  final expr e = parse(line);

  if (e.oper.equals("+"))
    return e.arg1 + e.arg2;
  if (e.oper.equals("-"))
    return e.arg1 + e.arg2;
  if (e.oper.equals("*"))
    return e.arg1 + e.arg2;

  return e.arg1/e.arg2;
  }

Parsing

static private expr
parse(String line) {

  final Pattern exprPattern = Pattern.compile(
    "\\p{Digit}+\\p{Space}*[-+/*]\\p{Space}*\\p{Digit}+")
  final Matcher matches = 
    exprPattern.matcher(line.trim())
  final MatchResult result = 
    matches.toMatchResult()

  return new expr(
    Double.parseDouble(result.group(1)), 
    result.group(2), 
    Double.parseDouble(result.group(3)));
  }

Calculating Example

$ javac ip2.java

$ java ip2
? 1 + 1
2.0000

? 1/2
0.5

? ^D

$ 

Storage

Evaluation With Storage

private static double
eval(String line)

  final expr e = parse(line)
  final double 
    a1 = lookUp(e.arg1)
    a2 = lookUp(e.arg2)

  if e.oper.equals("+")
    return a1 + a2
  if e.oper.equals("-")
    return a1 + a2
  if e.oper.equals("*")
    return a1 + a2
  if e.oper.equals("/")
    return a1/a2

  storage.put(e.arg1, a2)
  return a1/a2

Storage Look-Up

private static double
lookUp(String var) {

  try { return Double.parseDouble(var); }
  catch (Exception e) { }

  return storage.containsKey(var)
    ? Double.NaN
    : storage.get(var).asDouble()
  }

Storing Example

$ javac ip3.java

$ java ip3
? a = 1
1.0000

? b = 1
1.0000

? a + b
2.0000

? ^D

$ 

Interpreters

Scripting Languages

BeanShell

On-Demand Variables

Variables Example

Dynamic Environment

BeanShell Example

Extended Syntax

Extended-Syntax Example

$ java -classpath bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % map = new java.util.Hashtable();
bsh % print(map.get("one"));
null
bsh % map.put("one", 1);
bsh % print(map.get("one"));
1
bsh % print(map{"two"});
null
bsh % map{"two"} = 2;
bsh % print(map{"two"});
2
bsh % button = new JButton();
bsh % print(button.getLabel());

bsh % button.setLabel("Click me!");
bsh % print(button{"label"});
Click me!
bsh % button.label = "Press to play";
bsh % print(button.label);
Press to play
bsh % 

Interactive Run-Time

Run-Time Discovery Example

$ java -classpath bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % 
bsh % add(a, b) { return a + b; }
bsh % 
bsh % print(add(1, 2));
3
bsh % print(add("hello ", "world!"));
hello world!
bsh % 
bsh % print(add("hello ", 1));
hello 1
bsh % 

Static-Typing Example

bsh % 
bsh % int add(int a, int b) { return a + b; }
bsh % 
bsh % bsh % print(add(1, 2));
3
bsh % print(add("1", "2"));
// Error: EvalError: Command not found: 
   add( java.lang.String, java.lang.String ) : 
   at Line: 3 : in file: <unknown file> : 
   add ( "1" , "2" ) 
bsh % 

The Environment as this

This-Environment Example

$ java -classpath bsh-2.0b4.jar bsh.Interpreter
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % button = new JButton("Click me!");
bsh % frame = new JFrame();
bsh % frame.getContentPane().add(button);
bsh % frame.pack();
bsh % frame.setVisible(true);
bsh %
bsh % actionPerformed(e) { print("Thanks!"); }
bsh %
bsh % button.addActionListener(this);
bsh % Thanks!
Thanks!
Thanks!
bsh %

BeanShell Example.

dragText() {
  f = new Frame("Drag in the box");
  f.setFont(new Font("Serif", Font.BOLD, 24));
  f.setSize(300, 300);
  f.show();

  gc = f.getGraphics();
  gc.setColor(Color.cyan);

  mouseDragged(e) {
    gc.drawString("Drag Me!", e.getX(), e.getY());
    }
  mouseMoved(e) { }

  f.addMouseMotionListener(this);
  }

BeanShell Example..

dragText() {
  f = new Frame("Drag in the box");
  f.setFont(new Font("Serif", Font.BOLD, 24));
  f.setSize(300, 300);
  f.show();

  gc = f.getGraphics();
  gc.setColor(Color.cyan);

  mouseDragged(e) {
    gc.drawString("Drag Me!", e.getX(), e.getY());
    }
  mouseMoved(e) { }

  f.addMouseMotionListener(this);
  }

Using Interpreters

Embedding Example

$ CLASSPATH=/usr/local/packages/beanshell-2.0b4/bsh-2.0b4.jar:.

$ cat emb.java
import bsh.Interpreter;
import javax.swing.*;

class t {
  public static void main(String args[]) throws bsh.EvalError {
    final Interpreter i = new Interpreter();

    i.set("button", new JButton());
    i.set("frame", new JFrame());

    ((JFrame) i.get("frame")).setTitle("Hi!");
    i.eval("button.label = \"Click me!\"");
    System.out.println(i.get("button.label"));
    }
  }

$ javac emb.java

$ java t
Click me!

$ 

Scripting Java

Java Scripting Support

The Scripting API

Script Engines

Script-Engine Example

$ cat se.java
import javax.script.ScriptException;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.swing.JButton;

class se {
  public static void main(String args[]) 
  throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    engine.put("button", new JButton("Click Me!"));
    engine.eval("print(button.getLabel() + '\\n')");
    }
  }
$ javac se.java

$ java se
Click Me!

$ 

Nesting Illustrated

JavaScript in Java

Credits


This page last modified on 7 April 2008.

Creative
    Commons License