I am working on an application which has REST endpoints and for a Get-By-ID service, I am populating a resource (basically a POJO) by collecting data from the persistent store. Now, before sending the response back, I have to populate the HREF in the POJO resource. I want to do it in a generic way so that various other REST services (search etc.) can use it. I want to do this HREF population at a common place for reusability purpose. In a nutshell, my resource POJO can go through various massaging layers to have different state changed and finally sent back to the consumer.
Resource POJO --> Massager 1 --> Massager 2 --> Final Massaged POJO
Could someone help me to figure out a design pattern that can fit my problem.
I thought of Decorator pattern, but somehow it does not sail my ship.
~ NN
You could adapt Chain Of Responsability to your needs. Instead of having a series of processing objects which pass your POJO from one to another in case it cannot handle it, you could process your POJO and then pass it further.
abstract class Messager{
private Messager nextMessager;
void setNextMessager(Messager messager){
this.nextMessager = messager;
}
Messager getNextMessager(){
return this.nextMessager;
}
abstract void handle(Pojo pojo);
}
class FooMessager extends Messager{
void handle(Pojo pojo){
//operate on your pojo
if(pojo.getHref == null){
pojo.setHref("broken");
}
if(this.getNextMessager() != null){
this.getNextMessager().handle(pojo);
}
}
}
class BarMessager{
void handle(Pojo pojo){
//operate on your pojo
if(pojo.getHref().contains("broken")){
pojo.setHref(pojo.getHref().replace("broken","fixed"));
}
if(this.getNextMessager() != null){
this.getNextMessager().handle(pojo);
}
}
}
class Pojo{
private String href;
public Pojo() {
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
class Test{
public static void main(String[] args) {
Pojo pojo = new Pojo();
pojo.setHref(null);
Messager foo = new FooMessager();
Messager bar = new BarMessager();
foo.setNextMessager(bar);
foo.handle();
}
}
Even if the previous answers are good and does solve it, I want to propose you additional way if you want to go further. The communication between objects is very common, so a lot of concepts are out there and you can choose the one that fits best for your needs.
The Command pattern can help you with the encapsulation of a request as an object in
collecting data from the persistent store
It'll allow you to parameterize clients with queue or log requests.
The Mediator pattern can define your communication between the Massager 1 --> Massager 2 classes. By doing this it'll encapsulate your objects interaction. Also it promotes loose coupling by keeping objects from referring to each other explicitly, and it'll let you vary their interaction independently.
If you'll deal with how to notify change to Massager 1 --> Massager 2 classes
my resource POJO can go through various massaging layers to have different state changed
than the Observer pattern can define a dependency between your objects so that when one object changes state, all its dependents are notified and updated automatically.
Related
I am developing a client-server application in Java using Websocket. Currently, all the client messages are processed using switch-case as shown below.
#OnMessage
public String onMessage(String unscrambledWord, Session session) {
switch (unscrambledWord) {
case "start":
logger.info("Starting the game by sending first word");
String scrambledWord = WordRepository.getInstance().getRandomWord().getScrambledWord();
session.getUserProperties().put("scrambledWord", scrambledWord);
return scrambledWord;
case "quit":
logger.info("Quitting the game");
try {
session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "Game finished"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
String scrambledWord = (String) session.getUserProperties().get("scrambledWord");
return checkLastWordAndSendANewWord(scrambledWord, unscrambledWord, session);
}
The server has to process more than 50 different requests from client and that results in more than 50 case statements. And in future, I expect it to grow. Is there any better way to process Websocket messages from client? Or, is this how it is usually done?
I read somewhere about the use of hashtable to avoid long switch-case scenario by mapping to function pointers. Is this possible in Java? Or, is there any better solutions?
Thanks.
After a bit of testing and study, I found two alternatives to avoid long switch case scenario.
Anonymous class method (Strategy pattern)
Reflection with Annotations
Using Anonymous Class
Anonymous class method is the norm and following code shows how to implement it. I used Runnable in this example. If more control is required, create a custom interface.
public class ClientMessageHandler {
private final HashMap<String, Runnable> taskList = new HashMap<>();
ClientMessageHandler() {
this.populateTaskList();
}
private void populateTaskList() {
// Populate the map with client request as key
// and the task performing objects as value
taskList.put("action1", new Runnable() {
#Override
public void run() {
// define the action to perform.
}
});
//Populate map with all the tasks
}
public void onMessageReceived(JSONObject clientRequest) throws JSONException {
Runnable taskToExecute = taskList.get(clientRequest.getString("task"));
if (taskToExecute == null)
return;
taskToExecute.run();
}
}
Major drawback of this method is object creation. Say, we have 100 different tasks to perform. This Anonymous class approach will result in creating 100 objects for a single client. Too much object creation is not affordable for my application, where there will be more than 5,000 active concurrent connections. Have a look at this article http://blogs.microsoft.co.il/gilf/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements/
Reflection with Annotation
I really like this approach. I created a custom annotation to represent the tasks performed by methods. There is no overhead of object creation, like in Strategy pattern method, as tasks are performed by a single class.
Annotation
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface TaskAnnotation {
public String value();
}
The code given below maps the client request keys to the methods which process the task. Here, map is instantiated and populated only once.
public static final HashMap<String, Method> taskList = new HashMap<>();
public static void main(String[] args) throws Exception {
// Retrieves declared methods from ClientMessageHandler class
Method[] classMethods = ClientMessageHandler.class.getDeclaredMethods();
for (Method method : classMethods) {
// We will iterate through the declared methods and look for
// the methods annotated with our TaskAnnotation
TaskAnnotation annot = method.getAnnotation(TaskAnnotation.class);
if (annot != null) {
// if a method with TaskAnnotation is found, its annotation
// value is mapped to that method.
taskList.put(annot.value(), method);
}
}
// Start server
}
Now finally, our ClientMessageHandler class looks like the following
public class ClientMessageHandler {
public void onMessageReceived(JSONObject clientRequest) throws JSONException {
// Retrieve the Method corresponding to the task from map
Method method = taskList.get(clientRequest.getString("task"));
if (method == null)
return;
try {
// Invoke the Method for this object, if Method corresponding
// to client request is found
method.invoke(this);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
logger.error(e);
}
}
#TaskAnnotation("task1")
public void processTaskOne() {
}
#TaskAnnotation("task2")
public void processTaskTwo() {
}
// Methods for different tasks, annotated with the corresponding
// clientRequest code
}
Major drawback of this approach is the performance hit. This approach is slow compared to Direct Method calling approach. Moreover, many articles are suggesting to stay away from Reflection, unless we are dealing with dynamic programming.
Read these answers to know more about reflection What is reflection and why is it useful?
Reflection performance related articles
Faster alternatives to Java's reflection
https://dzone.com/articles/the-performance-cost-of-reflection
FINAL RESULT
I continue to use switch statements in my application to avoid any performance hit.
As mentioned in the comments, one of websockets drawback is that you'll to specify the communication protocol yourself. AFAIK, the huge switch is the best option. To improve code readability and maintenance, I'll suggest to use encoders and decoders. Then, your problem becomes: how should I design my messages?
Your game looks like Scrabble. I don't know how to play Scrabble so let's take the example of card game with money. Let's assume you have three types of actions:
Global action (join table, leave table ...)
Money action (place bet, split bet, ...)
Card action (draw card, etc)
Then your messages can look like
public class AbstractAction{
// not relevant for global action but let's put that aside for the example
public abstract void endTurn();
}
public class GlobalAction{
// ...
}
public class MoneyAction{
enum Action{
PLACE_BET, PLACE_MAX_BET, SPLIT_BET, ...;
}
private MoneyAction.Action action;
// ...
}
public class CardAction{
// ...
}
Once your decoder and encoders are properly defined, your switch would be easier to read and easier to maintain. In my project, the code would look like this:
#ServerEndPoint(value = ..., encoders = {...}, decoders = {...})
public class ServerEndPoint{
#OnOpen
public void onOpen(Session session){
// ...
}
#OnClose
public void onClose(Session session){
// ...
}
#OnMessage
public void onMessage(Session session, AbstractAction action){
// I'm checking the class here but you
// can use different check such as a
// specific attribute
if(action instanceof GlobalAction){
// do some stuff
}
else if (action instanceof CardAction){
// do some stuff
}
else if (action instance of MoneyAction){
MoneyAction moneyAction = (MoneyAction) action;
switch(moneyAction.getAction()){
case PLACE_BET:
double betValue = moneyAction.getValue();
// do some stuff here
break;
case SPLIT_BET:
doSomeVeryComplexStuff(moneyAction);
break;
}
}
}
private void doSomeVeryComplexStuff(MoneyAction moneyAction){
// ... do something very complex ...
}
}
I prefer this approach because:
The messages design can leverage your entities design (if you are using JPA behind)
As messages are not plain text anymore but objects, enumerations can be used and enumerations are very powerful in this kind of switch-case situation. With the same logic but in a lesser extend, class abstraction can be useful as well
The ServerEndPoint class only handles communication. The business logic is handled out of this class, either directly in Messages classes or in some EJB. Because of this split, code maintenance is much easier
Bonus: #OnMessage method can be read as a summary of the protocol but details should not be displayed here. Each case must contain few lines only.
I prefer avoid using Reflection: it'll ruin your code readability, in the specific scenario of websocket
To go further beyond code readability, maintenance and efficiency, you can use a SessionHandler to intercept some CDI event if this can improve your code. I gave an example in this answer. If you need a more advanced example, Oracle provides a great tutorial about it. It might help you to improve your code.
Our application is getting complex, it has mainly 3 flow and have to process based on one of the 3 type. Many of these functionalities overlap each other.
So currently code is fully of if-else statements, it is all messed up and not organised. How to make a pattern so that 3 flows are clearly separated from each other but making use of power of re-usability.
Please provide some thoughts, this is a MVC application, where we need to produce and consume web servicees using jaxb technology.
May be you can view the application as a single object as input on which different strategies needs to be implemented based on runtime value.
You did not specify what your if-else statements are doing. Say they filtering depending on some value.
If I understand your question correctly, you want to look at Factory Pattern.
This is a clean approach, easy to maintain and produces readable code. Adding or removing a Filter is also easy, Just remove the class and remove it from FilterFactory hashmap.
Create an Interface : Filter
public interface Filter {
void Filter();
}
Create a Factory which returns correct Filter according to your value. Instead of your if-else now you can just use the following :
Filter filter = FilterFactory.getFilter(value);
filter.filter();
One common way to write FilterFactory is using a HashMap inside it.
public class FilterFactory{
static HashMap<Integer, Filter> filterMap;
static{
filterMap = new HashMap<>();
filterMap.put(0,new Filter0());
...
}
// this function will change depending on your needs
public Filter getFilter(int value){
return filterMap.get(value);
}
}
Create your three(in your case) Filters like this: (With meaningful names though)
public class Filter0 implements Filter {
public void filter(){
//do something
}
}
NOTE: As you want to reuse some methods, create a FilterUtility class and make all your filters extend this class so that you can use all the functions without rewriting them.
Your question is very broad and almost impossible to answer without some description or overview of the structure of your application. However, I've been in a similar situation and this is the approach I took:
Replace conditions with Polymorphism where possible
it has mainly 3 flow and have to process based on this one of the 3
type. Many of these functionalities overlap each other.
You say your project has 3 main flows and that much of the code overlaps each other. This sounds to me like a strategy pattern:
You declare an interface that defines the tasks performed by a Flow.
public interface Flow{
public Data getData();
public Error validateData();
public void saveData();
public Error gotoNextStep();
}
You create an abstract class that provides implementation that is common to all 3 flows. (methods in this abstract class don't have to be final, but you definitely want to consider it carefully.)
public abstract class AbstractFlow{
private FlowManager flowManager
public AbstractFlow(FlowManager fm){
flowManager = fm;
}
public final void saveData(){
Data data = getData();
saveDataAsXMl(data);
}
public final Error gotoNextStep(){
Error error = validateData();
if(error != null){
return error;
}
saveData();
fm.gotoNextStep();
return null;
}
}
Finally, you create 3 concrete classes that extend from the abstract class and define concrete implementation for the given flow.
public class BankDetailsFlow extends AbstractFlow{
public BankDetailsData getData(){
BankDetailsData data = new BankDetailsData();
data.setSwiftCode(/*get swift code somehow*/);
return data;
}
public Error validateData(){
BankDetailsData data = getData();
return validate(data);
}
public void onFormSubmitted(){
Error error = gotoNextStep();
if(error != null){
handleError(error);
}
}
}
Lets take example, suppose you have model say "Data" [which has some attributes and getters,setters, optional methods].In context of Mobile application ,in particular Android application there can be two modes Off-line or On-line. If device is connected to network , data is sent to network else stored to local database of device.
In procedural way someone can , define two models as OnlineData,OfflineData and write code as[The code is not exact ,its just like pseudo code ]:
if(Connection.isConnected()){
OnlineData ond=new OnlineData();
ond.save();//save is called which stores data on server using HTTP.
}
else{
OfflineData ofd=new Onlinedata();
ofd.save();//save is called which stores data in local database
}
A good approach to implement this is using OOPS principles :
Program to interface not Implementation
Lets see How to DO THIS.
I am just writing code snippets that will be more effectively represent what I mean.The snippets are as follows:
public interface Model {
long save();//save method
//other methods .....
}
public class OnlineData extends Model {
//attributes
public long save(){
//on-line implementation of save method for Data model
}
//implementation of other methods.
}
public class OfflineData extends Model {
//attributes
public long save(){
//off-line implementation of save method for Data model
}
//implementation of other methods.
}
public class ObjectFactory{
public static Model getDataObject(){
if(Connection.isConnected())
return new OnlineData();
else
return new OfflineData();
}
}
and Here is code that your client class should use:
public class ClientClass{
public void someMethod(){
Model model=ObjectFactory.getDataObject();
model.save();// here polymorphism plays role...
}
}
Also this follows:
Single Responsibility Principle [SRP]
because On-line and Off-line are two different responsibilities which we can be able to integrate in Single save() using if-else statement.
After loong time I find opensource rule engine frameworks like "drools" is a great alternative to fit my requirement.
I have a "legacy" code that I want to refactor.
The code basically does a remote call to a server and gets back a reply. Then according to the reply executes accordingly.
Example of skeleton of the code:
public Object processResponse(String responseType, Object response) {
if(responseType.equals(CLIENT_REGISTERED)) {
//code
//code ...
}
else if (responseType.equals(CLIENT_ABORTED)) {
//code
//code....
}
else if (responseType.equals(DATA_SPLIT)) {
//code
//code...
}
etc
The problem is that there are many-many if/else branches and the code inside each if is not trivial.
So it becomes hard to maintain.
I was wondering what is that best pattern for this?
One thought I had was to create a single object with method names the same as the responseType and then inside processResponse just using reflection call the method with the same name as the responseType.
This would clean up processResponse but it moves the code to a single object with many/many methods and I think reflection would cause performance issues.
Is there a nice design approach/pattern to clean this up?
Two approaches:
Strategy pattern http://www.dofactory.com/javascript/strategy-design-pattern
Create dictionary, where key is metadata (in your case metadata is responseType) and value is a function.
For example:
Put this in constructor
responses = new HashMap<string, SomeAbstraction>();
responses.Put(CLIENT_REGISTERED, new ImplementationForRegisteredClient());
responses.Put(CLIENT_ABORTED, new ImplementationForAbortedClient());
where ImplementationForRegisteredClient and ImplementationForAbortedClient implement SomeAbstraction
and call this dictionary via
responses.get(responseType).MethodOfYourAbstraction(SomeParams);
If you want to follow the principle of DI, you can inject this Dictionary in your client class.
My first cut would be to replace the if/else if structures with switch/case:
public Object processResponse(String responseType, Object response) {
switch(responseType) {
case CLIENT_REGISTERED: {
//code ...
}
case CLIENT_ABORTED: {
//code....
}
case DATA_SPLIT: {
//code...
}
From there I'd probably extract each block as a method, and from there apply the Strategy pattern. Stop at whatever point feels right.
The case you've describe seems to fit perfectly to the application of Strategy pattern. In particular, you've many variants of an algorithm, i.e. the code executed accordingly to the response of the remote server call.
Implementing the Stategy pattern means that you have to define a class hierachy, such the following:
public interface ResponseProcessor {
public void execute(Context ctx);
}
class ClientRegistered implements ResponseProcessor {
public void execute(Context ctx) {
// Actions corresponding to a client that is registered
// ...
}
}
class ClientAborted implements ResponseProcessor {
public void execute(Context ctx) {
// Actions corresponding to a client aborted
// ...
}
}
// and so on...
The Context type should contain all the information that are needed to execute each 'strategy'. Note that if different strategies share some algorithm pieces, you could also use Templeate Method pattern among them.
You need a factory to create a particular Strategy at runtime. The factory will build a strategy starting from the response received. A possibile implementation should be the one suggested by #Sattar Imamov. The factory will contain the if .. else code.
If strategy classes are not to heavy to build and they don't need any external information at build time, you can also map each strategy to an Enumeration's value.
public enum ResponseType {
CLIENT_REGISTERED(new ClientRegistered()),
CLIENT_ABORTED(new ClientAborted()),
DATA_SPLIT(new DataSplit());
// Processor associated to a response
private ResponseProcessor processor;
private ResponseType(ResponseProcessor processor) {
this.processor = processor;
}
public ResponseProcessor getProcessor() {
return this.processor;
}
}
A legacy Java code-base that I'm currently working with makes use of a notorious framework. It provides me out-of-the-box domain classes in nicely packaged jars. The domain classes are nothing but bags of getters and setters.
This is preventing me from breeding a rich domain model, by extracting the procedural code from static Util classes into their rightful places, i.e. the domain classes themselves. For example, consider the logic within the following method:
public static boolean areFriends(User user1, User user2) {
for (User friend : user1.getFriends()) {
if (friend.equals(user2)) {
return true;
}
}
return false;
}
This could instead be nicely expressed as isFriendOf(User another) in the User class. However, the User class is all locked up. By the way, the framework uses life-cycle methods to pass in the User objects:
//Life-cycle method
public void execute(FrameworkBlob frameworFattyObject) {
...
User user = frameworFattyObject.getUser();
User loggedInUser = getLoggedInUserFromSomewhere();
bool areFriends = BadUtilClass.areFriends(user, loggedInUser);
...
}
Keeping testability in mind, is there a way I could say something like:
bool areFriends = user.isFriendOf(loggedInUser);
Not familiar with the notorious framework. I should comment first but it's too long.
Is it possible to inject something to the Life-cycle method?
For example:
public class AClassIDontKnow {
private DomainModelMapper mapper;//inject this
//Life-cycle method
public void execute(FrameworkBlob frameworFattyObject) {
...
UserDomainModel user = mapper.getUser(frameworFattyObject);
UserDomainModel loggedInUser = getLoggedInUserFromSomewhere();
bool areFriends = user.isFriendOf(loggedInUser);
...
}
}
public class DomainModelMapper {
UserDomainModel getUser(FrameworkBlob frameworFattyObject) {
User userAnemicModel = frameworFattyObject.getUser();
//map the anemicModel to a rich domain model
return ....;
}
}
Therefore the test strategy:
1) DomainModelMapperUnitTest is placed to test the mapping.
2) UserDomainModelUnitTest covers the isFriend(user)
3) Use mock for DomainModelMapper in AClassIDontKnowUnitTest if neccessary.
So, I'm coming up to speed on Jersey and have a "best practice" question. How strict should keep the resources self contained in one file. Should one resource class reference another class if needed?
An example:
I have a Person resource and an Appointment Resource. (ie: /Person/1 & /appointment/12345). I can also do something like /Person/1/Appointments to list all the appointments for person 1.
So, my question is should I implement a method getPersonAppointments() in the Person Resource class, or just someone get a reference to the Appointment resource class and call that method, keeping all the methods which return "Appointments" together.
I don't know that there is a right or a wrong way.
Since an appointment has multiple people, and a person has multiple appointments, the situation is symmetric and you have to pierce the barrier between the Persons and the Appointments.
Your REST API should simplify access to resources. One of the principles of REST is the idea of "Hypermedia as the Engine of Application State," which prefers to direct clients to related resources by their URIs so that the client doesn't need to know about how to construct URIs to certain resources a priori.
More information on that here: http://en.wikipedia.org/wiki/HATEOAS
The request to /person/1 should return information about that person, including a collection of appointment URIs. The client can then request any of those URIs to get information about each of those appointments. Implementing /person/1/appointments is redundant.
In your scenario I would put the logic for loading the appointments for person in one Resource and make it accessible from another Resource (in other words delegating the resource, what I'm assuming you doing already). The actual logic is stored in AppointmentService, so you can use it with your getPersonAppointments().
This way you can call it:
/person/1/appointments
/appointments?personId=1
Both resulting into same Response.
This is maybe not the best practise, but the logic is in one place and makes it more readable and reusable.
#Path("person")
public class PersonResource {
#GET
#Path("{personId: [0-9]+}/appointments")
public AppointmentsResource loadAppointmentsForPerson(#PathParam("personId") Long personId) {
return new AppointmentsResource(personId);
}
}
#Path("apointments")
class AppointmentResource {
private AppointmentService service;
private Long personId;
public AppointmentResource() {
}
public AppointmentResource(Long personId) {
this.personId = personId;
}
#GET
public Response loadAppointmentsForPerson(#QueryParam("personId") Long personId) {
Long personIdToUse = null;
if (this.personId != null) {
personIdToUse = this.personId;
} else if (personId != null) {
personIdToUse = personId;
} else {
//no input, bad request
}
List<Appointment> appointments = service.getPersonAppointments(personIdToUse)
//create your response from appointments
}
}
Of course in your AppointmentResource, you'll then have another stuff, like loading the appointment by specific ID.