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




Using Java Properties class


In this tutorial we will see about Java Properties class and how to use in our project to read property file values. Most of the time in our project we will be use configuration parameters like database connection details or other parameter related to project. Set the parameters in property file and read throughout the application using Java Properties.

Where here values can be easily modified or even we can add new parameters to the project through property file at run-time without reloading the context or editing any java file. 

project.properties


driver=org.postgresql.Driver
url=jdbc:postgresql://localhost/databasseName
user=postgres
password=postgres
maxconn=10
maxidle=0


import java.io.InputStream;
import java.util.Properties;

public class PropertiesTest {

 public static void main(String[] args) {
  
  String propertyFile = "project.properties";
  
  Properties property = new PropertiesTest().readPropertyFile(propertyFile);
  
  System.out.println("DRIVER   : "+property.getProperty("driver"));
  System.out.println("URL      : "+property.getProperty("url"));
  System.out.println("USER     : "+property.getProperty("user"));
  System.out.println("PASSWORD : "+property.getProperty("password"));
  System.out.println("MAX CONN : "+property.getProperty("maxconn"));
  System.out.println("MAX IDLE : "+property.getProperty("maxidle"));
 }
 
 public Properties readPropertyFile(String propertyFile){
  Properties properties = new Properties();
  InputStream inputstream = getClass().getResourceAsStream(propertyFile);
  try {
   properties.load(inputstream);
   System.out.println("NO OF PROPERTIES ::::: " + properties.size());   
  } catch (Exception e) {
   e.printStackTrace();
  }
  return properties;
 }
}


OUTPUT:


NO OF PROPERTIES ::::: 6
DRIVER   : org.postgresql.Driver
URL      : jdbc:postgresql://localhost/databasseName
USER     : postgres
PASSWORD : postgres
MAX CONN : 10
MAX IDLE : 0







Synchronization in Java

In multi-threading resources will be shared by each thread and they can change or modify the values accordingly. Suppose lets see simple example where 2 people are having joint account in a bank and both are withdrawing cash. 1st person from ATM and 2nd person from bank exactly on same time. In that case only 1 operation can permitted between different users(Multiple Threads) to withdraw cash.  

Synchronization can control the access of multiple threads on shared resources. Without synchronization, it is possible for one thread to modify or to change the shared object while another thread accessing the same object value. This often leads to error and application gets failed. So we can use Synchronization to handle these situations like accessing shared memory or objects. 

Synchronization can be implemented in 2 ways like applying Synchronization to complete method or making a single block to Synchronization. Very important that Synchronization will work only same objects, most of the developers will be misunderstanding with Synchronization on multiple Objects of same class. 

Best example which we have already implemented and tested in Singleton Pattern with Synchronization block. Also below we will see simple example for Synchronization block on Synchronization method.


Main class for both Synchronized method and block testing. 


public class SynchronizationMethod {
 public static void main(String[] args) {
  MyTestThreadClass obj = new MyTestThreadClass();
  for(int i=0;i<10;i++){
   // Same MyTestThreadClass class object passing
   Thread t = new Thread(obj);
   t.start();
  }
 }
}

Synchronized method:


public class MyTestThreadClass implements Runnable{
 
 int i = 0; 
 
 public void run() {
  try{
   incrementValue();
   System.out.println(Thread.currentThread().getName() + ": "+i);
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 private synchronized void incrementValue(){
  try{
   // Not allowing 'i' value to cross 6
   if(i <= 5){    
    // Making thread to sleep for few milliseconds
    Thread.sleep(new Random().nextInt(500));
    i++;
   }
  }catch (Exception e) {
   e.printStackTrace();
  }  
 }
}

OUTPUT:

Thread-0: 1
Thread-8: 2
Thread-9: 3
Thread-7: 4
Thread-5: 5
Thread-1: 6
Thread-6: 6
Thread-4: 6
Thread-2: 6
Thread-3: 6

We have used synchronized method in the above example and we can see the ouput that 'i' value didn't cross value 6. If we remove synchronized keyword in the method and if we test same code then we will get wrong output as like below 'i' value may get more than 6 even we place if condition.  


Thread-3: 1
Thread-6: 2
Thread-0: 3
Thread-8: 4
Thread-7: 5
Thread-5: 6
Thread-4: 7
Thread-2: 8
Thread-9: 9
Thread-1: 10

Synchronized block:

Synchronized method is nothing but applying Synchronized keyword to a block of keywork as like below example. 


public class MyTestThreadClass implements Runnable{
 
 int i = 0; 
 
 public void run() {
  try{
   incrementValue();
   System.out.println(Thread.currentThread().getName() + ": "+i);
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 private void incrementValue(){
  try{
   synchronized (MyTestThreadClass.class) {
    if(i <= 5){    
     // Making thread to sleep for few milliseconds
     Thread.sleep(new Random().nextInt(500));
     i++;
    }
   }   
  }catch (Exception e) {
   e.printStackTrace();
  }  
 }
}

OUTPUT:

Thread-0: 1
Thread-7: 2
Thread-9: 3
Thread-8: 4
Thread-6: 5
Thread-4: 6
Thread-2: 6
Thread-1: 6
Thread-3: 6
Thread-5: 6










Serialization in Java


Serialization is a important topic in Java where we will use to Serialize the Object into a file or database or even in memory buffer and can transmitted across the network. Serialized Object can be de-serialized at any time and can get same state of original Object as same as cloning the Object. 

If we say in simple words Serialization is streaming Java object to a sequence of byte and restoring same objects from the stream. For example we need to save the state of Object at run-time we can use Serialization and store the Object state in a file. If same Object state need to be used in future then we can de-derialization and can make use of the Object.

Basically for implementing Serialization we need to implement java.io.Serializable interface in the class where the Objects get Serialized. In below example we have implemented in MySerializable class where this class Objects get Serialized. Serialization can't be used in various class where we use Threads, Socket etc.,

While we Serialize complete class variables will get Serialized. Suppose if we feel some variables should not be Serialized then we need to mark those variables as transient as like we have made in our below example. Those variables will not get serialized and will give null while when we de-serialize those variables. 

Below are the simple example for Serialization where we are serializing MySerializable class Object into a file and again de-serializing same Object back. Also we have used transient for "company" variable which won't get Serialized.



public class MySerializable implements Serializable {

 private static final long serialVersionUID = 1023;
 
 private int id;
 private String name;
 private String gender;
 transient private String company; // Variable will not to be Serialized
 
 public MySerializable(int id, String name, String gender, String company){
  this.id = id;
  this.name = name;
  this.gender = gender;
  this.company = company;
 }
 
 public int getId() {
  return id;
 }
 public String getName() {
  return name;
 }
 public String getGender() {
  return gender;
 }
 public String getCompany() {
  return company;
 }
 }




public class SerializationSample {

 public static void main(String args[])  {
  try{
   
   MySerializable serialB = new MySerializable(101, "Steve", "Male", "XYZ Inc.,");
   
   // Serializing the Object and storing in a file
   serialize("C:\\serial.out", serialB);
   System.out.println("Serialization completed...");
   
  }catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void serialize(String file, Object seriObj)
  throws IOException {
  FileOutputStream fos = new FileOutputStream(file);
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(seriObj);
 } 
}


OUTPUT:

Serialization completed...




public class DeSerializableSample {
 
 public static void main(String[] args) {
  try{
   
   // De-serializing the Object from the file
   MySerializable obj = (MySerializable) deSerialize("C:\\serial.out");
   
   System.out.println("ID      : "+obj.getId());
   System.out.println("NAME    : "+obj.getName());
   System.out.println("GENDER  : "+obj.getGender());
   System.out.println("COMPANY : "+obj.getCompany());
   
  }catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 
 public static Object deSerialize(String seriObj)
  throws FileNotFoundException, IOException, ClassNotFoundException {
  FileInputStream fis = new FileInputStream(seriObj);
  ObjectInputStream ois = new ObjectInputStream(fis);
  return ois.readObject();
 }
}


OUTPUT:

ID      : 101
NAME    : Steve
GENDER  : Male
COMPANY : null






How to create executable jar file using eclipse

 

In most of the projects and applications we will use jar files. It can be 3rd party or even internal organization jar files. JAR files are nothing but Java ARchive which will be wrapped with the bundle of .class files, Java files, images, audio or video are any file formats. Its nothing but same as ZIP file which we used in our daily practice. 

By using any unzipping tools we can unwrap JAR files to get files inside. Since mainly its used for .class files and by using obfuscate developers can protect their code and implementation from other users.  

JAR files will be of 2 formats. 
1. Non executable JAR file
2. Executable JAR file

In this tutorial we will how to create executable jar using Eclipse and how to run in Windows. Important for creating executable jar file we need to have at-least single main() method in our project which will be executable. 


STEP - 1: Create new project which we need to implement our functionality  In this demo just we will add 2 numbers as like below. We have created Java Project called AddNumbers and we have class called Add2Numbers and we have implemented our code. Run and test the program once we have implemented. 


creating executable jar file using eclipse


STEP - 2: Right click on Project -> Export -> Java -> Runnable JAR file


creating executable jar file using eclipse


STEP - 3: Click Next and select Project and Class name under Launch configuration: <Add2Numbers - AddNumbers>

 Also enter the folder path and name to save the JAR file in Export destination: D:\\test\AddNubers.jar and click Finish. 

creating executable jar file using eclipse


STEP - 4: Next test your executable jar file from command prompt.


creating executable jar file using eclipse






Simple Web Service using SOAP


In one of our earlier tutorial we have seen Web Services in Java and we have discussed about SOAP Web Service and RESTful Web Services along with their differences. As further we will see a simple example for how to create Web Service server and client using SOAP. For this we will use eclipse J2EE IDE and Apache Tomcat as web server.

First we will create simple Server which will take 2 numbers as input and returns the addition of the program. Here by using Eclipse its very simple to create a service and to deploy and publish a service. Everything we can do it just by clicks rather than doing it lot manually. And also using IDE's will make life more easy than manually.

Server Program:

STEP - 1 : Create a Dynamic Web Project (File -> New -> Dynamic Web Project). Create your project by setting your Target run-time server to installed Apache Tomcat web server. In demo I have used Apache Tomcat 7.0 and you can decide your version according to your need. 

Simple Web Service using SOAP


STEP - 2 : Create a new class file under Java Resource by giving package and class name. Then implement the server side method to publish.  

Simple Web Service using SOAP


STEP - 3 : After finishing the server side method implementation, select New -> Others and type "web" in Wizards, where you can see Web Service under Web Services list. 

Simple Web Service using SOAP


STEP - 4 : Click next and select the class which you implemented the method to publish under Service implementation drop down box. As already we are ready with Develop service, so we have to
Assemble service
Deploy service
Install service
Start service 
Test service

to make Web Service server ready with publishing the service which we have implemented. So that just passing the WSDL (Web Services Description Language) to client they can understand the server implementation and can consume our service easily. Basically its XML which used to describe the functionality offered or published by a web service. For more details on WSDL you can refer to WSDL wiki.

Simple Web Service using SOAP


STEP - 5 : Our Web Service server created successfully and we are ready to test our service. In next screen you can see SOAP Binding and service created with WSDL. You can pass input parameter and can test the service as below 

Simple Web Service using SOAP


And also we can see SOAP request and response by switching from form to source in result tab as below. 

Simple Web Service using SOAP


STEP - 6 : Next you can check your WSDL file have created correctly or not in your web browser by passing. http://localhost:8080/MyServer/services/MyClass?wsdl

Simple Web Service using SOAP



We have done with server implementation by creating the service and publishing with the help of Eclipse of IDE. Next important that we are going to localhost as our web server so we should not stop the server which running. In real-time we will deploy our service in some web servers and we will access our service through internet. Where as for our demo we are localhost for both server and client. 

Next go-head and create the client and consume the service which we have published above. For that we need to create the client application given below. 


Client Program:

STEP - 7 :  Create a Dynamic Web Project (File -> New -> Dynamic Web Project).

Simple Web Service using SOAP


STEP - 8 : Next we need to create stub from WSDL file. For this server where we have published need to be running and as discussed above we haven't stopped the server which we have started while creating our server. 
For creating Web Service Client we need to select New -> Other and type "web" in the Wizards as given below and select the Web Service Client under Web Services tab.

Simple Web Service using SOAP


STEP - 9 : Click Next and pass the WSDL url in Service definition text box and set as Test client and click Finish which will read the WSDL file and generate the java stub code. 

Simple Web Service using SOAP


Once you finished we can see the Java stub created along with Service and Proxy classes. Next we can see the list of method(s) published by server. By selecting the method we can test directly from eclipse by giving inputs as below image.

Simple Web Service using SOAP


STEP - 10 : Next we need to write a client program to invoke the remote method using SOAP Web Services. Create new class called MyClient as below image.

Simple Web Service using SOAP


STEP - 11 : Just implement the client by using endpoint URL and service instance and test your Web Service using SOAP.

Simple Web Service using SOAP