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
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...
