Tag Archives: java

Design Pattern: Command and State together

In this article we will explain two JAVA design patterns:
Command and State.

In the main method we:

  1. first create the light object (aka receiver);
  2. then we check if the light is on or off;
  3. after that we create a light command passing to it the light we’ve just created;
  4. then we create a Remote Control and set the command into it;
  5. in the next step we press the button and we check the light state;
  6. finally, we repeat the process and check the light state again.

So lets start with the  code:

Here we have the client class (the one that have the main method)

package pt.joaobrito.client;

import pt.joaobrito.command.Command;
import pt.joaobrito.command.LightCommand;
import pt.joaobrito.command.invoker.RemoteControl;
import pt.joaobrito.state.receiver.Light;

/**
 * The client object 
 */
public class Client {

    public static void main(String[] args) {
        // receiver
        Light light = new Light();
        
        // prints to the console the current state of the light
        System.out.println("1st state - the light is " + (light.getCurrentState().isOn() ? "ON" : "OFF"));
        
        Command lightsCmd = new LightCommand(light);
        
        //invoker
        RemoteControl remoteControl = new RemoteControl();
        remoteControl.setCommand(lightsCmd);
        
        //switch on
        remoteControl.pressButton();
        System.out.println("2nd state - the light is " + (light.getCurrentState().isOn() ? "ON" : "OFF"));
        
        //switch off
        remoteControl.pressButton();
        System.out.println("3rd state - the light is " + (light.getCurrentState().isOn() ? "ON" : "OFF"));
    }
}

 

The Command Design Pattern implementation
Here we define our Command interface

package pt.joaobrito.command;

public interface Command {
    public void execute();
}

 

This is the remote control class.
Note that in the pressButton method we actually execute the Command passed previously in the set method. Notice that this class has no knowledge at all about the receiver. Instead it just knows that it has a Command and how to interact with it.

package pt.joaobrito.command.invoker;

import pt.joaobrito.command.Command;

/**
 * Invoker
 */
public class RemoteControl {

    private Command command;
    
    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {
        command.execute();
    }
}

 

Here we have the concrete  light command (the implementation of the Command interface). In the execute method we specify what the command really does: in this case with the help of the State Design Pattern we are simply saying to the light to go to the next state.

package pt.joaobrito.command;

import pt.joaobrito.state.receiver.Light;

/**
 * Concrete Command: light command
 */
public class LightCommand implements Command {
    //reference to the light
    private Light light;

    public LightCommand(Light light) {
        this.light = light;
    }

    public void execute() {
        light.switchToNextState();
    }
}

 

The next section is the State Design Pattern part
This is the Light class. From the Command point of view this is the receiver and from the point of view of the state design pattern this is the object that keeps the current state of the light (also known as a wrapper that will be passed to the concrete states).

package pt.joaobrito.state.receiver;

/**
 * This class is responsible to keep the state of the light
 */
public class Light {
    private State currentState;
    
    public Light() {
        // 1st state of light
        currentState = new LightOff();
    }

    public State getCurrentState() {
        return currentState;
    }

    public void setState(State state) {
        currentState = state;
    }

    /**
     * light switch
     */
    public void switchToNextState() {
        currentState.next(this);
    }

}

 

This is the state interface. Notice that here we have two methods that have to be implemented by the classes that implement the state interface.

package pt.joaobrito.state.receiver;

public interface State {
    void next(Light wrapper);
    boolean isOn();
}

 

The next class represents one of the possible state of the light (the concrete state that represents the ON state of the light)

package pt.joaobrito.state.receiver;

/**
 * Receiver
 */
public class LightOn implements State{
    
    @Override
    public void next(Light wrapper) {
        wrapper.setState(new LightOff());
    }

    @Override
    public boolean isOn() {
        return true;
    }
}

 

This is the other possible state (the concrete state that represents the OFF state of the light)

package pt.joaobrito.state.receiver;

/**
 * Receiver
 */
public class LightOff implements State{

    @Override
    public void next(Light wrapper) {
        wrapper.setState(new LightOn());
    }

    @Override
    public boolean isOn() {
        return false;
    }
}

 

And the results:

run:
1st state - the light is OFF
2nd state - the light is ON
3rd state - the light is OFF
BUILD SUCCESSFUL (total time: 0 seconds)

 

And that’s it. Feel free to comment.

Thank you!

Working with nested Maps in JAVA

In this post I will show you a simple and easy way of working with JAVA Maps, more precisely, how to add an element (a.k.a value) to a multi nested maps:

public void addElementToMap(Map<Long, Map<String, Map<Short, List<SomeDto>>>> map, SomeDto dto) {
	
	// get the first inner map
	Map<String, Map<Short, List<SomeDto>>> someMap = map.get(dto.gePrimaryKey());
	
	if(someMap == null){
		someMap = new HashMap<>();
		map.put(dto.gePrimaryKey(), someMap);
	}
	
	
	// get the second inner map
	Map<Short, List<SomeDto>> otherMap = someMap.get(dto.getSomeId());
	
	if(otherMap == null){
		otherMap = new HashMap<>();
		someMap.put(dto.getSomeId(), otherMap);
	}
	
	
	// get the inner list
	List<SomeDto> someList = otherMap.get(dto.getOtherId());
	
	if(someList == null){
		someList = new ArrayList<>();
		otherMap.put(dto.getOtherId()), someList);
	}
	
	// add dto to the list
	someList.add(dto);
}

That’s it. Simple, isn’t it? 😉

Source code: github

Builder Design Pattern

Here is the “usual” implementation of this design pattern.

package pt.joaobrito.builder;

/**
 * This is the main class
 */
public class BuilderExample {

	public static void main(String[] args) {
		Vehicle v1 = new Client(new CarBuilder()).constructVehicle();
		System.out.println(v1);

		Vehicle v2 = new Client(new BikeBuilder()).constructVehicle();
		System.out.println(v2);

		Vehicle v3 = new Client(new CarBuilder()).constructVehicleWithoutWindowsOrSeats();
		System.out.println(v3);

		Vehicle v4 = new Client(new BikeBuilder()).constructVehicleWithoutWindowsOrSeats();
		System.out.println(v4);
	}
}
/**
 * The Client class has the responsability of building the vehicles
 */
class Client {

	private final VehicleBuilder vehicleBuilder;

	public Client(VehicleBuilder vehicleBuilder) {
		this.vehicleBuilder = vehicleBuilder;
	}

	/**
	 * Builds a complete vehicle
	 * @return a vehicle
	 */
	public Vehicle constructVehicle() {
		return vehicleBuilder.buildType().buildSeats().buildWindows().get();
	}

	/**
	 * Builds a vehicle without parts
	 * @return a vehicle
	 */
	public Vehicle constructVehicleWithoutWindowsOrSeats() {
		return vehicleBuilder.buildType().get();
	}
}

/**
 * This class is the abstract builder
 */
abstract class VehicleBuilder {

	protected Vehicle vehicle;

	public VehicleBuilder() {
		this.vehicle = new Vehicle();
	}

	/**
	 * Vehicle get method
	 * @return the vehicle
	 */
	public Vehicle get() {
		return vehicle;
	}

	/**
	 * The 3 following lines are the methods that must be implemented on the concrete builders
	 * @return
	 */
	public abstract VehicleBuilder buildType();
	public abstract VehicleBuilder buildSeats();
	public abstract VehicleBuilder buildWindows();
}

/**
 * This is a concrete builder for Bikes
 */
class BikeBuilder extends VehicleBuilder {

	@Override
	public VehicleBuilder buildType() {
		vehicle.setType("Bike");
		return this;
	}

	@Override
	public VehicleBuilder buildWindows() {
		vehicle.setWindows(0);
		return this;
	}

	@Override
	public VehicleBuilder buildSeats() {
		vehicle.setSeats(2);
		return this;
	}

}

/**
 * This is the concrete builder for Cars
 */
class CarBuilder extends VehicleBuilder {

	@Override
	public VehicleBuilder buildType() {
		vehicle.setType("Car");
		return this;
	}

	@Override
	public VehicleBuilder buildSeats() {
		vehicle.setSeats(5);
		return this;
	}

	@Override
	public VehicleBuilder buildWindows() {
		vehicle.setWindows(4);
		return this;
	}


}

/**
 * This is the vehicle class
 */
class Vehicle {

	private String type;
	private int seats;
	private int windows;

	public void setType(String type) {
		this.type = type;
	}

	public void setSeats(int seats) {
		this.seats = seats;
	}

	public void setWindows(int windows) {
		this.windows = windows;
	}
	
	/**
	 * @return a printable vehicle
	 */
	@Override
	public String toString() {
		return "Vehicle[Type: " + type + "; Seats: " + seats + "; Windows: " + windows + "]";
	}

}

 

The result is:
builder2

UML
builder2_uml

 

 

Builder Design Pattern (simple way)

This design pattern allows us to create an object with the advantage that the same construction process can create different representations of that object. Here is the simplest implementation of this design pattern.

In a next tutorial we will explain the other way of doing the same thing, with more flexibility but with a more complex implementation.

So, let’s start creating a car!

package pt.joaobrito.builder;

/**
 * This is the class that we will create object of
 */
class Car {

	private String brand, model, version;

	/**
	 * This private constructor avoids the user to create the object in the complex way
	 * using the new keyword.
	 */
	private Car() {}

	/**
	 * This method allows us to get the builder of the car without instantiating the car
	 * 
	 * @return the builder instance
	 */
	public static Builder getBuilder() { return new Builder(); }

	public String getBrand() { return this.brand; }

	public String getModel() { return this.model; }

	public String getVersion() { return this.version; }

	/**
	 * This is the printable version of the car
	 * @return a printable car
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("Your new car -> ");
		if (brand != null) { sb.append("brand: " + brand); }
		if (model != null) { sb.append(", model: " + model); }
		if (version != null) { sb.append(", version: " + version); }
		return sb.toString();
	}

	/**
	 * This class is the builder itself.
	 * Notice that in every builder method we always return the builder instance. 
	 * This allows us to continue building more parts of the car in one single line.
	 */
	static final class Builder {

		/**
		 * Here we keep an instance of the car we are building. When finished we return it.
		 */
		private final Car car = new Car();

		/**
		 * This is the method that return the car we previously built (or not)
		 * @return
		 */
		public Car getInstance() { return car.getBrand() == null ? null : car; }

		public Builder buildBrand(String brand) {
			this.car.brand = brand;
			return this;
		}

		public Builder buildModel(String model) {
			this.car.model = model;
			return this;
		}

		public Builder buildVersion(String version) {
			this.car.version = version;
			return this;
		}
	}

}

public class Builder {

	public static void main(String[] args) {
		Car c1 = Car.getBuilder().buildBrand("BMW").buildModel("Serie 5").buildVersion("535d Touring").getInstance();
		Car c2 = Car.getBuilder().buildBrand("VW").buildModel("Passat").getInstance();
		Car c3 = Car.getBuilder().buildModel("Class E").getInstance();
		
		System.out.println(c1);
		System.out.println(c2);
		System.out.println(c3 == null ? "You don't have a car! Please create a car with a brand defined." : c3);
	}
}

 

The final result:

builder

Singleton Design Pattern

With his design patttern we allways get the same instance, as you can see next.

  1. The Singleton class:
package pt.joaobrito.singleton;

public final class Singleton {

	/**
	 * A private constructor. This is necessary in order to not allow create a new Singleton object
	 * from the outside with the keyword new
	 */
	private Singleton() {}

	private static final class SingletonHolder {
		public static final Singleton INSTANCE = new Singleton();
	}

	public static final Singleton getInstance() {
		return SingletonHolder.INSTANCE;
	}
}

 

2. The main class:

package pt.joaobrito.singleton;

public class Main {

	public static void main(String[] args) {
		Singleton s1 = Singleton.getInstance();
		Singleton s2 = Singleton.getInstance();

		// test if the reference are the same
		System.out.println(s1 == s2);
	}

}

 

3. The result:

singleton

 

UML
singleton

Reverse String/array recursively

Here is an example how to recursively invert the order of a string or an array in Java.

package pt.joaobrito;

public class Recursive {

	/**
	 * The main method
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Inverted string: " + reverseString("123456789"));

		System.out.print("Inverted array:  ");
		int[] ra = reverseArray(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9});
		for (int s : ra) {
			System.out.print(s);
		}
		System.out.println("");
	}

	/**
	 * This method inverts the order of the string
	 *
	 * @param s
	 * @return the reverse string
	 */
	public static String reverseString(String s) {
		if (s.length() == 0) {
			return s;
		}
		// recursive call
		return s.substring(s.length() - 1) + reverseString(s.substring(0, s.length() - 1));
	}

	/**
	 * This method inverts the order of the array
	 *
	 * @param array
	 * @return the inverted array
	 */
	public static int[] reverseArray(int[] array) {
		if (array.length <= 1) { // stop condition
			return new int[]{};
		}

		int[] aux = new int[array.length - 2];
		for (int i = 0; i < aux.length; i++) {
			aux[i] = array[i + 1];
		}

		int[] g = reverseArray(aux); // recursive call

		System.arraycopy(g, 0, array, 1, g.length);
		int firstPosition = array[0];
		array[0] = array[array.length - 1];
		array[array.length - 1] = firstPosition;
		return array;
	}

}

The output is:

output

Notice that in the string method we have twice the iterations that we have in the array method, because we go through all positions in the string.

If you know other ways of doing it, please feel free to comment it out.

Thanks.

Decoupling event producers and event consumers in Java EE 6 using CDI and JMS

In this post I will show you how to decouple event producer from the event consumers (aka async events).

  1. you must configure your application server (here the glassfish settings):
  2. call the EJB method sendEvent() to send the event (from a servlet or from a web page):
    @LocalBean
    @Stateless
    public class MyEJB {
    
    	@Inject
    	@InForeground
    	private Event<BaseEvent> event;
    
    	/**
    	 * fires the @InForeground event
    	 *
    	 * @throws InterruptedException
    	 */
    	public void sendEvent() throws InterruptedException {
    		event.fire(new MyEvent("Hello world event", new Date()));
    		Thread.sleep(5000);
    	}
    }
  3. the EJB fires the event anotaded with @InForeground qualifier.
  4. An observer method handle the event and send it to the JMS Queue with the help of a message producer:
    @Stateless
    public class BackgroundEventSender implements BackgroundEventSenderItf {
    
    	@Resource(mappedName = "myConnectionFactory") // the JNDI name for this connection factory
    	private ConnectionFactory connectionFactory;
    
    	@Resource(mappedName = "myQueue") // JNDI name for this queue
    	private Queue backgroundEventQueue;
    
    	private Connection connection;
    	private Session session;
    	private MessageProducer producer;
    
    	@PostConstruct
    	public void init() {
    		try {
    			connection = connectionFactory.createConnection();
    			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    			producer = session.createProducer(backgroundEventQueue);
    		} catch (JMSException ex) {
    			throw new RuntimeException(ex.getMessage(), ex);
    		}
    	}
    
    	@PreDestroy
    	public void destroy() {
    		try {
    			if (connection != null) {
    				connection.close();
    			}
    		} catch (Exception ex) {
    			// todo: handle the exception
    		}
    
    	}
    
    	/**
    	 * sends the foreground event to the queue with the help of the producer object
    	 *
    	 * @param event
    	 */
    	@Override
    	public void event(@Observes @InForeground BaseEvent event) {
    		try {
    			ObjectMessage msg = session.createObjectMessage();
    			msg.setObject(event);
    			producer.send(msg);
    		} catch (JMSException ex) {
    			throw new RuntimeException(ex.getMessage(), ex);
    		}
    
    	}
    
    }
  5. Now, in another (background) thread, the onMessage method handle the message and fires a new event (which wraps the received event) now annotated with @InBackground qualifier:
    @MessageDriven(mappedName = "myQueue", activationConfig = {
    	@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    	@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
    })
    public class BackgroundEventDispatcher implements MessageListener {
    
    	public BackgroundEventDispatcher() {
    	}
    
    	@Inject
    	@InBackground
    	private Event<BaseEvent> event;
    
    	/**
    	 * dispatches the message received from the queue and fires a new event (now with the @InBackground qualifier)
    	 *
    	 * @param message
    	 */
    	public void onMessage(Message message) {
    		if (!(message instanceof ObjectMessage)) {
    			throw new RuntimeException("Invalid message type received");
    		}
    		ObjectMessage msg = (ObjectMessage) message;
    		try {
    			Serializable eventObject = msg.getObject();
    			if (!(eventObject instanceof BaseEvent)) {
    				throw new RuntimeException("Unknown event type received");
    			}
    			BaseEvent evt = (BaseEvent) eventObject;
    			this.event.fire(evt);
    
    		} catch (JMSException ex) {
    			throw new RuntimeException(ex.getMessage(), ex);
    		}
    	}
    }
  6. And finally, if you have a method that consumes events annotated with @InBackground qualifier, then you receive the event and process it accordingly to your business needs.
    @Stateless
    public class EventConsumer implements EventConsumerItf {
    
    	/**
    	 * consumes the event sent by the JMS queue
    	 *
    	 * @param event
    	 */
    	@Override
    	public void afterMyEvent(@Observes @InBackground MyEvent event) {
    		System.out.println("Event message: " + event.getData());
    		System.out.println("Event time: " + new SimpleDateFormat("yyyy.MM.dd @ HH:mm:ss").format(event.getEventTime()));
    	}
    
    }

The event object it’s just a POJO like this one:

public class MyEvent extends BaseEvent {

	private String data;

	private Date eventTime;

	public String getData() {
		return data;
	}

	public MyEvent(String data, Date eventTime) {
		this.data = data;
		this.eventTime = eventTime;
	}

	public void setData(String data) {
		this.data = data;
	}

	public Date getEventTime() {
		return eventTime;
	}

	public void setEventTime(Date eventTime) {
		this.eventTime = eventTime;
	}
}

You can get the full code from github. Thank you!

Feel free to comment.

Simple CDI Events Example

In this post I will show you how to produce a CDI event and how to handle it even if it is deployed in another application.

The Event class

public class LoggerEvent {
	private String message;

	public LoggerEvent(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}
}

A simple JSF Page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>CDI Event Example</title>
    </h:head>
    <h:body>
		<h1>#{controller.message}</h1>
    </h:body>
</html>

This page only shows a simple message from the backing bean (the call to the bean produces the bean’s initialization).

Backing Bean

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class Controller {

	@Inject
	private Event<LoggerEvent> event;

	private String message = "CDI Events Example";

	@PostConstruct
	public void init() {
		event.fire(new LoggerEvent("Hello from CDI events"));
	}

	public String getMessage() {
		return message;
	}
}

Here we Inject an event (LoggerEvent) via CDI Inject annotation. Then inside the init method annotated with PostConstruct we fire the event with a new instance of the event. This is the simplest way to fire a CDI event. No matter who are listening to this event will be notified.

A simple Logger Event Handler

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.enterprise.event.Observes;

@Stateless
public class LoggerEventHandler {

	public void log(@Observes LoggerEvent event) {
		Logger.getLogger("LoggerEventHandler.class").log(Level.INFO, event.getMessage());
	}
}

This class will listen for events annotated with the keyword @Observes. Because of this, it will execute the method. In this case it will print to the console a log message passed to the constructor of the event instance when it was created: Hello from CDI events as you can see in the next picture.

Result (console result)

cdi events
cdi events

AS you can see, it’s just that simple to create a CDi event and listen to it. This technique uses the Observer design pattern here with the help of @Observes annotation.

Feel free to comment. Download the souce code CDIEvents.

Thanks.

Static Binding vs Dynamic Binding in JAVA

package staticbinder;

class Animal {
	static void talk() { System.out.println("Animal doesen't talk!!"); }

	void eat() { System.out.println("Animal eating..."); }
}

class Dog extends Animal {

	static void talk() { System.out.println("Dog barking..."); }

	@Override
	void eat() { System.out.println("Dog eating..."); }
}

public class Main {
	public static void main(String[] args) {
		Animal a = new Dog();

		/* static binding happens in private, final, static and
		 * overloaded methods at compile time
		 */
		a.talk(); // will print: Animal doesen't talk!!

		/* dynamic binding happens in overriding methods at
		 * run time
		 */
		a.eat(); // will print: Dog eating...
	}
}