Sunday, September 15, 2013
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart"), a trademark of Carnegie Mellon University, is a type of challenge-response test used in computing to determine whether or not the user is human. This requires the user to type the letters of a distorted image, sometimes with the addition of an obscured sequence of letters or digits that appears on the screen. Because the test is administered by a computer, in contrast to the standard Turing test that is administered by a human, a CAPTCHA is sometimes described as a reverse Turing test. This test is most common when someone registers or opens a new account in any website.
       Here we will be using jcaptcha library for captcha generation and validation. In our demo we will follow MVC architecture to carry this out. We have the following classes, servlets and JSPs in our project.

  • login.jsp : This is the home page. Here the captcha challenge image will be shown with a text-box to enter the characters.  On submitting it is validated by a servlet.
  • CaptchaService class : This is a singleton class that is responsible for generating the instance that will help in generating the challenge image.
  • CaptchaGeneratorServlet class : this servlet has a GET method which generates the image with CaptchaService class and converts it to a byte array and then writes to the output stream. The image is generated using the session id of the user which is used as the captcha id.
  • CaptchaVerifierServlet class : It has a POST method which receives the input characters from usere and validates it. The result is returned as a boolean which is set as a session attribute and for the result to be shown it is forwarded to a JSP.
  • results.jsp : It extracts the session attribute and displays result according to that.


-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
/* Code for login.jsp */
<!DOCTYPE html>
<html>
<head>
<title>JCaptcha Demo</title>
</head>
<body>
   <h2>JCaptcha Demo</h2>
   <form action="captcha-verifier" method="post">
      <input type="hidden" name="captchaID" value="<%= session.getId() %>"/>
      <table><tr>
           <td valign="middle">Enter these letters:<br/>
           <img src="./captcha-generator" align="middle" alt="Enter the 
             characters appearing in this image" border="1"/></td>
           <td><input type="text" name="inChars"/></td>
         </tr>
         <tr>
           <td><input type="submit" value="Submit"/></td>
         </tr>
      </table>
   </form>
</body>
</html>


/* Code for CaptchaService.java */
package java_code_house.jcaptcha;

import com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;

public class CaptchaService{
    // a singleton class
    private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
    
    public static ImageCaptchaService getInstance(){
     return instance;
    }

}



/* Code for CaptchaGeneratorServlet.java */
package java_code_house.jcaptcha;

import com.octo.captcha.service.CaptchaServiceException;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/captcha-generator")
public class CaptchaGeneratorServlet extends HttpServlet{
 private static final long serialVersionUID=1L;
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  ByteArrayOutputStream imgStream = new ByteArrayOutputStream();
  byte[] captchaBytes=null;

   try{
   // Session ID is used to identify the particular captcha
   String captchaId = request.getSession().getId();
   // Generate the captcha image
   BufferedImage img = CaptchaService.getInstance().getImageChallengeForID(
     captchaId, request.getLocale() );
   ImageIO.write(img, "jpeg", imgStream );
   captchaBytes = imgStream.toByteArray();

    // Clear any existing flag
   request.getSession().removeAttribute("result");
  }catch( CaptchaServiceException|IOException ex ) {
   System.out.println(ex);
  }

   // Set appropriate http headers
  response.setHeader( "Cache-Control", "no-store" );
  response.setHeader( "Pragma", "no-cache" );
  response.setDateHeader( "Expires", 0 );
  response.setContentType( "image/jpeg");

   // Write the image to the client
  OutputStream os = response.getOutputStream();
  os.write(captchaBytes);
  os.flush();
  os.close();
 }

}



/* Code for CaptchaVerifierServlet.java */
package java_code_house.jcaptcha;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;

@WebServlet("/captcha-verifier")
public class CaptchaVerifierServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // Get the request params
  String cId = request.getParameter("captchaID");
  String inChars = request.getParameter("inChars");

   // Validate whether input from user is correct
  boolean hasPassed = validateCaptcha(cId, inChars );
  
  // Set flag into session
  request.getSession().setAttribute( "result", new Boolean(hasPassed) );

   // Forward request to results page
  request.getRequestDispatcher( "/results.jsp" ).forward( request, response );
 }

  private boolean validateCaptcha( String captchaId, String inputChars ){
  boolean b = false;
  try{
   b = CaptchaService.getInstance().validateResponseForID( captchaId, inputChars );
  }catch( CaptchaServiceException cse ){}
  return b;
 }

}



/* Code for results.jsp */
<!DOCTYPE html> 
<html>
<head>
<title>JCaptcha Demo - Result</title>
</head>
<body>
    <% Boolean b = (Boolean)session.getAttribute("result");
        if ( b!=null && b.booleanValue() ){
    %>
             Congrats!  You passed the Captcha test!
    <% } else { %>
             Sorry, you failed the Captcha test.
    <% } %>
</body>
</html>

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
NOTE : While exporting the project from eclipse, optimization for Apache Tomcat v7 was done. Also it includes the source files as well as the jar files required to execute this.

Happy coding :)
Sunday, September 1, 2013
In our vlast posts we only concentrated on sniffing class declaration and its members. But this time we will go beyond it and try to get and set field values of a given class using Java Reflection.For this we just need an instance of a class. Though here we will deal with public fields only and someone might think that we can get and set field values in thes cases directly using instance of that class. But this is not the actual case in real situation. This is done only in places where directly we cannot set thopse values as in case of private members. So here we have used method getDeclaredField() (we will deal with private members later). Here we will just show that once you have the class refernce and the instance of a particualr class you can get and set the field values whether its an integer,float,string or array. There are seperate methods for different primitive data types like getInt() and setInt() for int , getLong() and setLong() for long and so on. But for data types other than primiotive ones you have to use get() and set() methods.
      Here in our demo we jave created a class Person with fields of type int, String and a String array. So you will be able to uinderstand clearly how to use different methods depending on data type.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.lang.reflect.Field;
import java.util.Arrays;

import static java.lang.System.out;

class Person{
public int id=1521;
public String name="Luther";
public String hobbies[]={"cricket","music"};
}

public class FieldChanger {
public static void main(String[] args) {
try{
    Class c=Person.class;  //getting class reference
    Person pobj=new Person();
    
    Field id=c.getDeclaredField("id");  //getting field reference
    out.println("BEFORE :   id = "+id.getInt(pobj));  //getting initial int value
    id.setInt(pobj, 1926);  //setting a new int value
    out.println(" AFTER :   id = "+id.getInt(pobj));
    
    Field name=c.getDeclaredField("name");
    out.println("BEFORE :   name = "+name.get(pobj));  //getting initial String value
    name.set(pobj, "Jennifer");  //setting a new String value
    out.println(" AFTER :   name = "+name.get(pobj));
    
    Field hobbies=c.getDeclaredField("hobbies");
    //showing initial array values
    out.println("BEFORE :   hobbies = "+Arrays.asList(pobj.hobbies));
    String[] nhob={"football"};
    hobbies.set(pobj, nhob);  //setting new values for array
    out.println(" AFTER :   hobbies = "+Arrays.asList(pobj.hobbies));
    
}catch(NoSuchFieldException|
IllegalAccessException e){ }
}
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
BEFORE :   id = 1521
 AFTER :   id = 1926
BEFORE :   name = Luther
 AFTER :   name = Jennifer
BEFORE :   hobbies = [cricket, music]
 AFTER :   hobbies = [football]
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------

Happy coding :)
Saturday, August 10, 2013
In our last post we were only concerned in retrieving the declaration details of any class. Today I will go further and try to sniff inside any class. So today I will show you how you can retrieve all the constructors, fields and methods of any class using Java Reflection. For now we will only try to discover all the public members of a class and deal with private ones later. The java.lang.Class provides suitable methods for discovering the members. Here in our sample code we will first take as input the concerned class name and load it using Class.forName(). Then in order to get all its public constructors we vwill use getConstructors(), for fields use getFields() and for methods use getMethods(). An important thing to mention here is that these will return all the public members declared in that class as well as those inherited from its parent. You wont be able to retrieve the private members declarec using these methods. In order to get private members also use getDeclaredConstructors(), getDeclaredFields() and getDeclaredMethods(); but in this case you wont be able to get the inherited members.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import static java.lang.System.out;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ClassSniffer {
        public static void main(String[] args) {
        out.print("Enter Class Name : ");
        String cname=System.console().readLine();
        try {
        Class c=Class.forName(cname);
        out.println("\n------OUTPUT------");
            //getting all constructors
        out.println("\nConstructors : ");
            Constructor<?> cons[]=c.getConstructors();
            for(Constructor<?> con : cons)
                 out.println("  "+con);
            //getting all fields
            out.println("\nFields : ");
            Field fs[]=c.getFields();
            if(fs.length>0)
                for(Field f : fs)
                      out.println("  "+f);
            else
                out.println("  --No Fields Declared--");
            //getting all methods
            out.println("\nMethods : ");
            Method ms[]=c.getMethods();
            for(Method m : ms)
                     out.println("  "+m);
   } catch (ClassNotFoundException e) {
          e.printStackTrace();
   }
}
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Enter Class Name : ClassSniffer

------OUTPUT------

Constructors :
  public ClassSniffer()

Fields :
  --No Fields Declared--

Methods :
  public static void ClassSniffer.main(java.lang.String[])
  public final void java.lang.Object.wait(long,int) throws java.lang.Interrupted
Exception
  public final native void java.lang.Object.wait(long) throws java.lang.Interrup
tedException
  public final void java.lang.Object.wait() throws java.lang.InterruptedExceptio
n
  public boolean java.lang.Object.equals(java.lang.Object)
  public java.lang.String java.lang.Object.toString()
  public native int java.lang.Object.hashCode()
  public final native java.lang.Class java.lang.Object.getClass()
  public final native void java.lang.Object.notify()
  public final native void java.lang.Object.notifyAll()

NOTE : Here you can see that the methods inherited from Object class are also listed. The name of the class is mentioned just before the method name which shows the methods inherited from other class and those declared in the class itself. Try running this code with getDeclaredConstructors(), getDeclaredFields() and getDeclaredMethods() instead and see the output.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Thursday, August 8, 2013
Today I will show you how to retrieve all the declaration components of a class using Java Reflection. The declaration components means the modifiers, the generic type parameters, implemented interfaces, classes inherited i.e. inheritance path and all the annotations declared. These are all the meta informations related with a class. We can get all modifiers using method getModufiers(). The different modifiers include private, protected, public, static, final, abstract etc. We can get annotations using getAnnotations(). We can get type parameters using getTypeParameters() while interfaces using getGenericInterfaces() and super-class using getSuperClass().
           Here in the example we will take input from user the fully qualified class name and then print all the declaration components of that class using the methods mentioned above and thus sniff class declaration. If the class name eneterd is not found then it will throw ClassNotFoundException.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.io.Console;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;

import static java.lang.System.out;

public class ClassDeclarationSniffer {
    public static void main(String[] args) {
Console console=System.console();
System.out.print("Enter Class Name : ");
String cname=console.readLine();  //reading class name
try {
Class<?> c=Class.forName(cname);  //loading class
out.println("\n------OUTPUT------");
out.println("Class : "+c.getCanonicalName());
//getting all modifiers
out.println("\nModifiers : "+Modifier.toString(c.getModifiers()));
//getting generic type parameters
out.print("\nType Parameters : ");
TypeVariable[] tv = c.getTypeParameters();
   if (tv.length != 0)
   for (TypeVariable t : tv)
       out.print(t.getName()+" ");
   else
       out.print("  -- No Type Parameters --");
   //getting all implemented interfaces
   out.println("\n\nImplemented Interfaces :");
   Type[] intfs = c.getGenericInterfaces();
   if (intfs.length != 0)
   for (Type intf : intfs)
       out.println("  "+intf.toString());
   else
       out.println("  -- No Implemented Interfaces --");
   //getting inheritance hierarchy
   out.println("\nInheritance Path : ");
   List<Class> lst = new ArrayList<Class>();
   printParent(c, lst);
   if (lst.size() != 0)
   for (Class<?> parent : lst)
       out.println("  "+parent.getCanonicalName());
   else
       out.println("  -- No Super Classes --");
   //getting all annotations
   out.println("\nAnnotations : ");
   Annotation[] anns = c.getAnnotations();
   if (anns.length != 0)
   for (Annotation a : anns)
       out.println("  "+a.toString());
   else
out.println("  -- No Annotations --");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
    
    private static void printParent(Class<?> c, List<Class> l) {
    Class<?> parent = c.getSuperclass();  //getting superclass
      if (parent != null) {
       l.add(parent);  //adding to hierarchy list
       printParent(parent, l);  //recursive calling for another parent
      }
    }
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Enter Class Name : java.util.ArrayList

------OUTPUT------
Class : java.util.ArrayList

Modifiers : public

Type Parameters : E

Implemented Interfaces :
  java.util.List<E>
  interface java.util.RandomAccess
  interface java.lang.Cloneable
  interface java.io.Serializable

Inheritance Path :
  java.util.AbstractList
  java.util.AbstractCollection
  java.lang.Object

Annotations :
  -- No Annotations --
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Sunday, August 4, 2013
Synchronization is built around an internal intity known as intrinsic lock or monitor lock. It helps in achieving an exclusive access to an object's state and establishes a happens-before relationship. In java every object has an intrinsic lock associated with it. A thread can have exclusive access only when it has acquired an intrinsic lock on that object. When it has completed its operation, it must release the lock. No other threads can acquire lock on that object in the meantime. If any other threads try to do that it will be blocked. In Java, a thread acquires an intrinsic lock as soon as it call a synchronized method or block. The lock is released when the method returns or block ends. Here we will use this technique to solve the famous Producer-Consumer example.
About Producer-Consumer Example : This is a famous problem where a producer will produce messages in a buffer and the consumer will consume those messages from buffer. Here buffer is the shared resource. There is no problem if it is unbounded buffer, but in practical situations its always bounded (Here also we will show with bounded buffer). If the buffer is empty, then the consumer must wait for producer to produce; and if buffer is full, producer must wait for consumer to consume.
       In our example, we will have a shared queue where the data will be produced. After producing , producer thread will go to sleep for a random time. Similarly for consumer , after it consumes a data it will go to sleep for random time. Producer thread will produce data and call produce() method while consumer thread will call consume() method and these two methods are synchronized. Whenever buffer is empty or full the concerned thread will wait by calling wait() method, and as soon as there is a change in status of buffer it will be informed using notifyAll(). So we can also say that we are trying to solve this problem using wait and notify.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
/* Code for the Shared-Object */
package intrinsic;

import java.util.LinkedList;
import java.util.Queue;

public class SharedObject {
     //buffer to store data
     private Queue<Integer> queue=new LinkedList<>();
     private final int SIZE;  //maximum size of buffer
     
     public SharedObject(int size){
    SIZE=size;
     }
     
     public synchronized void produce(int i){
     while(queue.size()==SIZE){
    System.out.println("Queue full."+Thread.currentThread().getName()+" is waiting to produce");
    try {
wait();  //wait if buffer is full
} catch (InterruptedException e) {
e.printStackTrace();
}
    }
     queue.add(i);  //storing the data
 System.out.println("Produced : "+i);
     notifyAll();  //notify consumer that status has changed
     }
     
     public synchronized int consume(){
     while(queue.size()==0){
    System.out.println("Queue empty."+Thread.currentThread().getName()+" is waiting to consume");
    try {
wait();  //wait if buffer is empty
} catch (InterruptedException e) {
e.printStackTrace();
}
    }
     notifyAll();  //notify producer that status has changed
     return queue.remove();  //consume the data
     }
}

/* Code for Producer thread */
package intrinsic;

import java.util.Random;

public class Producer implements Runnable {
private SharedObject so;
public Producer(SharedObject so){
this.so=so;
}
@Override
public void run() {
Random r=new Random();
for(int i=1;i<=10;i++){
so.produce(i);
try {
Thread.sleep(r.nextInt(5000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

/* Code for Consumer thread */
package intrinsic;

import java.util.Random;

public class Consumer implements Runnable {
private SharedObject so;
public Consumer(SharedObject so){
this.so=so;
}
@Override
public void run() {
Random r=new Random();
int i=0;
while((i=so.consume())<10){
System.out.println("Consumed : "+i);
try {
Thread.sleep(r.nextInt(5000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
                System.out.println("Consumed : "+i);
}
}

/* Code to run this example */
package intrinsic;

public class Demo {

public static void main(String[] args) {
SharedObject so=new SharedObject(2);
(new Thread(new Producer(so), "Producer")).start();
(new Thread(new Consumer(so), "Consumer")).start();
}
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Produced : 1
Consumed : 1
Queue empty.Consumer is waiting to consume
Produced : 2
Consumed : 2
Produced : 3
Consumed : 3
Produced : 4
Produced : 5
Queue full.Producer is waiting to produce
Consumed : 4
Produced : 6
Queue full.Producer is waiting to produce
Consumed : 5
Produced : 7
Queue full.Producer is waiting to produce
Consumed : 6
Produced : 8
Queue full.Producer is waiting to produce
Consumed : 7
Produced : 9
Queue full.Producer is waiting to produce
Consumed : 8
Produced : 10
Consumed : 9
Consumed : 10
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------

Total Pageviews

Followers


Labels

Popular Posts

free counters