Welcome!

PowerBuilder Authors: Dan Joe Barry, Ian Thain, Yakov Werde, Paul Slater, Bruce Armstrong

Related Topics: PowerBuilder

PowerBuilder: Article

Is EAServer a Language-Neutral Platfom?

Is EAServer a Language-Neutral Platfom?

In Part 1 (PBDJ, Vol. 9, issue 11), we discussed a lot of different languages that could be compiled to Java bytecode. This month I'll provide a real example by using Jython in EAServer.

Introduction to Jython
Botanists know that if you cross-pollinate two different strains of plants, you create a hybrid, a new plant that exhibits the strengths of both its parents. Jython is a programming hybrid, an implementation of the Python scripting language written in 100% Pure Java that runs under any compliant Java Virtual Machine (JVM). Using Jython, you can write Python programs that interact with any Java code. The Jython interpreter supports a number of shortcuts that make using Java libraries as easy as using your own Python code.

Jython combines a scripting language of unparalleled ease of development with an operating environment for which many powerful tools have been written. The combination can be immensely valuable for programmers, enabling you to cut development time significantly while still retaining the ability to use existing Java tools, such as applets and servlets. Just as Python was originally conceived as the glue to bind together other programs, Jython helps you get the most out of Java-based tools. In particular, Jython excels at simplifying the use of complex Java programming libraries and APIs, such as the Swing graphical interface toolkit or the JDBC database connectivity API.

What's Jython Good For?
As demonstrated in Part 1, it helps to think of the JVM as a platform. We have seen that a number of different languages run under a JVM in one way or another, but for most people so far, the JVM and Java programming have been effectively synonymous. Uses of Jython can be split into two areas: things you might want to do within a JVM for which Java is not a great choice, and things you might want to do where Java seems like a strong choice.

In the first category are the kinds of programs at which scripting languages have traditionally excelled. Programs that are small utility tools, one-time-only scripts, or rapid development prototypes have all been in the purview of scripting languages such as Python. The Java language, for all its usability benefits over, say C++, was not designed for that kind of rapid development or scripting work. Jython makes that kind of programming easier on a JVM, giving you scripting language flexibility where it did not exist previously. This also suggests a place for Jython as an adjunct to existing Java programs - performing cleanup and maintenance functions, for example.

Web programming is another area in the first category. You will agree when I say that Java has made tremendous strides as a server-side Web application tool over the last few years, primarily due to the creation of good industrial-strength server environments like EAServer. Writing the actual Web application in Java, however, is still a chore, especially when maximum response to changed requirements is needed.

Outside the Java world, many (if not most) Web applications are still written in dynamic scripting-style languages such as ColdFusion, Perl, or Python. It's no accident that template languages or other scripting languages written specifically for Java Web applications have proliferated. Jython as a Web language gives you a scripting language that is more powerful and established than other Java Web tools, but still gives you full access to the Java servlet libraries.

Another area that Java doesn't really cover is the use of a scripting language by your Java program. The Jython interpreter can be embedded inside any Java program, allowing you full access to Jython for scripting inside the program. One use of this feature common in Python is to have your preference or properties file be a "live" Jython script, saving you the trouble of having to convert a properties or XML file to actual functionality.

Jython is likely to improve your productivity for a great number of project types that are currently performed in Java. In the following section, I'll start to explore the reasons why I believe this to be true. I'll also suggest some reasons why Jython might be a good addition to your toolkit even if you are already a CPython programmer.

For Java Programmers
If you're already programming in Java, you're probably wondering why you need another language to run under the JVM. Doesn't Java work just fine? Sure, Java is great, but by using Jython instead of Java, you'll probably find that the number of lines of code in your program has dropped by as much as 50%. (You may already have noticed that when you've written a PowerBuilder component, it's the same there.) Many programming studies suggest that shorter programs have fewer bugs. In addition, programmer productivity tends to be about the same for any number of lines of code even if, as in Jython or PowerBuilder, each line of code tends to do more than it might in another language. In other words, an expert Jython programmer will likely produce programs faster and with fewer bugs than an expert Java programmer (this is why we, as PowerBuilder developers or consultants, still earn a lot of money).

I don't mean to attack Java. Like every programming language, it's a tool that has its uses and I do like it. However, it's hard to use Java for any length of time and not realize that it's an exceptionally verbose and often inflexible language. After you've written lines of code like the following, which includes a typecast that's only there to keep the compiler happy:

MyClass instance = (MyClass)list.get(2);

it's easier to write what we already know from PowerBuilder coding:

instance = list[2]

The difference between the Java and Python code emphasizes one of the main sources of the productivity advantage of Jython - dynamic typing. In Python, you don't need to declare variables for use, nor do you need to tell the interpreter what the expected data type of a variable is. It's important to note that despite being dynamically typed, Python also has strong typing. This means that a line of code such as "1" + 1 is an error in Python (unlike many other scripting languages that would quietly allow this).

If you've never programmed in a dynamic language, the idea of not declaring variables or types may make you a little nervous. After all, isn't the point of static typing to allow the compiler to catch errors before the program runs? It's certainly true that static typing can do that.

The Benefits of Jython
It is possible to use a different language in EAServer; however, you should also be able to improve your productivity for a number of EAServer projects in which you may be using PowerBuilder and Java components. Here are some reasons why Jython might be a good addition to your toolkit.

Extensive Included Library
Jython includes most of the Python standard library. Although some of that functionality is duplicated in the Java standard library, much of it is not. Examples include regular expression support (finally coming in JDK 1.4), parsers, network support, and unit test frameworks.

All this additional functionality comes without sacrificing integration with existing Java code. Jython code can be compiled to Java .class or .jar files, and these files can be distributed like any other compiled Java files - the fact that the code was written in Jython can be made completely transparent to the end user.

Extended Reach
Using Jython, you can deploy a Python language program in arenas that are simply not possible using CPython. The most notable examples of this are Web-based - namely, the creation of applets that will be accepted by mainstream browsers, and the creation of servlets that can be run by a Java servlet or J2EE servers.

Ease of Distribution
Jython makes it easy to distribute your program as a cross-platform binary in .jar format. Although there are binary tools for CPython on different platforms, there is no similar cross-platform tool for CPython.

Tools and Libraries
This is the biggest advantage of Jython. Although the Python standard library and available third-party tools are varied and wonderful, Java has benefited from a much larger pool of available tools, particularly enterprise-level. The Swing GUI toolkit is more complete and more cross-platform than any GUI toolkit available for CPython, and is arguably easier to use. Database tools are much more widely available and standardized in the Java world. There is a large quantity of high-level tools for XML data. All these libraries and tools can be used from Jython at least as easily as other Java tools would be able to use them.

The Speed Question
Everybody asks it at some point. Whenever you try to sell somebody on using a high-level scripting-style language, the question inevitably comes up: "Isn't it slow?" As a long-time programmer of scripting languages and other languages that have been branded as slow (including Java), I have a variety of reasons why raw benchmark speed is less important than it might be when choosing a programming tool. In fact, I'll also argue that for most of you, most of the time, the speed difference is not going to hurt at all.

What is the exact magnitude of the speed difference? It's notoriously difficult to get good information about performance across languages. Sometimes, the person compiling the numbers has an axe to grind and has chosen a task that favors one language. More often, the person compiling the examples has just done a better job optimizing one version over the other. So, any cross-language speed comparison needs to be taken with a grain of salt.

That said, my experience in running identical code under both Python 2.1 and Jython 2.1a3 (using Sun's JDK 1.3) suggests that CPython takes 75% of the time that Jython does. Jython is about 1-10 times slower than equivalent Java code, although admittedly useful hard numbers on this are difficult to come by because the exact speed difference strongly depends on the nature of your application. Programs that spend a lot of time doing operations on primitive data types will show the largest speed difference between Java and Jython.

Jython performance is heavily dependent on the specifics of the JVM, of course. Specifically, the Sun JDK 1.4 is expected to make significant improvements in the performance of Java reflection and, as a result, Jython should make substantial speed gains under JVM 1.4. Still, up to 10 times slower seems like a big speed difference, and for some programs and projects it might be. But for most, the benchmark speed hit will not be as noticeable in practice as you might think.

For a large number of programs, the bottleneck is either user input speed or network latency, and even a large performance hit in these cases is not noticeable to users. Java programs tend to frequently be in this category - if raw speed was the issue, you probably wouldn't be using Java in the first place. As always, the rule is "Make it work, then make it fast." Jython is a fabulous environment for making it work, and if at some point you find that you still need to make it faster, there are mechanisms to try, both within Jython and by converting some code to Java.

Jython with EAServer
Now it's time to dive into Jython. We're going to use Jython within EAServer. To see it up and running we have to:

  • Download and install Jython
  • Write a simple servlet in Jython
  • Compile it to Java bytecode
  • Deploy it to EAServer
  • Call the servlet by a browser
Installation
Download Jython from www.jython.org/download.html. It's distributed as a self-extracting .class file (see Figure 1). Download this file into C:\Jython. To install Jython, open the command line to the directory in which you have placed the jython-21.class file and type:

java jython-21

Note that it may be necessary to set the CLASSPATH to include the current directory:

java - classpath.jython-21

Walk through the wizard and when asked for the path, enter C:\Jython as shown in Figure 2.

You can test the installation by typing:

jython -c "import java; print java.util.Date()"

into a Dos-Box (see Figure 3).

If this doesn't work, open the jython.bat file (c:\Jython\jython-2.1\jython.bat) and check that the path to java.exe is set correctly.

A Simple Servlet Written in Jython
Why do we do this? In addition to showing you an alternative way to write servlets, sometimes it makes life easier if you have the best of both worlds - Jython adds Python's dynamic OO and scripting flexibility to a servlet while having all the Java libraries (JDBC, XML, etc.) seamlessly accessible. So let's dive into the example:

  • First create and install a Web application in EAServer (call it Jython).
  • Create the directories for the Web application:

    %Jaguar%/Repository/Jython/Web-Inf/classes

    and

    %Jaguar%/Repository/Jython/Web-Inf/lib

  • Copy C:\Jython\jython-2.1\jython.jar into the created lib directory.
  • Code the servlet. Notice how the Jython class extends the Java HTTP servlet class, overrides Java methods, and invokes Java objects directly. This Jython code compiles into a Java class file and is a complete servlet by itself.

    # Hello.py

    from javax.servlet.http import HttpServlet

    class Hello(HttpServlet):
    def doGet(self, req, res):
    res.setContentType("text/html")
    out = res.getWriter()
    out.println("<html><head><title>Hello World!</title>\
    </head><body><h1>Hello
    World!</h1></body></html>")

  • To compile it use Compile.bat. You'll find the Java file and two class files in:

    .\jpywork

  • Move the .class files into

    %Jaguar%\Repository\WebApplication\Jython\Web-Inf\classes

  • Add the servlet to your Web application by adding a "New Web ComponentŠ" using Jaguar Manager and creating a servlet mapping (Hello) for this newly created component.
  • A shown in Figure 4, refresh the Web application, fire your browser, and test the Jython servlet by pointing it to http://localhost:8080/Jython/Hello.

    SETLOCAL

    set OLD_CLASSPATH=%CLASSPATH%
    set CLASSPATH=.
    set CLASSPATH=%CLASSPATH%;%JAGUAR%\java\lib\easj2ee.jar
    set CLASSPATH=%CLASSPATH%;%OLD_CLASSPATH%

    c:\Jython\jython-2.1\jythonc.bat Hello.py

    ENDLOCAL

    Conclusion
    Jython is an implementation of the high-level, dynamic, object-oriented language Python and is seamlessly integrated with the Java platform. The predecessor to Jython, JPython, is certified as 100% Pure Java. Jython is freely available for both commercial and noncommercial use and is distributed with source code. Jython is complementary to Java and is especially suited for the following tasks:

  • Embedded scripting: Java programmers can add the Jython libraries to their system to allow end users to write simple or complicated scripts that add functionality to the application.
  • Interactive experimentation: Jython provides an interactive interpreter that can be used to interact with Java packages or with running Java applications. This allows programmers to experiment and debug any Java system using Jython.
  • Rapid application development: Python programs are typically 2-10 times shorter than the equivalent Java program. This translates directly to increased programmer productivity. The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.

    Software Used

  • EAServer 4.1.3 (free evaluation version): www.sybase.com
  • Jython 2.1 (free version): www.jython.org/download.html
  • More Stories By Berndt Hamboeck

    Berndt Hamboeck is a senior consultant for BHITCON (www.bhitcon.net). He's a CSI, SCAPC8, EASAC, SCJP2, and started his Sybase development using PB5. You can reach him under admin@bhitcon.net.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.