I want to see the most minimal example of using the new Push technology in Vaadin 7, such as the new @Push
annotation.
I am having problems getting server-push to work in my app. I would like to try a simple example app before trying to fix my own app.
Here is a simple but full Vaadin 8 example that demonstrates how to use server push and Java EE messaging APIs to send messages between different UIs using the Broadcaster pattern described in Vaadin docs. If you are not interested in messaging or broadcasting to other users, then look at ReceiveMessageUI only.
In principle it all boils down to the following:
@Push
to enable server push (by default over a WebSocket connection)Wrap UI updates with
access()
when accessing it from other threads, sending updates happens automatically by default:Use the Broadcaster pattern to publish messages to other users and to subscribe to their messages.
Simplification Of Example In The Book Of Vaadin
The Book Of Vaadin includes a chapter on Push, including an example using Vaadin Charts.
Below is my code. While based on that Vaadin Charts example mentioned above, I simplified it by replacing the use of a
Chart
object with a simpleLabel
object. The Label updates every second or so to tell you the current time.For Example Use Only – Use an Executor in real-world project
Caveat: My example below is built for simplicity, not intended as production code. Sleeping a thread is a crude and awkward way to manage scheduled threaded work. Java provides the
Executor
facility for this kind of work. In a real-world project I would use a ScheduledExecutorService rather than a single sleepingThread
object to schedule our task (of telling time). Related tip: Never use aTimer
in a Servlet environment. For a fuller and more real-world example, see my Answer to a similar Question about Push with Vaadin.I took other shortcuts in this example, such as: I place the
Label
widget directly on theUI
whereas real-world work would use aLayout
to contain theLabel
.My Configuration
My code is using Vaadin 7.3.7 with Java 8 Update 25 in NetBeans 8.0.2 and Tomcat 8.0.15 on Mac OS X 10.8.5 (Mountain Lion).
Push technology is relatively new, especially the WebSocket variety. Be sure to use recent versions of your web server, such as recent updates to Tomcat 7 or 8.
How To Use This Example
This code is a single file, the
MyUI.java
file. To use this code:MyUI
class with the code below.@Push
AnnotationBeside the code in the middle, note how we added the
@Push
annotation to theMyUI
class definition.Example Code