Transcript
Page 1: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Using Jython to Speed Development

Don Coleman, Aaron Mulder, Tom PurcellChariot Solutions

Page 2: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Goal

Use Jython to make software development easier.

Page 3: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Who are we?

• We are J2EE Architects

• We write commercial Java software

• We use Jython as a tool for developing and testing Java software

Page 4: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Presentation Agenda

• About Jython─ Language Overview─ Using the Interactive Interpreter

• Server Side Jython─ Accessing Databases─ Accessing EJBs─ PyServlet─ Embedded Jython

• Advanced Jython

Page 5: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

About Jython

Page 6: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

What is Jython?

• Jython is an implementation of the Python language that runs on the JVM

• Jython excels at scripting and is excellent for exploring and debugging code

• Jython's interpreted nature allows you to work with Java without a compiler and manipulate live objects on the fly

• Jython gives you the power of Java + Python

Page 7: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

What is Python?

Python is a mature language that ...

• has clear syntax

• is easy to learn

• is easy to use

• is object oriented

• is powerful

Page 8: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Installing Jython

• Install JDK 1.4

• Download Jython from http://www.jython.org

• cd to the directory with jython-21.class

• Start the installer$ java -cp . jython-21

Page 9: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Sample Code

class Greeter: def sayHello(self, name = None): if name == None: print "Hello" else: print "Hello, %s" % name

def sayGoodbye(self): print "Goodbye"

Page 10: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Why would you use Jython?

• Live interaction with Java for experimentation

• Testing and debugging

• Write quick scripts without needing to compile

• Quick runtime tests─ BigDecimal("0").equals(BigDecimal("0.00"))

• Inspecting private variables or methods

• Rapid development

• Embedded scripting

Page 11: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Interactive Command Line

$ jython

>>> print “Hello world!”

Hello world!

>>>

Use CTRL+D to exit on UNIX

Use CTRL+Z to exit on Windows

Page 12: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Language Overview

Page 13: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Language Overview

• supports modules, classes and methods

• dynamic typing (don't declare variable types)

• familiar control structures (for, if, while ...)

• uses # for comments

• built-in collection types (lists, dictionaries)

• indentation for code blocks { not braces }

• no semicolons to indicate end of line;

• omits “new” keyword (“o = Object()”)

Page 14: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Variable Assignment and Printing

>>> s = 17

>>> print s

17

>>> s = “JavaOne”

>>> print s

JavaOne

>>>

Page 15: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Creating a method

>>> def add(a,b):

... return a + b

...

>>> add(4,5)

9

>>>

Page 16: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Creating a class

>>> class Calc:

... def add(self, a, b)

... return a + b

...

>>> c = Calc()

>>> c.add(4,5)

9

>>>

Page 17: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Lists

Lists are like arrays and ArrayLists>>> l = []

>>> l.append(1)

>>> l.append('string')

>>> l.append(12.3)

>>> print l

[1, 'string', 12.3]

>>> len(l)

3

>>> l[2]

12.3

Page 18: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Dictionaries

Dictionaries are similar to HashMaps>>> dict = {}

>>> dict['color'] = 'red'

>>> dict[17] = 'seventeen'

>>> dict

{'color':'red', 17:'seventeen'}

>>> dict['color']

'red'

>>>

Page 19: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Loops / Iterators

>>> l = ['spam','bacon','eggs']

>>> for item in l:

... print item

...

spam

bacon

eggs

>>>

Page 20: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Using Java in Jython

>>> from java.lang import *

>>> System.getProperty(“user.home”)

'/home/dcoleman'

>>> from java.math import BigDecimal

>>> b = BigDecimal(“17”)

>>> b

17

>>>

Page 21: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Jython Modules

• A module is a collection of jython code

• May contain, code, methods, classes

• Import modulesimport modulefrom module import object

• Run modules like a script─ $ jython module.py

Page 22: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Inheriting from Java

from javax.swing import *

from java.awt import Color

class GreenPanel(JPanel):─ def __init__(self):─ self.background = Color.green─ def toString(self):─ return "GreenPanel"

if __name__ == "__main__":─ f = Jframe("Green", size=(200,200))─ f.getContentPane().add(GreenPanel())─ f.show()

Page 23: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Server-Side Jython

Page 24: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Database Access

• Can use standard JDBC calls in Jython

• There's a more “pythonic” DB API called zxJDBC, included with Jython 2.1

• Use whichever you're comfortable with, though zxJDBC is a little more compact

Page 25: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

JDBC Example

from java.lang import *from java.sql import *

Class.forName("org.hsqldb.jdbcDriver")conn = DriverManager.getConnection( "jdbc:hsqldb:demo",

"sa", "")

stmt = conn.createStatement()rs = stmt.executeQuery("SELECT code, desc FROM states")while rs.next(): print rs.getString("code"),rs.getString("desc")

rs.close()stmt.close()conn.close()

Page 26: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

zxJDBC Example

from com.ziclix.python.sql import zxJDBCfrom pprint import pprint

conn = zxJDBC.connect("jdbc:hsqldb:demo", "sa", "", "org.hsqldb.jdbcDriver")

cursor = conn.cursor()cursor.execute("SELECT code, desc FROM states")data = cursor.fetchall()cursor.close()conn.close()pprint(data)

Page 27: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

A Jython EJB Client

• Set up the classpath, jndi.properties like normal, then...

>>> from javax.naming import *>>> c = InitialContext()>>> home = c.lookup("Demo")>>> demo = home.create()>>> demo.setFoo("Jython")>>> demo.getFoo()'Jython'>>> demo.getDate()Tues Jun 10 11:45:17 PST 2003

Page 28: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

PyServlet

• Jython includes a servlet that executes *.py scripts

• Similar to the way *.jsp files are executed

• Just need to map the servlet in the web.xml file

• Can provide “python.home” and “python.path” init-params to customize the Jython libs and configuration

Page 29: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Mapping PyServlet

<web-app> <servlet> <servlet-name>PyServlet</servlet-name> <servlet-class> org.python.util.PyServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping></web-app>

Page 30: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Embedded Jython

• Can execute Jython within a servlet or EJB container

• Jython can load resource references, local EJB references, etc. like any other component

• Can set up a client to interact with the Jython in the server, just like the normal interpreter

• Probably need to customize the environment to make additional JARs visible to Jython

Page 31: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Demo

Page 32: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Advanced Jython

Page 33: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

PyUnit

• PyUnit is based on the JUnit Framework

• Test are generally shorter with PyUnit

• Ability to access private methods

• Ant integration (using JUnit task)

Page 34: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

PyUnit

import unittest

class DemoTestCase(unittest.TestCase):

def testBar(self): self.assertEquals(5, len("hello"))

if __name__ == '__main__': unittest.main()

Page 35: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Accessing non-public code

Edit the Jython registry file

The registry is a text file in the Jython installation directory

# Setting this to false will allow Jython to provide access to

# non-public fields, methods, and constructors of Java objects.

python.security.respectJavaAccessibility = false

Page 36: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Compiling Jython to Java

• allows Jython code to run in Java

• jythonc is the compiler.py > .java > .class

• jython.jar must be in the classpath

• special @sig comment to declare the method's signature in Java

Page 37: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Jython Standard Libraries

• Jython includes a rich set of built-in libraries

• You can run most Python code except where - modules implemented in C - modules that target a particular platform - modules where JVM lacks functionality

Page 38: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Code Completion

Jython Console with Code Completion

http://don.freeshell.org/jython

Page 39: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Conclusion

Page 40: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069

Q&A

Page 41: Using Jython to Speed Development

| JavaOne 2003 | BOF-10691

Links...

•This presentation is available from http://www.chariotsolutions.com/presentations.html

•Jython www.jython.org

•Python www.python.org

•Jython Console http://don.freeshell.org/jython

•Jython Essentials by Samuele Pedroni & Noel Rappin http://www.oreilly.com/catalog/jythoness/

•JEdit http://www.jedit.com

•Eclipse Python Integration http://www.python.org/cgi-bin/moinmoin/EclipsePythonIntegration

Page 42: Using Jython to Speed Development

| JavaOne 2003 | BOF-1069


Top Related