Design pattern to process events - java

I am trying to understand the most suitable (Java) design pattern to use to process a series of messages. Each message includes a "type" which determines how the data contained in the message should be processed.
I have been considering the Command pattern, but are struggling to understand the roles/relevance of the specific Command classes. So far, I have determined that the receiver will contain the code that implements the message processing methods. Concrete commands would be instantiated based on message type. However, I have no idea how the actual message data should be passed. Should it be passed to the receiver constructor with the appropriate receiver methods being called by the concrete command execute method? Maybe the message data should be passed in the receiver action method invocations?
I am fairly new to all of this so any guidance would be appreciated.
This may help:
public interface Command {
public void execute(String msg);
}
public class AO1Command implements Command {
Receiver rec = new Receiver();
public void execute(String msg) {
rec.admit(msg);
}
}
public class CommandFactory {
public protected CommandFactory () { }
public static Command getInstance(String type) {
if (type.equals("A01")) return new A01Command();
else if (type.equals("A02")) return new A02Command();
else {
return null;
}
}

Ok, your title says a pattern for handling events. If you are talking about an actual event framework, then the Observer/Observable pattern comes to mind. This would work when you want do fire an event of some type, then have event handlers pick up the processing of the events.
Seems like your problem is in the implementation details of the command pattern. Can you post some code that shows where you are stuck?
Note that patterns are not mutually exclusive, you could use the command pattern in the context of the Observable pattern.
EDIT -- based on your code, you should
1) make the CommandFactory static.
2) pass the type to the getCommand method, which should also be static.
3) You don't need reflection for this, you can simply do
if (type == "type1") return new Command1();
else if (type == "type2") return new Command2();
...
Im not saying you can't use reflection, I'm saying its overcomplicating what you are trying to do. Plus, they way you are doing it binds the the String that represents the message type to the implementation details of the command class names, which seems unnecessary.

You are on the right track. A Command pattern is the appropriate solution to the outlined problem.
To answer your question, you would have your CommandFactory instantiate an appropriate Command instance based on the data differentiator (in this case some data in your message). You would then invoke a method on the Command instance, passing in your message. It is common (best) practice to call this method Execute(...), but you can call it whatever you want.

You may want to take a look to the Jakarta Digester project (to process XML), it has a SAX implementation, wich is an event based API as explained here http://www.saxproject.org/event.html, it's a short explanation but could serve as a starting point for you.

Related

Identification of a service

Service interface:
public interface UserInterface {
void present();
void onStart();
void onStop();
}
I have two implementations: TextUserInterface and GraphicalUserInterface.
How can I identify the one I want to use when I launch my program? Source
private static void main(String[] args) {
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.? //what to do to identify the one I want to use?
}
I was thinking of introducing an enum with the type of UI, so I could just iterate through all services and pick the one I'd like to, but isn't this approach just a misuse of services? In this case when I want to pick GraphicalUserInterface I could just skip the ServiceLoader part and just instantiate one. The only difference I see is fact that without services, I'd have to require the GraphicalUserInterface module, which "kind of" breaks the encapsulation.
I don't actually think that it would be a misuse of it. As a matter of fact, what you get from ServiceLoader.load(...) method is an Iteratable object, and if you need for a specific service, you will have to iterate through all the available instances.
The idea of the enum is not that bad, but I suggest that you take advantage of the Java stream and filter for the instance you need. For example, you might have something like that:
enum UserInterfaceType {
TEXT_UI, GRAPH_UI;
}
public interface UserInterface {
UserInterfaceType getTypeUI();
...
}
// In your main method
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.steam()
.filter(p -> p->getTypeUI() == <TypeUIyouNeed> )
.findFirst()
.get();
That is open to a number of possibilities, for example you can put this is a separated method, which receives in input a UserInterfaceType value, and it can retrieve the service implementation based on the type enum value you passed.
As I said, that is just the main idea, but definitely you are not doing any misuse of the ServiceLoader.

Bridge Pattern applied to messaging API

I wish to have the bridge pattern applied for a project, basically I want this project to be able to trigger requests towards multiple different channels.
Example, I want to create messages which can be SMSs, E-mails or Viber for example... Obviously each of them is a message, but each with some different things, and so I wanted to have the Bridge applied there.
Is the bridge pattern the right one? If yes, how can it be implemented? In case another one should be used, also, please let me know how to use it in this context.
Thank you!
DISCLAMER This example is built from my understanding of the bridge pattern. If you feel like I'm not giving an appropriate definition, please let me know and I will happily remove it.
Bridge pattern is a good guess, but not for your objects. You can simply use polymorphism to create an Abstract Message class. This class could be extend in all of your specific objects.
public abstract class Message {
/* ... */
}
public class SmsMessage extends Message {
/* ... */
}
Where the bridge pattern could be useful is when you want to actually send the message. Chances are you are going to need different protocol to send different message so implementing a bridge pattern is a good idea.
The benefit of the bridge pattern is to generalize some classes, that way, if you need to add a new type of those classes, the code that uses it doesn't change.
Lets say your sending logic is tangle into a 3000 line class and that each time you want to send a message, you need to check what type of message it is, to send via the correct protocol. Well, adding a new message type, like FlyingPigeonMessage would be a real pain, since you need to replace every code that check what message to send.
On the other hand, if your 3000 line classes never know what TYPE of message they are, only that they are MESSAGEs, they adding a new type is a walk in the park. With that in mind, here is a simple implementation of the bridge pattern.
First, we need to define our bridge. In our case, it can be an interface that implements a simple method send.
public interface IMessageProvider {
public void send(Message message)
}
We then need to create different implementation of that Interface, one for each type of message. Here I'm only going to build the SMS class because this is an example.
public class SmsMessageProvider implements IMessageProvider {
#override
public void send(Message message) {
/* call a sms service or somehting... */
}
}
Once we have multiple providers, we need a way to instanciate them depending on a given condition. I like to use factories for that, you can pass it an object and depending on it's type, you get a specific implementation.
/**
* Creates message providers.
*/
public class MessageProviderFactory {
public static IMessageProvider getProviderForMessage(Message message) {
// we return an implementation of IMessageProbvider depending on the type of message.
if(message instanceOf SmsMessage) {
return new SmsMessageProvider();
} else {
// other types of message
}
}
}
Now, we have a bridge interface, we have implementations and we have a factory. All we need is to send the message. The beauty of the bridge pattern is that the function that call the send methods doesn't need to know exactly what object it has. Which make it way easier to maintain.
public class Application() {
public static void main(String[] args) {
Message message;
Boolean isSendingSMS = true; // user prefer sms over email
// we build the message depending on the config.
if(isSendingSMS) {
message = new SmsMessage("my awesome message");
} else {
/* ... */
}
// will send the message we built.
Application.sendMessage(message);
}
public static void sendMessage(Message message) {
// for a given message, we retreive the appropriate provider
IMessageProvider provider = MessageProviderFactory.getProviderForMessage(message);
// using this provider we send the message
provider.send(message);
}
}
In the end, we end up sending a message via the correct provider without having to actually know what provider it was. We used the bridge pattern to build the provider and simple polymorphism to build our object.
NOTE I havn't done Java in a long time, this code might not be syntaxically valid but I hope it provide a good example.

How does the Command pattern decouple the sender from the receiver?

The Command pattern has an IReceiver interface with few methods and corresponding to each method there are concrete Command objects (implementing an interface ICommand with execute() method).
I have read that the client knows about the concrete receiver and concrete command and it is usually the client setting up the receiver object in the concrete command object. Then why it is said it decouples the sender and the receiver?
When the client already knows the concrete receiver then I feel this is not loose coupling and also the client in this case can directly call the APIs (methods) on the receiver object.
You can think of Command pattern workflow as follows.
Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation.
The Receiver has the knowledge of what to do to carry out the request.
The Invoker holds a command and can get the Command to execute a request by calling the execute method.
The Client creates ConcreteCommands and sets a Receiver for the command.
The ConcreteCommand defines a binding between the action and the receiver.
When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.
Have a look at sample code to understand things in better way.
public class CommandDemoEx{
public static void main(String args[]){
// On command for TV with same invoker
Receiver r = new TV();
Command onCommand = new OnCommand(r);
Invoker invoker = new Invoker(onCommand);
invoker.execute();
// On command for DVDPlayer with same invoker
r = new DVDPlayer();
onCommand = new OnCommand(r);
invoker = new Invoker(onCommand);
invoker.execute();
}
}
interface Command {
public void execute();
}
class Receiver {
public void switchOn(){
System.out.println("Switch on from:"+this.getClass().getSimpleName());
}
}
class OnCommand implements Command{
private Receiver receiver;
public OnCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute(){
receiver.switchOn();
}
}
class Invoker {
public Command command;
public Invoker(Command c){
this.command=c;
}
public void execute(){
this.command.execute();
}
}
class TV extends Receiver{
public TV(){
}
public String toString(){
return this.getClass().getSimpleName();
}
}
class DVDPlayer extends Receiver{
public DVDPlayer(){
}
public String toString(){
return this.getClass().getSimpleName();
}
}
output:
java CommandDemoEx
Switch on from:TV
Switch on from:DVDPlayer
To answer your question :
I have read client knows about the concrete receiver and concrete command and it is usually client setting up the receiver object in the concrete command object. Then why it is said it decouples the sender and the receiver
To standardize the words, replace "sender" with "invoker". Now go through the code.
Invoker simply executes the ConcreteCommand (OnCommand in this case) by passing ConcreteReceiver.
ConcreteCommand executes Command through ConcreteReceiver i.e. ConcreteCommand defines binding between Action and Receiver.
If you see the workflow, Invoker does not change with additional commands and you can add business logic in execute() method of Invoker like java.lang.Thread, which has been explained as below.
In this way Client (sender) and Receiver are loosely couple through Invoker, which has knowledge of what command to be executed.
Thread example from this link
You can create Thread by implementing Runnable object.
Thread t = new Thread (new MyRunnable()).start();
=>
Invoker invoker = new Invoker(new ConcreteCommand());
invoker.start()
and you have logic in start() to call ConcreteCommand.execute() which is run() in above case.
start() method will call run() method in Thread. What happens if you directly call run() method directly? It won't be treated as thread.
Like start() method of this thread, you can add some business logic in Invoker.
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
private native void start0(); // Native code is not here but this method will call run() method
public void run() {
if (target != null) {
target.run();
}
}
EDIT:
On your last query
Here we are creating the command object, Receiver object and Invoker Object.Then passing the receiver object in the command object and then passing the command object in invoker object. This we do for each Receiver like we do here for TV and DVDPlayer. Also in the method 'main' Object of TV and DVDPlayer are known and in fact are created. We can simply do tvObject.switchOn() and dvdPlayer.switchOn(). How does Command pattern help
Client need not worry about changes in Receiver class. Invoker directly works on ConcreteCommand, which has Receiver object. Receiver object may change siwtchOn() to switchOnDevice() in future. But client interaction does not change.
If you have two different commands like switchOn() and switchOff(), still you can use same Invoker.
Directly from Wikipedia:
The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.
Edit
After re-reading the Gang of Four's section on the Command pattern, I thought up a better scenario. Let's say you have a GUI library, which defines the following:
public interface Command {
public void execute();
}
public class Button {
private Command command;
public Button(Command command) {
this.command = command;
}
public void click() {
command.execute();
}
}
The Button, in this case, is the receiver of a command, and your code, that creates actual instances of Buttons, is the client. Of course, when you create a button, you have to define some concrete implementations of the Command interface. But the GUI library does not need to know about these classes; all it needs is the interface. This is how the GUI code is decoupled from your code.
Loose coupling isn't the main goal of Command
Here's the class diagram for the Command pattern from the original Design Patterns book:
As you said, Client knows about the ConcreteCommand and the Receiver, so there's not decoupling there.
why it is said it decouples the sender and the receiver
My copy of the book doesn't say that's the goal of the Command pattern:
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Andrew's answer touches on the fact that the logic thread is decoupled from the commands. You can maybe better see the loose coupling between Invoker and Command when you refer to the sequence diagram of the pattern described in the Design Patterns:
Many design patterns define a Client that is loosely coupled from the variations (e.g., Visitor, Strategy, Observer, Iterator, etc.). Loose coupling is a benefit to maintainability, so-called design for change. Command is special, since the Client who's protected from changes is Invoker -- it is decoupled from ConcreteCommmand classes. I think that's the classic decoupling you're looking for. Adding new commands will require changing the Client, but shouldn't break Invoker, who only knows the Command abstraction.
I have always thought of the Command pattern as unique, because its main goal seems to be about providing functional requirements: undo, redo, logging, macro-command operations, transactions, etc.
Edit
Regarding IReceiver abstraction and decoupling from Client and concrete Receiver classes: that is possibly just the Strategy pattern being used with Command. I quoted the original book. Lots of variants of patterns exist (Wikipedia is not always a great reference for patterns because of this).

Handling Objects coming from RMI server and delegating to objects in the client

I am creating a instant chat application using RMI. The server sends through certain objects which I need the client to handle.
For example the server will send a JoinedGroupOperation class. In my client application I need to recognise the class and let my handler take over (HandleJoinedGroupOperation). This class will do a bunch of stuff on the client side.
My question is how can I handle classes that come from the server so I don't need to do any if statements? ie
if(server.getResponse() instanceof JoinedGroupOperation){
HandleJoinedGroupOperation handle = new HandleJoinedGroupOperation();
handle.foo();
}
One of the possible option in your case is to use chain of responsibility design patern.
You should create some abstraction of your possible handlers(like HandleJoinedGroupOperation), then link those handlers(preferebly at start time). As a example, create an interface
interface OperationHandler {
void handle(Operation op);
}
where Operation is also a basic type for all possible operations. This type(Operation) can contain a field of enum type OperationType:
enum OperationType {
...
}
Then in the concrete handlers you can simply check this field(although it will contain if statement, but those statements will be encapsulated in each specific handler)
As a simple example, here is a default implementation of a handler
class SimpleHandler implements OperationHandler {
private OperationHandler next;
public void handle(Operation op) {
if (op.getType() == OperationType.SOMEYOURTYPE) {
//do some stuff
} else {
next.handle(op);
}
}
}
In this case your server.getResponse() method simply will return basic type of Operation hierarchy
Also read the article to get more information

Is getMethod on form value safe?

recently I found a function like this in a generic JSR245 portlet class:
public class MyGenericPortlet extends GenericPortlet {
#Override
public void processAction(ActionRequest rq, ActionResponse rs) throws PortletException{
String actParam = rq.getParameter("myAction");
if( (actParam != null) && (!("").equals(actParam))) {
try{
Method m = this.getClass().getMethod(actParam, new Class[]{ActionRequest.class, ActionResponse.class});
m.invoke(this, new Object[]{rq, rs});
}
catch(Exception e){
setRequestAttribute(rq.getPortletSession(),"error", "Error in method:"+action);
e.printStackTrace();
}
}
else setRequestAttribute(rq.getPortletSession(),"error", "Error in method:"+action);
}
}
How safe is such code? As far as I can see the following problems might occur:
A parameter transmitted from the client is used unchecked to call a function. This allows anyone who can transmit data to the corresponding portlet to call any matching function. on the other hand the function to be called must have a specific interface. Usually such functions are very rare.
A programmer might accidentaly add a function with a corresponding interface. As only public functions seem to be found this is no problem as long as the function is private or protected.
The error message can reveal information about the software to the client. This shouldn't be a problem as the software itself is Open Source.
Obviously there is some room for programming errors that can be exploited. Are there other unwanted side effects that might occur? How should I (or the developers) judge the risk that comes from this function?
If you think it is safe, I'd like to know why.
The fact that only public methods with a specific signature can be invoked remotely is good. However, it could be made more secure by, for example, requiring a special annotation on action methods. This would indicate the developer specifically intended the method to be an invokable action.
A realistic scenario where the current implementation could be dangerous is when the developer adds an action that validates that the information in the request is safe, then passes the request and response to another method for actual processing. If an attacker could learn the name of the delegate method, he could invoke it directly, bypassing the parameter safety validation.

Categories

Resources