Python and Jelly: Scripting Power for Java and XML

Do More With Less (Lines of Code)

Gerald Bauer (Chairmain, CEO, CFO and CTO of Me, Myself & I, Inc.)
Java User Group (JUG) Austria Talk, February 2003

Table of Contents

Python and Jelly

Who is this guy?

Agenda - The Road Ahead

What is Python?

Python Logo

Python is a dynamic object-oriented scripting language created by Guido van Rossum in the early 90's to bridge the gap between shell and C programming. Python's elegant, easy to learn syntax, high-level data types, elaborate library, portability, and ease of extending and embedding in C/C++ all contribute to Python's popularity. Originally designed as an advanced scripting language, Python found new uses as a rapid application development language for web, database and GUI applications as well as for distributed systems and mobile code.

What is Jython?

Jython Logo

Jython is a 100 % Java version of the Python scripting language that allows you to compile Python scripts to Java byte code that runs on any Java Virtual Machine. Jython offers seamless and smoth Java intergration: from Python you can access all Java libraries, you can build applets or Java beans, you can derive from Java classes in Python and vice versa. Like Python, and unlike Java, you can use Jython interactively: just type in some Jython code at the prompt and see the story unfold immediately.

One Language Can't Do It All: Beyond Hairballs and Spaghetti Code

Scripting on the Rise. The Death of General Purpose Languages and Monolithic Applications.

Prefer the single-purpose languages below to general-purpose languages such as Java, C# or Shark.

Scripting vs. Systems (Hard-Core) Programming / Python vs. Java

Python does not replace Java. Python complements Java and doesn't compete head-on. Python is a scripting language. Java is a hard-core programming language (systems language).

First Impression - Servus Austria Example


public class ServusAustria
  public static void main( String args[] )
     System.out.println( "Servus Austria" );


print 'Servus Austria'

Second Impression - Servus Austria Swing Remix


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ServusAustria extends JFrame
   public ServusAustria( String title )
      super( title );

      addWindowListener( new WindowAdapter() {
         public void windowClosing( WindowEvent ev )
      } );

      JButton button = new JButton( "Servus Austria" ); 
      button.setPreferredSize( new Dimension( 200, 50 ) );
      button.addActionListener( new ActionListener() {
         public void actionPerformed( ActionEvent ev )
      } );

      getContentPane().add( button );     

   public void exit()
      System.exit( 0 );

   public static void main( String args[] )
      ServusAustria frame = new ServusAustria( "Python" );



import java.lang as lang
import javax.swing as swing

def exit( event ): 

frame = swing.JFrame( 'Python', windowClosing=exit )
button = swing.JButton( 'Servus Austria', preferredSize=(200,50), actionPerformed=exit )
frame.contentPane.add( button )

Python + XUL

import java.lang as lang

def exit( event ): 

<window title="Python" onclosing="exit()">
  <button label="Servus Austria" style="width: 200; height: 50;" onclick="exit()" />

Third Impression - Interactive Session

>>> 2 + 2
>>> _
>>> x = 4
>>> x * 2
>>> print 'Servus Austria'
Servus Austria

>>> import java.lang as lang
>>> import javax.swing as swing
>>> def exit( event ):
...   lang.System.exit(0)
>>> frame = swing.JFrame( 'Python', windowClosing=exit )
>>> frame
>>> button = swing.JButton( 'Servus Austria', preferredSize=(200,50), actionPerf
ormed=exit )
>>> button
ctedIcon=,selectedIcon=,text=Servus Austria,defaultCapable=true]
>>> frame.contentPane.add( button )
ctedIcon=,selectedIcon=,text=Servus Austria,defaultCapable=true]
>>> frame.pack()

Why Python? Top 10 Reasons

It's object-oriented. Ideal for scripting (glueing together) components build in Java, C# or C++; easy reuse through classes, polymorphism, operator overloading and even multiple inheritance.

It's free. Open-Source; no restrictions on copying or adding Python to your app (Apache-style license)

It's portable. Written in portable ANSI C, compiles and runs anywhere (Linux, Mactionosh, Amiga, OS/2, VMS, QNX and many more); scripts compiled to portable bytecode run on any Python runtime

It's powerful. Simplicity and ease of use of a scripting language (Dynamic typing; Built-in object types; Extensive Libraries (=Batteries Included); Automatic Memory Management) along with programming in-the-large contructs (Modules, Classes, Exceptions)

It's mixable. Extend Python with components in C, C++ or Java; embed Python into your app and call it from C, C++ or Java; Python supports COM on Windope

It's easy to use. Easy syntax (no curly braces, no semicolons, dynamic typing and so on); high-level built-in types (lists, maps, big numbers, and more)

It's easy to learn. Get started in days (or if you're already an experienced pro in hours); programming for everyone

It's interactive. Create, view or change objects at run-time on the fly; no compile and link steps; instand turnaround .

It's robust. Exception handling; Automatic Memory Management (=Garbage Collection); Dynamic Type Checking; No Unsafe Pointers

It's dynamic. "Late-Binding" Lanuage; Add Methods At Runtime; Call Methods Using Reflection

Who is Guido van Rossum?


Python History - Guido At Work

Jython History - More Modern-Day Heros

Python Goodies Missing In Java

Python Goodies: Syntactic Sugar for Lists


List list = new LinkedList();
list.add( new Integer( 1 ) );
list.add( new Integer( 2 ) );
list.add( new Integer( 3 ) );


list = [1, 2]
list.append( 3 )

Python Goodies: Syntactic Sugar for Maps


Map map = new HashMap();
map.put( "one", new Integer( 1 ) );
map.put( "two", new Integer( 2 ) );
map.put( "three", new Integer( 3 ) );

System.out.println( map.get( "one" ) );


map = { "one" : 1, "two" : 2, "three" : 3 }
print map[ "one" ]

Python Goodies: For Loop Shortcut


double sum = 0.0;
for( Iterator it=nums.iterator(); it.hasNext() )
  sum += ((Double);


sum = 0.0
for x in nums:
  sum = sum + x

Python Goodies: Named Method Parameters


JFrame frame = new JFrame( "Servus" );
frame.setSize( new Dimension( 200, 200 ) );
frame.setVisible( true );


frame = JFrame( "Servus", visible=1, size=(200,200) )

Python Goodies: String Formatting Shortcuts


double x = 10000.0 / 3.0;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits( 2 );
nf.setMaximumFractionDigits( 2 );
String s = nf.format( x );
for( int i = s.length(); i < 10; i++ )
    System.out.print( ' ' );
System.out.print( s );


x = 10000.0 / 3.0
print "%10.2f" % x

Python Goodies: Raw Strings And More

Java Python
"\\$\\d+,\\d+\\." r'\$\d+,\d+\.'
"\\s((::)(\\w+))\\b" r'\s((::)(\w+))\b'
"c:\\sandbox\\doc\\talk" r'c:\sandbox\doc\talk'
"Christina says, \"Python Rocks\"" 'Christina says, "Python Rocks"'

Python Data Types

Basic Data Types

Java Python Comments
boolean Python has no boolean type yet. Python uses 1 for true, and 0 or any empty string, list or map as false.
char string Python uses a string of length 1 as a character.
byte, short, int int
long long Python longs are unbound (like Java's BigInteger).
float, double float Python floats use the same precision as Java doubles.
complex Python has built-in support for complex numbers e.g. 3.5+1.2j or 2.0J

More Data Types

Java Python Comments
java.lang.String string
java.util.List list Python has built-in support for lists e.g. [1, 2]
java.util.Map dictonary Python has built-in support for maps e.g. { "one" : 1, "two" : 2 }

Python Logical And Arithmetic Operators

Logical Operators. Python tends to use English words for its logical operators instead of symbols.

Java Python Comments
&& and
|| or
! not
== is Test for identical object identity.
equals() == Test for same value.
x < y && y < z x < y < z Python supports chained comparisons.

Arithmetic Operators. Python use the same operators as Java with some exceptions:


0 < x <= 5
1 << 16, x & 0xff, x|1, ~x, x^y 

Python Control Flow - No Curly Braces, No Semicolons

if Conditionals

if( a > b )
  return 1;
else if( a < b )
  return -1;
  return 0;
if a > b:
  return 1
elif a < b:
  return -1
  return 0

for Loop

for( int i=0; i < 10; i++ )
   System.out.println( i );
for i in range(10):
   print i
for( Iterator it=lines.iterator(); it.hasNext(); )
   System.out.println( (String) );
for line in lines:
   print line

while Loop

int i=0;
while( i < 5 )
   System.out.println( i );
while i < 5:
   print i
   i = i+1

Exception Handling

  divide_by_zero( 2 );
catch( ArithmeticException ex )
  System.out.println( "Can't divide by zero: " 
       + ex.getMessage() );
  divide_by_zero( 2 )
except ZeroDivisonError, message:
  print "Can't divide by zero: ", message
FileInputStream in = 
   new FileInputStream( new File( name ) );
  process_file( in );
file = open( name )
  process_file( file )                    
throw new IndexOutOfBoundsException();
raise IndexError

Python Class Example: Servus Applet


import java.applet.*;

public class Servus extends Applet
   public void paint( Graphics g )
       g.drawString( "Servus Applet", 10, 10 );


from java.applet import Applet

class Servus( Applet ):
    def paint( self, g ):
       g.drawString( "Servus Applet" )

Python Class Example: Servus Servlet


import javax.servlet.*;

public class Hello extends HttpServlet
   public void doGet( HttpServletRequest request,
                      HttpServletResponse response )
      response.setContentType( "text/html" );
      PrintWriter out = response.getWriter();
        + "<head><title>Servus Servlet</title></head>"
        + "<body>Servus Servlet at " + new Date() + "</body>"
        + "</html>"


import java, javax, sys

class hello( javax.servlet.http.HttpServlet ):
   def doGet( self, request, response ):
      response.contentType = "text/html"
      out = response.outputStream
      print >> out, """<html>
<head><title>Servus Servlet</title></head>
<body>Servus Servlet at %s</body>
""" % java.util.Date()

Python Class Example: Dynamic Properties/Getters

Python Class

class DynProps:

   def __init__( self, **args ):
       self.props = args

   def __getattr__( self, attribute ):
       return self.props[ attribute ]

Usage Example
>>> capital = DynProps( austria="vienna", canada="ottawa" )
>>> print capital.austria
>>> print capital.canada
>>> capital.props[ "peru" ] = "lima"
>>> print capital.peru

Embedding Python in Your App

import org.python.util.PythonInterpreter;
import org.python.core.*;

public class SimpleEmbedded
  public static void main( String args[] ) throws PyException
    // create a phyton interpreter
    PythonInterpreter interp = new PythonInterpreter();
    // execute a statement 
    interp.exec( "import sys" );
    interp.exec( "print sys" );

    // create a int variable n with the value 7
    interp.set( "n", new PyInteger( 7 ));
    // print value of n
    interp.exec( "print n" );

    // assign value to new variable x
    interp.exec( "x = 2+2" );

    PyObject x= interp.get( "x" );

    // print value of x
    System.out.println( "x: " + x );

Real-World Example: Adding Python Macros to Notepad

Python. Macro Doubles Text in Notepad (e.g. Hello becomes Hello Hello)

  allText = textEditor.getText()
  allText = allText + allText
  textEditor.setText( allText )

Java. Code For Running Python Macro.

PythonInterpreter interp = new PythonInterpreter();
interp.exec( "from javax.swing.text import JTextComponent" );
interp.set( "textEditor", getEditor() );

for( Iterator it=scriptLines.iterator(); it.hasNext(); )
  String line = (String);
  System.out.println( "[Script] " + line );
  interp.exec( line );

Compiling Python Using jythonc

jythonc lets you compile (=freeze) Python scripts to stand-alone Java bytecode (that is, .class files).

Why? You can use Python scripts compiled to plain-vanilla Java classes as applets, Java beans and so on and distribute your frozen Python scripts in jars.

Usage Examples

Compile all applet Python script examples and pack them up in appletdemo.jar

jythonc --core --deep --jar appletdemo.jar *.py

Create a sekeleton class to allow usage of a Python class in a Java GUI (as a java.awt.Component)


Compiler Options Sampling

Option Description
--package package Put all compiled code into the named Java package.
--addpackages packages Include Java dependencies from this list of packages.
--core Include the core Python libraries.
--all Include all of the Python libraries (that is, everything in core plus compiler and parser).
--bean jar Compile into jar, include manifest for bean.
--workdir directory Specify working directory for compiler (default is ./jpywork)
--compileropts options Options passed directly to the Java compiler. Alternatively, you can set the property python.jpythonc.compileropts in the registry.

Python At Work

Pythonistas - Who's Using Python?

Some Statistics

Alternative Scripting Languages in 100 % Java

Tcl. Jacl (Java Command Language) is a free, open-source Tcl 8.x scripting interpreter in 100 % Java initially created by Sun Labs in 1998 and now headed Mo DeJong . Jon Ousterhout created Tcl in the late 80's as an embeddable command language for interactive Unix tools. More Info at

JavacScript. Rhino is a free, open-source Mozilla-licensed Javascript engine in 100 % Java. Netscape started work on Rhino in Fall 1997 for the now defunct "Javagator". More Info at

Dynamic Java / Java Lite. BeanShell is a free, open-source, small (~175k) scripting interpreter in 100 % Java that runs standard Java statements and expressions and also sports a dynamically typed, casting optional Java lite syntax. Headed by Patrick Niemeyer. More Info at

Ruby. JRuby is a free, open-source Ruby interpreter in 100 % Java that you can easily add to your app to script any Java class. More Info at

Rexx. NetRexx is a 100 % Java interpreter for a Rexx dialect created by Mike Cowlishaw, the Rexx inventor. Mike Cowlishaw created Rexx in 1979 for simplifying programming tasks on IBM's CMS timesharing system. More Info at

Smalltalk. Bistro is a free, open-source variant of Smalltalk in 100 % Java than runs on any Java Virtual Machine. Bistro mixes the best of Smalltalk and Java. More Info at

Scheme. Skij is small Scheme interpreter in 100 % Java with extension to interactively create, view or change any Java object at run-time. (Scheme is a modern variant of Lisp.) More Info at

And Many More (Lua, Basic, and so on and on). See Robert Tolksdorf's list of programming languages for the Java Virtual Machine for more.

Bonus: Beanshell (bsh) Scripting Example

foo = "Foo";
four = (2 + 2)*2/2;
// print is a built-in bean shell (bsh) command
print( foo + " = " + four );  

// do a loop
for( i=0; i<5; i++ )
  print( i );

// popup a frame with a button
button = new JButton( "Hello" );
frame = new JFrame( "Bean Shell" );
frame.getContentPane().add( button );

// scripted method
add( a, b ) { return a + b; }

Scripting Languages Comparison Chart

Feature Python Tcl Perl Java Script Ruby Visual Basic
Speed of use Rapid development Yes Yes Yes Yes Yes Yes
Flexible, rapid evolution Yes Yes Yes Yes Yes Yes
Great regular expressions Yes Yes Yes Yes
Breadth of functionality Easily extensible Yes Yes Yes Yes
Embeddable Yes Yes Yes
Easy GUIs Yes Yes Yes Yes
Internet and Web-enabled Yes Yes Yes Yes Yes Yes
Enterprise usage Cross platform Yes Yes Yes Yes Yes
Internationalization support Yes Yes Yes Yes
Thread safe Yes Yes Yes
Database access Yes Yes Yes Yes Yes Yes


Python vs. Java Script vs. Basic

Python supports programming in-the-large

Python Benefits Cheat Sheet

Feature Benefits
No compile or link steps Rapid development cycle turnaround
No type declarations Simpler, shorter, and more flexible programs
Automatic memory management Garbage collection avoids bookkeeping code
High-level datatypes and operations Fast development using built-in object types
Object-oriented programming Code reuse, C++, Java, and COM integration
Embedding and extending in C Optimization, customization, system "glue"
Classes, modules, exceptions Modular "programming-in-the-large" support
A simple, clear syntax and design Readability, maintainability, ease of learning
Dynamic loading of C modules Simplified extensions, smaller binary files
Dynamic reloading of Python modules Modify programs without stopping
Universal "first-class" object model Fewer restrictions and special-case rules
Runtime program construction Handles unforeseen needs, end-user coding
Interactive, dynamic nature Incremental development and testing
Access to interpreter information Metaprogramming, introspective objects
Wide interpreter portability Cross-platform programming without ports
Compilation to portable bytecode Execution speed, protecting source code
Standard portable GUI toolkit Tkinter scripts run on X, Windows, and Macs
Standard Internet protocol support Easy access to email, FTP, HTTP, CGI, etc.
Standard portable system calls Platform-neutral system scripting
Built-in and third-party libraries Vast collection of precoded software components
True open-source software May be freely embedded and shipped

Source: Programming Python, Mark Lutz

What is Jelly?

Jelly Logo

First Impression: Servus Jelly

Jelly Script

<j:jelly xmlns:j="jelly:core">

    <j:when test="${user.locale}=='de_AT'">
        Servus ${}
        Hello ${}


Second Impression: Jelly Tag Plug-Ins For Web Services

Jelly Script

<babelfish:translate from="en" to="fr">
    Welcome ${} to Jelly

Third Impression: Creating UIs Using XUL


  <menubar id="MAIN">
    <menu label="Bookmarks">
       <menuitem label="Luxor XUL Home Page"  href="" />
       <menuitem label="Mozilla XUL Home Page"  href="" />
       <menuitem label="Mozilla XUL Reference"  href="" />
       <menuitem label="XUL Tutorial"  href="" />

Jelly Script

<j:jelly xmlns:j="jelly:core"  xmlns:sql="jelly:sql">

        password="" />

  <sql:query var="results">

    <menubar id="MAIN">
      <menu label="Bookmarks">

        <j:forEach items="${results.rowsByIndex}" var="row">
           <menuitem label="${row[0]}" href="${row[1]}" />



Jelly Tag Library Sampling

Library Description
core Core tags from the JSTL (Java Server Pages Standard Tag Library)
xml XML tags from the JSTL
sql SQL tags from the JSTL
ant A tag library that lets you use Ant tasks within Jelly
log A tag library that lets you create logging infos for log4j, Java 1.4 java.util.logging and other logging toolkits
http A tag library that lets you perform GET, POST and other HTTP actions
html A tag library that lets you parse HTML and process it XML-style using XPath expressions and more
junit A tag library that lets you write or fire off unit tests

and many more

Jelly At Work - Propelled By Jelly

Projects Description
Maven Project Management tool built on top of Ant
Latka Functional (end-to-end) testing tool in Java using an XML syntax to define a series of HTTP requests and set of checks for verify error-free processing
Luxor Coming Soon; XUL toolkit in Java; lets you build UIs using XML

Python Books

Jython / Python for Java

Jython Essentials by Samuele Pedroni and Noel Rappin, 304 pages, O'Reilly, ISBN: 0596002475, (March 2002)
Python Programming with the Java Class Libraries by Richard Hightower, 640 pages, Addison-Wesley, ISBN: 0201616165, (June 2002)

Python General

Practical Python by Magnus Lie Hetland, 648 pages, Apress, ISBN: 1590590066, (August 2002)
Core Python by Wesley J. Chun, 816 pages, Prentice Hall, ISBN: 0130260363, (December 2000)
Learning Python by Mark Lutz and David Ascher, 366 pages, O'Reilly, ISBN: 1565924649, (May 1999)
Python Cookbook by Alex Martell and David Ascher, 606 pages, O'Reilly, ISBN: 0596001673, (July 2002)
Python in a Nutshell by Alex Martelli, 600 pages, O'Reilly, ISBN: 0596001886, (March 2003)

and many more

Python Links

Official Python Site

Python Tutorial

Python FAQ

Python Language Reference

Python Library Reference

Official Jython Site


Tips for Scripting Java with Jython
by Noel Rappin, O'Reilly Network, March 2002

Jython Typs for Python Programmers
by Noel Rappin, O'Reilly Network, April 2002

Introduction to Jython
by Samuele Pedroni and Noel Rappin, Sample Chapter 1 from Jython Essentials Book, O'Reilly, 2002

JPython: The Felicitous Union of Python and Java
by Mark Lutz and David Ascher, Sample Chapter 10 from Learning Python Book, O'Reilly, 1999


Daily Python URL


Guido Van Rossum Talks
Introduction to Python @ Linux World 2002, State of the Python Union @ OSCON 2002, And Many More

Scripting for Java: Paradigms for the 21st Century
by Dana Moore and Bill Wright (BBN Technologies), JavaOne 2002, 50 slides, includes lots of real-world examples such as

More Python Links

O'Reilly Network Python Dev Center

Scripting: Higher Level Programming for the 21st Century

Paper by John K. Ousterhout, Father of Tcl/Tk, published in IEEE Computer in March 1998

Scripting Is On The Rise; Different Tools for Different Tasks

Scripting languages and system programming languages are complementary, and most major computing platforms since the 60's have provided both kinds of languages. The languages are typically used together in component frameworks, where components are created with system programming languages and glued together with scripting languages. However, serveral recent trends, such as faster machines, better scripting languages, the increasing importance of graphical user interfaces and component architectures, and the growth of the Internet, have greatly increased the applicability of scripting languages.

Full story at

That's it - The Future Just Happened

Visit for more info