JAVA Unit Test: Why they can “save” our life?

The Unit Test cases raise the quality of your final product and then you will raise the quality of your reputation

In the last weeks I was working on a JAVA legacy system that needs to add some new features. The contract with the client included a clause that said “the new release should raise the Test Coverage until 70% of the code”.
We discussed about this with my team and several members proposed not “lose” development time in this task and test only the “the happy path” and some simple cases to achieve these value.

After 15 year in IT area I still feel a little heart attack when I hear that. So I took a breath and explained them about the importance to create (always) the proper Unit Test for each line of code that we wrote, write and will write.

Now, I share with you some points and ideas from that discussion. I hope they can help you… and save your life too 🙂

Some Advantages:

  • Automates the test process at the build time (for example when you run the mvn install command) for everyone who works in the project instead run isolated manual tests (that can add human errors or subjective test cases)
  • Makes your code and the application behavior predictable
  • If you did undesired changes (or temporary changes and forgot them) a good Unit Test will fail at the build time as a check-point alarm
  • Helps to find bugs or unexpected behaviors early before QC/QA time: this could help us to save time and a lot of money
  • Helps to avoid the “gold plating” (add unnecessary features)

Some Tips for our development process:

  • For each development task add and estimate the Unit Test write process as an extra task
  • Remember that develop Unit Test cases takes about of 50%-80% of the time estimated for the development tasks (if you estimate 8 hours to write a new feature class probably create the proper Unit Test cases for it take you about 5 or 6 hours)
  • Never subestimate the necessary time to write the Unit Tests
  • Explain to client the importance to create a good Unit Test cases
  • Create the Unit Test cases for each code that you made as a “life routine” (independently of the requirements of the client)
  • If you can use TDD techniques everytime and everywhere (for example, when you write “new” code)
  • Test the happy path, of course, but also write Unit Test cases for all your code: expected behaviors, rare business logic cases, error handling, etc.
  • Check not only the line coverage, verify that all the code branches have the proper Unit Test for each expected behavior: if you receive the user name as String parameter you have to test the behavior of these value when it is valid, non valid, numeric, null, empty, blank, etc. Or if you have an if block with a true-false condition, test the true path but also the false path.
  • Remove the unnecessary code or features
  • Everytime run the cobertura plugin in your IDE (like Eclipse or IntelliJ) or the Maven plugin (mvn cobertura:cobertura) and check the line coverage but also the branch coverage
  • Do the Unit Test more effective with Mock frameworks like Mockito, PowerMock or EasyMock
  • All the Unit Test cases should be documented and should include the scenario to test and the expected result (you can add it to the method’s Javadoc)

Here is a little example about how a Unit Test can work as check-point when we did undesired changes like modify a SQL query for develop purpose and forgot undo the changes.
In this case the developer forgot remove the “DEV” suffix from the table name:

@Repository("SecureDAO")
public class ExampleSecureDAOImpl implements ExampleDAO {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExampleSecureDAOImpl.class);
	
	final static String QUERY_FIND_ALL_SECURE = " SELECT ID, NAME, USER, PASSWORD FROM USERS_DEV WHERE USER = ?";
	
	@Autowired
	DataSource dataSource;
...
}

Instead use “anyString” feature for the query, in the Unit Test case we include (and test) the real query statement:

@RunWith(SpringRunner.class)
public class ExampleSecureDAOImplTest {
	
	// include the query because if you change the query accidentally the test case will fail (it's a good checkpoint)
	final static String QUERY_FIND_ALL_SECURE = " SELECT ID, NAME, USER, PASSWORD FROM USERS WHERE USER = ?";
...
}	

So the Unit Test case will fail because the queries are different… and that’s a good check-point:

Results :

Tests in error:
  ExampleSecureDAOImplTest.findUserInfoByUserWithValidArgumentsShouldReturnAListWithUserInfo:84 ▒ NullPointer

Tests run: 15, Failures: 0, Errors: 1, Skipped: 0

Final notes
I think you should write the Unit Test cases not for the client or to achieve a project requirement. The Unit Test cases are for you and your team. Include and document them as part of your development routine is very important to improve the quality of your code (and the quality of your job) and is a good way to reduce the possibility of bugs and undesired behaviors. Also, a good Unit Test plan could help you to save a lot time (and money) in the future.

And the most important thing: if you raise the quality of your final product you will raise the quality of your reputation!

If you know a better solution for one or more cases or you want to share your best practices with us, please, let me know and I will update this post 🙂

You can visit my public GitHub repository:
https://github.com/Gabotto/

Let me know if you have any problem, comment or new ideas:
WordPress: https://gabelopment.wordpress.com/
Email: gabelopment@gmail.com

Also you can find me at Upwork

See you soon with more development notes…

Use JAVA SQL Parameters and improve your application security

Use parameters in a JAVA SQL Prepared Statement is a good practice for performance reasons but also is good way to improve the security of your application.

Recently I had to do some maintenance tasks in a legacy system. You know, work with code that you didn’t write can be a very interesting experience… or a nightmare…
In this case, I found several issues about code structure, performance and security. But the most important (I think) were related with the queries used by the application: they didn’t use any SQL parameter to perform the select, insert, update and delete operations.

After finish that work I thought “maybe not everybody knows about this, maybe could be a good idea write a sample code”… So, here is a little example about how to use parameters in a JAVA SQL Prepared Statement. Remember: use parameters is a good way, not only to improve the performance (because the statements “are” in the DB cache), also to improve the security of your application.

Of couse, if you know a better solution for one or more cases or you want to share your best practices with us, please, let me know and I will update this post 🙂

Some Notes about Secutiry

  • use POST restful end-points whenever you can
  • return only one object instead a list of objects (for example if you expect the user’s details from a service return an user object instead a list of user objects)
  • validate the input in each method and, if you can, create a common validator class for that
  • check the size the response: if you expect one and only one user’s record, check it before send the response to the client
  • query for the columns of the table instead use *
  • avoid return extra data: if you need user’s name and birth date, only return that
  • avoid hardcode values in your statements: always user SQL parameters
  • avoid store decrypted password in files, tables, etc.
  • avoid return detailed errors to the client: messages with the table name, complete query or expected values for the where clause

Imagine that you have a table with this structure and data:
2017-06-25-Captura-001
And want to create and Restful end-point to get the user’s details.
Also, imagine that you get the data from table without parameters…

Example of Controller Class

package com.example.sample.db.securestmt.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.sample.db.securestmt.dto.ExampleDTO;
import com.example.sample.db.securestmt.service.ExampleService;

/**
 * Handles the request for the example. 
 * @author Gabriel
 *
 */
@RestController
public class ExampleController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExampleController.class);
	
	@Autowired
	ExampleService exampleService;
	
	/**
	 * Gets all configured names.
	 * @return
	 */
	@RequestMapping(path="/user/info", produces= MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> getUserInfo(@RequestParam final String user) {
		LOGGER.info("getUserInfo - start");
		
		ResponseEntity<?> responseEntity = null;
		
		try{
			List<ExampleDTO> users = exampleService.getUserInfo(user);
			responseEntity = ResponseEntity.ok(users);
		} catch (Exception e) {
			responseEntity = ResponseEntity.badRequest().body("ERROR : " + e.getMessage());
		}
		
		LOGGER.info("getUserInfo - end");
		return responseEntity;		
	}	
}

Example of Service Class

package com.example.sample.db.securestmt.service;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.example.sample.db.securestmt.dao.ExampleDAO;
import com.example.sample.db.securestmt.dto.ExampleDTO;

/**
 * Services for the example.
 * @author Gabriel
 *
 */
@Service
public class ExampleService {
	
	@Autowired
	@Qualifier("NonSecureDAO")
	ExampleDAO exampleDAO;
	
	/**
	 * Gets all configured names.
	 * @return
	 * @throws SQLException
	 */
	public List<ExampleDTO> getUserInfo(final String user) throws SQLException {
		return exampleDAO.findUserInfoByUser(user);
	}
}

Example of Unsecured DAO Class

package com.example.sample.db.securestmt.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.example.sample.db.securestmt.dto.ExampleDTO;

@Repository("NonSecureDAO")
public class ExampleNonSecureDAOImpl implements ExampleDAO {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExampleNonSecureDAOImpl.class);
	
	final static String QUERY_FIND_ALL_UNSECURE = " SELECT * FROM USER_TEST WHERE USER = ";
	
	@Autowired
	DataSource dataSource;
	
	public List<ExampleDTO> findUserInfoByUser(final String user) throws SQLException {
		List<ExampleDTO> records = new ArrayList<>();
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		try {
			connection = dataSource.getConnection();
			preparedStatement = connection.prepareStatement(QUERY_FIND_ALL_UNSECURE + "'"+ user +"'");
			resultSet = preparedStatement.executeQuery();
			
			while (resultSet.next()) {
				ExampleDTO dto = new ExampleDTO();
				dto.setId(resultSet.getString(1));
				dto.setName(resultSet.getString(2));
				dto.setUser(resultSet.getString(3));
				dto.setPassword(resultSet.getString(4));
				
				records.add(dto);
			}
			
			return records;
		} catch (SQLException sqle) {
			LOGGER.error("Error performing query: " + QUERY_FIND_ALL_UNSECURE, sqle);
			throw sqle;
		} finally {
			closeSQLObject(resultSet, ResultSet.class.getName());
			closeSQLObject(preparedStatement, PreparedStatement.class.getName());
			closeSQLObject(connection, Connection.class.getName());
		}
	}
	
	/**
	 * Closes the given SQL AutoCloseable object.
	 * @param sqlObject
	 * @param sqlObjectType
	 */
	private void closeSQLObject(final AutoCloseable sqlObject, final String sqlObjectType) {
		try {
			sqlObject.close();
		} catch (Exception e) {
			LOGGER.warn("Exception closing : {}", sqlObjectType);
		}
	}
}

In the “happy path” the application or an user should get the user’s details setting the user parameter as user=[User Value]:
2017-06-25-Captura-002

But if someone tries to check if you have a security hole? Maybe could do something like user=’AND (or another non valid SQL syntax) to get an exception:
2017-06-25-Captura-003

And if you or team return detailed exceptions to the client-side, maybe someone could do something worse… like set add an OR clause with a true condition to get the details from all user in the table: user=’ OR ‘ABC’=’ABC’
2017-06-25-Captura-004

Use parameters in your SQL statements can solve this kind of issues quickly:

Example of Secured DAO Class

package com.example.sample.db.securestmt.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.example.sample.db.securestmt.dto.ExampleDTO;

@Repository("SecureDAO")
public class ExampleSecureDAOImpl implements ExampleDAO {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExampleSecureDAOImpl.class);
	
	final static String QUERY_FIND_ALL_SECURE = " SELECT ID, NAME, USER, PASSWORD FROM USER_TEST WHERE USER = ?";
	
	@Autowired
	DataSource dataSource;
	
	public List<ExampleDTO> findUserInfoByUser(final String user) throws SQLException {
		List<ExampleDTO> records = new ArrayList<>();
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		try {
			connection = dataSource.getConnection();
			preparedStatement = connection.prepareStatement(QUERY_FIND_ALL_SECURE);
			preparedStatement.setString(1, user);
			resultSet = preparedStatement.executeQuery();
			
			while (resultSet.next()) {
				ExampleDTO dto = new ExampleDTO();
				dto.setId(resultSet.getString(1));
				dto.setName(resultSet.getString(2));
				dto.setUser(resultSet.getString(3));
				dto.setPassword(resultSet.getString(4));
				
				records.add(dto);
			}
			
			return records;
		} catch (SQLException sqle) {
			LOGGER.error("Error performing query. Please contact the User Support Service", sqle);
			throw sqle;
		} finally {
			closeSQLObject(resultSet, ResultSet.class.getName());
			closeSQLObject(preparedStatement, PreparedStatement.class.getName());
			closeSQLObject(connection, Connection.class.getName());
		}
	}
	
	/**
	 * Closes the given SQL AutoCloseable object.
	 * @param sqlObject
	 * @param sqlObjectType
	 */
	private void closeSQLObject(final AutoCloseable sqlObject, final String sqlObjectType) {
		try {
			sqlObject.close();
		} catch (Exception e) {
			LOGGER.warn("Exception closing : {}", sqlObjectType);
		}
	}
}

Final notes
Remember: use parameters in your SQL statements can avoid security issues and also improve the performance of your application… and are easier to develop and maintain that the “hardcoded” where conditions! 🙂

You can get the complete code from my public GitHub repository:
https://github.com/Gabotto/SampleDBSecureStatements

Let me know if you have any problem, comment or new ideas:
WordPress: https://gabelopment.wordpress.com/
Email: gabelopment@gmail.com

Also you can find me at Upwork

See you soon with more development notes…

The magic of Interfaces: use JMS to create Queue/Topic producers and consumers

Remove particular implementations and use interfaces (for JMS or other features) improve the independency and flexibility of your application: with a few changes you can change providers, APIs or products without modify your business/main logic

A few week ago I had a requirement to create a message producer for a TIBCO-EMS Topic. It was a very simple task.
The problem started when I needed to test if the sent messages were on the Topic… and I didn’t have access to the Topic’s Admin console.
So I started to research how to create a message producer but also a message consumer. I founded a lot of examples on Internet but most of them depended of the queue/topic implementation and they didn’t use JMS interfaces.
Finally, I created a producer/consumer JAVA program for the TIBCO-EMS implementation. My co-workers found it very useful to test the sent and received messages and asked to me if I could “configure” for IBM-MQ queues.
The original program became in a Spring Boot Application that removes the particular implementations and uses JMS interfaces for several operations. The next step was transform the local project in a Web Application with a very simple (and ugly) interface to test the send, browse/consume and remove operations on different configured topics and queues: the JmsToolkitWeb.
If you found a better solution for one or more feature or you want to share your best practices with us, please, let me know and I will update this post 🙂

Some tips

  • The application uses JAVA JMS interfaces so you don’t depend of the implementation of the queue/topic provider
  • You only need to create a JMS ConnectionFactory Bean using the Connection Factory provided by you selected queue/topic driver
  • You don’t need access to Administrator console to perform operation with the messages
  • Includes Restful End-points for different queue/topic operations
  • Creates initial topic subscribers for the configured topics when the Application starts (you don’t need to create through the Administrator console)
  • Developed with Spring Boot Application 1.5.3.RELEASE version (and also tested with 1.4.2.RELEASE version)
  • Configured by default to use Apache Active-MQ
  • Tested with TIBCO-EMS, IBM-MQ and Apache ActiveMQ providers

Configuration

  • TIBCO-EMS
    • add the Maven dependency to pom.xml
    • create a Bean for the JMS ConnectionFactoring using new com.tibco.tibjms.TibjmsConnectionFactory(url)
    • set the specific values using a JmsTemplate and set the ConnectionFactory to this JmsTemplate
    • instantiate the JmsTemplate to get the ConnectionFactory in your services (for example, use @Autowired annotation)
  • IBM-MQ
    • add the Maven dependency to pom.xml
    • create a Bean for the JMS ConnectionFactoring using new com.ibm.mq.jms.MQConnectionFactory();
    • set the specific values for the MQ Connection Factory
    • instantiate the ConnectionFactory in your services (for example, use @Autowired annotation)
  • Apache Active-MQ
    • add the Maven dependency to pom.xml
    • create a Bean for the JMS ConnectionFactoring using new ActiveMQConnectionFactory();
    • set the specific values for the MQ Connection Factory
    • instantiate the ConnectionFactory in your services (for example, use @Autowired annotation)

Example for ActiveMQ

Add the Maven dependencies

Add the Spring Boot starter test dependency to your pom.xml

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-activemq</artifactId>
		</dependency>

Create a JMS ConnectionFactory Bean

Here you create your Queue/Topic connection using your provider method(s). In the other classes you only use JMS interfaces so if in the future you need to change your provider you only will modify this bean 🙂

package com.example.jms.config;

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * Configuration class for JMS beans.
 * @author Gabriel
 *
 */
@Configuration
@ConfigurationProperties("com.exmaple.jms.config.activemq")
@Profile("default")
public class JmsLocalConfig {

	private String url;
	private String user;
	private String password;
	
	/**
	 * Creates a {@link ConnectionFactory} for your configured JMS provider.
	 * @return
	 */
	@Bean
	public ConnectionFactory createConnectionFactoryBean() {
		ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
		connectionFactory.setBrokerURL(url);
		connectionFactory.setUserName(ActiveMQConnection.DEFAULT_USER); // or connectionFactory.setUserName(user);
		connectionFactory.setPassword(ActiveMQConnection.DEFAULT_PASSWORD); // or connectionFactory.setPassword(password);
		return connectionFactory;
	}
	
	// methods for getters and setters
}	

Create a JMS Queue producer

package com.example.jms.service.queue;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;

import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Services for JMS queues.
 * @author Gabriel
 *
 */
@Service
public class QueueService {

	private static final Logger LOGGER = LoggerFactory.getLogger(QueueService.class);
	
	private static final int RECEIVE_TIME_OUT_MILISECONDS = 5000;
	
	@Autowired
	ConnectionFactory connectionFactory;

	/**
	 * Sends the given message to the given queue code.
	 * @param queueDestinationName
	 * @param message
	 * @return
	 */
	public boolean sendMessageTo(final String queueDestinationName, final String message) {
		LOGGER.info("sendMessageTo - start");
		
		Connection connection = null;
		Session session = null;

		try {
			connection = connectionFactory.createConnection();
			connection.setClientID("SendQueueSample");

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(queueDestinationName);

			session.createProducer(destination).send(session.createTextMessage(message));
			return true;
		} catch (Exception e) {
			LOGGER.error("ERROR : ", e);
			return false;
		} finally {
			closeSession(session);
			closeConnection(connection);
			LOGGER.info("sendMessageTo - end");
		}
	}
}

Create a JMS Topic producer

package com.example.jms.service.topic;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;

import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.jms.enums.ResourcesEnum;

/**
 * Services for topics.
 * @author Gabriel
 *
 */
@Service
public class TopicService {

	private static final Logger LOGGER = LoggerFactory.getLogger(TopicService.class);
	
	private static final String SUBSCRIBER_NAME = "theSubscriber";
	private static final int RECEIVE_TIME_OUT_MILISECONDS = 5000;
	
	private Map<String,String> subscribers = new HashMap<>();
	
	@Autowired
	ConnectionFactory connectionFactory;
	
	/**
	 * Sends the given message to the given topic resource. 
	 * @param topicDestinationName
	 * @param message
	 * @return
	 */
	public boolean sendMessageTo(final String topicDestinationName, final String message) {
        LOGGER.info("sendMessageTo - start");
        
        Connection connection = null;
        Session session = null;
    
        try {
            connection = connectionFactory.createConnection();
            connection.setClientID(topicDestinationName);
            
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Destination destination = session.createTopic(topicDestinationName);            
            
            session.createProducer(destination).send(session.createTextMessage(message));
            
            LOGGER.debug("sendMessageTo - message sent ok to : {}", topicDestinationName);
            LOGGER.debug("sendMessageTo - message sent as    : {}", SUBSCRIBER_NAME);
            LOGGER.debug("sendMessageTo - message body       : {}", message);
            
            return true;
        } catch (Exception e) {
        	LOGGER.error("ERROR", e);
            return false;
        } finally {
            closeSesion(session);
            closeConnection(connection);                        
            LOGGER.info("sendMessageTo - end");
        }
	}
}

Create a JMS Queue consumer

	/**
	 * Removes/Consumes the messages from a given queue resource.
     * Only for test purpose: this feature will be executed through the queue's administrator console.
	 * @param queueDestinationName
	 * @return
	 */
	public boolean removeMessagesFrom(final String queueDestinationName) {
		LOGGER.info("removeMessagesFrom - start");
		
		Connection connection = null;
		Session session = null;
		MessageConsumer messageConsumer = null; 
				
		try {
			connection = connectionFactory.createConnection();
			connection.setClientID("ConsumeQueueSample");
			connection.start();
			
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(queueDestinationName);

			messageConsumer = session.createConsumer(destination);
			Message receivedMessage = messageConsumer.receive(RECEIVE_TIME_OUT_MILISECONDS);

			while (receivedMessage != null) {
				receivedMessage = messageConsumer.receive(RECEIVE_TIME_OUT_MILISECONDS);
			}

			return true;
		} catch (Exception e) {
			LOGGER.error("EROR : ", e);
			return false;
		} finally {
			closeMessageConsumer(messageConsumer);
			closeSession(session);
			closeConnection(connection);
			LOGGER.info("removeMessagesFrom - end");
		}
	}

Create a JMS Topic subscriber

    /**
     * Removes/Consumes the messages from a given topic resource.
     * Only for test purpose: this feature will be executed through the topic's administrator console.
     * @param topicDestinationName
     * @return
     */
	public boolean removeMessagesBySubscriberFrom(final String topicDestinationName) {
		LOGGER.info("removeMessagesBySubscriberFrom - start");
		
        Connection connection = null;
        Session session = null;
        
        try {
            connection = connectionFactory.createConnection();
            connection.setClientID(topicDestinationName);
            connection.start();
            
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic destination = session.createTopic(topicDestinationName);            

            for (String subscriber : subscribers.keySet()) {
            	if (subscribers.get(subscriber).equals(topicDestinationName)) {
                	LOGGER.debug("removeMessagesBySubscriberFrom - topic : {} - subscriber : {}", topicDestinationName, subscriber);
                	
		        	MessageConsumer messageConsumer = session.createDurableSubscriber(destination, subscriber);
		        	Message receivedMessage = messageConsumer.receive(RECEIVE_TIME_OUT_MILISECONDS);
		            
		            while(receivedMessage != null) {
		            	receivedMessage = messageConsumer.receive(RECEIVE_TIME_OUT_MILISECONDS);
		            }
		            
		            closeMessageConsumer(messageConsumer);
            	}
            }
            return true;
        } catch (Exception e) {
        	LOGGER.error("ERROR", e);
            return false;
        } finally {
            closeSesion(session);
            closeConnection(connection);  
            LOGGER.info("removeMessagesBySubscriberFrom - end");
        }
	}

Create a JMS Queue browser

	/**
	 * Browses and gets the messages from the given queue resource.
	 * @param queueDestinationName
	 * @return
	 */
	public Map<String, String> browseMessagesFrom(final String queueDestinationName) {
		LOGGER.info("browseMessagesFrom - start");
		
		Map<String, String> queueMessages = new HashMap<>();
		Connection connection = null;
		Session session = null;
		
		try {
			connection = connectionFactory.createConnection();
			connection.setClientID("BrowseQueueSample");
			connection.start();
			
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Queue destination = session.createQueue(queueDestinationName);

			int elements = 1;

			@SuppressWarnings("unchecked")
			Enumeration<Message> messages = session.createBrowser(destination).getEnumeration();

			while (messages != null && messages.hasMoreElements()) {
				Message message = messages.nextElement();
				String textMessage = ((TextMessage) message).getText();
				queueMessages.put(String.valueOf(elements++), textMessage);
				
				LOGGER.debug("browseMessagesFrom - message : {}", textMessage);
			}
			
			return queueMessages;
		} catch (Exception e) {
			LOGGER.error("ERROR : ", e);
			return queueMessages;
		} finally {
			closeSession(session);
			closeConnection(connection);
			LOGGER.info("browseMessagesFrom - end");
		}
	}

Final notes
Remove particular implementations and use interfaces (for JMS or other features) improve the independency and flexibility of your application: with a few changes you can modify providers, APIs or products without change your busines/main logic.

You can get the complete code from my public GitHub repository:
https://github.com/Gabotto/JmsToolkitWebApplication

Let me know if you have any problem, comment or new ideas:
WordPress: https://gabelopment.wordpress.com/
Email: gabelopment@gmail.com

Also you can find me at Upwork

See you soon with more development notes…