IP and Domain Name Lookup using Java

 

In this tutorial we will see how to find IP address from domain name and how to find host from IP. We have used dnsjava open source library for this demo. You can download dnsjava jar from external link and can add it in your project.


import java.net.InetAddress;
import java.net.UnknownHostException;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Name;
import org.xbill.DNS.PTRRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.ReverseMap;
import org.xbill.DNS.Type;

public class FindDomain {

 public static void main(String[] args) {
   try {
    InetAddress address = InetAddress.getLocalHost();
    System.out.println("LOCAL ADDRESS : " + address.getHostAddress());
    System.out.println("LOCAL HOST : " + address.getHostName());

    InetAddress ipAddress = java.net.InetAddress.getByName("www.javadiscover.com");
    String ip = ipAddress.getHostAddress();
    System.out.println("\nJAVADISCOVER IP : " + ip);

    final InetAddress ip2 = InetAddress.getByName("74.125.135.121");
    final byte[] bytes = ip2.getAddress();
    final String host = getHostByIPAddress(bytes);
    System.out.println("\nJAVADISCOVER HOST : " + host);

   } catch (UnknownHostException e) {
    System.out.println("Host NOT Avaialble");
   }

  }

  public static String getHostByIPAddress(byte[] addr) throws UnknownHostException {

   Name name = ReverseMap.fromAddress(InetAddress.getByAddress(addr));

   // OPEN DNS SERVERS
   final String[] openDNS = new String[] {"208.67.222.222", "208.67.220.220"};
   final Resolver resolver = new ExtendedResolver(openDNS);
   final Lookup lookUp = new Lookup(name, Type.PTR);
   lookUp.setResolver(resolver);
   Record[] records = lookUp.run();
   if (records == null) {
    throw new UnknownHostException();
   }
   return ((PTRRecord) records[0]).getTarget().toString();
  }
}


OUTPUT:


LOCAL ADDRESS : 10.70.50.16
LOCAL HOST : anandkumar-inl

IP : 74.125.135.121

HOST : ni-in-f121.1e100.net.








How to access Abstract class concrete methods in java?


Basically we can't create instance for Abstract class. In that case if we need to access the concrete methods of abstract class then we need to extend abstract class to other class and by instance of those classes we call Abstract class concrete methods.

In other way we can create anonymous class and by using those instance we can call abstract class methods. Lets see example for both the approaches below,

My Abstract class:


public abstract class MyAbstract {
 
 public abstract void add();
 
 public void test(){
  System.out.println("Inside ABSTRACT class");
 }
}


Using Instance of other class:


public class MyTestClass extends MyAbstract{
 
 @Override
 public void add() {
  System.out.println("Inside add method");
 }
 
 public static void main(String[] args) {
  
  MyTestClass obj  = new MyTestClass();
  obj.test();
  obj.add(); 
 }
}

OUTPUT:


Inside ABSTRACT class
Inside add method



Using anonymous class:



public class MyTestClass {
 
 public static void main(String[] args) {
  
  MyAbstract obj = new MyAbstract() {
   
   @Override
   public void add() {
    System.out.println("Inside add method");
    
   }
  }; 
  obj.test();
  obj.add();   
 }
}


OUTPUT:


Inside ABSTRACT class
Inside add method







Difference between HashMap and HashTable in Java


Map is one of the important Interface in Java Collections and Maps contains key and value which always stores unique keys and values. Both HashMap and Hashtable implements Map interface and works based on hashing algorithm. 

Even HashMap and Hashtable implements Map interface but there are few important difference between these. Before using HashMap and Hashtable in application we need to know the functionality of both, by mistake if we select incorrect implementation class then it leads to lot of performance impact and error in our application. 

From JDK 1.4 onwards Hashtable included in Collection
Lets see few important difference between HashMap and Hashtable in Java.


Difference between HashMap and Hashtable.

  • First important difference between HashMap and Hashtable is, Hashtable is thread-safe (by default synchronized) and HashMap is not thread-safe.
  • HashMap allows null key and null value, but Hashmap won't allow null key and value which will give runtime NullPointerException.
  • As performance wise HashMap will be faster than Hashtable since its not synchronized. 
  • Iterator in HashMap class is a fail-fast iterator and enumerator in Hashtable is fail-safe and throw ConcurrentModificationException if any other Thread modifies.


Alternate for Hashtable:

If we need to use HashMap with thread-safe then we can convert HashMap to synchronized HashMap or we can for ConcurrentHashMap class. How to convert HashMap to synchronized HashMap have seen in our earlier tutorial.

Below are simple example for HashMap and Hashtable.

HashMap:


public  class MyTestClass {

 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMap<String, String>();
  hm.put(null, null);
  hm.put("1", "one");
  System.out.println("Value : "+ hm.get(null));
  
  // Converting HashMap to Synchronized HashMap
  hm = Collections.synchronizedMap(hm);  
 }
}


Hashtable:


public  class MyTestClass {

 public static void main(String[] args) {
  
  Map<String, String> ht = new Hashtable<String, String>();
  
  // gives NullPointerException
  //ht.put(null, null);
  
  ht.put("1", "one");
  System.out.println("Value : "+ ht.get(null));
 }
}









Difference between Abstract Class and Interface


This is one of the important interview question ever asked in Java interviews like, What is the the difference between Abstract class and Interface? When we need to use Abstract class and Interface? etc., First lets walk through what is Abstract Class and Interface. 

Abstract Class:


Abstract class is a class which declared as abstract, may or may not contain abstract methods. Abstract method is a method which wont't have any method definition. So in this case abstract class can have abstract methods as well as concrete methods. Once we say these answer few other questions which may asked from interviewer are,


Abstract class can have class variable or not?

Answer: Yes.

Abstract class can have multiple abstract methods and concrete methods? 

Answer: Yes, abstract class can have any no. of abstract and concrete methods.

Abstract class can extend other abstract class and can implement interfaces?

Answer: Yes, It can extend any class and can implement N no. of interfaces. 

Abstract class can also be a Final class?

Answer: No, it can either one only. 

Abstract class can be instantiated?

Answer: No, Abstract class can not be instantiated directly. But we can instantiate by using anonymous class. 

Main thing which we need to remember is, if a class contains any abstract method then compulsory class needs to be declared as abstract.



Interface:
Interfaces will be declared only with method declarations, there will not be method definition. In general all methods are implicitly abstract methods in Interface. Suppose if a Interface declared without any method declaration or variable, then its a Marker Interface. As same as Abstract class few other questions which may be on Interface are,

Interface can have variable or not?
Answer: Yes we can have but it should be Final variable. 

Interface can extend other class ?
Answer: No, Interface can extends only other interfaces.

How many Interfaces can be extended in a single Interface?
Answer: Interface can extends multiple Interfaces like below

public interface MyInterface  extends FirstInterface, SecondInterface {

public int val = 10;

public void myMethod();
}


Difference between Abstract class and Interface?

  • Abstract class can have Abstract method and as well as concrete methods. But Interface always should will have Abstract methods. 
  • Overriding all the Abstract method is not mandatory while we extends Abstract class. But if its a Final class then we need to Override all abstract methods. On other hand when we implements Interface we need to Override all abstract methods in our class. Only in case of Abstract class we don't need to provide implementation (Override) for all methods in Interface. 
  • Abstract class methods can have any access modifiers. But Interface methods should be always public. 
  • As we seen above Abstract class and extends only one class, where as Interface can extends multiple Interfaces. 
  • Abstract class can have Final and non-Final variables. Where as Interface can contain only Final variables. 
  • Abstract class can have Constructors, but Interface cannot have Constructor.
  • As by performance Abstract class will be faster than Interface since it consumes little more time on routing to Override methods. 
  • When we add any new methods in Abstract class then the base classes won't get affected. But in case of Interface if we add any method then all implemented classes will get affected and need to implemented those new methods also.

When to use Abstract class and Interface in Java?

Whenever we talk about When to use Abstract class and Interface in Java will lead to a multiple questions and answers. So in that case programmer need to decide to choice his best in his design stage. Lets see few choices of using Abstract class or Interface according to our needs,

  • Abstract class is more suited for code reuse like inheritance, where as Interfaces are better suited for Type declaration.
  • Using Interface will be suitable if we feel API will be stable for quite long time.
  • Abstract classes are better if we add any methods in our future, since it won't break the code. 
  • Abstract class will be better when we have common method definition and also non public methods and variables. 
  • Interface will be better when we need similar to multiple inheritance. 
  • Best suitable for Template pattern will be Abstract class declaration. 
  • Prefer Interface for providing more design flexibility. 





Google Maps API with multiple marker


In our application or site we will be in need of showing Google MAP with markers of office or other location details. Here we will see simple example for showing a multiple animate overlay markers. Its a basic HTML code were everyone will be searching online. 

Lets see simple example like showing markers in Indian cities like New Delhi, Mumbai, Kolkata, Chennai, Coimbatore, Bangalore and Haldwani. Below is the code while shows marker in each cities. 








<html> 
 <head> 
   <title>Indian Cities </title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
 </head> 

 <body>
  <div id="india" style="width: 650px; height: 700px;"></div>

  <script type="text/javascript">
   
   var cities = [ ['New Delhi', 28.630657, 77.220154, 1],
           ['Mumbai', 19.059868, 72.880554, 2],
         ['Kolkata', 22.571240, 88.360291, 3],
         ['Chennai', 13.042734, 80.260620, 4],
         ['Bangalore', 12.967803, 77.590942, 5],
         ['Haldwani', 29.212430, 79.521790, 6],
         ['Coimbatore', 11.014352, 76.956482, 7] ];

   var map = new google.maps.Map(document.getElementById('india'), {
     zoom: 5,
     center: new google.maps.LatLng(23.322080, 82.134766),
     mapTypeId: google.maps.MapTypeId.ROADMAP,
     animation:google.maps.Animation.BOUNCE
   });

   var infowindow = new google.maps.InfoWindow();

   var marker;

   for (var i = 0; i < cities.length; i++) {  
     marker = new google.maps.Marker({
    position: new google.maps.LatLng(cities[i][1], cities[i][2]),
    animation:google.maps.Animation.BOUNCE,
    map: map
     });

     google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(cities[i][0]);
      infowindow.open(map, marker);
    }
     })(marker, i));
   }
    </script>
 </body>
</html>


Difference between String, StringBuffer and StringBuilder


In this tutorial we will see about difference between String, StringBuffer and StringBuilder. The most important difference that String Object is immutable but whereas StringBuffer/ StringBuilder are mutable. 

So what is immutable and mutable?
Once a value assigned to the String Object then the values can't be modified or changed is called as immutable class. On the other end the values can be changed and modified is called as mutable class.

How String works in Java?
Since String is immutable class we can't change the values once we placed in String Object. But we are able to modify the String value in Java and how its possible? Yes, whenever we modify a String Object new Object will be created. Below example will explain more details on how String works in Java.

String val = "My";
val = val + " Friend";
System.out.println(val);

Output of above code will be "My Friend". We assume that value of "val" gets concatenated. But internally Java creates Object for every String operation which we does. In Java we can create String Object by 2 ways like 

Using "new" operator:
String val = new String("My");

Using String Literal:
String val = "Friend";

Since String creates Objects at each time, we need to switch to StringBuffer or StringBuilder whenever we does String concatenations to avoid multiple String Objects creation and to increase our application performance.

Internally StringBuilder and StringBuffer or mutable, then what is the difference?
If we go back to JDK versions StringBuffer introduced in JDK 1.4 and StringBuilder introduced in JDK 1.5 version. 
Other main difference between StringBuffer and StringBuilder are synchronization. Internally StringBuffer is synchronized and StringBuilder is non-synchronized. Synchronized means it is thread safe and we can use when we implement any multi-threading operations, only one thread can modify StringBuffer at a time. Whereas StringBuilder is not thread safe.

Lets see how to create StringBuffer and StringBuilder

StringBuffer:
StringBuffer str = new StringBuffer();
str.append("My");
str.append(" Friend");
System.out.println(str);

StringBuilder:
StringBuilder str = new StringBuilder();
str.append("My");
str.append(" Friend");
System.out.println(str);






Creating Captcha using Java


In this tutorial we will see how to create Captcha using Java code and to validate through JSP. In recent days we will be seeing in most of the websites are using Captcha for security and to reduce spam entries to their website. 
Captcha is nothing but displaying text, numbers or symbols combination as an image which can not traced automatically by computers, only human can identify. In online there are lot built-in Captcha are available which can be directly included in our sites. Some will be better than other sites like it included text, voice etc.,

Here lets see simple Java code to create Captcha and to test with web application using JSP. Below are the list of files which we are going to use in this demo. 

CaptchaImage.java is a class which will generate random Captcha BufferedImage.

index.jsp used to display Captcha image and to test



CaptchaImage.java


import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

public class CaptchaImage {

    String captchaString = "";

    // Function to generate random captcha image and returns the BufferedImage
    public BufferedImage getCaptchaImage() {
        try {
            Color backgroundColor = Color.white;
            Color borderColor = Color.black;
            Color textColor = Color.black;
            Color circleColor = new Color(190, 160, 150);
            Font textFont = new Font("Verdana", Font.BOLD, 20);
            int charsToPrint = 6;
            int width = 160;
            int height = 50;
            int circlesToDraw = 25;
            float horizMargin = 10.0f;
            double rotationRange = 0.7; 
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
            g.setColor(backgroundColor);
            g.fillRect(0, 0, width, height);

            // lets make some noisey circles
            g.setColor(circleColor);
            for (int i = 0; i < circlesToDraw; i++) {
                int L = (int) (Math.random() * height / 2.0);
                int X = (int) (Math.random() * width - L);
                int Y = (int) (Math.random() * height - L);
                g.draw3DRect(X, Y, L * 2, L * 2, true);
            }
            g.setColor(textColor);
            g.setFont(textFont);
            FontMetrics fontMetrics = g.getFontMetrics();
            int maxAdvance = fontMetrics.getMaxAdvance();
            int fontHeight = fontMetrics.getHeight();

            // i removed 1 and l and i because there are confusing to users...
            // Z, z, and N also get confusing when rotated
            // this should ideally be done for every language...
            // 0, O and o removed because there are confusing to users...
            // i like controlling the characters though because it helps prevent confusion
            String elegibleChars = "ABCDEFGHJKLMNPQRSTUVWXYabcdefghjkmnpqrstuvwxy23456789";
            char[] chars = elegibleChars.toCharArray();
            float spaceForLetters = -horizMargin * 2 + width;
            float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);
            StringBuffer finalString = new StringBuffer();
            for (int i = 0; i < charsToPrint; i++) {
                double randomValue = Math.random();
                int randomIndex = (int) Math.round(randomValue * (chars.length - 1));
                char characterToShow = chars[randomIndex];
                finalString.append(characterToShow);

                // this is a separate canvas used for the character so that
                // we can rotate it independently
                int charWidth = fontMetrics.charWidth(characterToShow);
                int charDim = Math.max(maxAdvance, fontHeight);
                int halfCharDim = (int) (charDim / 2);
                BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
                Graphics2D charGraphics = charImage.createGraphics();
                charGraphics.translate(halfCharDim, halfCharDim);
                double angle = (Math.random() - 0.5) * rotationRange;
                charGraphics.transform(AffineTransform.getRotateInstance(angle));
                charGraphics.translate(-halfCharDim, -halfCharDim);
                charGraphics.setColor(textColor);
                charGraphics.setFont(textFont);
                int charX = (int) (0.5 * charDim - 0.5 * charWidth);
                charGraphics.drawString("" + characterToShow, charX, (int) ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));
                float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
                int y = (int) ((height - charDim) / 2);
                g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);
                charGraphics.dispose();
            }
            g.setColor(borderColor);
            g.drawRect(0, 0, width - 1, height - 1);
            g.dispose();
            captchaString = finalString.toString();
            System.out.println(captchaString);
            return bufferedImage;
        } catch (Exception ioe) {
            throw new RuntimeException("Unable to build image", ioe);
        }
    }

    // Function to return the Captcha string
    public String getCaptchaString() {
        return captchaString;
    }
}


index.jsp


<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.File"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="com.test.CaptchaImage"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Captcha</title>
</head>
<body>

<%
 String result = "Invalid Entry.... :(";
 String color = "red";
    if(request.getParameter("captcha") != null && session.getAttribute("captchaStr") != null){
  if(session.getAttribute("captchaStr").equals(request.getParameter("captcha"))){
   result = "Valid Entry.... :)";
   color = "green";
  }
 }

 CaptchaImage obj = new CaptchaImage();
 BufferedImage ima = obj.getCaptchaImage();
 File outputfile = new File("c://image.jpg");
 ImageIO.write(ima, "jpg", outputfile);
 String captchaStr = obj.getCaptchaString();
 
 session.setAttribute("captchaStr", captchaStr);

%>


<form action="index.jsp" method="post">
 <table>
  <tr>
   <td><img alt="Captcha" src="c://image.jpg"/> </td>
  </tr>
  <tr>
   <td> <input type="text" value="" name="captcha"> </td>
  </tr>
  <tr>
   <td> <input type="submit" value="Submit"> </td>
  </tr>
  <tr>
   <td> <font color="<%=color%>">Value : <%= result %></font></td>
  </tr>
 </table>
</form>

</body>
</html>


OUTPUT:

Creating Captcha using Java





Creating Captcha using Java