Developing Vaadin apps with Python

    To accomplish exactly what?

    Luckily Python can make use of Java classes and vice versa. For detailed tutorial how to accomplish this in general please see 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 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.

    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

    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 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.

    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. if (applicationModuleName == null) {
    28. throw new ServletException(
    29. "Application not specified in servlet parameters");
    30. }
    31. String[] appModuleSplitted = applicationModuleName.split("\\.");
    32. if(appModuleSplitted.length < 1) {
    33. throw new ServletException("Cannot parse class name");
    34. }
    35. final String applicationClassName = appModuleSplitted[appModuleSplitted.length-1];
    36. try {
    37. PythonInterpreter interpreter = new PythonInterpreter();
    38. interpreter.exec("from "+applicationModuleName+" import "+applicationClassName);
    39. PyObject pyObj = interpreter.get(applicationClassName).__call__();
    40. Application pyApp = (Application)pyObj.__tojava__(Application.class);
    41. applicationClass = pyApp.getClass();
    42. } catch (Exception e) {
    43. e.printStackTrace();
    44. throw new ServletException("Failed to load application class: "
    45. + applicationModuleName, e);
    46. }
    47. }
    48. @Override
    49. protected Application getNewApplication(HttpServletRequest request)
    50. throws ServletException {
    51. // Creates a new application instance
    52. try {
    53. final Application application = getApplicationClass().newInstance();
    54. return application;
    55. } catch (final IllegalAccessException e) {
    56. throw new ServletException("getNewApplication failed", e);
    57. } catch (final InstantiationException e) {
    58. throw new ServletException("getNewApplication failed", e);
    59. } catch (ClassNotFoundException e) {
    60. throw new ServletException("getNewApplication failed", e);
    61. }
    62. }
    63. @Override
    64. protected Class<? extends Application> getApplicationClass()
    65. throws ClassNotFoundException {
    66. return applicationClass;
    67. }
    68. }

    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

    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. }

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

    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. 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 .

    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.

    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.