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.

Tuesday, 4 October 2016

JBOSS Fuse application or OSGI Bundle example

When we read about OSGI, we get confused by the various terminologies like modular application, dynamic components, microservices, libraries, reusable components, OSGI bundle, features and etc. So here, in this blog, we are not gonna care about it. We'll just see an simple application which can be deployed in JBOSS Fuse.

What are we gonna do?
                     Let's say a user is logging in to an application like amazon or filpkart. You need to fetch and display the products that you want to suggest to the user to purchase, in home page. Our application is a restful web service to get all the products with its id, name, company name.  We are gonna make two jar file, one for rest API and one for the actual service which has the real implementation.

Products module:
                     Let's first look at the actual implementation without the rest API. Later we'll see how to create the rest API jar and how it make use of the actual implementation jar. Click here to download the code base of this module.

How does it differ from the traditional jar or library file?
                     MANIFEST.MF and blueprint.xml are making the differences. Even though we get a jar file while building this project, we call this jar file by the name OSGI bundle, because of these two files.

blueprint.xml
Below is the blueprint.xml of our implementation jar. 


<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
       http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">

  <bean id="productServices" class="com.flexy.products.services.ProductServicesImpl">
      <property name="productDao" ref="productDao"/>
  </bean>
  
  <bean id="productDao" class="com.flexy.products.repository.ProductDaoImpl"/>
  
  <service ref="productServices" interface="com.flexy.products.services.IProductServices"/>

</blueprint>


Note down this service definition. We will access this service from rest API jar.

MANIFEST.MF
                     Next, the MANIFEST.MF file. We won't have this file in our project. This file will be generated and placed inside the jar under the META-INF folder, while building the application. To add this file in your jar, we should have the below maven plugin in your pom.xml.


<plugin>
 <groupId>org.apache.felix</groupId>
 <artifactId>maven-bundle-plugin</artifactId>
 <version>2.3.7</version>
 <extensions>true</extensions>
 <configuration>
  <instructions>
   <Bundle-SymbolicName>products</Bundle-SymbolicName>
   <Import-Package>
    org.osgi.service.blueprint,
    java.text,
    java.util,
    org.slf4j
   </Import-Package>
   <Export-Package>
    com.flexy.products.services,
    com.flexy.products.model
   </Export-Package>
  </instructions>
 </configuration>
</plugin>


Once we build this module, we get the below MANIFEST.MF file inside the jar.

Manifest-Version: 1.0
Bnd-LastModified: 1475582457289
Build-Jdk: 1.7.0_75
Built-By: arunv
Bundle-ManifestVersion: 2
Bundle-Name: User Products
Bundle-SymbolicName: userproducts
Bundle-Version: 1.0.0.6
Created-By: Apache Maven Bundle Plugin
Export-Package: com.flexy.userproducts.services;uses:="javax.ws.rs,javax
 .jws,com.flexy.products.model,com.flexy.products.services,org.slf4j";ve
 rsion="1.0.0.2"
Import-Package: com.fasterxml.jackson.jaxrs.json;version="[2.4,3)",com.f
 lexy.products.model;version="[1.0,2)",com.flexy.products.services;versi
 on="[1.0,2)",javax.jws,javax.ws.rs;version="[2.0,3)",javax.ws.rs.core;v
 ersion="[2.0,3)",org.osgi.service.blueprint;version="[1.0.0,2.0.0)",org
 .slf4j;version="[1.7,2)"
Import-Service: com.flexy.products.services.IProductServices;multiple:=f
 alse
Tool: Bnd-1.50.0

Service element vs Export-Package:
                     The service element in blueprint.xml and these export packages may look like both have the same responsibilities. But both are completely different and each has its own responsibility. The classes inside the exported packages can be imported in other modules as we do in traditional way. If the class depends on any other class like dependency injection, we have to do this ourselves in our own module. But we can use the service classes without worrying about its implementation and its dependencies.You can get the better clarity when you look at the reference element of blueprint.xml, which we’ll see in a min,

User Product Module:
                     Now we will see how to use this jar file in the rest API jar. Click here to download the code base of this module. 

blueprint.xml
As we mentioned above, this rest API is also a OSGI bundle. Let's look at it's blueprint.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
    xmlns:cxf="http://cxf.apache.org/blueprint/core"
    xsi:schemaLocation="
      http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
      http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
      http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">
 
 <jaxrs:server id="userProductService" address="/userproducts">
        <jaxrs:serviceBeans>
            <ref component-id="userproducts"/>
        </jaxrs:serviceBeans>
        
        <jaxrs:providers>
           <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
        </jaxrs:providers>
        
    </jaxrs:server>
 
    <cxf:bus>
        <cxf:features>
          <cxf:logging />
        </cxf:features>
    </cxf:bus>
    
  <bean id="userproducts" class="com.flexy.userproducts.services.UserProductServiceImpl">
      <property name="productServices" ref="productServices"/>
  </bean>
  
  <reference id="productServices" interface="com.flexy.products.services.IProductServices"></reference>
  
</blueprint>


The reference element is used to mention the service which we want to use from the dependent jars.
Now we have a question where to mention or configure the dependency jar. That's features.xml and we can also call features repository. We can have n number of features repository and each repository can have n number of feature. feature is again a confusing word. It's nothing but a jar or library or dependency or OSGI bundle.

features repository:
                     We can keep this features.xml file wherever we want, add it in the feature repository. But here, we kept it along with our project. Below is our features.xml,


<?xml version="1.0" encoding="UTF-8"?>
<features name="userproductfeature-1.0.0-1" xmlns="http://karaf.apache.org/xmlns/features/v1.0.0">

 <feature name="products" version="1.0.0-2" resolver="(obr)">
  <bundle dependency="true">mvn:com.flexy/products/1.0.0-2</bundle>
 </feature>

</features>


Summarizing the items which we should note it down,
features.xml - feature or dependency repository to specify the dependent jar.
META-INF/MANIFEST.MF
                     Import packages - to specify the dependent packages.
                     Export packages - classes inside the packages can be used by other bundles or jars.
blueprint.xml
                     service - registering a service in the OSGI service registry. This service can be accessed by other OSGI bundles using reference element.
                     reference - find the service in service registry and get the bean.

There are lot to know about the deployment and advantages of it. But adding too much in a single article will make us tired. So we will try to explore more and publish more in the next article.

For Javascripts, visit http://flexydevcenter.blogspot.com/

Friday, 30 September 2016

Immutable objects

An immutable object is an object whose state cannot be modified after its creation. Once object is created, you can not change the properties of it. Immutable object is sort of design pattern. We have to follow certain rules or patterns to create immutable objects.

In java, once you initialized an object , you'll never be allowed to set the values of its property through the setter methods and not to be allowed to have any method that will change the state of the object. You will only be allowed to set the values at the time of object creation through constructor arguments. Mutable property of the class will never be assigned even through the constructor. Instead, it will copy the values from the arguments and getter method will also make another copy to return to the caller.

One last thing is that it's a final class, You will never be allowed to inherit it, which means you can not create sub class of it.
We can get a better understanding, when we look at the below code.

Example:

public final class Product {
 
 private final String productId;
 
 private final String productName;

 private final String companyName;
    
 private final List versions;
 
 public List getVersions() {
  return new ArrayList(versions);
 }

 public String getProductId() {
  return productId;
 }

 public String getProductName() {
  return productName;
 }

 public String getCompanyName() {
  return companyName;
 }
 
 public Product(String productId,String productName,String companyName,List versions) {
  this.productId = productId;
  this.productName = productName;
  this.companyName = companyName;
  this.versions = new ArrayList(versions);
 }

}


String and Integer objects are the examples of immutable objects in JDK.


Summarising the guidelines below,
Final class - can not create subclass
No public setter method - Can not set or change properties
No public method that will change the object state
Constructor argument- set properties, while creating objects.
Copy mutable property - while setting through constructor and returning through the getter.


When/where to use:

We are fetching some meta data from the data base and those data should not be updated by the user. So here, we can store those data in an immutable object and use it to avoid altering the original data.
Let's consider Amazon or Flipkart application. You can not modify the price, item name, description, review comments,etc in the item which you want to buy. So you can have immutable objects in your code to hold all these metadata to avoid modifying and updating the values in database.

In a multithreaded environment, we can safely use the immutable objects. If we use mutable objects without any need in such places, possibly there could be the chances of creating concurrency issues. For example, one thread is trying to change the state of an object, while another thread is accessing the state of it.
To avoid this, we have to make methods synchronized. Synchronizing methods may cause performance issues. So if we use immutable objects in multithreaded environment, we can come out of these issues and focus only on the other part of implementations.

Caching immutable objects is safer than the mutable objects. If a map has objects for its keys, we have to consider using immutable objects to avoid changing states. Because in most cases, hashcode value is calculated based on the object state.

For Javascripts, visit http://flexydevcenter.blogspot.com/


Friday, 16 September 2016

JQuery ajax GET request call

Below is the example of an jQuery ajax call. It's making a GET request.

 <head>  
      <script>  
      $( document ).ready(function() {  
           $( "#mainMenuArea" ).load( "html/mainMenu.html" );  
           $.ajax({url: "http://localhost:8080/services/usersproducts/allproduct",   
             success: function(result){  
                var productArray = result.products  
                $( "#div_appArea" ).append("<table>");  
                $( "#div_appArea" ).append("<tr><th>Mobile No<th><th>Possession Status<th>");  
                $( "#div_appArea" ).append("<th>Company Name<th><th>Recommended<th></tr>");  
                $( "#div_appArea" ).append("<th>User Product Id<th><th>Recommended<th></tr>");  
                for(var i in productArray){  
                     $( "#div_appArea" ).append("<tr>");  
                     $( "#div_appArea" ).append("<td>"+productArray[i].productId+"<td>");  
                     $( "#div_appArea" ).append("<td>"+productArray[i].productName+"<td>");  
                     $( "#div_appArea" ).append("<td>"+productArray[i].companyName+"<td>");  
                     $( "#div_appArea" ).append("</tr>");  
                }  
                $( "#div_appArea" ).append("</table>");  
        }});  
      });  
     </script>  
 </head>  
 <body>  
     <div id="div_appArea">  
 </body>  

Saturday, 27 August 2016

Quick sort

Introduction
Pivot , Divide and Conquer , Wall , Randomized algorithm are the four terminologies we should know, when come to quick sort.

Pivot value selection:
Randomly select an element from the array. Here, we are choosing the last element as a pivot.

Wall:
Left side of the wall will always have the values that's smaller than pivot. Right side will always have bigger values.The index of the wall will start at the start index and keep moving on. 

Comparison:
Compare the elements from wall to pivot, with the pivot value. If we found any value less than the pivot, swap the value with wall and move the wall by one index. Once you did the comparison of all elements with pivot, swap the pivot with wall. Now the pivot has placed successfully in its position.

Divide and conquer:
Now if we divide the elements by the wall, we get 2 arrays. Continue the same process again as we mentioned above. No need of conquering.

Look at the below code to get the better understanding,

Code:


public void doQuickSort(int[] a,int strtIdx,int lstIdx) {
 int pivotValue = a[lstIdx];
 int wall = strtIdx;
 for(int i=strtIdx;i < lstIdx;i++) {
  if(a[i] < pivotValue){
   swap(a,wall,i);
   wall++;
  }
 }
 swap(a,wall,lstIdx);
 if(strtIdx < wall-1){
  doQuickSort(a, strtIdx, wall-1);   
 }
 if(wall+1 < lstIdx){
  doQuickSort(a, wall+1, lstIdx);   
 }
 System.out.println();
 for(int i=0;i < a.length;i++) {
  System.out.print(a[i]+" ");
 }
}
Complexity:
The time complexity of this sorting is O(n2) in a worst case scenario. The worst case is when your pivot value is always the smallest or largest element than rest of the elements. Each time if the list is divided into 2 equal sized list, then the complexity will be O(nlogn) which is the best case complexity of this algorithm. 

Tuesday, 12 July 2016

Bubble Sort

Prerequisite:
Algorithm, Sorting, Asymptotic complexity(time complexity, space complexity)

Introduction:
Bubble sort may look same as insertion sort, because the outcome of the bubble sort looks same as insertion sort. In case of sorting in ascending order, Insertion sort will keep taking out the min value at end of the each iteration, whereas bubble sort will take out the max value. So both insertion and bubble sort look same.But there are few differences, when you look at the implementation.

Code:

 public int[] doBubbleSort(int[] ip) {  
      boolean isSwapped = false;  
      for(int i=1;i<ip.length;i++){  
           for(int j=0;j<ip.length-i;j++){  
                if(ip[j]>ip[j+1]){  
                     swap(ip, j, j+1);  
                     isSwapped = true;  
                }  
           }  
           if(!isSwapped){  
                break;  
           }  
      }  
      return ip;  
 }  

Complexity:
The time complexity of this sorting is O(n2) in a worst case scenario. In a best case scenario where the list is already sorted, the time complexity is O(n). The auxiliary memory/space is taken by this algorithm will never increase based on the number of elements. It always use the constant extra space. So the space complexity is O(1).

When/where to use:
Even though it has the interesting implementation and the fancy name, it will not be suitable for any case. We can say It's suitable for smaller array which has 10 or 15 elements, because of easy implementation. You can also use this algorithm, if the array is already sorted where the complexity is O(n). But in such cases, insertion sort is a better choice than this.

Sunday, 10 July 2016

JMS

(The main objective of this article is to identify the places where JMS is needed)

JMS(Java messaging service) is a widely used technology. It has two different mechanism called Queue and Topic(publish-subscribe). A queue may have multiple listeners. But when u push a message, it will be picked up by only one listener whereas in topic, message will be received by all the subscribers who subscribed to the topic.

So now the question is where does it need?

Let's consider a case, you have a centralised database which has to be updated by the multiple applications. But you don't want other application to access this database. So here, you can have a queue and all the applications will just push their data to this queue. You will take care of dequeue them, process them & store them in the DB.

In another case, you need to send a mail and call a web service, before Storing the user data into your application database, when user submit a request.

Here, there's no guarantee that the email service and the web service will always be up and running. So the entire flow will fail or we have to skip the mailing part and/or calling web service, if they are down. Even though both the servers are up, there'll be some delay in storing data and sending the response back to the user with respect to the time taken by the external services.

To avoid such issues, we can have a queue where we push the messages and go ahead with the storing data in DB. A separate JMS listener component will take care of sending emails and calling/updating the web service.

You may think that we can store the same data which we are pushing to the queue, in DB and later, we can fetch them from DB and process them.Yes, you can also use DB. If you are ok to expose your database to other components or if you want to store those data permanently or if the size of the message is large, you can go for DB instead of queues.

If your application needs to send a message to multiple applications/components, you may go for the topic. As we told before, if a message comes into the topic , it will be received by more than one subscribers which is actually an another application or component. Queue and Topic both can be used as a middleware which use to connect components/applications written in various languages.

Thursday, 7 July 2016

Insertion sort

Prerequisite: 
Algorithm, Sorting, Asymptotic complexity(time complexity, space complexity)

Introduction:
Insertion sort will take elements from 0 to n and compare & swap it with the left part of the array which is already sorted among the elements, until it find the right place where the element has to be. You may be clear, when look at the below code,

Code:
public int[] doInsertionSort(int[] ip) {
 for(int i =1;i<ip.length;i++) {
  for(int j=i;j>0;j--) {
   if(ip[j]<ip[j-1]){
    swap(ip, j, j-1);
   }else {
    break;
   }
  }
 }
 return ip;
}

Performance:
Time complexity of this sorting is O(n2) in a worst case scenario, O(n) in a best case scenario. O(n), when the array is already sorted. Worst case space complexity is O(1).

Where/when to use:
Even though it took more time or steps to sort the list than the other algorithms like Heap & merge sort, we still can use it in some places.It's easy to implement as selection sort, so we can use this for smaller arrays. But it may do more swaps than selection sort.
It's good to use this sort in a place where the element are all already sorted.Let's consider you already have a sorted list & a new element is added to the list. So now u need to place the last element in right place to make the list sorted again.

Tuesday, 5 July 2016

Design Patterns

          A programmer may write a better program to solve a problem. He may consider the memory management, Asympotatic complexity. 
          An Object oriented programmer will see everything as an object. Once he got the requirements, he can easily see all the objects or entities involved in it & he can write the services of the objects. 
          An application designer will figure out the relationship between the Objects and wire them by any design. A well designed application will help us in easy maintenance.
We can say that a better programmer would have all roles which We mentioned above.

There are several design issues have already been resolved by programmers. Below are the names of those design patterns,

  1. Observer pattern
  2. Decorator pattern
  3. Factory pattern
  4. Singleton pattern
  5. Command Pattern
  6. Adapter & Facade pattern
  7. Template method pattern
  8. Iterator & Composite pattern
  9. State pattern
  10. Proxy pattern
  11. Immutable Objects Pattern
  12. Mediator Pattern

Monday, 4 July 2016

Selection Sort

Prerequisite: 
Algorithm , Sorting , Asymptotic complexity(Time & Space Complexity)

Introduction :
If someone gives you a list to sort and we are not aware of various sorting algorithm, most of us will write the below code, 

Code:
 public int[] doSelectionSort(int[] ip) {  
      int temp = 0;  
      for(int i=0;i<ip.length-1;i++) {  
           temp = i;  
           for(int j=i+1;j<ip.length;j++) {  
                if(ip[j]<ip[temp]) {  
                     temp = j;  
                }  
           }  
           if(i!=temp) {  
                swap(ip, i, temp);  
           }  
      }  
      return ip;  
 }  
Performance: 
Time complexity of this sorting is O(n2) regardless of worst or best case. It requires O(1) auxiliary space regardless of any case. It has relatively poor performance than others. 

Where/When to use:
The only use of this algorithm is that it is easy to implement. But we may use it in few places. for instance, we have less than 10 elements in the list or we need only top 5 records out of 1000 or more records.
You may get some confusion that why i said we can use this sorting to find the top 5 record out of 1000 elements. Because we will be having 5*1000 comparison & we can skip the remaining comparisons in this sorting whereas insertion sort and merge sort has to execute all the comparisons with the time complexity O(n2) and O(n log n) respectively. You may think that bubble sort will also have the same 5*1000 comparison.But it needs more swap than the selection sort in a worst case scenario.