Finding the current root and application

There are many cases where you need a reference to the active Application or Root, for instance for showing notifications in a click listener. It is possible to get a reference to the component from the event and then a reference from the component to the Root but Vaadin also offers an easier way through two static methods:

Java

  1. Root.getCurrent()
  2. Application.getCurrent()

For example when you want to show the name of the current Root class:

Java

  1. Button helloButton = new Button("Say Hello");
  2. helloButton.addListener(new ClickListener() {
  3. public void buttonClick(ClickEvent event) {
  4. Notification.show("This Root is " + Root.getCurrent().getClass().getSimpleName());
  5. }
  6. });

Similarly for Application, for instance to find out if the application is running in production mode:

Java

  1. public void buttonClick(ClickEvent event) {
  2. String msg = "Running in ";
  3. msg += Application.getCurrent().isProductionMode() ?
  4. "production" : "debug";
  5. msg += " mode";
  6. Notification.show(msg);
  7. }

Note that these are based on ThreadLocal so they won’t work in a background thread (or otherwise outside the standard request scope).