Developing Vaadin apps with Python

To accomplish exactly what?

This article describes how to start developing Vaadin apps with Python programming language. Goal is that programmer could use Python instead of Java with smallest amount of boilerplate code necessary to get the environment working.

Luckily Python can make use of Java classes and vice versa. For detailed tutorial how to accomplish this in general please see http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html and http://wiki.python.org/jython/UserGuide.

Requirements

For setup used in this article you will need to install PyDev plugin to your Eclipse and Jython. See http://pydev.org/ and http://www.jython.org/ for more details.

Let’s get started

To get started create a new Vaadin project or open existing as you would normally do. As you have PyDev installed as Eclipse plugin you can start developing after few steps.

  • Add Python nature to your project by right clicking the project and selecting PyDev → Set as PyDev Project. After this the project properties has PyDev specific sections.

  • Go to PyDev - Interpreter/Grammar and select Jython as your Python interpreter.

  • Add a source folder where your Python source code will reside. Go to section PyDev - PYTHONPATH and add source folder. Also add vaadin-x.x.x.jar to PYTHONPATH in external libraries tab.

  • Add jython.jar to your project’s classpath and into deployment artifact.

  • Map your python source folder into WEB-INF/classes in deployment artifact. Go to Deployment Assembly → Add → Folder.

Deploy artifact

Modify web.xml and ApplicationServlet

First of all to build a basic Vaadin app you need to define your app in web.xml. You have something like this in your web.xml:

XML

  1. <servlet>
  2. <servlet-name>Vaadin Application</servlet-name>
  3. <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
  4. <init-param>
  5. <description>Vaadin application class to start</description>
  6. <param-name>application</param-name>
  7. <param-value>com.vaadin.example.ExampleApplication</param-value>
  8. </init-param>
  9. </servlet>

This will have to be modified a bit. Servlet init parameter application is a Java class name which will be instantiated for each user session. Default implementation of com.vaadin.terminal.gwt.server.ApplicationServlet can only instantiate Java classes so therefore you must override that class so that it is able to instantiate Python objects. Of course if you want the main Application object to be a Java class there is no need to modify the web.xml.

Here’s the modified section of web.xml. Implementation of PythonServlet is explained later. Init parameter application is now actually Python class.

XML

  1. <servlet>
  2. <servlet-name>Python Application</servlet-name>
  3. <servlet-class>com.vaadin.example.pythonapp.PythonServlet</servlet-class>
  4. <init-param>
  5. <description>Vaadin application class to start</description>
  6. <param-name>application</param-name>
  7. <param-value>python.vaadin.pythonapp.PyApplication</param-value>
  8. </init-param>
  9. </servlet>

And here’s the PythonServlet. This is altered version of original Vaadin ApplicationServlet.

Java

  1. package com.vaadin.example.pythonapp;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.python.core.PyObject;
  5. import org.python.util.PythonInterpreter;
  6. import com.vaadin.Application;
  7. import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;
  8. public class PythonServlet extends AbstractApplicationServlet {
  9. // Private fields
  10. private Class<? extends Application> applicationClass;
  11. /**
  12. * Called by the servlet container to indicate to a servlet that the servlet
  13. * is being placed into service.
  14. *
  15. * @param servletConfig
  16. * the object containing the servlet's configuration and
  17. * initialization parameters
  18. * @throws javax.servlet.ServletException
  19. * if an exception has occurred that interferes with the
  20. * servlet's normal operation.
  21. */
  22. @Override
  23. public void init(javax.servlet.ServletConfig servletConfig)
  24. throws javax.servlet.ServletException {
  25. super.init(servletConfig);
  26. final String applicationModuleName = servletConfig
  27. .getInitParameter("application");
  28. if (applicationModuleName == null) {
  29. throw new ServletException(
  30. "Application not specified in servlet parameters");
  31. }
  32. String[] appModuleSplitted = applicationModuleName.split("\\.");
  33. if(appModuleSplitted.length < 1) {
  34. throw new ServletException("Cannot parse class name");
  35. }
  36. final String applicationClassName = appModuleSplitted[appModuleSplitted.length-1];
  37. try {
  38. PythonInterpreter interpreter = new PythonInterpreter();
  39. interpreter.exec("from "+applicationModuleName+" import "+applicationClassName);
  40. PyObject pyObj = interpreter.get(applicationClassName).__call__();
  41. Application pyApp = (Application)pyObj.__tojava__(Application.class);
  42. applicationClass = pyApp.getClass();
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. throw new ServletException("Failed to load application class: "
  46. + applicationModuleName, e);
  47. }
  48. }
  49. @Override
  50. protected Application getNewApplication(HttpServletRequest request)
  51. throws ServletException {
  52. // Creates a new application instance
  53. try {
  54. final Application application = getApplicationClass().newInstance();
  55. return application;
  56. } catch (final IllegalAccessException e) {
  57. throw new ServletException("getNewApplication failed", e);
  58. } catch (final InstantiationException e) {
  59. throw new ServletException("getNewApplication failed", e);
  60. } catch (ClassNotFoundException e) {
  61. throw new ServletException("getNewApplication failed", e);
  62. }
  63. }
  64. @Override
  65. protected Class<? extends Application> getApplicationClass()
  66. throws ClassNotFoundException {
  67. return applicationClass;
  68. }
  69. }

The most important part is the following. It uses Jython’s PythonInterpreter to instantiate and convert Python classes into Java classes. Then Class object is stored for later use of creating new instances of it on demand.

Java

  1. PythonInterpreter interpreter = new PythonInterpreter();
  2. interpreter.exec("from "+applicationModuleName+" import "+applicationClassName);
  3. PyObject pyObj = interpreter.get(applicationClassName).__call__();
  4. Application pyApp = (Application)pyObj.__tojava__(Application.class);

Now the Python application for Vaadin is good to go. No more effort is needed to get it running. So next we see how the application itself can be written in Python.

Python style Application object

Creating an Application is pretty straightforward. You would write class that is identical to the Java counterpart except it’s syntax is Python. Basic hello world application would look like this

python

  1. from com.vaadin import Application
  2. from com.vaadin.ui import Label
  3. from com.vaadin.ui import Window
  4. class PyApplication(Application):
  5. def __init__(self):
  6. pass
  7. def init(self):
  8. mainWindow = Window("Vaadin with Python")
  9. label = Label("Vaadin with Python")
  10. mainWindow.addComponent(label)
  11. self.setMainWindow(mainWindow)

Event listeners

Python does not have anonymous classes like Java and Vaadin’s event listeners rely heavily on implementing listener interfaces which are very often done as anonymous classes. So therefore the closest equivalent of

Java

  1. Button button = new Button("java button");
  2. button.addListener(new Button.ClickListener() {
  3. public void buttonClick(ClickEvent event) {
  4. //Do something for the click
  5. }
  6. });

is

python

  1. button = Button("python button")
  2. class listener(Button.ClickListener):
  3. def buttonClick(self, event):
  4. #do something for the click
  5. button.addListener(listener())

Jython supports for some extend AWT/Swing-style event listeners but however that mechanism is not compatible with Vaadin. Same problem applies to just about anything else event listening interface in Java libraries like Runnable or Callable. To reduce the resulted verbosity some decorator code can be introduced like here https://gist.github.com/sunng87/947926.

Creating custom components

Creating custom Vaadin components is pretty much as straightforward as the creation of Vaadin main application. Override the CustomComponent class in similar manner as would be done with Java.

python

  1. from com.vaadin.ui import CustomComponent
  2. from com.vaadin.ui import VerticalLayout
  3. from com.vaadin.ui import Label
  4. from com.vaadin.ui import Button
  5. from com.vaadin.terminal import ThemeResource
  6. class PyComponent(CustomComponent, Button.ClickListener):
  7. def __init__(self):
  8. mainLayout = VerticalLayout()
  9. button = Button("click me to toggle the icon")
  10. self.label = Label()
  11. button.addListener(self)
  12. mainLayout.addComponent(self.label)
  13. mainLayout.addComponent(button)
  14. self.super__setCompositionRoot(mainLayout)
  15. def buttonClick(self, event):
  16. if self.label.getIcon() == None:
  17. self.label.setIcon(ThemeResource("../runo/icons/16/lock.png"));
  18. else:
  19. self.label.setIcon(None)

Containers and PythonBeans

Although not Python style of doing things there are some occasions that require use of beans.

Let’s say that you would like to have a table which has it’s content retrieved from a set of beans. Content would be one row with two columns where cells would contain strings “first” and “second” respectively. You would write this code to create and fill the table.

python

  1. table = Table()
  2. container = BeanItemContainer(Bean().getClass())
  3. bean = Bean()
  4. bean.setFirst("first")
  5. bean.setSecond("second")
  6. container.addItem(bean)
  7. table.setContainerDataSource(container)

and the Bean object would look like this

python

  1. class Bean(JavaBean):
  2. def __init__(self):
  3. self.__first = None
  4. self.__second = None
  5. def getFirst(self):
  6. return self.__first
  7. def getSecond(self):
  8. return self.__second
  9. def setFirst(self, val):
  10. self.__first = val
  11. def setSecond(self, val):
  12. self.__second = val

and JavaBean

Java

  1. public interface JavaBean {
  2. String getFirst();
  3. void setFirst(String first);
  4. String getSecond();
  5. void setSecond(String second);
  6. }

Note that in this example there is Java interface mixed into Python code. That is because Jython in it’s current (2.5.2) version does not fully implement reflection API for python objects. Result without would be a table that has no columns.

Implementing a Java interface adds necessary piece of information of accessor methods so that bean item container can handle it.

Filtering container

Let’s add filtering to previous example. Implement custom filter that allows only bean that ‘first’ property is set to ‘first’

python

  1. container.addContainerFilter(PyFilter())
  2. class PyFilter(Container.Filter):
  3. def appliesToProperty(self, propertyId):
  4. return True
  5. def passesFilter(self, itemId, item):
  6. prop = item.getItemProperty("first")
  7. if prop.getValue() == "first":
  8. return True
  9. else:
  10. return False

Again pretty straightforward.

Debugging

Debugging works as you would debug any Jython app remotely in a servlet engine. See PyDev’s manual for remote debugging at http://pydev.org/manual_adv_remote_debugger.html.

Setting breakpoints directly via Eclipse IDE however does not work. Application is started as a Java application and the debugger therefore does not understand Python code.

Final thoughts

By using Jython it allows easy access from Python code to Java code which makes it really straightforward to develop Vaadin apps with Python.

Some corners are bit rough as they require mixing Java code or are not possible to implement with Python as easily or efficiently than with Java.

How this differs from Muntjac?

Muntjac project is a python translation of Vaadin and it’s goal is pretty much same as this article’s: To enable development of Vaadin apps with Python.

Muntjac’s approach was to take Vaadin’s Java source code and translate it to Python while keeping the API intact or at least similar as possible. While in this article the Vaadin itself is left as is.

Simple Python applications like shown above can be executed with Vaadin or Muntjac. Application code should be compatible with both with small package/namespace differences.

Muntjac requires no Jython but it also lacks the possibility to use Java classes directly.

The problems we encountered above with requiring the use of mixed Java code are currently present in Muntjac (v1.0.4) as well. For example the BeanItemContainer is missing from the Muntjac at the moment.