We are currently porting our app to vaadin 7 and I want to track wether a user has been active during the last 30s or so.
We used to track user activity in a custom CommunicationManager, but since this class is deprecated, I figured we might have to try differently.
I created an extension that I extend the UI with.
For simplicity's sake let's say, we count clicking and keyboard usage as user activity:
// this is the extend method in the extension connector
#Override
protected void extend (ServerConnector target) {
UIConnector uiConnector = (UIConnector) target;
VUI uiWidget = uiConnector.getWidget();
uiWidget.addDomHandler(this.keyPressed(), KeyPressEvent.getType());
uiWidget.addDomHandler(this.mouseClicked(), ClickEvent.getType());
}
The extension will then schedule a timer that will call the server via RPC every 30s, but only if the user has been active.
This Timer works. What does not work is the DOM Events, they never seem to reach the Event Listeners I added.
What am I doing wrong?
Based on your implementation, I would suggest you give Refresher add-on a try. It works in similar manner but gives you more control regarding polling interval, server-side listener. Plus, you don't have to maintain it.
The other alternative would be taking advantage of Vaadin polling support (see https://vaadin.com/wiki/-/wiki/Main/Using%20polling).
Related
I am trying to have a auto refresh feature for the grid which basically, updates the grid with latest data from the server every 'n' seconds.
I was able to implement the PollListner whenever the user enables Auto-Refresh.
UI ui= TestUI.getCurrent();
Boolean value = isRefreshChkBox.getValue();
PollListener listener = e -> {
explorer.reloadUI();
};
if (value) {
String refreshRateValue = refreshRateTxtField.getValue();
int refreshRate = Integer.valueOf(refreshRateValue);
int millis = (int) TimeUnit.SECONDS.toMillis(refreshRate);
absUI.setPollInterval(millis);
absUI.addPollListener(listener);
} else {
absUI.setPollInterval(-1);
absUI.removePollListener(listener);
}
With the above code, I add PollListener everytime autorefresh is enabled and I remove it on disable.
I found similar question here VAADIN 7: What is the simplest way to refresh a Vaadin View in 5 minute intervals?
But what I want to understand, is there a better approach to achieve a simple usecase AutoRefresh UI?? where should PollListener be implemented?? I thought of creating PollListener once for the view and just update the PollInterval everytime user changes the refresh rate.
Any pointers on which approach is better or is there completely new concept in Vaadin to achieve this?
TIA
See the correct Answer by Leif Åstrand. I will add a bit of discussion, and a complete example app using both Polling and Push.
Vaadin 8 has two ways to automatically update the display of information without the user making a gesture: Polling & Push.
Polling
In Vaadin 8’s Polling feature, you set a polling interval of milliseconds on your UI subclass. The default value of -1 disables Polling.
myUI.setPollInterval( ( int ) TimeUnit.MINUTES.toMillis( 1 ) ); // Specify milliseconds for polling interval.
When enabled, the Vaadin JavaScript library installed in the user’s web browser checks in with the Vaadin server. Being a PollNotifier, the UI checking-in causes an event to be fired on the server-side.
If you define a class that implements the PollListener interface, your instance will have its poll method invoked.
Upon registering your PollListener. get back a Registration object. That object provides a remove method to unregister your listener, if need be.
You have your choice of defining your PollListener using lambda syntax, an anonymous inner class, or a separately-defined class.
Registration registration = this.addPollListener( new UIEvents.PollListener() {
#Override
public void poll ( UIEvents.PollEvent pollEvent ) {
System.out.println( "TRACE - PollListener::poll running. " + Instant.now() );
…
}
} );
Or, lambda syntax:
Registration registration = this.addPollListener( ( UIEvents.PollListener ) pollEvent -> {
System.out.println( "TRACE - PollListener::poll running. " + Instant.now() );
…
} );
During this invocation, your code can register a Runnable to be invoked at a convenient time with your UI subclass.
That Runnable does the work of updating widgets contained in your UI subclass. Remember to never access or modify widgets from a background thread. You may get away with it, or you may cause terrible things to happen. Be safe: Always call UI::access to pass a Runnable that accesses the widgets. That Runnable will be run on the main user-interface thread of your web app, the thread in charge of your UI subclass instance.
getUI().access( new Runnable() {
#Override
public void run ( ) {
subscriber.refresh( new ArrayList <>( statusList ) ); // Copy the list in case the `Grid` modifies it, such as sorting.
}
} );
Pros
The upside of using the Polling feature is that the programming you must do is simpler than with Push (discussed below). Polling is likely a better route to take when learning about automated non-user-generated updates.
One simple aspect is that each instance of your UI subclass is in charge of its own polling, choosing if and when to do polling and controlling how often to poll. Each UI subclass instance calls its own setPollInterval method. More polling may be nice for the user, but the chattiness increases network traffic, thereby making your network admin cranky. So you can tune the frequency by UI subclass instance. Remember that not only does each user have their own UI subclass instance, but also, Vaadin 8 is capable of multi-window/tab apps. One web app in each web browser can have multiple windows/tabs open, each running their own instance of the same or different UI subclasses.
Cons
One downside aesthetically is that polling breaks the request-response elegance of the HTTP design. While this is a pet-peeve of mine, that ship has sailed long ago, so I'll not waste bytes here ranting about using a document-delivery system as an interactive client-server app architecture.
A more practical downside is unnecessary traffic on the network. If you are able to use Push via WebSocket or Webpush, then an open connection is maintained between client and server with very little traffic all the while until the server generates an event to be communicated to the client. But be aware that WebSocket is easily defeated by firewalls & proxies, and Webpush may not be implemented/supported, in which case the Push implementation in Vaadin (the Atmosphere Framework library by async-io.org) may fall back to polling techniques.
Another downside is inefficiency of each client doing its own repeated polling and each triggering a separate execution on the server-side such as the search for fresh data in the database. If you have many clients all consuming the same set of immutable objects, then Push can be more efficient doing a single search for fresh data and delivering the same bunch of data objects to all the clients.
Push
The combination of Vaadin with Atmosphere (linked above) vastly simplifies using Push technology in your web app. Nevertheless, it is a bit more complicated with more moving parts than seen with the Polling feature.
Firstly, enable Push with the #Push annotation on your UI subclass.
Then schedule the firing of an event every minute using a ScheduledExecutorService. Set up that executor with a ServletContextListener. See example code below for all this.
Pros
Push can be quite efficient in terms of network traffic able to use WebSocket technology or Webpush, as mentioned above.
Cons
Unfortunately WebSocket can be defeated by firewalls & proxies. And Webpush is new and may not be widely supported. In this case, Vaadin/Atmosphere may fall-back to using a polling approach.
Another downside is that the coding is a bit more complex. A programmer new to this work may take a while to grasp the various moving pieces.
You need a background thread on the server-side to track the time, in our case firing every minute. The modern approach to that is using a ScheduledExecutorService to handle the threading and firing schedule.
To setup that executor service, you will need to implement a ServletContextListener as discussed below.
Be aware that some of the push approaches, especially WebSocket, involve maintaining an open network connection. So this consumes resources such as port numbers on your server machine.
Example app
I built a complete working example app using Vaadin 8.6beta1. This app supports both Polling and Push. Not sure if you would ever mix both in a real web app, but perhaps.
Access the main files on my Google Drive. Add to a project created via the Maven archetype vaadin-archetype-application provided by Vaadin Ltd.
Caveat: This example was cobbled together part-time over days. So it may or may not be production-ready code, and may or may not show proper technique. But hopefully it will help to guide a newbie.
Caveat: I am not an expert in this arena. So take all my discussion above and my example code here with a grain-of-salt. Do your own research and study.
This app allows you to enable and disable each approach via radio buttons. You can also force an immediate refresh by clicking the Refresh manually now button.
The green-shading indicates changed values since the last refresh.
You can run multiple windows. Watch them update together or separately or not all, depending on your radio button settings.
Database
The main idea of this example app is to simulate a database maintaining a current status of some ten pieces of equipment/processes/people/whatever. Each status in identified by a number 1-10. Each has a status with a domain of ten values, 1-9. And each status records the moment it was last updated.
These ten status records are displayed as rows in a Vaadin Grid widget.
All this data is recorded in a relational database, the H2 Database Engine. As a demo, we’ve no need for persistence, so the database is in-memory. A background thread randomly updates the status rows in the database.
MyDbService.java
This database-service code establishes our in-memory H2 database, defining the table for our Status, and populating ten rows. This class also can randomly update the value of some of the rows. And you can ask to retrieve a List of Status objects representing the currently stored values.
Status.java
Each status record is represented in Java by the Status class, a simple POJO.
Lifecycle
Vaadin is based on Java Servlet technology. Your Vaadin app is one big Servlet implementation. As a servlet, it responds to incoming requests by the users’ web browsers.
Before that first incoming request, we need to do some set-up work. For one thing, we need to establish and populate that database with our ten status records.
The Servlet specification requires all web containers to support the ServletContextListener interface. If you write a class implementing that interface, and declare it to the web container, then it will be invoked before the first request and after the last request.
In our example, we use that hook to establish the database. We also set up a background thread that randomly changes our stored status records to simulate either users’ updates or fresh data from a feed.
Context listener
Here is our example ServletContextListener.
The easiest way to declare its presence to our web container is by the #WebListener annotation but you can choose other routes as needed in your deployment scenario.
#WebListener
public class MyServletContextListener implements ServletContextListener {
…
MyUI.java
The entry point into this Vaadin web app is our subclass of UI, MyUI.java. It has two jobs: (a) Get our user-interface content on-screen, and (b) Register itself as a PollListener to react to polling updates.
DataDisplayLayout.java
Here is our user-interface content. This is the centerpiece of this example app. It displays the Vaadin Grid whose display is to be updated with fresh data.
DataDisplayLayoutRefreshManager.java
This manager oversees the pub-sub (Publish-Subscribe) model of signing up instances of our DataDisplayLayout that want to be updated via Push.
A collection of weak references are used here to track the subscribers. So the subscribing DataDisplayLayout instance can gracefully notify of their desire to no longer be updated, or the instance can simply go out-of-scope to eventually be dropped as a subscriber.
The Polling approach does not need this manager, as each instance of our UI subclass (MyUI) is individually polling the server.
mytheme.scss
The green coloring of the cell in the Vaadin Grid denoting a fresh value is set via CSS. In Vaadin 8, we do this by editing the mytheme.scss file found buried in your project’s webapp folder.
Here we define the style name fresh_row.
#import "../valo/valo.scss";
#mixin mytheme {
#include valo;
// Insert your own theme rules here
.v-grid-row.fresh_row > td:nth-child(2) {
background-color: honeydew;
}
}
We must assign that style name to our Vaadin Grid rows by implementing a style generator.
this.grid.setStyleGenerator( ( StyleGenerator ) o -> {
Status s = ( Status ) o;
if ( s.getUpdated().isAfter( this.whenRowLastUpdated ) ) {
return "fresh_row";
} else {
return null;
}
} );
There are basically two ways of updating a Vaadin UI from background activity: poll and push. Each has their own pros and cons.
Polling is the technically more simple approach. It's based on a timer in the browser that triggers a request at a regular interval. Any pending changes will be delivered to the client in the response to that request. In addition, you can add a listener that gets run for every such request so that you can manually check for changes and if needed, update the UI.
Push is based on keeping a persistent connection open between the client and the server, so that the server can send changes to the client immediately instead of having to wait until the client opens a connection and asks for changes. The benefit here is that changes can be sent to the client immediately when they happen, instead of only at regular intervals.
Which to use depends on your requirements. Polling may use slightly less resources because there's no need to keep a connection open all the time. Polling may also be beneficial if there is no server-side trigger when the data changes, but instead, the server-side logic would still have to periodically explicitly check whether anything has changed. The main benefit of push is that changes can be sent immediately when something happens.
I am trying to make a demo Android project using Redux architecture but I am having trouble to wrap my head around showing flash messages for example as a reaction to successful/failed async action.
If it was a long-lived view, that informs user about the result I would just dispatch another action which alters state with particular flag and display the view. However if I want to use Toast or SnackBar for it, I don't have means to cancel the flag and it would just show the message again after another state change.
I am new to Redux, but I read that reducers must be pure functions and if I understand the pure function concept correctly, showing a flash message is a side-effect which is not allowed. So I can't dispatch an action that would be reduced to only invoke without altering the state.
So the only option I can see is that I handle all async operations outside the Redux flow, dispatch actions in reaction to those events and show flash messages in event handlers as well. But to my mind, every UI change is also a change in state, and not reflecting it in Store is a problem. So by doing this I feel like violating Redux pattern and taking a lot from the architecture itself as it will reduce its testing capabilities.
Is there a way out?
Redux describe a component such Middleware.
http://redux.js.org/docs/advanced/Middleware.html
Quote from article:
'It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.'
You can create middleware for this side effect. In your system you have actions such as SetSuccessLoadingAction and SetFailedLoadingAction. In your middleware you can determine these actions and do what you need.
For example you can see how middleware works for another side affect - logging every incomming action.
https://github.com/zyvpeople/Redux
Let me first sketch the concrete situation I find myself in, although my question is actually more general. I'm writing a component containing several sliders and I have listeners listening for events from these sliders. When one of these sliders changes I want my component to send an event to its own listeners to notify them that its state has changed. I would however like to limit the number of events that are sent, i.e. if there are several events waiting when my component notifies its listeners, I would like to collapse all these events into a single event.
My question is whether there are standard techniques for this. If so, any example would be welcome, because I couldn't find any. (Maybe collapsing is not the correct terminology?)
I believe collapsing is the correct term. An example class from the Java Core libraries that implements such behavior is RepaintManager. I would check out it's source code to see how it collapses multiple repaint requests.
Before you do any such thing you should make sure that it is really necessary.
I guess you would need to access the EventQueue from your listener. When an event triggers the callback method, this method should first look in the queue to see if there are more recent events of the relevant type and, if so, process the most recent event only and then remove all events of that type from the queue.
Since the callbacks are always on the Swing (awt) event thread, you don't need to worry about concurrency.
I'm designing a stand-alone, multi-threaded application in Java.
I'm trying to choose the best event-handling solution for his project.
I have 1-3 threads generating events (e.g comm thread completes file upload), while other threads might want to be registered for notification on this event.
I want the event-generating and event listening to be as uncoupled as possible.
What do you suggest?
Use an event bus.
An event bus can be thought of as a
replacement for the observer pattern,
where in the observer pattern, each
component is observing an observable
directly. In the event bus pattern,
each component simply subscribes to
the event bus and waits for its event
notification methods to be invoked
when interesting events have occurred.
In this way, an event bus can be
thought of like the observer pattern
with an extra layer of decoupling.
Here's a nice presentation about using an event bus ins GWT. It should give you a good idea about the benefits (and it's quite funny, too).
EDIT
The first link is mainly given as an example. It's really not that hard implementing something similar on your own which fits your needs.
I would use ExecutorServices to manage your thread pools. This way when you have a listener to an event, you can ensure the event is added to the right service either using a Proxy, or hande coded. e.g.
public void onEventOne(final Type parameter) {
executorService.submit(new Runnable() {
public void run() {
wrappedListener.onEventOne(parameter);
}
}
}
You can pass this listener wrapper as and be sure the event will be processed using the desired thread pool.
Using a Proxy allows you to avoid this type of boiler plate code. ;)
Do you really need a solution where each thread can register as a listener for each type of event? If so, use an event bus type solution (or a centralized observable with typed events).
If you don't need this flexibility a manager-worker setup could suffice, where the manager gets notified of events (like: "I'm finished with my job") and can fire up workers as needed.
Usage of an event bus is definitely the right choise. There are various solutions out there. You can also check out MBassador https://github.com/bennidi/mbassador.
It is annotation driven, very light-weight and uses weak references (thus easy to integrate in environments where objects lifecycle management is done by a framework like spring or guice or somethign). It provides an object filtering mechanism and synchronous or asynchronous dispatch/message handling. And it's very fast!
Google Guava has an event bus as well but it uses strong references which can be a pain if you do not have full control over your object lifecycle (e.g. spring environment)
EDIT: I created a performance and feature comparison for a selection of available event bus implementations including Guava, MBassador and some more. The results are quite interesting. Check it out here
http://codeblock.engio.net/?p=37
use command design pattern to decoupling
I'm developing a java swing application that will have several subsystems. For all intents and purposes, let's assume that I am making an internet chat program with a random additional piece of functionality. That functionality will be... a scheduler where you can set a time and get a reminder at that time, as well as notify everyone on your friend list that you got a reminder.
It makes sense to organize this functionality into three classes: a GUI, a ChatManager, and a Scheduler. These classes would do the following:
GUI - Define all of the swing components and events
ChatManager - Create a chat connection, send and receive messages, manage friend list
Scheduler - Monitor system time, send notifications, store a file to remember events between sessions
For the program to work, each of these classes must be capable of communicating with the other two. The GUI needs to tell the ChatManager when to send a message and tell the Scheduler when to start monitoring. The ChatManager needs to display messages on the GUI when they're received, and finally, the Scheduler needs to both notify the GUI when it's finished, and send a status update or whatever to the ChatManager.
Of course, the classes as described here are all pretty simple, and it might not be a bad idea to just let them communicate with each other directly. However, for the sake of this question, let's assume the interactions are much more complex.
For example, let's say we can register a particular event with the scheduler instead of a particular time. When sending a message, I went to send it to the user, store it in a log file, create an event object and pass it to the scheduler, and handle any exceptions that might be thrown along the way.
When communication becomes this complex, it becomes difficult to maintain your code if communication with these classes can be happening in many different places. If I were to refactor the ChatManager, for example, I might also need to make significant chaneges to both the GUI and Scheduler (and whatever else, if I introduce something new). This makes the code difficult to maintain and makes us sleep-deprived programmers more likely to introduce bugs when making changes.
The solution that initially seemed to make the most sense is to use the mediator design pattern. The idea is that none of these three main classes are directly aware of each other, and instead, each is aware of a mediator class. The mediator class, in turn, defines methods that handle communication between the three classes. So, for example, the GUI would call the sendMessage() method in the mediator class, and the mediator would handle everything that needed to happen. Ultimately, this decouples the three main classes, and any changes to one of them would likely only result in changes to the mediator.
However, this introduces two main problems, which ultimately resulted in me coming here to seek feedback. They are as follows:
Problems
Many tasks will need to update the GUI, but the Mediator isn't aware of the components. - Suppose the user starts the program and enters their username/password and clicks login to login to the chat server. While logging in, you want to report the login process by displaying text on the login screen, such as "Connecting...", "Logging in...", or "Error". If you define the login method in the Mediator class, the only way to display these notifications is to create a public method in the GUI class that updates the correct JLabel. Eventually, the GUI class would need a very large amount of methods for updating its components, such as displaying a message from a particular user, updating your friend list when a user logs on/off, and so on. Also, you'd have to expect that these GUI updates could randomly happen at any time. Is that okay?
The Swing Event Dispatch Thread. You'll mostly be calling mediator methods from component ActionListeners, which execute on the EDT. However, you don't want to send messages or read/write files on the EDT or your GUI will become unresponsive. Thus, would it be a good idea to have a SingleThreadExecutor available in the mediator object, with every method in the mediator object defining a new runnable that it can submit to the executor thread? Also, updating GUI components has to occur on the EDT, but that Executor thread will be calling the methods to update the GUI components. Ergo, every public method in the GUI class would have to submit itself to the EDT for execution. Is that necessary?
To me, it seems like a lot of work to have a method in the GUI class to update every component that somehow communicates with the outside, with each of those methods having the additional overheard of checking if it's on the EDT, and adding itself to the EDT otherwise. In addition, every public method in the Mediator class would have to do something similar, either adding Runnable code to the Mediator thread or launching a worker thread.
Overall, it seems like it is almost as much work to maintain the application with the Mediator pattern than to maintain the application without it. So, in this example, what would you do different, if anything?
Your GUI classes will end up with many methods to keep it up to date and that is fine. If it worries you there is always the option of breaking up the GUI into sub GUIs each with a different functionality or a small set of related functionality. The number of methods will obviously not change, but it will be more organised, coherent and decoupled.
Instead of having every method in your GUI create a Runnable and use SwingUtilities.invokeLater to put that update on the EDT I'd advise you to try out another solution. For my personal projects I use The Swing Application Framework (JSR296) which has some convenient Task classes for launching background jobs and then the succeed method is automatically on the EDT thread. If you cannot use this you should try and create your own similar framework for background jobs.
Here, a partial answer to you design questions...
It looks like you want to have loose coupling between your components.
In your case, I would use the mediator as a message dispatcher to the GUI.
The ChatManager and the Scheduler would generate UpdateUIMessage.
And I would write my GUI that way
public class MyView {
public void handleUpdateMessage(final UpdateUIMessage msg){
Runnable doRun = new Runnable(){
public void run(){
handleMessageOnEventDispatcherThread(msg);
}
};
if(SwingUtilities.isEventDispatcherThread()){
doRun.run();
} else {
SwingUtilities.invokeLater(doRun);
}
}
}
So you have only one public method on your GUI, which handles all the EdT stuff.
If you want to have a loose coupling between the GUI and the other components (meaning : you do not want the GUI to know all the API of the other components), the GuiController could also publish ActionMessage (on a specific Thread?), which would be dispatched by the mediator to the other components.
Hope it helps.
Well, I will change the world you are working with. You have 3 classes and each of them is just observer of the chat-world. The MVC is the way how to deal with your problem. You had to create Model for your world, in this case chat program. This model will store data, chat queue, friend list and keep eye on consistency and notify everybody interested about changes. Also, there will be several observers which are interested in state of world and are reflecting its state to user and server. The GUI is bringing visualization to friends-list and message queue and reacts on their changes. The Scheduler is looking about changes in scheduled tasks and update model with their results. The ChatManager will be better doing its job in several classes like SessionManager, MessageDispatcher, MessageAcceptor etc. You have 3 classes with empty center. Create center and connect them together using this center and Observer Pattern. Then each class will deal only with one class and only with interesting events. One GUI class is bad idea. Divide to more subclasses representing logical group (view of model). This is the way how to conquer your UI.
You might want to look at a project that originally started as a MVC framework for Flex development. PureMVC has been ported to many programming languages meanwhile, including Java. Though it is only in a alpha status as of writing this!