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.
-------------------------------------------------------------------------------------------------------------------------
/* Code for login.jsp */
/* Code for CaptchaService.java */
/* Code for CaptchaGeneratorServlet.java */
/* Code for CaptchaVerifierServlet.java */
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; } }
<!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 :)
Labels:J2EE | 8
comments
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.
-------------------------------------------------------------------------------------------------------------------------
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){ }
}
}
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 :)
Labels:Reflection | 0
comments
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.
--------------------------------------------------------------------------------------------------------------------------
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();
}
}
}
--------------------------------------------------------------------------------------------------------------------------
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
--------------------------------------------------------------------------------------------------------------------------
Labels:Reflection | 0
comments
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.
--------------------------------------------------------------------------------------------------------------------------
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
}
}
}
--------------------------------------------------------------------------------------------------------------------------
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 --
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
--------------------------------------------------------------------------------------------------------------------------
Labels:Reflection | 0
comments
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.
--------------------------------------------------------------------------------------------------------------------------
/* 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
}
}
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
--------------------------------------------------------------------------------------------------------------------------
Labels:Threads | 0
comments
Wednesday, July 31, 2013
In current times, we are always trying to complete our tasks in least possible amount of time. This has given rise to the need for multithreading. In multithreaded application, we have more than one threads running at the same time. We can see that when we are writing some document in Microsoft Word we can write as well as run the spell-checker at the same time. This is done by multithreading. But the real problem arises when a shared resource is being accessed by more than one thread at the same time.
For an example, let us consider that we we are in a situation where a couple Williams and Jennifer, both have an access to the same bank account but have two ATM cards one for each. Now, both of them are trying to withdraw a certain amount from the same account. Now here arises the problem. Suppose, they have now currently $1000 in account and can withdraw a maximum of $300. Before withdrawing, they must check balance and then withdraw. Now Williams checks the balance and waits for withdrawing while in the meantime Jennifer checks balance and sees that she can also withdraw a maximum of $300. Since both have the information that they can withdraw a maximum of $300, it results in "inconsistency" of data. This should be avoided. So we need synchronization.
Synchronization will help in atomic operation. If we take our previous example then Jennifer should not be allowed to access the account until and unless Williams has completed his operation. So, she should be locked from accessing it.
Object locking in Java can be done in two way - intrinsic locks and explicit locks. Intrinsic lock is achieved using the "synchronized" keyword in Java. On using this in a method or block will ensure that all the operations done inside that method or block will be done in a single operation. Explicit locks is done using Lock objects.
We will discuss in detail on intrinsic and explicit locks using Producer-Consumer example in our next posts. Keep in touch with us.
For an example, let us consider that we we are in a situation where a couple Williams and Jennifer, both have an access to the same bank account but have two ATM cards one for each. Now, both of them are trying to withdraw a certain amount from the same account. Now here arises the problem. Suppose, they have now currently $1000 in account and can withdraw a maximum of $300. Before withdrawing, they must check balance and then withdraw. Now Williams checks the balance and waits for withdrawing while in the meantime Jennifer checks balance and sees that she can also withdraw a maximum of $300. Since both have the information that they can withdraw a maximum of $300, it results in "inconsistency" of data. This should be avoided. So we need synchronization.
Synchronization will help in atomic operation. If we take our previous example then Jennifer should not be allowed to access the account until and unless Williams has completed his operation. So, she should be locked from accessing it.
Object locking in Java can be done in two way - intrinsic locks and explicit locks. Intrinsic lock is achieved using the "synchronized" keyword in Java. On using this in a method or block will ensure that all the operations done inside that method or block will be done in a single operation. Explicit locks is done using Lock objects.
We will discuss in detail on intrinsic and explicit locks using Producer-Consumer example in our next posts. Keep in touch with us.
Labels:Java FAQs,Threads | 0
comments
Wednesday, July 24, 2013
Today I will show you how you can use the power of filters to do session tracking. We will create a special type of filter here that will do session tracking. You people must have experienced that when you visit some websites(like facebook,twitter etc) you cannot access all the pages until you are logged in. Today we will implement this feature. We will write a session filter that checks for a certain attribute in the session object to see whether the user is already logged in or not. If the user is logged in then he can access those pages otherwise will be redirected to the home page. Here the filter will act as a phantom and intercept the request and according to that send the response.
Here we will consider that as soon as the user logs in a attribute named "user" is set with object of some User class that contains all user details using methods getSession(false) and getAttribute(). So we will test whether taht attribute exists or not. If it exists then he will be able to access the requested page, otherwise will be redirected to login page using sendRedirect().
--------------------------------------------------------------------------------------------------------------------------
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionFilter implements Filter {
public void destroy() {
System.out.println("SessionFilter destroyed");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request; //casting
HttpServletResponse res=(HttpServletResponse)response;
HttpSession session=req.getSession(false); //getting session object
if(session!=null){
Object usr=session.getAttribute("user"); //getting attribute
if(usr==null){ //if its null then not logged in
System.out.println("Invalid Session");
res.sendRedirect("./login.jsp"); //redirecting to login page
}
else
chain.doFilter(req, res); //permitting to access if logged in
}
else
res.sendRedirect("./login.jsp"); //redirecting if no session object
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("SessionFilter initialized");
}
}
Here we will consider that as soon as the user logs in a attribute named "user" is set with object of some User class that contains all user details using methods getSession(false) and getAttribute(). So we will test whether taht attribute exists or not. If it exists then he will be able to access the requested page, otherwise will be redirected to login page using sendRedirect().
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionFilter implements Filter {
public void destroy() {
System.out.println("SessionFilter destroyed");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request; //casting
HttpServletResponse res=(HttpServletResponse)response;
HttpSession session=req.getSession(false); //getting session object
if(session!=null){
Object usr=session.getAttribute("user"); //getting attribute
if(usr==null){ //if its null then not logged in
System.out.println("Invalid Session");
res.sendRedirect("./login.jsp"); //redirecting to login page
}
else
chain.doFilter(req, res); //permitting to access if logged in
}
else
res.sendRedirect("./login.jsp"); //redirecting if no session object
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("SessionFilter initialized");
}
}
NOTE : If you are using servlet 3.0 then mention the url's for which you want to add this filter using WebFilter annotation. But if you are using Servlet2.5 then use the <filter-mapping> tag in web.xml to map this filter to url's. So depending on your web-app use the different way you want , so I am not mentioning it in my code.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:J2EE | 0
comments
Sunday, June 16, 2013
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock avoidance algorithm that tests for safety by simulating the allocation of predetermined maximum possible amount of all resources, and then makes a check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. Here we have 3 input matrix where
max[][] - denotes maximum resources that will be required by processes
allocate[][] - denotes currently allocated resources to processes
avail[][] - denotes resources available in the system
We will calculate need matrix and then try to allocate. I f we can allocate safely then give a suitable message.
--------------------------------------------------------------------------------------------------------------------------
max[][] - denotes maximum resources that will be required by processes
allocate[][] - denotes currently allocated resources to processes
avail[][] - denotes resources available in the system
We will calculate need matrix and then try to allocate. I f we can allocate safely then give a suitable message.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner; public class Bankers{ private int need[][],allocate[][],max[][],avail[][],np,nr; private void input(){ Scanner sc=new Scanner(System.in); System.out.print("Enter no. of processes and resources : "); np=sc.nextInt(); //no. of process nr=sc.nextInt(); //no. of resources need=new int[np][nr]; //initializing arrays max=new int[np][nr]; allocate=new int[np][nr]; avail=new int[1][nr]; System.out.println("Enter allocation matrix -->"); for(int i=0;i<np;i++) for(int j=0;j<nr;j++) allocate[i][j]=sc.nextInt(); //allocation matrix System.out.println("Enter max matrix -->"); for(int i=0;i<np;i++) for(int j=0;j<nr;j++) max[i][j]=sc.nextInt(); //max matrix System.out.println("Enter available matrix -->"); for(int j=0;j<nr;j++) avail[0][j]=sc.nextInt(); //available matrix sc.close(); } private int[][] calc_need(){ for(int i=0;i<np;i++) for(int j=0;j<nr;j++) //calculating need matrix need[i][j]=max[i][j]-allocate[i][j]; return need; } private boolean check(int i){ //checking if all resources for ith process can be allocated for(int j=0;j<nr;j++) if(avail[0][j]<need[i][j]) return false; return true; } public void isSafe(){ input(); calc_need(); boolean done[]=new boolean[np]; int j=0; while(j<np){ //until all process allocated boolean allocated=false; for(int i=0;i<np;i++) if(!done[i] && check(i)){ //trying to allocate for(int k=0;k<nr;k++) avail[0][k]=avail[0][k]-need[i][k]+max[i][k]; System.out.println("Allocated process : "+i); allocated=done[i]=true; j++; } if(!allocated) break; //if no allocation } if(j==np) //if all processes are allocated System.out.println("\nSafely allocated"); else System.out.println("All proceess cant be allocated safely"); } public static void main(String[] args) { new Bankers().isSafe(); } }
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Enter no. of processes and resources : 3 4
Enter allocation matrix -->
1 2 2 1
1 0 3 3
1 2 1 0
Enter max matrix -->
3 3 2 2
1 1 3 4
1 3 5 0
Enter available matrix -->
3 1 1 2
Allocated process : 0
Allocated process : 1
Allocated process : 2
Safely allocated
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Algorithms | 24
comments
Saturday, June 15, 2013
Today I will show you how to install Java on Ubuntu. New Linux users may find it difficult to install, so I will be sharing this post to help you people out. There are two procedures to do that. First is do it directly from terminal and the second is do it manually if you already have the binaries. We will show you the second procedure.
Step 1 : Download Java from Oracle Java SE Downloads . Download the appropriate version according to your platform architecture. [NOTE : The download link is subject to change. If dead please report it. ]
Step 2 ; Unpack the archive using the following command
tar xvzf <file-name> [ e.g. jdk-7u21-linux-x64.tar.gz ]
You will get a folder something named jdk1.7.0.
Step 3 : Next we will have to create a directory named jvm and copy the extracted folder into it with following command.
mkdir jvm
cp -r <extracted-folder-name> jvm [ e.g. cp -r jdk1.7.0 jvm ]
Now we will have to move this jvm folder to /usr/lib directory.
sudo mv jvm /usr/lib . Enter password when asked.
Step 4 : Since we have successfully copied the folder, now we will only have to tell the Linux system where your Java is installed.
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
-It will tell that JRE is available
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
-It will tell Java Compiler is available
Step 1 : Download Java from Oracle Java SE Downloads . Download the appropriate version according to your platform architecture. [NOTE : The download link is subject to change. If dead please report it. ]
Step 2 ; Unpack the archive using the following command
tar xvzf <file-name> [ e.g. jdk-7u21-linux-x64.tar.gz ]
You will get a folder something named jdk1.7.0.
Step 3 : Next we will have to create a directory named jvm and copy the extracted folder into it with following command.
mkdir jvm
cp -r <extracted-folder-name> jvm [ e.g. cp -r jdk1.7.0 jvm ]
Now we will have to move this jvm folder to /usr/lib directory.
sudo mv jvm /usr/lib . Enter password when asked.
Step 4 : Since we have successfully copied the folder, now we will only have to tell the Linux system where your Java is installed.
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
-It will tell that JRE is available
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
-It will tell Java Compiler is available
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1
-It will tell Java Web Start is available
NOTE : There are many more executables that you may need to install like jar, javap, appletviewer and so on. Just perform the step 4 for installing any other features. We have just mentioned about java, javac and javaws. Also note that it is not mandatory to name the folder as jvm.
Hope this helps you. Keep coding :)
Labels:Java FAQs | 0
comments
Thursday, June 13, 2013
Today I am going to show you how you can perform edge detection on any image using Java. Here we will use the convolution operator to perform this. But for this we need a kernel to perform this operation. But before that we will first give a breif description about this.
ConvolveOp class : ConvolveOp is one of the most versatile image operators in the 2D API. It represents a spatial convolution, which is a fancy mathematical term that means that the color of each destination pixel is determined by combining the colors of the corresponding source pixel and its neighbors. A convolution operator can be used to blur or sharpen an image, among other things.
ConvolveOp class : ConvolveOp is one of the most versatile image operators in the 2D API. It represents a spatial convolution, which is a fancy mathematical term that means that the color of each destination pixel is determined by combining the colors of the corresponding source pixel and its neighbors. A convolution operator can be used to blur or sharpen an image, among other things.
Kernel class : The convolution operator uses a kernel to specify how a source pixel and its neighbors are combined. A kernel is simply a matrix, where the center of the matrix represents the source pixel and the other elements correspond to the neighboring source pixels. The destination color is calculated by multiplying each pixel color by its corresponding kernel coefficient and adding the results together.
How the operation will be performed - We will first read an image using read() method of ImageIO as BufferedImage. Next pass this to a function edgeDetect() where the operation will be carried out. Here we will first create a 3x3 array for kernel whose values add upto less than 1, which means that the image that will be produced will be darker. Next we will create the convolution operator creating ConvolveOp instance using the Kernel. Next we will call filter() method to perform the operation.
Screenshots of the images
Original Image |
Image after Edge Detection |
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import javax.imageio.ImageIO;
public class EdgeDetection {
public BufferedImage detectEdge(BufferedImage src){
//kernel for edge detection adding upto less than 1
float edgeArr[]={0,-1,0,-1,4,-1,0,-1,0};
//creating the convolution operator
ConvolveOp edgeOp=new ConvolveOp(new Kernel(3,3,edgeArr),ConvolveOp.EDGE_NO_OP,null);
return edgeOp.filter(src, null); //operating on image
}
public static void main(String[] args)throws Exception {
EdgeDetection obj=new EdgeDetection();
BufferedImage src=ImageIO.read(new File("src_edge.jpg")),
dest=obj.detectEdge(src); //edge detection
ImageIO.write(dest, "jpeg",new File("dest_edge.jpg"));
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Hope this helps. Keep coding :)
Labels:Graphics2D-Images | 0
comments
Tuesday, June 11, 2013
Today I will show you how you can flip an image vertically and horizontally. Flipping an image means reflecting an image along a miiror axis. Mathematically when we flip along horizontal axis x'=x and y'=-y whereas when flipped along vertical axis x'=-x and y'=y, where (x',y') is the transformed point and (x,y) is the original point. Here in our sample code we will first read the image from file as BufferedImage. Since there is no flip function available in Java so we will first perform scaling and then translation. We will use AffineTransformOp to transform the image and call filter() method that returns the transformed image.The transformation will be carried out in following way --->
Horizontal Flip : scale(1.0,-1.0) and translate(0,-image.getHeight())
Vertical Flip : scale(-1.0,1.0) and translate(-image.getWidth(),0)
Flip both ways : scale(-1.0,-1.0) and translate(-image.getWidth(),-image.getHeight())
AffineTransform class : It represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. Affine transformations can be constructed using sequences of translations, scales, flips, rotations, and shears.
AffineTransformOp class : This class uses an affine transform to perform a linear mapping from 2D coordinates in the source image or Raster to 2D coordinates in the destination image or Raster. The type of interpolation that is used is specified through a constructor, either by a RenderingHints object or by one of the integer interpolation types defined in this class.
Screenshots of the transformation
--------------------------------------------------------------------------------------------------------------------------
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class FlipImage {
public BufferedImage flipVertical(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(-1.0,1.0); //scaling
tx.translate(-src.getWidth(),0); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public BufferedImage flipHorizontal(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(1.0,-1.0); //scaling
tx.translate(0,-src.getHeight()); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public static void main(String[] args)throws Exception {
FlipImage obj=new FlipImage();
BufferedImage src=ImageIO.read(new File("src.jpeg")); //reading image
BufferedImage dest=obj.flipVertical(src); //flipping vertically
ImageIO.write(dest,"jpeg",new File("dest_flipVer.jpg"));
dest=obj.flipHorizontal(src); //flipping horizontally
ImageIO.write(dest,"jpeg",new File("dest_flipHor.jpg"));
dest=obj.flipVertical(dest); //flupping both ways
ImageIO.write(dest,"jpeg",new File("dest_flipBoth.jpg"));
}
}
Horizontal Flip : scale(1.0,-1.0) and translate(0,-image.getHeight())
Vertical Flip : scale(-1.0,1.0) and translate(-image.getWidth(),0)
Flip both ways : scale(-1.0,-1.0) and translate(-image.getWidth(),-image.getHeight())
AffineTransform class : It represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. Affine transformations can be constructed using sequences of translations, scales, flips, rotations, and shears.
AffineTransformOp class : This class uses an affine transform to perform a linear mapping from 2D coordinates in the source image or Raster to 2D coordinates in the destination image or Raster. The type of interpolation that is used is specified through a constructor, either by a RenderingHints object or by one of the integer interpolation types defined in this class.
Screenshots of the transformation
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class FlipImage {
public BufferedImage flipVertical(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(-1.0,1.0); //scaling
tx.translate(-src.getWidth(),0); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public BufferedImage flipHorizontal(BufferedImage src){
AffineTransform tx=AffineTransform.getScaleInstance(1.0,-1.0); //scaling
tx.translate(0,-src.getHeight()); //translating
AffineTransformOp tr=new AffineTransformOp(tx,null); //transforming
return tr.filter(src, null); //filtering
}
public static void main(String[] args)throws Exception {
FlipImage obj=new FlipImage();
BufferedImage src=ImageIO.read(new File("src.jpeg")); //reading image
BufferedImage dest=obj.flipVertical(src); //flipping vertically
ImageIO.write(dest,"jpeg",new File("dest_flipVer.jpg"));
dest=obj.flipHorizontal(src); //flipping horizontally
ImageIO.write(dest,"jpeg",new File("dest_flipHor.jpg"));
dest=obj.flipVertical(dest); //flupping both ways
ImageIO.write(dest,"jpeg",new File("dest_flipBoth.jpg"));
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Graphics2D,Graphics2D-Images | 0
comments
Saturday, June 8, 2013
Today I will tell you how you can create shaped windows in Java. This is an extraordinary feature which was added in Java7. According to this feature you can create any shape and use that shape for your window. You can also create complex shapes and give your windows that shape. Different shapes like oval, round rectangle or complex like L-shape or I-shape. Here we will inherit the JFrame class and then add the ComponentListener to it. This is because when the window will be resized the shape will be calculated automatically. We will create a shape using Ellipse2D.Double and then call setShape() method to assign the shape to it. Below is a screenshot
--------------------------------------------------------------------------------------------------------------------------
import java.awt.Shape;
import java.awt.GridBagLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.geom.*;
public class OvalShapedWindow extends JFrame {
public OvalShapedWindow() {
super("Oval Window");
setLayout(new GridBagLayout()); //setting layout
addComponentListener(new ComponentAdapter() {
// If the window is resized, the shape is recalculated
@Override
public void componentResized(ComponentEvent e) {
Shape winShape=new Ellipse2D.Double(0,0,getWidth(),getHeight());
setShape(winShape); //giving shape
}
});
setUndecorated(true); //removing title-bar
setSize(350,250);
setLocationRelativeTo(null); //positioning at center
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JButton("Click Me")); //adding Button
}
public static void main(String[] args) {
// Creating UI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OvalShapedWindow sw = new OvalShapedWindow();
sw.setVisible(true); // Display the window
}
});
}
}
--------------------------------------------------------------------------------------------------------------------------
An oval-shaped window as seen on Ubuntu 12.04 |
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.awt.Shape;
import java.awt.GridBagLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.geom.*;
public class OvalShapedWindow extends JFrame {
public OvalShapedWindow() {
super("Oval Window");
setLayout(new GridBagLayout()); //setting layout
addComponentListener(new ComponentAdapter() {
// If the window is resized, the shape is recalculated
@Override
public void componentResized(ComponentEvent e) {
Shape winShape=new Ellipse2D.Double(0,0,getWidth(),getHeight());
setShape(winShape); //giving shape
}
});
setUndecorated(true); //removing title-bar
setSize(350,250);
setLocationRelativeTo(null); //positioning at center
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JButton("Click Me")); //adding Button
}
public static void main(String[] args) {
// Creating UI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
OvalShapedWindow sw = new OvalShapedWindow();
sw.setVisible(true); // Display the window
}
});
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Swing | 0
comments
Friday, May 10, 2013
The heapsort algorithm starts by using BUILD-MAX-HEAP to build a max-heap on the input array A[1 : : n ],where n=A:length. Since the maximum element of the array is stored at the root A[1] , we can put it into its correct final osition by exchanging it with A[n] . If we now discard node n from the heap - and we can do so by simply decrementing A:heap-size-- we observe that the children of the root remain max-heaps, but the new root element might violate the max-heap property. All we need to do to restore the max-heap property, however, is call MAX-HEAPIFY(A, 1), which leaves a max-heap in A[1 : : n -1] . The heapsort algorithm then repeats this process for the max-heap of size n- 1 down to a heap of size 2.
The program written below has build_max_heap() to build the max-heap, max_heapify() to retain the max-heap property and heap_sort() for sorting. The most important thing of the code is that you can use this to sort anything. Just pass an array of any object which is comparable i.e. implements Comparable interface or any array of wrapper class objects like Integer, Float etc. This is only beacause we have done this using Java's generics feature to make this code generic and general and no need for different implementations.
--------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
/*This code can take in any array of Comparable i.e whose data can be compared and generates the sorted elements using heap sort*/
public class HeapSort<E extends Comparable<? super E>>{
private int heap_size;
private E A[];
public HeapSort(E a[]){
A=a;
}
private void build_max_heap(){ //building max-heap
heap_size=A.length-1;
for(int i=heap_size/2;i>=0;i--)
max_heapify(i);
}
private void swap(int i,int j){
E tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}
private void max_heapify(int i){
int l=2*i,r=2*i+1; //left and right child
int largest;
if(l<=heap_size && A[l].compareTo(A[i])>0)
largest=l;
else largest=i;
if(r<=heap_size && A[r].compareTo(A[largest])>0)
largest=r;
if(largest!=i){ //finding largest, swapping and then reheapify
swap(i,largest);
max_heapify(largest);
}
}
public E[] heap_sort(){
build_max_heap();
for(int i=A.length-1;i>=0;i--){
swap(0,i); //swapping with first
heap_size--; //decreasing size
max_heapify(0); //reheapify
}
return A;
}
public static void main(String[] args)throws Exception{
Scanner sc=new Scanner(System.in);
System.out.print("Enter size : ");
int n=sc.nextInt();
Integer a[]=new Integer[n];
System.out.println("Enter elements to be sorted -->");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
HeapSort<Integer> obj=new HeapSort<Integer>(a);
a=obj.heap_sort();
System.out.println("Sorted array -->");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
The program written below has build_max_heap() to build the max-heap, max_heapify() to retain the max-heap property and heap_sort() for sorting. The most important thing of the code is that you can use this to sort anything. Just pass an array of any object which is comparable i.e. implements Comparable interface or any array of wrapper class objects like Integer, Float etc. This is only beacause we have done this using Java's generics feature to make this code generic and general and no need for different implementations.
Heapsort operation |
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.util.Scanner;
/*This code can take in any array of Comparable i.e whose data can be compared and generates the sorted elements using heap sort*/
public class HeapSort<E extends Comparable<? super E>>{
private int heap_size;
private E A[];
public HeapSort(E a[]){
A=a;
}
private void build_max_heap(){ //building max-heap
heap_size=A.length-1;
for(int i=heap_size/2;i>=0;i--)
max_heapify(i);
}
private void swap(int i,int j){
E tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}
private void max_heapify(int i){
int l=2*i,r=2*i+1; //left and right child
int largest;
if(l<=heap_size && A[l].compareTo(A[i])>0)
largest=l;
else largest=i;
if(r<=heap_size && A[r].compareTo(A[largest])>0)
largest=r;
if(largest!=i){ //finding largest, swapping and then reheapify
swap(i,largest);
max_heapify(largest);
}
}
public E[] heap_sort(){
build_max_heap();
for(int i=A.length-1;i>=0;i--){
swap(0,i); //swapping with first
heap_size--; //decreasing size
max_heapify(0); //reheapify
}
return A;
}
public static void main(String[] args)throws Exception{
Scanner sc=new Scanner(System.in);
System.out.print("Enter size : ");
int n=sc.nextInt();
Integer a[]=new Integer[n];
System.out.println("Enter elements to be sorted -->");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
HeapSort<Integer> obj=new HeapSort<Integer>(a);
a=obj.heap_sort();
System.out.println("Sorted array -->");
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Generics,Sorting | 0
comments
Subscribe to:
Posts
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...