How to handle server side event dispatching and handling in Java? - java

I'm working on a web based application which uses java servlets for RPC calls.
I'm looking for a good way of dispatching and handling events on the server. In a PHP application I'm familiar with using Symfony's EventDispatcher class for adding event listeners and dispatching events, but I'm having a hard time finding something comparable in Java as most stuff I can find is about dealing with UI events and I'm wanting to both listen for and fire events on the server.
I'd also like the actual event handling to happen asynchronously on a separate thread or something so that, for example, an API call to handle adding a payment can do what's necessary, fire and event, and return immediately, even though the event might trigger some more time intensive stuff like sending emails or contacting a partner to inform them of the new balance.
Would I be best off just implementing this myself using my own event interfaces, ExecutorService/Runnable and Observer or Publish/Subscribe patterns? Or are there existing libraries (or built in features I don't know about) for doing some of this for me?
Thank you!

Related

Java - Swing UI separate socket logic

I become desperate, I develop a simple multi-user chat in Java based on the client-server principle. I already wrote a basic multi-threaded server application and it works great. My problem is the client on the basis of the Swing GUI Toolkit. A basic UI with a runtime loop for receiving messages in the background. My problem is that I want to separate the socket logic from the UI, this means that in the best case I've two different classes one for the socket runtime loop and another to manage the UI. Because of the problem, that the runtime loop must notify/add messages to the UI, they depend on each other.
MessengerView is my main class which contains the swing ui and all depended components. At the moment this class contains also the socket logic, but I want to extract them to an external class.
ClientRuntime the class which should hold the socket logic...
My question is, how could I separate them and how could I connect them? For example I tried swing-like events with registering of methods like this:
addListener(MessageArrivedListener listener);
emitMessageArrivedEvent(String message);
The problem is, that it is very confusing if the count of events raises! As already said my second options is to hold socket logic and ui design in one class, but I think it's a bad idea because it makes it very hard to write unit tests for it or to find bugs...
In my time with C++ I used sometimes friend-classes for this issue, because this makes it possible to access class members of other classes! But this solution is often also very confusing and I found no such option for Java.
So are there any other possibilities to hold the connection between the swing widgets and the socket logic, without storing them in the same class (file)?
how could I separate them and how could I connect them?
Connect them with BlockingQueue - this the first choice when choosing ways to connect threads.
ClientRuntime class must start 2 threads: one takes requests from the blocking queue and sends them to the server, and the second constantly reads the messages from the server through the socket and sends them to the UI thread. The UI thread has already input blocking queue for messages: it is accessed by SwingUtilities.invokeLater(Runnable);. The ClientRuntime class does not access UI queue directly: it calls a method from MessengerView and passes what it received from the socket, a binary array or json string, and that UI method converts it to some Runnable which actually updates the UI.
they depend on each other
Well, they don't really. The "socket" layer only cares about been started, running, posting some messages and stopping.
How all that actually get done/handled it doesn't care about, it just "starts" when told, processes input/output messages, posts notifications and "stops" when asked to.
This is basically an observer pattern, or if you prefer, a producer/consumer pattern.
So the socket layer needs to define a "protocol" of behaviour or contract that it's willing to work with. Part of that contract will be "how" it generates notifications about new messages, either via an observer or perhaps through a blocking/readonly queue - that's up to you to decide.
As for the UI, it's a little more complicated, as Swing is single threaded, so you should not block the UI with long running or blocking operations. This is where something like a SwingWorker would come in handy.
It basically acts a broker between the UI and the mechanism made available by the socket layer to receive messages. Messages come from the socket layer into the SwingWorker, the SwingWorker then publishes them onto the UI's event thread which can then be safely updated onto the UI
Maybe start with Concurrency in Swing and Worker Threads and SwingWorker
My question is, how could I separate them and how could I connect them? For example I tried swing-like events with registering of methods like this:
The problem is, that it is very confusing if the count of events raises!
I don't think so (IMHO). What you want to do is focus on the "class" of events. For example, from the above, you have "life cycle" events and you have "message" events. I'd start by breaking those down into two separate interfaces, as those interested in "message" events probably aren't that interested in "life cycle" events, this way you can compartmentalise the observers.
The important concept you want to try and get your head around is the proper use of `interfaces to define "contracts", this becomes the "public" view of the implementations, allowing you devise different implementations for different purposes as you ideas change and grow. This decouples the code and allows you to change one portion without adversely affecting other parts of the API

Showing flash messages with Redux on Android

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

Event handling in multithreaded application

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

What are the advantages of using Spring application event publishing?

I work on a web app that uses some Spring Application Event publishing and I was wondering what the advantages of it are? Why not just create a service call for everything that happens in the event handler's onApplicationEvent, and then call that service in place of publishing the event?
One of the advantages to using Spring's event publishing (observer pattern - http://en.wikipedia.org/wiki/Observer_pattern) is that the components are loosely coupled - there is no direct coupling between the publisher and the subscriber. Sure, they both have a dependency on the Spring Event API, but not on each other. This makes it possible to extend the application by adding/removing subscribers without affecting other subscribers (assuming that your subscribers don't depend on each other).
On the other hand, as you might have found, it can make debugging more tricky because it introduces a level of indirection between the source of an event and the overall outcome.
Yes, you can usually replace an event with a direct API call. Using Events are a good fit when:
you might in future need to take more than one independent action when the event occurs
the processing needs to be handed off to another thread to prevent blocking, e.g. sending an email (using a custom ApplicationEventMulticaster).
how the system handles the event, e.g. AuthorizationFailureEvent, does not depend on the outcome of the listeners.
You are writing a library, e.g. Spring Security, and direct API calls are not an option.
In answer to the part of the question that asks why not just create a service call; because someone else has already written the code, documented it and tested it.
Use Cases of Event-based Listener -
TDD becomes very handy(which in turn will eliminate bugs)
Best suited for Single Responsibility pattern (clean code) (Link for reference - https://www.youtube.com/watch?v=h8TWQM6fKNQ)

Java Swing design pattern for complex class interaction

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!

Categories