Monday 1 March 2010

Maven, Jython & Glassfish Example

I keep meaning to get stuck in and learn some Python, and especially make use of some Jython. After coming across this post about using Jython with Glassfish, I thought I'd give it a go myself.

This post is about creating a Maven WAR project making use of Python scripts running on embedded Jython on an embedded Glassfish v3 instance.

Here is the projects POM:


<project xmlns="" xmlns:xsi=""

  <name>Maven WAR-Jython-Glassfish Example</name>

    Example project for creating a Jython WAR running on Glassfish.
    Usage: mvn clean install embedded-glassfish:run



      <name>Adrian Walker</name>

    Use project lib directory as repository





    Jython version 2.5.1 and it's standard library
    are included in the project lib directory

I couldn't find the latest version (2.5.1) of the Jython JAR in any Maven repository, so I have included it with the project source code in the lib directory. Also, I wanted the Jython instance to be completely self contained, so instead of referencing an install external to the project, I have JAR'ed up the standard library and included it in the project as lib/jython-lib-2.5.1.jar.

The project uses the embedded Glassfish v3 plugin to quickly start a basic configuration Glassfish server.

PyServlet, distributed with Jython is used to create Java Servlets using Jython source files. It is configured in the project's web.xml:


<web-app xmlns:xsi=""
         xsi:schemaLocation="" id="Message" version="2.5">




Python code to create a Java servlet which uses the Python calendar library:

import time
import calendar
from javax.servlet.http import HttpServlet

class Calendar (HttpServlet):
  def doGet(self, request, response):
    response.setContentType ("text/html")
    out = response.getWriter()

    out.println ("""
    """ % calendar.calendar(time.localtime()[0]))

Run the project with 'mvn clean install embedded-glassfish:run' and point your brower at http://localhost:8080/example/.

Source Code