Welcome to NALIN.

It's all about Technology and Programming.


This blog includes information to the trending technologies, hottest programming tutorials and solution to programming problems.


Do you want to contribute to this blog with your knowledge and skills? If yes, then contact us here


Thank you !!!

HTML templating with jQuery

Leave a Comment
In this short article, we’ll see some techniques to generate DOM elements and section using jQuery and its chaining feature.

Dynamic DOM elements creation

There are 2 techniques out there to create dynamic DOM elements.
  1. Using the createElement() method on the Document standard oject:
    var myDiv = document.createElement("div");
    var mySpan = document.createElement("span");
    mySpan.createTextNode(displayedText);
    myDiv.appendChild(mySpan);

  2. Using jQUery
    var myDiv = $('div').append(($('span').html(displayText));
Clearly the second method is better and cleaner. However this technique is suitable only for occasionnal dynamic DOM creation. If you need to create iterable items (like a table or a list of items) with dynamic data, it’ll become quickly a nightmare.

HTML templating with jQuery

The idea

Here is a very common use case: you are designing a user search page. There is a search form with various parameters. Below the search section is the result section where you display all found users in a table.

In the old style architecture, a click on “Search” button will submit the form to the server, which will then execute the query and build the result table and render the response page. All the job is done server-side.

With RESTfull architecture, the server only takes care of the DB querying and will return a list of JSON objects as results. The client-side is responsible for the data formatting. There “HTML templating” comes into play.

The idea is to create a template row representing a result and hide it at the end of the page:

<div>
    <form id="searchForm">
        ...
        <button type="submit" onclick="doSearch()">Search</button>
        ...
    </form>
    <section id="resultArea">
        <table id="resultTable">
            <thead>...</thead>
            <tbody></tbody>
        </table>
    </section>
</div>    
<div id="templates" style="display:none;">
    <tr id="rowTemplate">
        <td class="name">Name</td>
        <td class="age">Age</td>
        <td class="skills">Java, C#, Python</td>
        <td class="xp">5 years</td>
    </tr>
     
    <span id="someOtherTemplate">
        ...
        ...
    <span>
</div>

As shown above, all the DOM element templates are nested inside a div container with style=”display:none;” so it will not be visible on the page.

The same div can contain several template elements, like our template row for search result or any other templates. You need to give them a unique id so they can be easily fetched using jQuery selector.

Implementation

Now let’s see how we can format result row upon reception of the JSON data from server. Let’s assume that the returned data is a list of JSON objects representing each an user details:

{
  "name": "John Skit",
  "age": "29",
  "skills": "Java, Groovy, HTML5",
  "xp": "7 years"
}

function doSearch()
{
    $.ajax({
        type: 'GET',
        url:  '/search',
        dataType: 'json',
        success: function(data)
        {
            $.each(data, function(index,user)
            {
                $('#rowTemplate').clone().attr('id','')
                .find('.name').html(data.name).end()
                .find('.age').html(data.age).end()
                .find('.skills').html(data.skills).end()
                .find('.xp').html(data.xp).end().
                .appendTo('#resultTable tbody');
            });
        }
    });
}

In the ajax success function, upon reception of the JSON data set, we iterate through the “data” list. For each user JSON we:
  1. clone the #rowTemplate
  2. clear its id
  3. find each row column by its class
  4. fill in its HTML content with JSON data
  5. append the whole row to the body of #resultTable
That’s pretty simple. The job is done with a jQuery chain using end() method to go back and forth to the row element .

Please notice that at step 2, we need to clear the id of the cloned element otherwise we’ll end up having several rows with the same id in the DOM, big trouble!

Of course, the example is quite straightforward because the logic is minimalist. If you have complex logics with if/else if blocks involved, all the jQuery chaining beauty is gone!

function doSearch()
{
    $.ajax({
        type: 'GET',
        url:  '/search',
        dataType: 'json',
        success: function(data)
        {
            var row;
            $.each(data, function(index,user)
            {
                row =$('#rowTemplate').clone().attr('id','');
 
                row.find('.name').html(data.name).end()
                .find('.age').html(data.age);
 
                // Age discrimination
                if(data.age > 50) 
                {
                    row.find('.age').addClass('oldDuffer'); 
                }
                 
                row.find('.skills').html(data.skills).end()
                .find('.xp').html(data.xp);
 
                // XP highlighting
                if(data.xp < 3) 
                {
                    row.find('.xp').addClass('junior'); 
                }
 
                row.appendTo('#resultTable tbody');
            });
        }
    });
}

Variable shadowing in Java

Leave a Comment
Today I’ll show you a rare feature of Java: variable shadowing. First, let me define what is a shadowed field or method:

A field is considered shadowed when;

  • a subclass of its declaring class declares a field with the same name
  • a variable having the same name and type is declared in the local scope
  • a method argument/parameter is declared with a same name and type

Local variable shadowing


public class MyClass{
    private int count = 10;
    private void localVariable(){
        int count = 5;
        System.out.println("count = "+ count);
    }
    public static void main(String[] args){
        MyClass test = new MyClass();
        test.localVariable();
    }
}

Result : count = 5

because the count local variable declared inside localVariable() method shadows the variable count declared at class level. If we want to access the instance variable, we need to add the this keyword.

private void localVariable(){
    int count = 5;
    System.out.println("count = "+ this.count);
}

Method argument shadowing

private int count;
public void setCount(int count){
    this.count = count;
}

The this keyword is mandatory to resolve the ambiguity. Without this, the compiler cannot know whether we are assigning the count method argument value to itself. If you remove the this keyword, you would get a compilation warning anyway.

Superclass field shadowing

Let’s consider the following classes:

public class SuperClass {

    protected String val = "SUPER_VAL";
    protected void display(){
        System.out.println("val = "+this.val);
    }
}
public class ChildClass extends SuperClass{

    private String val;
    public ChildClass(String value){
        this.val = value;
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass("CHILD_VAL");
        child.display();
    }
}

The execution gives: val = SUPER_VAL

The val field has been declared in the SuperClass but is shadowed in the ChildClass because the latter declares another field with same name and type. Although the ChildClass has been instantiated with “CHILD_VAL”, the execution of child.display() gives you “SUPER_VAL”.

The reason is simple. When the child instance is created, there are 2 variables val. The one from SuperClass with value “SUPER_VAL” and the one from ChildClass with injected value “CHILD_VAL” through constructor.

When the display() method is called, since it is define in the SuperClass, it is the val field in the context of SuperClass which is used. Not surprising that the output shows “SUPER_VAL”.

public class ChildClass extends SuperClass
{
    private String val;
    public ChildClass(String value){
        this.val = value;
        super.val = value;
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass("CHILD_VAL");
        child.display();
    }
}

In the above modified code, we force the value for the hidden val field in SuperClass with super.val = value, and the output gives: val = CHILD_VAL

Now let’s add another class in the hierarchy;

public class AncestorClass{
    protected String val = "ANCESTOR_VAL";
}
public class SuperClass extends AncestorClass{
    protected String val = "SUPER_VAL";
}
public class ChildClass extends SuperClass{
    private String val = "CHILD_VAL";
    public void displayVal(){
        System.out.println("val = " + super.val);
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass();
        child.displayVal();
    }
}

Obviously, the output will display: val = SUPER_VAL

The question now is: what if we want to display the val value of AncestorClass ? Obviously the super keyword only refers to the first parent class up in the class hierarchy. Casting comes to the rescue. Indeed we can force the this keyword representing the current class instance to a particular type in the class hierarchy !

public class ChildClass extends SuperClass{
    private String val = "CHILD_VAL";
    public void displayVal(){
        System.out.println("val = " + ((AncestorClass) this).val);
    }
    public static void main(String[] args){
        ChildClass child = new ChildClass();
        child.displayVal();
    }
}

This time, we do have val = ANCESTOR_VAL

Happy Coding !

Issue analysis and solved : No mapping found for HTTP request with URI [/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'.

Leave a Comment
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/WEB-INF/views/home.html] in DispatcherServlet with name 'appServlet'

I got above PageNotFound (ERROR 404) message while loading home.html page in Spring Web MVC project with Google App Engine nature. But when I use home.jsp then it works fine.

Then I searched and analysed how the flow of servlet container goes through the request.

  1. First the DispatcherServlet is invoked by the Servlet Container.
  2. The DispatcherServlet finds a mapping which maps to the home method of the Controller and the home method returns a view name "home".
  3. Now the DispatcherServlet uses a View Resolver (InternalResourceViewResolver) to find the View to render the model through, since the name is "home", this maps to the /WEB-INF/view/home.html view.
  4. Now essentially a call is made to RequestDispatcher.forward("/WEB-INF/views/home.html")
  5. The Servlet container at this point tries to find the servlet which can handle /WEB-INF/views/home.html uri - if it had been a .jsp there is a JSPServlet registered which can handle rendering the jsp, however for *.html there is no servlet registered, so the call ends up with the "default servlet", which is registered with a servlet-mapping of / which probably the DispatcherServlet is.
  6. Now the Dispatcher servlet does not find a controller to handle request for /WEB-INF/views/home.html and hence the message that I saw during project run.
If you are also getting this type of error and you want this kind of a extension to be handled by the servlet container, say tomcat, you can register *.html extension to be handled by JSPServlet and then it should work cleanly. Or return forward:/resources/HelloWorld.html which will be considered a static file relative to your resources folder.

And one of my friend asked how he would register *.html extension to be handled by JSPServlet. So, I told him that it can be achieved in two simple steps.
  1. By adding this servletmapping for the JSP servlet.

    <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    This tells the application container to use the the JSP servlet when serving html files.
  2. Comment out the <mime-mapping> for text/html mime type (*.html) files so that the container won't handle HTML files as static content.
Happy Debugging !

Difference between Setter vs Constructor Injection in Spring.

Leave a Comment

Spring Setter vs Constructor Injection

Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article.

Difference between Setter and Constructor Injection in Spring framework

Spring supports both setter and constructor Injection which are two standard way of injecting dependency on beans managed by IOC constructor. Spring framework doesn't support Interface Injection on which dependency is injected by implementing a particular interface. In this section we will see a couple of difference between setter and constructor Injection, which will help you decide when to use setter Injection over constructor Injection in Spring and vice-versa.

1) The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected.  Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring's IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.

2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it's not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.

3) Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.

4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is much bigger concern. Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using "dependency-check" attribute of  tag or tag. Another worth noting point to remember while comparing Setter Injection vs Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, if some of those arguments is optional than using Builder design pattern is also a good option.

Send HTTP request GET/POST in Java

Leave a Comment
HTTP stands for Hypertext Transfer Protocol. It is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. A web browser sends HTTP request to an application that resides on the remote host computer and the application responses to that request. HTTP request can be of different type.

In this post I am going to give an example of HTTP GET/POST request using Java.

1. Java HttpURLConnection example

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {

private final String USER_AGENT = "Mozilla/5.0";

public static void main(String[] args) throws Exception {

  HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}

// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=nepal";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());

}
}

2. Apache HttpClient

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientExample {

private final String USER_AGENT = "Mozilla/5.0";

public static void main(String[] args) throws Exception {

HttpClientExample http = new HttpClientExample();

System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();

}

// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=developer";

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);

// add request header
request.addHeader("User-Agent", USER_AGENT);

HttpResponse response = client.execute(request);

System.out.println("\nSending 'GET' request to URL :" + url);
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(new
InputStreamReader( response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}

// HTTP POST request
private void sendPost() throws Exception {
String url ="https://selfsolve.apple.com/wcResults.do";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("sn","C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("cn", ""));
urlParameters.add(new BasicNameValuePair("locale",""));
urlParameters.add(new BasicNameValuePair("caller",""));
urlParameters.add(new BasicNameValuePair("num","12345"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL: " + url);
System.out.println("Post parameters : " +post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
}

What is Docker and how to install it in Ubuntu ?

2 comments
Docker is the world's leading software containerization platform which wrap a piece of software in a complete filesystem that contains everything needed to run: code, runtime, system tools, system libraries – anything that can be installed on a server. Docker guarantees that the software will always run the same, regardless of its environment.

Docker containers are one of the main components of the Docker system. They are lightweight and running on the same machine shares the same operating system kernel; they start instantly and use less RAM. Images are constructed from layered filesystems and share common files, making disk usage and image downloads much more efficient.

Docker containers are based on open standards, enabling containers to run on all major Linux distributions. Containers isolate applications from one another and the underlying infrastructure.

Upto this date, Docker is supported on these Ubuntu operating systems:
  • Ubuntu Xenial 16.04 (LTS)
  • Ubuntu Wily 15.10
  • Ubuntu Trusty 14.04 (LTS)
  • Ubuntu Precise 12.04 (LTS)
Note: Docker requires a 64-bit installation regardless of your Ubuntu version and kernel must be 3.10 at minimum.

To check your current kernel version, open a terminal and use uname -r to display your kernel version:

nalin@localhost:~$ uname -r
3.16.0-77-generic

Update your apt sources

Docker’s APT repository contains Docker 1.7.1 and higher. To set APT to use packages from the new repository:
  1. Log into your machine as a user with sudo or root privileges.
  2. Open a terminal window.
  3. Update package information, ensure that APT works with the https method, and that CA certificates are installed.
    $ sudo apt-get update
    $ sudo apt-get install apt-transport-https ca-certificates
  4. Add the new GPG key.
    $ sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
  5. Open the /etc/apt/sources.list.d/docker.list file in your favorite editor. If the file doesn’t exist, create it.
  6. Remove any existing entries.
  7. Add an entry for your Ubuntu operating system.
    1. On Ubuntu Precise 12.04 (LTS)
      deb https://apt.dockerproject.org/repo ubuntu-precise main
    2. On Ubuntu Trusty 14.04 (LTS)
      deb https://apt.dockerproject.org/repo ubuntu-trusty main
    3. Ubuntu Wily 15.10
      deb https://apt.dockerproject.org/repo ubuntu-wily main
    4. Ubuntu Xenial 16.04 (LTS)
      deb https://apt.dockerproject.org/repo ubuntu-xenial main
  8. Save and close the /etc/apt/sources.list.d/docker.list file.
  9. Update the APT package index.
    $ sudo apt-get update
  10. Purge the old repo if it exists.
    $ sudo apt-get purge lxc-docker
  11. Verify that APT is pulling from the right repository.
    $ apt-cache policy docker-engine
From now on when you run apt-get upgrade, APT pulls from the new repository.

Prerequisites by Ubuntu Version

For Ubuntu Trusty, Wily, and Xenial, it’s recommended to install the linux-image-extra kernel package. The linux-image-extra package allows you use the aufs storage driver.

To install the linux-image-extra package for your kernel version:

  1. Open a terminal on your Ubuntu host.
  2. Update your package manager.
    $ sudo apt-get update
  3. Install the recommended package.
    $ sudo apt-get install linux-image-extra-$(uname -r)
  4. Go ahead and install Docker.
If you are installing on Ubuntu 14.04 or 12.04, apparmor is required. You can install it using: apt-get install apparmor.

Install

Make sure you have installed the prerequisites for your Ubuntu version.

Then, install Docker using the following:
  1. Log into your Ubuntu installation as a user with sudo privileges.
  2. Update your APT package index.
    $ sudo apt-get update
  3. Install Docker.
    $ sudo apt-get install docker-engine
  4. Start the docker daemon.
    $ sudo service docker start
  5. Verify docker is installed correctly.
    $ sudo docker run hello-world
This command downloads a test image and runs it in a container. When the container runs, it prints an informational message. Then, it exits.

Happy Dockering !

Sending Email using Java

Leave a Comment
To send an email using Java Application, you need JavaMail API and Java Activation Framework (JAF). You can download the latest version of JavaMail API from Java's website. Click here to open the Java's website. For the download of latest version of JAF you can click here.

Just download and extract those files in your machine. You will find number of files but you only need mail.jar and activation.jar. Just add those files in your project CLASSPATH.


Send a Simple E-mail

Before sending a simple email, first you have to connect your machine with the internet. Here is a sample code for sending a simple email. Create a project in any IDE (I am using Eclipse) and create a java file named as SendEmail.java and paste the below code.

// File Name SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args)
   {    
      // Recipient's email ID needs to be mentioned.
      String to = "abc@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "xyz@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new 
         InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Now just run this file as Java Application and your email will be sent to the recipient's email address.

If you have multiple recipient for sending the email, then you can specify the multiple email id as follows:

void addRecipients(Message.RecipientType type, Address[] addresses)throws MessagingException

Here, type can be set to TO, CC or BCC. CC represents Carbon Copy and BCC represents Black Carbon Copy. Example, Message.RecipientType.TO
and addresses is the array of email ID. You have to use InternetAddress() method for specifying email IDs.


User Authentication

If sending email fails due to required authentication to the mail server then you can provide the user authentication by following ways and the rest of the process is as it is.


properties.setProperty("mail.user", "myuser");
properties.setProperty("mail.password", "mypwd");