Sunday, 16 April 2017

Installing NOOBS in SD card

To use Raspberry device, we need NOOBS boot loader to install any IoT Operating system such as Raspbian or Ubuntu mate.

Following are the steps to install the NOOBS in SD card.

1. Insert an SD card that is 4GB or greater in size into your computer.
(Preferred to use SD card adapter or SD Card reader).

2. Format the SD card using the platform-specific instructions below:  (Formatting tool might have only less than 500kb.)
   a. Windows
      i. Download the SD Association's Formatting Tool from SDFormatter windows
      ii. Install and run the Formatting Tool on your machine
      iii. Set "FORMAT SIZE ADJUSTMENT" option to "ON" in the "Options" menu
      iv. Check that the SD card you inserted matches the one selected by the Tool
      v. Click the "Format" button
   b. Mac
      i. Download the SD Association's Formatting Tool from SDFormatter Mac
      ii. Install and run the Formatting Tool on your machine
      iii. Select "Overwrite Format"
      iv. Check that the SD card you inserted matches the one selected by the Tool
      v. Click the "Format" button
   c. Linux
      i. We recommend using gparted (or the command line version parted)
      ii. Format the entire disk as FAT

3. Extract the files contained in this NOOBS zip file.
(You can download NOOBS.zip from the following link.
  NOOBS Latest )

4. Copy the extracted files onto the SD card that you just formatted so that this file is at the root directory of the SD card. Please note that in some cases it may extract the files into a folder, if this is the case then please copy across the files from inside the folder rather than the folder itself.
(You can find these instructions in readme.txt in extracted files)

5. Insert the SD card into your Pi and connect the power supply.


Post Installation instructions :



Your Pi will now boot into NOOBS and should display a list of operating systems that you can choose to install.
(You need to connect to internet to download the Operating system by NOOBS)
If your display remains blank, you should select the correct output mode for your display by pressing one of the following number keys on your keyboard:

1. HDMI mode - this is the default display mode.
2. HDMI safe mode - select this mode if you are using the HDMI connector and cannot see anything on screen when the Pi has booted.
3. Composite PAL mode - select either this mode or composite NTSC mode if you are using the composite RCA video connector.
4. Composite NTSC mode

Thursday, 1 December 2016

MongoDB with Spring framework

As we know, MongoDB is a no-SQL database. Before looking at the example of MongoDB with spring framework, we need to know few things about it.
We can go for mongodb instead of relation databases, when your data is sort of document data which means you just need to open the document, do the changes and save it again, it doesn’t have any relationship among them. we can also have the mongodb when we want to compute user data before accessing it and having it ready to read be the user at anytime which we use to call precomputation.

Before seeing an example, we’ll see how to set up mongodb, 

Command to start the server : 
<mongodb_Home_directory>/bin/mongod --dbpath <mogodb_workspace> &
Default port : 27017
DB client, we used here : Robomongo (version : 0.8.5)

Connected the mongodb server from this Robomongo and created a database named Mine. Inside the database, we can see Collections, Functions and Users. I have create my own collection named studentdocs.

Now we used these connection details and the collection in the below configuration bean. It extended the AbstractMongoConfiguration class from spring and Overrode the methods getDatabaseName and mongo which returns the Database name and the MongoClient respectively. MongoClient object was created from the hostname 127.0.0.1 and port 27017. So now, spring can take care of creating connection and managing it.
@Configuration
public class SpringMongoDBConfig extends AbstractMongoConfiguration {
    @Override
    public String getDatabaseName() {
        return "Mine";
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient("127.0.0.1",27017);
    }
}
Created a Student class and mapped it with the collection studentdocs we created earlier. 
@Document(collection = "studentdocs")
public class Student implements Serializable {
    @Id
    private String studentDocId;
    private String studentId;
    private String studentName;
    private String dob;
    private String contactNo;
    private Address address;
    private StudentCourse studentCourse;
    private Set<MonthAttendance> monthAttendances;
    private Set<Subject> subjects;
//accessors and mutators are here }
Now we had the connection and collection class. We’ll see how to fetch the student records by the contactNo and by the courseId. For this, we created StudentRepository interface which extends another interface CrudRepository of spring framework.
public interface StudentRepository extends CrudRepository<Student, String> {     Iterable<Student> findByContactNo(String contactNo);     Iterable<Student> findByStudentCourseCourseId(String courseId); }
The first method findByContactNo will fetch the student objects which has the contactNo which we pass and return the same. Note that the second method findByStudentCourseCourseId will fetch the student object which has the courseId which we pass. Here, courseId is the property of studentCourse.
CrudRepository has some default methods like save, delete, findAll and etc. We can also use these methods.
Spring framework has the implementation for all these methods. Please see the below service class where we used all these methods.
@Service public class StudentServiceImpl implements StudentService {     @Autowired     private StudentRepository studentRepository;     public Map<String, Iterable<Student>> getStudentsByContactNo(String contactNo) {         Map<String, Iterable<Student>> studentData = new HashMap<String, Iterable<Student>>();         Iterable<Student> iStudent = studentRepository.findByContactNo(contactNo);         studentData.put(contactNo,iStudent);         return studentData;     }     public Map<String, Iterable<Student>> getStudentsByCourseId(String courseId) {         Map<String, Iterable<Student>> studentData = new HashMap<String, Iterable<Student>>();         Iterable<Student> iStudent = studentRepository.findByStudentCourseCourseId(courseId);         studentData.put(courseId,iStudent);         return studentData;     }     public boolean saveContactsProducts(List<Student> students) {         Iterable<Student> resultUserProducts = studentRepository.save(students);         if(null != resultUserProducts)             return true;         return false;     } }
Click here to download this project from GitHub.

Sunday, 27 November 2016

Communication between Backbone Views

There are few ways to communicate between two backbone views and model.
Consider an application contains Menu view and you want to update the application area based on the menu selection.
For example, consider an e-commerce application which contains the following views.
1. MenuView
2. Recharge View
3. Shopping View
4. Book Ticket View

For this the very basic approach or the easiest way is that creating the object for all other three views in MenuView. But by doing this, all views are tightly coupled with one another.
To overcome this we’re going to use Event aggregator pattern. 
Backbone provides Router concept for event aggregator.

In index.html we’ve included all the html templates.

index.html


 


After that, related Backbone view files are created with the basic information.

MenuView.js

var MenuView = Backbone.View.extend({
 
 model : new MenuModel(),
 initialize : function(){
  
 },
 events : {
  
 },
 render : function(){
  var menuTemplate = _.template($('#menu-template').html());
  this.$el.html(menuTemplate(this.model.toJSON()));
  return this;
 }
});


RCView.js

var RCView = Backbone.View.extend({
 el: '#contentArea',
 initialize : function(){
  
 },
 
 events : {
  'click #rcSubmitButton':'doOnRCSubmitButton'
 },
 render : function(){
  var rcTemplate = _.template($('#recharge-template').html());
  this.$el.html(rcTemplate(null));
  return this;
 },
 
 doOnRCSubmitButton : function(){
  alert("RC click!!");
 }
});
As of now, views are containing only the render part which renders the corresponding template into the application area.

We’ve defined three links in the index.html menu area. For every menu item, there are independent actions. The event should be passed to corresponding views without any dependency. For this purpose we’ve created the router in the main.js file. Once the routes and its functions are defined, for all the menu selection it’ll redirected to its route.

main.js

$(document).ready(function(){
 var menuView = new MenuView();
 menuView.setElement($('#menuArea'));
 menuView.render();
 new MyRouter();
 Backbone.history.start();
});

var MyRouter = Backbone.Router.extend({
 routes : {
  "recharge":"onRecharge",
  "bookticket" : "onBookTicket",
  "shop":"whileShopping"
 },

 viewFactory : function(){
  return{
   rcView : typeof rcView == 'undefined' ? new RCView() : rcView,
   ticketView : typeof ticketView == 'undefined' ? new TicketView() : ticketView,
   shopView : typeof shopView == 'undefined' ? new ShopView() : shopView
  };
  
 },
 onRecharge : function(){
  this.viewFactory().rcView.render();
 },
 
 onBookTicket : function(){
  this.viewFactory().ticketView.render();
 },
 
 whileShopping : function(){
  this.viewFactory().shopView.render();
 }
});



You can download this working sample in this Github URL.

Reference for event aggregator pattern :  http://martinfowler.com/eaaDev/EventAggregator.html

Wednesday, 16 November 2016

Spring Singleton vs Prototype

                            Bean scopes will be specified by the scope attribute of the <bean/> element. We will see the example as we go down to this article. Spring bean has 5 different scopes which we listed below,
  1. Singleton
  2. Prototype 
  3. Global
  4. Session
  5. Application
When it comes to standalone application, we don't have the last three scopes that are applicable only for web applications. Here, In this article, we'll just look at the first two, singleton and the prototype.

                            Singleton beans are created by the spring container only once which means you will have only one instance of the bean through out our application. Prototype beans are right opposite to this. It's a multiton bean which means more than one instance can be created. When we call the getBean method of ApplicationContext or inject in other beans, we will get a new instance of it. Let's see this by an example,

ApplicationContext.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

   <bean id="student" class="com.studentact.model.Student" scope="prototype" destroy-method="destroy" init-method="init"/>  

   <bean id="studentDao" class="com.studentact.dao.StudentDaoImpl" destroy-method="destroy" init-method="init">  
     <property name="student" ref="student"/>  
   </bean>  

   <bean id="studentServiceProxy" class="com.studentact.proxy.StudentServiceProxy" init-method="init" destroy-method="destroy">  
     <property name="student" ref="student"/>  
   </bean>  

   <bean id="studentService" class="com.studentact.service.StudentService" destroy-method="destroy" init-method="init">  
      <property name="studentServiceProxy" ref="studentServiceProxy"/>  
      <property name="studentDao" ref="studentDao"/>  
   </bean>  

 </beans>  

We can see that the scope of student bean is specified as prototype and other beans don't have this scope attribute which means they are all singleton.
Let's say StudentServiceProxy's method getVOCTopStudent gets student data from some web service and assign them in student object. Likewise StudentDaoImpl's method getGovtStudent gets the from DB and assign them in student object. StudentService will call these methods and store the return student object in a list as below,

StudentService.java
 public class StudentService implements IStudentService {  
      private IStudentDao studentDao;  
      private IStudentServiceProxy studentServiceProxy;  
      public IStudentDao getStudentDao() {  
           return studentDao;  
      }  
      public void setStudentDao(IStudentDao studentDao) {  
           this.studentDao = studentDao;  
      }  
      public IStudentServiceProxy getStudentServiceProxy() {  
           return studentServiceProxy;  
      }  
      public void setStudentServiceProxy(IStudentServiceProxy studentServiceProxy) {  
           this.studentServiceProxy = studentServiceProxy;  
      }  
      @Override  
      public List<Student> getTopStudents() {  
           List<Student> topStudents = new ArrayList<Student>();  
           topStudents.add(studentDao.getGovtStudent());  
           topStudents.add(studentServiceProxy.getVOCTopStudent());  
           return topStudents;  
      }  
      public void destroy(){  
           System.out.println("detroy method of StudentService");  
      }  
      public void init(){  
           System.out.println("init method of StudentService");  
      }  
      //Other operations go here  
 }  

We can use the below code to test whether the list has same student object or different objects.
 StudentService studentService = (StudentService) applicationContext.getBean("studentService");  
 List<Student> students = studentService.getTopStudents();  
 System.out.println(students);  
 Student aStudent = null;  
 for(Student student:students){  
      if(null == aStudent){  
           aStudent = student;                      
      } else if(student == aStudent) {  
           Assert.assertFalse(true);  
      }  
 }  
We mentioned student bean scope as prototype and injected it in other beans like studentDao and studentServiceProxy. So the resultant list will have different student objects. If it’s a singleton, then both studentDao and studentServiceProxy will have the same object and the resultant list will have the same student objects.

Initialization and destruction:
                            If you assign any method to init-method attribute of bean element, the method will be called after the bean properties is set, but before the bean is completely initialized. We can use this, when we need to initialize something like opening file, creating or checking the database connections. This method will be called by spring container regardless of singleton or prototype beans. 
                            But destroy-method will be called by the spring container, only if the bean is singleton. It will never be called in case of the bean scope is prototype. The methods which we assign to this destroy-method attribute will be called by the spring container, before the object is destroyed. But we have to use this AbstractApplicationContext interface and call the registerShutdownHook method as we used in below test class,
 public class StudentServiceTest extends BaseTest {  
      protected AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");  
      @Test  
      public void testGetTopStudents() {  
           applicationContext.registerShutdownHook();  
           StudentService studentService = (StudentService) applicationContext.getBean("studentService");  
           List<Student> students = studentService.getTopStudents();  
           System.out.println(students);  
           Student aStudent = null;  
           for(Student student:students){  
                if(null == aStudent){  
                     aStudent = student;                      
                } else if(student == aStudent) {  
                     Assert.assertFalse(true);  
                }  
           }  
      }  
 }  
                            The methods we use as init-method and destroy-method should not accept any arguments, but can be defined to throw exceptions. We can define initialization and destruction methods in all beans with same method signature and can specify it in default-init-method and default-destroy-method of beans elements, instead of specifying it in all the bean elements. Also please have a look at other beans attribute like default-autowire-candidates and default-lazy-init.

                            Singleton bean objects will be created when application context is loaded. Though it’s not used anywhere. Prototype scoped bean objects will always be created when it’s needed. But if we want singleton objects to be created when it’s needed, we can use the lazy-init attribute of bean element. 

Please do more examples like singleton-scoped bean has prototype-scoped beans and vice versa.

Click here to download this example project from GitHub.

Wednesday, 19 October 2016

Backbone JS Simple Application

BackboneJS is a light weight JavaScript library that allows to develop and structure client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

This example illustrates the Simple Backbone JS application.

The main components of Backbone JS we’ve used here are :
1. Backbone View
2. Backbone Model

At first, we need to include the scripts needed for Backbone JS in the Html file. Underscore JS is the only hard dependency for the Backbone JS.

We can include any other JS libraries if it is necessary. Here we’ve included JQuery which is common.
Let’s look at the "index.html" file. It’s a very basic well known div element with username and password.
As of now, we’ve not separated HTML View part in a different file.

index.html

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 <title>Backbone Tutorial ONE</title>  
 <script src="js/libs/jquery.js"></script>  
 <script src="js/libs/underscore.js"></script>  
 <script src="js/libs/backbone.js"></script>  
 <script src="js/UserView.js"></script>  
 <script src="js/UserModel.js"></script>  
 <script src="js/main.js"></script>  
 <div id="appArea">  
 <label for="userNameText">Enter User Name :</label><input type="text" id="userNameText">  
 <label for="passwordText">Enter Password :</label><input type="password" id="passwordText">  
 <button id="submitButton">Submit</button>  
 </div>  

Now, create a Backbone View named “UserView.js” for this screen. In the UserView.js file, we’ve added the events and we do have initialize method. Blur event listener added for userNameText field.

UserView.js

 var UserView = Backbone.View.extend({  
  events : {  
  'blur #userNameText':'onUserNameBlur',  
  'click #submitButton':'onSubmit'  
  },  
  onUserNameBlur : function(e){  
  var value = $(e.currentTarget).val().trim();  
  $(e.currentTarget).val(value);  
  },  
  render : function(){  
  //Empty implementation  
  },  
  onSubmit : function(){  
  var userModel = new UserModel();  
  userModel.set("userName",$('#userNameText').val());  
  userModel.set("password",$('#password').val());  
  userModel.save({  
   success : function(response){  
   alert("Success");  
   },  
   error : function(response){  
   alert("Error");  
   }  
  });  
  }  
 });  

In the "UserModel.js" file, just simply added two parameters with userName and password.

UserModel.js

 var UserModel = Backbone.Model.extend({  
  initialize : function(){  
  },  
  defaults : {  
  userName : '',  
  password : ''  
  },  
  url : 'http://localhost:8080/backbone/login'  
 });  

So now we’ve a html file, a Backbone View file and a Backbone Model file. Now we need to execute the methods in UserView.js. In Backbone, events will bind for the elements only in the “el” element.
There are two ways to set el element. Either we can set el : “elementId" or else we can set the element by calling the setElement method. In this example, setElement method is used.

main.js

 $(document).ready(function(){  
  var userView = new UserView();  
  userView.setElement($('#appArea'));  
 });  

Now the el element is set to appArea. So events are binded with those elements.
If Submit button is clicked, onSubmit function will be triggered and Backbone Model will be triggered.

You can download this sample in the following URL. Github

Tuesday, 18 October 2016

Hibernate Mapping

Hibernate is a ORM framework which will map our database tables into our POJO classes. By this, we can do the database operations like insert, update, select and etc. When we come to hibernate mapping, we have the below relationships between entities as in RDBS,
  1. OneToOne
  2. OneToMany
  3. ManyToOne
  4. ManyToOne
We can wire the relationships between our entities by these mappings. We can do these mappings in both the ways, unidirectional and bidirectional. But we just concentrate only on unidirectional mapping here.

Example:
Let's consider we have student database where we have 6 tables named student, student_address, course_details, month_attendance, academic_subject, student_subject.

OneToOne
Each student has one address and each address has one student. So student has one to one relationship with address entity.

OneToMany
We are tracking monthly attendance of every student in month_attendance table. Each student has more than one record in month_attendance. At the same time, one record in month_attendance is associated with only one student. So student has OneToMany relationship with month_attendance.

ManyToOne
Each student has one course, but one course can have more than one student.

ManyToMany
One student can have multiple subjects and one subject can have many students. So this's a ManyToMany relationship.

Please note down the mapping table student_subject which establishes the many to many relationship between student and subject.

Now let's see the below code snippets to know how we wire the relationships between these entities.

Code:
Student.java
 @Entity  
 @Table(name="student")  
 public class Student implements Serializable {  

   @Id  
   @Column(name="student_id")  
   @GeneratedValue(strategy= GenerationType.AUTO)  
   private String studentId;  

   @Column(name="student_name")  
   private String studentName;  

   @Column(name="date_of_birth")  
   private String dob;  

   @OneToOne  
   @JoinColumn(name="student_id")  
   private Address address;  

   @ManyToOne  
   @JoinColumn(name="course_id")  
   private StudentCourse studentCourse;  

   @OneToMany(mappedBy = "monthAttendancePK.studentId")  
   private Set<MonthAttendance> monthAttendances;  

   @ManyToMany  
   @JoinTable(name = "student_subject",joinColumns = @JoinColumn(name = "student_id"),  
       inverseJoinColumns = @JoinColumn(name = "subject_id"))  
   private Set<Subject> subjects;  

   /*  
   *Other properties and mutators  
   */  
 }  

Address.java
 @Entity  
 @Table(name="student_address")  
 public class Address {  
   @Id  
   @Column(name="student_id")  
   private String studentId;  

   private String location;  

   private String city;  

   private String country;  

   /*   
   *Other properties and mutators   
   */   
 }  

Notice the variables location, city, country. We didn't specify the column annotation. Because the variable name and database column name both are same here. So no need to specify it explicitly.

StudentCourse.java
 @Entity  
 @Table(name="course_details")  
 public class StudentCourse implements Serializable {  

   @Id  
   @Column(name="course_id")  
   @GeneratedValue(strategy= GenerationType.IDENTITY)  
   private String courseId;  

   @Column(name="course_name")  
   private String courseName;  

   private String department;  

   @Column(name="class_location")  
   private String classLocation;  

   private String hod;  

   /*   
   *Other properties and mutators   
   */   
 }  

Composite Primary Key:
Creating a entity class for the month_attendance table is quite different from all other entities which we saw above. Because month_attendance has composite primary key means it's a combination of  two different columns, student_id and month_year. So we declare MonthAttendancePK entity, which holds only the primary key columns, along with MonthAttendance entity which holds all column properties other than the primary keys. We will get a better understanding, when we look at the below code.

MonthAttendancePK.java
 @Embeddable  
 public class MonthAttendancePK implements Serializable {  

   @Column(name="student_id")  
   private String studentId;  

   @Column(name="month_year")  
   private String monthYear;  

   /*   
   *Other properties and mutators   
   */   
 }  

The below MonthAttendance class will have this MonthAttendancePK and it's annotated by @EmbeddedId

MonthAttendance.java
 @Entity  
 @Table(name="month_attendance")  
 public class MonthAttendance implements Serializable {  

   @EmbeddedId  
   private MonthAttendancePK monthAttendancePK;  

   @Column(name="percentage")  
   private String percentage;  

   @Column(name="medical_leaves")  
   private String medicalLeaves;  

   @Column(name="planned_leaves")  
   private String plannedLeaves;  

   @Column(name="urgent_leaves")  
   private String urgentLeaves;  

   /*   
   *Other properties and mutators   
   */   

 }  

Please take a note that we didn't use the @Id annotation, when it comes to composite primary key. Let's have a look at the many to many relationship.

Subject.java
 @Entity  
 @Table(name="academic_subject")  
 public class Subject {  

   @Id  
   @Column(name="subject_id")  
   @GeneratedValue(strategy= GenerationType.AUTO)  
   private String subjectId;  

   @Column(name="subject_name")  
   private String subjectName;  

   @Column(name="recommended_books")  
   private String recommendedBooks;  

   /*   
   *Other properties and mutators   
   */   
 }  

We didn't have any entity for the table student_subject. Because it's just a mapping table represents the many to many relationship between student and academic_subject.

SessionFactory:
We can do the database operations through EntityManagerFactory or SessionFactory. EntityManagerFactory is JPA specific API means that it is provided by the Java. Hibernate has the implementation of this API. If we use this EntityManagerFactory, we can easily move between different ORM frameworks. But, In this example, we used hibernate specific SessionFactory. Because hibernate is a more popular and commonly used ORM framework nowadays and it has more features than the JPA specific API. So we don't need to move to different ORM framework. Now let's see how we configured the SessionFactory in ApplicationContext file,

   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
     <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
     <property name="url" value="jdbc:mysql://localhost:3306/usersproduct" />  
     <property name="username" value="root"/>  
     <property name="password" value="9may89mysql"/>  
   </bean>  
   <!-- Hibernate 4 SessionFactory Bean definition -->  
   <bean id="sessionFactory"  
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
     <property name="dataSource" ref="dataSource" />  
     <property name="annotatedClasses">  
       <list>  
         <value>com.sample.model.Student</value>  
         <value>com.sample.model.StudentCourse</value>  
         <value>com.sample.model.MonthAttendance</value>  
         <value>com.sample.model.Subject</value>  
         <value>com.sample.model.Address</value>  
       </list>  
     </property>  
     <property name="hibernateProperties">  
       <props>  
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
         <prop key="hibernate.show_sql">true</prop>  
       </props>  
     </property>  
   </bean>  
   <tx:annotation-driven transaction-manager="transactionManager"/>  
   <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
     <property name="sessionFactory" ref="sessionFactory" />  
   </bean>  

We used this SessionFactory in the below dao class to fetch all the students and to fetch a student by the given student id along with address, attendance, course, subject details as we configured the relationships.

StudentDaoImpl.java
 @Repository  
 public class StudentDaoImpl implements StudentDao{  
   @Autowired(required = true)  
   private SessionFactory sessionFactory;  
   public List<Student> listStudents() {  
     Session session = this.sessionFactory.openSession();  
     List<Student> studentList = session.createQuery("from Student").list();  
     return studentList;  
   }  
   public Student getStudentData(String studentId) {  
     Session session = this.sessionFactory.openSession();  
     List<Student> studentList = new ArrayList<Student>();  
     Student student = session.get(Student.class,studentId);  
     return student;  
   }  
 }  


Please Click here to download this project from GitHub.


Sunday, 9 October 2016

JMS Implementation

Java Messaging Service API to send messages between different components. We can see the definition of it in many places.So we’re skipping to define it. We are just going to see the various implementations of sending and receiving messages. As we know, we have two JMS mechanisms, Queue and Topic. Now we will just explore the implementation of JMS queue, not the JMS topic that we will see in the next part of JMS article. This article covers the below,
  1. Message Sending to a queue.
  2. Message Reception from a queue. 
      1. Synchronous Message Reception.
      2. Asynchronous Message Reception.
Note : the examples are based on spring framework.

Message Sending and Synchronous Message Reception:

We need to create jmstemplate in application context. Please see the below application context,
      <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
           <property name="brokerURL" value="tcp://localhost:61616" />  
      </bean>  
      <bean id="messageDestination" class="org.apache.activemq.command.ActiveMQQueue" >  
           <constructor-arg value="employee" />  
      </bean>  
      <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
           <property name="connectionFactory" ref="connectionFactory" />  
           <property name="receiveTimeout" value="10000" />  
      </bean>  
      <bean id="employeeMsgSender" class="com.employee.proxy.EmployeeMsgSender">  
           <property name="destination" ref="messageDestination" />  
           <property name="jmsTemplate" ref="jmsTemplate" />  
      </bean>  
      <bean id="employeeMsgConsumer" class="com.employee.proxy.EmployeeMsgConsumer">  
           <property name="destination" ref="messageDestination" />  
           <property name="jmsTemplate" ref="jmsTemplate" />  
      </bean>  
Destination represents the queue and the queue name is employee. EmployeeMsgSender and 
EmployeeMsgConsumer will send and receive messages respectively by using this jmstemplate. 
please see below code snippets,

sendEmployeeToQueue method of EmployeeMsgSender,
 public void sendEmployeeToQueue(final Employee employee) {  
           System.out.println("Producer sends " + employee);  
           ObjectMapper objectMapper = new ObjectMapper();  
           String strEmployee = null;  
           try {  
                strEmployee = objectMapper.writeValueAsString(employee);  
           } catch (JsonGenerationException e) {  
                e.printStackTrace();  
           } catch (JsonMappingException e) {  
                e.printStackTrace();  
           } catch (IOException e) {  
                e.printStackTrace();  
           }  
           final String employeeMsg = strEmployee;  
           jmsTemplate.send(destination, new MessageCreator() {  
                public Message createMessage(Session session)  
                          throws JMSException {  
                     return session.createTextMessage(employeeMsg);  
                }  
           });  
      }  

getNewEmployeeMsg method of EmployeeMsgConsumer,
 public Employee getNewEmployeeMsg(){  
           TextMessage textMessage = (TextMessage) jmsTemplate  
                     .receive(destination);  
           String employeeMsg = null;  
           try {  
                employeeMsg = textMessage.getText();  
           } catch (JMSException e1) {  
                e1.printStackTrace();  
           }  
           ObjectMapper objectMapper = new ObjectMapper();  
           Employee employee = null;  
           try {  
                employee = objectMapper.readValue(employeeMsg, Employee.class);  
           } catch (JsonParseException e) {  
                e.printStackTrace();  
           } catch (JsonMappingException e) {  
                e.printStackTrace();  
           } catch (IOException e) {  
                e.printStackTrace();  
           }  
           return employee;  
      }  


MessageConverter:
                      If we want to keep this message conversion separated, we can use MessageConverter. For this, Create a class which implements MessageConverter and implements the methods fromMessage and toMessage.
 public class EmployeeConverter implements MessageConverter{  
      @Override  
      public Object fromMessage(Message arg0) throws JMSException,  
                MessageConversionException {  
           Employee employee = null;  
           ObjectMapper objectMapper = new ObjectMapper();  
           ActiveMQTextMessage activeMQTxtMsg = (ActiveMQTextMessage) arg0;  
           try {  
                String employeeMsg = activeMQTxtMsg.getText();  
                employee = objectMapper.readValue(employeeMsg, Employee.class);  
           } catch (JMSException | IOException e) {  
                e.printStackTrace();  
           }  
           return employee;  
      }  
      @Override  
      public Message toMessage(Object arg0, Session arg1) throws JMSException,  
                MessageConversionException {  
           Employee employee = (Employee) arg0;  
           ObjectMapper objectMapper = new ObjectMapper();  
           String strEmployee = null;  
           try {  
                strEmployee = objectMapper.writeValueAsString(employee);  
           } catch (JsonGenerationException e) {  
                e.printStackTrace();  
           } catch (JsonMappingException e) {  
                e.printStackTrace();  
           } catch (IOException e) {  
                e.printStackTrace();  
           }  
           Message message = arg1.createTextMessage(strEmployee);  
           return message;  
      }  
 }  

Now we don't need to convert the employee object before sending and after receiving. Instead we can directly send the Employee object by convertAndSend method and receive employee object by receiveAndConvert method.Spring will take of converting before sending and after receiving the message by calling the above methods in MessageConverted class. Please see the below code snippets,

convertAndSendEmployee method of EmployeeMsgSender. We can call this method instead of calling the sendEmployeeToQueue method.
 public void convertAndSendEmployee(final Employee employee) {  
       jmsTemplate.convertAndSend(destination,employee);  
 }  

receiveAndConvertEmployee method of EmployeeMsgConsumer. We can use this method instead of the getNewEmployeeMsg method.
 public Employee receiveAndConvertEmployee(){  
      Employee employee = (Employee) jmsTemplate  
                     .receiveAndConvert(destination);  
      return employee;  
 }  

Please Click here to download this example.



Asynchronous Message Reception:

Create a class which implements MessageListener interface and it's onMessage method.
 public class EmployeeMessageListener implements MessageListener {  
      @Override  
      public void onMessage(Message arg0) {  
           Employee employee = null;  
           ObjectMapper objectMapper = new ObjectMapper();  
           ActiveMQTextMessage activeMQTxtMsg = (ActiveMQTextMessage) arg0;  
           try {  
                String employeeMsg = activeMQTxtMsg.getText();  
                employee = objectMapper.readValue(employeeMsg, Employee.class);  
           } catch (JMSException | IOException e) {  
                e.printStackTrace();  
           }  
           System.out.println("Received Employee Object is : "+employee);  
      }  
 }  

Create a message listener container and add this above message listener class as a reference. We also need to pass the connection factory reference and the queue name. Please see the below application context for the better understanding,
      <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
           <property name="brokerURL" value="tcp://localhost:61616" />  
      </bean>  
      <bean id="employeeMessageListener" class="com.employee.listener.EmployeeMessageListener"/>  
      <bean id="jmsContainer"  
           class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
           <property name="connectionFactory" ref="connectionFactory" />  
           <property name="destinationName" value="employee" />  
           <property name="messageListener" ref="employeeMessageListener" />  
      </bean>  
When we start your application by instantiating ApplicationContext, this'll start listening to the queue names employee for the incoming message. We can test this by sending message to this queue. The onMessage method will be called when the queue received any message.

Please Click here to download this example.

Please have a look at the message converter, before closing the JMS queue exploration.