tag:blogger.com,1999:blog-65845800982685675632024-02-07T14:25:58.046+05:30Java Code HouseDeals anything related to JavaAnonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.comBlogger76125tag:blogger.com,1999:blog-6584580098268567563.post-12662940275435311812014-08-03T00:03:00.000+05:302014-08-03T12:17:27.298+05:30How to verify a Digital Signature in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgocCzdwb0Oh-RAbi_Ez8eEne9OL9HY6Vv8KImlBhy78AobkPBiUrI_tNs2nEQoqKqeT6HthmBwCqOLtwQN8qVNDI50t9VRkowXWJO2Dmq175fYY2IxIeuaFjvea4wOQ_2t029tIHNUJphf/s1600/Digital-signatures.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgocCzdwb0Oh-RAbi_Ez8eEne9OL9HY6Vv8KImlBhy78AobkPBiUrI_tNs2nEQoqKqeT6HthmBwCqOLtwQN8qVNDI50t9VRkowXWJO2Dmq175fYY2IxIeuaFjvea4wOQ_2t029tIHNUJphf/s1600/Digital-signatures.jpg" height="200" width="136" /></a></div>
In an earlier post <a href="http://javaingrab.blogspot.com/2014/06/how-to-generate-and-sign-data-with.html" target="_blank">here</a> , we have shown you how to sign data and generate a digital signature in Java. Generating the signature alone does not provide security, you will also have to verify the digital signature. So according to that today I am going to show you how to verify a Digital Signature in Java. Here in our example we will show how you can do it once you are provided with the original dta, the public key (whose corresponding private key was used to sign the data) and finally the signature bytes that were generated earlier.<br />
In our previous article we have stored the public key in encided form in a file with an extension .pubkey and the signature bytes in a file with extension .dsa . So in order to verify first we will try to read the key bytes and pass them to <span style="font-family: Courier New, Courier, monospace;">X509EncodedKeySpec</span> object. Then use the <span style="font-family: Courier New, Courier, monospace;">KeyFactory</span> to reconstruct the public key. Next we have to create the <span style="font-family: Courier New, Courier, monospace;">Signature</span> object with the same algorithm as earlier and initialize with the public key. <br />
<a name='more'></a>Next read the signature bytes from file in a byte array. After that we have to read the original data file and update signature object. Finally we have to call <b><i><span style="color: #3d85c6;">verify()</span></i></b> method to understand whether the signature is verified or not.<br />
<br />
<br />
------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.io.*;
import java.security.*;
import java.security.spec.*;
public class SignatureVerifier {
/**
* Verifies digital signature of a file
* @param pkPath String - path of file with public key
* @param sPath String - path of file with signature
* @param fPath String - path of file with data to be verified
* @throws FileNotFoundException
* @throws IOException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws SignatureException
*/
public void verify(String pkPath,String sPath,String fPath) throws FileNotFoundException, IOException, InvalidKeySpecException, InvalidKeyException,NoSuchAlgorithmException, NoSuchProviderException, SignatureException{
byte keyBytes[] = readFromFile(pkPath); //read the key in bytes
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); //reconstruct key
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
sig.initVerify(pubKey); //initialize signature with public key
byte sigToVerify[] = readFromFile(sPath); //read the signature earlier generated
try(BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fPath))){
byte buf[] = new byte[4096];
int read = 0;
while((read = bin.read(buf)) != -1) //read data to be signed
sig.update(buf, 0, read); //update signature object with data
}
boolean verifies = sig.verify(sigToVerify); //verify signature
System.out.println("signature verifies: " + verifies);
}
/**
* Reads the binary data from file and returns a byte array
* @param path String - path of file to be read
* @return byte[] - data read from file
* @throws FileNotFoundException
* @throws IOException
*/
public byte[] readFromFile(String path) throws FileNotFoundException, IOException{
byte data[] = null;
try(FileInputStream fis = new FileInputStream(path)){
data = new byte[fis.available()];
fis.read(data);
}
return data;
}
public static void main(String[] args) {
try {
String fPath = "sample.txt";
new SignatureVerifier().verify(fPath+".pubkey", fPath+".dsa", fPath);
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
}
}</pre>
------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Download Links </i></b></div>
------------------------------------------------------------------------------------------------------
<br />
<a href="http://www.mediafire.com/download/ygayx0trntmhanu/SignatureVerifier.java" target="_blank"><b>DOWNLOAD the source from Mediafire</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-88226761525216796212014-07-27T22:01:00.000+05:302014-07-27T22:01:00.886+05:30Implementation of 0/1 Knapsack problem using Dynamic Programming in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2tDpIL4zdWn9M9I1HYcjV4KoDePY6F194nE9BAWNKe34DOalFIUymDGI57WnTxtrhVXQVspSO5AyUAloWRK43yL39PPJgwIt4RittPFmQZw6FxjQCQT-_RYBVg5WqNrmqCSKp8iGqRXdc/s1600/486px-Knapsack.svg.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2tDpIL4zdWn9M9I1HYcjV4KoDePY6F194nE9BAWNKe34DOalFIUymDGI57WnTxtrhVXQVspSO5AyUAloWRK43yL39PPJgwIt4RittPFmQZw6FxjQCQT-_RYBVg5WqNrmqCSKp8iGqRXdc/s1600/486px-Knapsack.svg.png" height="277" width="320" /></a></div>
Today in this article I will show you how to solve 0-1 Knapsack problem using the concept of dynamic programming in Java. This problem can also be solved by recursion but the problem is that it will result in solving of already solved sub-problem. So we will be using dynamic programming to solve by storing the results of solved sub-problems. Also this technique can be used to solve the problem in polynomial time. The complexity of solving it using this algorithm is O(n*W).<br />
<b>What is 0/1 Knapsack problem ?</b><br />
The knapsack or rucksack problem is a problem in combinatorial optimization. Here there are a set of items(n) which has a profit value(v) and weight(w). There is a bag which has a maximum capacity(W). Now the problem is to fill the bag with the following restrictions :<br />
1. You can either choose an item completely or reject it. (0 or 1)<br />
2. The total weight of bag must not exceed its maximum capacity W. i.e. (Sum of w[i]) <= W<br />
3. The total value or profit of items chosen must be maximum. i.e. Sum of p[i] is maximum<br />
where 0 < i <=n.<br />
<b>How to solve 0/1 Knapsack problem in Java ?</b><br />
Step1: Structure: Characterize the structure of an optimal solution.<br />
– Decompose the problem into smaller problems, and find a relation between the structure of the optimal solution of the original problem and the solutions of the smaller problems.<br />
<a name='more'></a><br />
Step2: Principle of Optimality: Recursively define the value of an optimal solution.<br />
– Express the solution of the original problem in terms of optimal solutions for smaller problems.<br />
Step 3: Bottom-up computation: Compute the value of an optimal solution in a bottom-up fashion by using a table structure.<br />
<br />
Step 4: Construction of optimal solution: Construct an optimal solution from computed information.<br />
<div>
------------------------------------------------------------------------------------------------------</div>
<div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
</div>
<div>
------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.util.Scanner;
public class Knapsack {
private int n,W; //number of items and maximum capacity
private int w[],v[]; //weights and values of items
private int V[][]; //table to store results of sub-problems
/**
* Takes necessary inputs and initializes for solving
*/
private void initialize(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of items : ");
n = sc.nextInt(); //number of items
System.out.print("Enter W of knapsack : ");
W = sc.nextInt(); //capacity of knapsack
w = new int[n];
v = new int[n];
System.out.println("Enter ws and vs of items : ");
for(int i = 0; i < n; i++){
w[i] = sc.nextInt(); //weight of item
v[i] = sc.nextInt(); //profit of item
}
V = new int[n+1][W+1]; //initializing the table to hold results
for(int i = 0; i <= W; i++) V[0][i] = 0;
}
/**
* Computes the result
*/
public void knapsack(){
//table for backtracking to get the items chosen
int x[][] = new int[n+1][W+1];
//filling tables
for(int i = 1; i <= n; i++)
for(int j = 0; j <= W; j++)
if((w[i-1] <= j) && (v[i-1]+V[i-1][j-w[i-1]] > V[i-1][j])){
V[i][j] = v[i-1] + V[i-1][j-w[i-1]];
x[i][j] = 1;
}
else{
V[i][j] = V[i-1][j];
x[i][j] = 0;
}
//backtracking
System.out.printf("Items Chosen\n%5s%7s%7s\n", "Item","Weight","Profit");
int K = W;
for(int i = n; i >= 1; i--)
if(x[i][K] == 1){
System.out.printf("%5d%7d%7d\n",i,w[i-1],v[i-1]);
K -= w[i-1];
}
System.out.println("Maximum profit : "+V[n][W]);
}
public static void main(String[] args) {
Knapsack obj = new Knapsack();
obj.initialize();
obj.knapsack();
}
}</pre>
------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/5484ep8r06qysyr/Knapsack.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/BDQgX2JIba/Knapsack.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com1tag:blogger.com,1999:blog-6584580098268567563.post-70157965617251667622014-07-22T17:36:00.004+05:302014-07-22T17:36:46.590+05:30Postfix to Infix Conversion using Stack in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaycw7UG-rY4KLqt2NCQAwa8XmoK1TNzR-VICR34DFU5eeDVO0UycjuGkPRA8fBLdsFUyOZgg-33iy-TEEgGcSTP4BtZYceS6e6ZbHa3-O0-z3fgNfBn1rHkaJ8M-gV0xqxO9F_4RCXMTg/s1600/infix-postfix.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaycw7UG-rY4KLqt2NCQAwa8XmoK1TNzR-VICR34DFU5eeDVO0UycjuGkPRA8fBLdsFUyOZgg-33iy-TEEgGcSTP4BtZYceS6e6ZbHa3-O0-z3fgNfBn1rHkaJ8M-gV0xqxO9F_4RCXMTg/s1600/infix-postfix.jpg" /></a></div>
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post <a href="http://javaingrab.blogspot.com/2014/05/infix-to-postfix-conversion-using-stack.html" target="_blank">here</a> we ahve shown how to convert an infix expression to postfix using stack. Here we will just try to do the reverse. Here in our example we will be able to convert any postfix expression to infix irrespective of the operators. A number of parenthesis may be generated extra which were not there in original infix expression. The parenthesis that may be generated extra will have no impact on actual expression, they are just for better understanding. The process of postfix to infix conversion is summarised below -<br />
<a name='more'></a><br />
<br />
1. Create an empty stack that can hold string values.<br />
2. Scan the postfix expression from left to right<br />
2a. If operand then push into stack<br />
<div>
2b. If operator then</div>
<div>
1. Pop first two elements</div>
<div>
2. Now make a string with "(" + operand2 + operator + operand1 + ")"</div>
<div>
3. Push the new string onto stack</div>
<div>
3. Pop the element on stack.</div>
<div>
<div>
------------------------------------------------------------------------------------------------------</div>
</div>
<div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
</div>
<div>
------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.util.Scanner;
import java.util.Stack;
public class PostfixToInfix {
/**
* Checks if the input is operator or not
* @param c input to be checked
* @return true if operator
*/
private boolean isOperator(char c){
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
return true;
return false;
}
/**
* Converts any postfix to infix
* @param postfix String expression to be converted
* @return String infix expression produced
*/
public String convert(String postfix){
Stack<String> s = new Stack<>();
for(int i = 0; i < postfix.length(); i++){
char c = postfix.charAt(i);
if(isOperator(c)){
String b = s.pop();
String a = s.pop();
s.push("("+a+c+b+")");
}
else
s.push(""+c);
}
return s.pop();
}
public static void main(String[] args) {
PostfixToInfix obj = new PostfixToInfix();
Scanner sc =new Scanner(System.in);
System.out.print("Postfix : ");
String postfix = sc.next();
System.out.println("Infix : "+obj.convert(postfix));
}
}</pre>
<div>
------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Output
</i></b></div>
------------------------------------------------------------------------------------------------------
<br />
<pre>Postfix : ABC^^
Infix : (A^(B^C))
</pre>
------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/lgsax6g2aai8ld8/PostfixToInfix.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/VZ8xXQHIce/PostfixToInfix.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com6tag:blogger.com,1999:blog-6584580098268567563.post-60813428960863223832014-07-12T13:21:00.000+05:302014-07-12T13:21:06.962+05:30How to use Executor in Java - A simple example<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEij_hNyfiM0_gE8D2sExZwC9aH8_ji7mNp7UKu7h8FI024U4gt4qeMhvPfzLRDHFZGUuChF21datusBf5xd_zHFcHIN2uSWHwhc4ApDOpYSdwiQpG3wF6ydqwNGU_qHioUAhrQlZc9E4JK2/s1600/Concurency.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEij_hNyfiM0_gE8D2sExZwC9aH8_ji7mNp7UKu7h8FI024U4gt4qeMhvPfzLRDHFZGUuChF21datusBf5xd_zHFcHIN2uSWHwhc4ApDOpYSdwiQpG3wF6ydqwNGU_qHioUAhrQlZc9E4JK2/s1600/Concurency.jpg" height="131" width="320" /></a></div>
Today I am going to deal with an e3xcellent feature of the Java Concurrency framework. You can consider it as one of the most basic things of the framework. Here I will show you how to use the Executor with a simple demo example. You would like to know why to use Executor? Earlier you must have learnt during your basic learning on Java threads, that whenever you will have to do multi-threading you will have to create a task either implementing Runnable interface or extending Thread class. Then you would have to start the thread created by calling start() method. This is actually very low-level implementation where you are dealing with threads. This is completely alright for small applications. But when you are handling large applications, you would never like to handle and manage threads directly, as your main work is to deal with the task properly and concentrate on that. So keeping that in mind, her comes the advantage of Executor where you only have to create the task and <br />
<a name='more'></a>submit it to the executor. It will automatically create a new thread and assign the task to it. Its advantage is not much noticable in small cases. But suppose you have a large number of tasks and your system supports only a small number of threads to be run efficiently. In that case, if you manually create threads and assign tasks and manage them throttling resources will be a very difficult task. In those cases, all thnose things will be managed without much of programmer's effort as the tasks will be kept in queue and will re-use the worker threads, as creating new threads consumes a lot of resources. To sum up, it completely depends on Executor implementation that whether a new thread, or in a pooled thread or in the current thread the task will be executed. More of this and resource throttling will be discussed with proper examples in later tutorials.<br />
Here in the example below we will just create a private inner class that implements Runnable interface and try to print odd numbers. To understand multi-threading we will carry out another task of printing even numbers in the main thread. We will submit the task of odd number generation to a executor and execute it; The executor for the task is created by calling newSingleThreadExecutor() meaning that a executor with only one thread is created which will carry out the task.<br />
------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ExecutorDemo {
private static class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i += 2) { //odd number generation
try {
Thread.sleep(500); //executors thred sleeping
System.out.println(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Runnable r = new MyRunnable();
Executor e = Executors.newSingleThreadExecutor(); //creating a executor
e.execute(r); //submitting and executing the task
for (int i = 0; i <= 10; i += 2) { //even number generation
try {
Thread.sleep(500); //main-thread sleeping
System.out.println(i);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}</pre>
------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/k2i4v5lq66dhjdg/ExecutorDemo.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/XzPnlyq5ba/ExecutorDemo.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a><br />
<br />
Happy coding :)</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-38965778374290837982014-07-05T22:33:00.001+05:302014-07-05T22:33:46.616+05:30How to write or create a JPA entity<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRIrjOp8UGoqmeLo4WEbtWCof6tFfv8Tbs6y8eO5YOgj2KlcBf3_GUw5j6204QOgcilj_t2ftlD5qdzrVxkMBFkLL6TpEcOnkCrnyek2rxEp-smxgmGvgQwyWp5IMr9WFTsTY5l3jsQtdp/s1600/Java-persistence.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRIrjOp8UGoqmeLo4WEbtWCof6tFfv8Tbs6y8eO5YOgj2KlcBf3_GUw5j6204QOgcilj_t2ftlD5qdzrVxkMBFkLL6TpEcOnkCrnyek2rxEp-smxgmGvgQwyWp5IMr9WFTsTY5l3jsQtdp/s1600/Java-persistence.PNG" height="142" width="320" /></a></div>
Today I am going to discuss with the first step of JPA - Java Persistence API. JPA helps you in object-relational mapping and reduces a lot of task of coders, otherwise they have to write a lot of JDBC codes. All those things are done automatically by the Persistence provider. Throughout all the topics related to JPA that we will cover will consider EclipseLink as the JPA provider.<br />
After all necessary setups, the first thing you will have to do is to write a JPA entity. Many IDE like Eclipse can automatically create it, but we will show how to write it and what are the steps. You must have seen the JavaBean style classes. Here our first task is to write a class in that style only. Next we will make some modifications to make it a JPA entity. <br />
<a name='more'></a>We will create a class named Employee. But you must remember that the entity name must match with the name of a table in database (though it can differ, we will only deal with name of table as same as entity).</div>
<pre class="brush: java">public class Employee {
private int id;
private String name;
private double salary;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary;}
}</pre>
After our task of writing the bean class is over, we will have to create a table named Employee with column names as same names as the attributes of the Employee class.
<br />
<pre class="brush: sql">CREATE TABLE Employee
(id number primary key,name varchar(30),salary float);</pre>
Our next task is to modify our bean class to make it a JPA entity. To do this, we have to first annotate the class with the <span style="font-family: Courier New, Courier, monospace;">@Entity</span> annotation. This is just a marker annotation to notify to the persistence engine that it is a JPA entity<br />
Next we have to mention the primary key as every entity has a primary key and we also have a primary key in our database table. In order to mention the primary key, we have to annotate the field id with the <complete id="goog_569859709"><span style="font-family: Courier New, Courier, monospace;">@Id </span>annotation.</complete></div>
<pre class="brush: java">import javax.persistence.*;
@Entity
public class Employee {
@Id private int id;
private String name;
private double salary;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary;}
}</pre>
When the @Id annotation is placed on the field or property, user can choose to annotate either the declared field or the getter method of a JavaBean-style property. Either field or property strategy is allowed, depending on the needs of the entity developer. We will discuss the details of annotating persistent state using field or property access later.<br />
The fields in the entity are automatically made persistable by virtue of their existence in the entity. Default mapping and loading configuration values apply to these fields and enable them to be persisted when the object is persisted. The entity is automatically mapped to the table Employee and the fields are mapped to the respective columns.</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-45012011755024003412014-06-29T22:54:00.000+05:302014-06-29T22:57:08.923+05:30How to generate and sign data with Digital Signature in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPcAVKkuSHZLyW9Sz8dY1En63NjM2_bJUSo-e1bv1uhD7siFkmIaumNLxkTkVFIwWd3wff0R6ebsUlK4MWVDYcOXL65l9WLjBMBiMuDwsuEel5jb9uFxZxhbThLUsplWzjDKk9jAgMrkBl/s1600/Digital-signatures.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPcAVKkuSHZLyW9Sz8dY1En63NjM2_bJUSo-e1bv1uhD7siFkmIaumNLxkTkVFIwWd3wff0R6ebsUlK4MWVDYcOXL65l9WLjBMBiMuDwsuEel5jb9uFxZxhbThLUsplWzjDKk9jAgMrkBl/s1600/Digital-signatures.jpg" height="320" width="220" /></a></div>
Today in this tutorial I am going to show you how to generate and use Digital Signature to sign any data or document in Java. Digital Signatures are a very important part of security. It ensures authenticity and non-repudiation of any data. In order to prove authenticity, the sender of the data signs the data with a digital signature and the receiver verifies the signature. Here we will only consider about signing the data, while verifying digital signature will be discussed in another later tutorial.<br />
<br />
<b>How to sign data with digital signature ?</b><br />
1. Form the message to be signed.<br />
2. Generate a public-private key pair<br />
3. Calculate hash of the message and encrypt it with sender's private key<br />
4. Send the dugutally signed message with the signature along with the public key.<br />
<br />
In this tutorial, we will be signing the data stored in a file. The file path will be taken as an input. The resulting output will be two file : a .dsa file containing the digital signature, and a .pubkey file containing the public key in encoded form. <br />
<a name='more'></a>You can directly use keys either stored in keystore or files but here we will generate the key pair. The procedure taken here to sign data is described step by step<br />
<br />
<ul style="text-align: left;">
<li>Create <span style="font-family: Courier New, Courier, monospace;">KeyPairGenerator</span> object with DSA as algorithm using <b><i><span style="color: #3d85c6;">getInstance()</span></i></b> method.</li>
<li>Initialize the object created with the key-size using <b><i><span style="color: #3d85c6;">initialize()</span></i></b> method, e.g. 1024 bits</li>
<li>Generate the <span style="font-family: Courier New, Courier, monospace;">KeyPair</span> object from <span style="font-family: Courier New, Courier, monospace;">KeyPairGenerator</span> object and extract <span style="font-family: Courier New, Courier, monospace;">PrivateKey</span> and <span style="font-family: Courier New, Courier, monospace;">PublicKey</span> object.</li>
<li>Save the public key in encoded form in a file.</li>
<li>Create the <span style="font-family: Courier New, Courier, monospace;">Signature</span> object with SHA1withDSA (where SHA1 is the message digest algorithm and DSA is the signature algorithm) using <b><i><span style="color: #3d85c6;">getInstance()</span></i></b> method.</li>
<li>Initialize the signature object with the private key using <b><i><span style="color: #3d85c6;">initSign()</span></i></b> method.</li>
<li>Read the data from file and go on updating signature object with the data using <b><i><span style="color: #3d85c6;">update() </span></i></b>method.</li>
<li>Finally get the signature as output using <b><i><span style="color: #3d85c6;">sign()</span></i></b> method and save it in a file.</li>
</ul>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
</div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
public class DataSigner {
/**
* Signs the data in a file and saves the digital signature and
* public key in two seperate files withot changing original data
* @param path File path whose data to be signed
* @throws FileNotFoundException
* @throws IOException
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public void sign(String path) throws FileNotFoundException, IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException{
//get key pair generator for Digital Signature Algorithm
KeyPairGenerator kGen = KeyPairGenerator.getInstance("DSA");
kGen.initialize(1024); //1024 is the key size
KeyPair keyPair = kGen.generateKeyPair(); //generate orivate-public key pair
PrivateKey privKey = keyPair.getPrivate(); //extract private key from pair
PublicKey pubKey = keyPair.getPublic(); //extract public key from pair
saveToFile(pubKey.getEncoded(), path+".pubkey"); //save public key to file in encoded form
//Get signature object for signing with SHA1 as MessageDigest and DSA as signature algorithm
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initSign(privKey); //initialize signature object for signing
try(BufferedInputStream bin = new BufferedInputStream(new FileInputStream(path))){
byte buf[] = new byte[4096];
int read = 0;
while((read = bin.read(buf)) != -1) //read data to be signed
signature.update(buf, 0, read); //update signature object with data
}
byte out[] = signature.sign(); //sign the data
saveToFile(out, path+".dsa"); //save the digital signature in file
}
/**
* Saves a byte array in file
* @param data byte array to be saved
* @param path File path of the data to be saved
* @throws IOException
*/
public void saveToFile(byte[] data, String path) throws IOException{
try(FileOutputStream fos = new FileOutputStream(path)){
fos.write(data);
}
}
public static void main(String[] args) {
try {
new DataSigner().sign("sample.txt");
} catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
}
}
}</pre>
<b>NOTE</b> : You will need a sample.txt file to run this code. As an output two files will be created with names as the original file name (with its extension intact) with extensions .pubkey and .dsa. For example in this case the files will be sample.txt.dsa having signature and sample.txt.pubkey having the public key.<br />
------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
------------------------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/s77rsx30m27h84r/DataSigner.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<br />
Happy coding and keep in touch to know the verification of digital signature.</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-29038761159447546292014-06-15T00:30:00.000+05:302014-06-15T00:30:43.872+05:30How to watch or monitor a file/folder in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKv1KB3F-7Md4AOOSB5wczE78e5QH2GCwhNok_LxtYFciLWe0pxdk7SXB4rlN5jhHoCuDPELf69mfOGLS2HtWofeaTXs3_wAJRGKmVKPj7Z6-h3jNqJMNbTpN-lUrSu9q7PomJ5MYX2mUU/s1600/java-nio.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKv1KB3F-7Md4AOOSB5wczE78e5QH2GCwhNok_LxtYFciLWe0pxdk7SXB4rlN5jhHoCuDPELf69mfOGLS2HtWofeaTXs3_wAJRGKmVKPj7Z6-h3jNqJMNbTpN-lUrSu9q7PomJ5MYX2mUU/s1600/java-nio.png" height="222" width="320" /></a></div>
Today in this article I will discuss with an amazing feature of Java7. Here I will show you how to create a file/folder watcher/watch service. In other words I will actually write Java code which will be able to monitor a file/folder/directory for changes. This will require Java 7 NIO .2. This monitoring service is very useful in many applications like IDE. Also this can be used for hot deployment in servers. Monitoring or watching a folder for changes means that whenever there is a change in file system associated with the folder then an event is triggerd. The event is catched and associated change is extracted to know what change has occurred and based on that different actions can be taken.<br />
Below are the steps you must follow to implement watch service<br />
<b>1. <i>Get the path of the folder</i> </b>- The first step is to get the Path object associated with the folder. This is done using <b><i><span style="color: #3d85c6;">Paths.get()</span></i></b> method.<br />
<b>2.</b><i style="font-weight: bold;"> Get file system of the path</i> - Next step is to get the FileSystem object associated with the Path object. This is done using <b><i><span style="color: #3d85c6;">getFileSystem()</span></i></b> method.<br />
<b>3. <i>Get watch service</i></b> - Next you have to get WatchService from FileSystem object using <b><i><span style="color: #3d85c6;">newWatchService()</span></i></b> method.<br />
<a name='more'></a><br />
<b>4. <i>Register to watch service and events</i></b> - In this step you will have to register the Path object to the watch service created. With that you will also have to mention all the events that you want to monitor. There are four events <i>ENTRY_CREATE</i>, <i>ENTRY_DELETE</i>, <i>ENTRY_MODIFY</i>, <i>OVERFLOW</i>. This is done using <b><i><span style="color: #3d85c6;">register()</span></i></b> method.<br />
<b>5. <i>Start infinite loop</i></b> - You will have top start the infinite loop to watch the folder continously.<br />
<b>5a. <i>Poll the events for watch key</i></b> - Inside the loop you will have to poll for events using <b><i><span style="color: #3d85c6;">pol()</span></i></b> or <b><i><span style="color: #3d85c6;">take()</span></i></b> methods. Though there are two poll methods but its is better sometimes to use take method as it waits until an event occurs, whereas for poll methods they return null value so you have to keep a null check otherwise NullPointer Exception will be thrown.<br />
<b>5b. <i>Retrieve pending events</i></b> - Next you have to retrieve the pending events. There can be more than one event, so use a for loop and get events from WatchKey. Depending on event take necessary actions.<br />
<b>5c. <i>Reset the key</i></b> - Next reset the key and wait for next events using <b><i><span style="color: #3d85c6;">reset()</span></i></b> method.<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<pre class="brush: java">import java.nio.file.FileSystem;
import java.nio.file.Path;
import static java.nio.file.StandardWatchEventKinds.*;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchService;
import java.util.concurrent.TimeUnit;
public class FolderMonitor {
/**
* Monitors a folder for changes
* @param path Path to be monitored
* @throws Exception
*/
public void monitor(Path path) throws Exception{
FileSystem fs = path.getFileSystem(); //get file system
try(WatchService ws = fs.newWatchService()){ //get watch service in try block
//register for events to warch service
path.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watching : "+path);
while(true){ //poll loop
final WatchKey key = ws.take(); //wait and get watch key
for(WatchEvent<?> we : key.pollEvents()){
final Kind<?> kind = we.kind(); //get event kind
if(kind == OVERFLOW)
return;
else if(kind == ENTRY_CREATE)
printEvent("New path created", we);
else if(kind == ENTRY_DELETE)
printEvent("Path deleted", we);
else if(kind == ENTRY_MODIFY)
printEvent("Path modified", we);
}
if(!key.reset()) //reset
break;
}
}
}
/**
* Displays event occurred
* @param desc Description of event
* @param we watch event
*/
private void printEvent(String desc, WatchEvent<?> we){
System.out.println(desc+" : "+((WatchEvent<Path>)we).context());
}
public static void main(String[] args) throws Exception {
FolderMonitor fm = new FolderMonitor();
fm.monitor(Paths.get("C:/demo"));
}
}</pre>
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Download Links </i></b></div>
-------------------------------------------------------------------------------------------------------------------------
<br />
<b><a href="http://www.mediafire.com/download/midaisl9n54mdu4/FolderMonitor.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/zFZ0XuNdba/FolderMonitor.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-12965607239337513692014-06-09T23:08:00.001+05:302014-06-09T23:08:28.641+05:30How to create a GUI based Tower of Hanoi game in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4lJZb1W3g-c_FKF2q8ya037kALfgqFY0kMnVVY74But7Qk2-e5km7BWRwv71yv3hJJpeSQ0Eo9wex4Bqux3QHaDxvl_3ihrGUv7jUq-l2t_Q8R84wITAl-NrPDDqrRe1B-1yZXbA5rney/s1600/Tower_of_Hanoi.jpeg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4lJZb1W3g-c_FKF2q8ya037kALfgqFY0kMnVVY74But7Qk2-e5km7BWRwv71yv3hJJpeSQ0Eo9wex4Bqux3QHaDxvl_3ihrGUv7jUq-l2t_Q8R84wITAl-NrPDDqrRe1B-1yZXbA5rney/s1600/Tower_of_Hanoi.jpeg" height="141" width="320" /></a></div>
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 that is solved by recursion. It has 3 towers and the first tower contains n number of disks. A person is said to have completed or solve the problem if he is able to move all the disks to the third tower with certain constraints.<br />
Similarly in the game that is developed here follows the rules - 1. Only one disk can be moved at a time. 2. Cannot place a larger disk on a smaller disk. The game her when starts will start with 4 initial disks. You will have to move all the disk to 3rd tower. You can use this game and ask people to complete and win the game of Tower of Hanoi. You also have a choice to select the number of disks you want to play with. So our main objective her is that we will actually not solve the Tower of Hanoi problem, rather use it as a game and ask players of the game to solve the problem.<br />
<a name='more'></a><br />
Here in our code we have two classes. The <b><i><span style="color: #3d85c6;">Run_Game</span></i></b> class contains the main method and build the frame and menus of the game. The second class <b><i><span style="color: #3d85c6;">Tower</span></i></b> is the important one and backbone of the game. Here first of all 2 arrays (size of 3) of stacks are created. One for holding disk values and other for color of disk. We need array of size 3 as there are three towers. So actually there are 3 stacks to contain disks. Now whenever a player clicks on a disk it is checked on which tower it is located. Now if it is on top of that tower then he can drag the disk. Now as soon as he releases his mouse again the tower where mouse is released is calculated and after that it is checked whether it is smaller than the top disk of that tower. If it is larger then an error message is generated and disk is placed at its previous position. But if it is a valid move then it is placed on that tower. In this way the game goes on until all the disks are moved.<br />
<table cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjq0rvi4dC77Aw04DrTliPUFst3MzUhhh3pf9bD90522jPJlFKx5Z411EelIZtF7BHtqPN5meHrYdF-qqbO9rOwv1o-PyQBasbqnXYHyDeyLv2wcT1PDSlLEphyphenhyphenIMGU3h39sc_gvJ4gRJle/s1600/TOH_Game-1.jpg" imageanchor="1" style="clear: left; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjq0rvi4dC77Aw04DrTliPUFst3MzUhhh3pf9bD90522jPJlFKx5Z411EelIZtF7BHtqPN5meHrYdF-qqbO9rOwv1o-PyQBasbqnXYHyDeyLv2wcT1PDSlLEphyphenhyphenIMGU3h39sc_gvJ4gRJle/s1600/TOH_Game-1.jpg" height="140" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Initial position</td></tr>
</tbody></table>
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggA9o1VirJ61JA4GJtDAYBtHkG4CJVvycOZZ4qd9P3dqntHWMPrtiKwHKRd8FI6KWwYsqwPU3-SLsMZVQGpnoG3lTKlb-PVpA9SbuwetZw8jkHYVmbjrfuuNqO3MKLxPI-oSqOjQRyA_aX/s1600/TOH_Game-2.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggA9o1VirJ61JA4GJtDAYBtHkG4CJVvycOZZ4qd9P3dqntHWMPrtiKwHKRd8FI6KWwYsqwPU3-SLsMZVQGpnoG3lTKlb-PVpA9SbuwetZw8jkHYVmbjrfuuNqO3MKLxPI-oSqOjQRyA_aX/s1600/TOH_Game-2.jpg" height="140" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Game in transition</td></tr>
</tbody></table>
<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
Source Code for Tower.java</div>
<pre class="brush: java">import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Tower extends JPanel implements MouseListener,MouseMotionListener{
public static final long serialVersionUID=0xff;
private Stack<Rectangle2D.Double> s[]=new Stack[3];
private Stack<Color> disk_color[]=new Stack[3];
private static Rectangle2D.Double top=null;
private Color top_color=null;
private double ax,ay,w,h;
private boolean draggable=false,firstTime=false;
public Tower() {
firstTime=true;
init(4);
addMouseListener(this);
addMouseMotionListener(this);
}
public void init(int val){
Color c[]={Color.yellow,Color.red,Color.blue,Color.pink,Color.cyan,Color.magenta,Color.green,Color.orange,Color.lightGray};
s[0]=new Stack<Rectangle2D.Double>();
s[1]=new Stack<Rectangle2D.Double>();
s[2]=new Stack<Rectangle2D.Double>();
disk_color[0]=new Stack<Color>();
disk_color[1]=new Stack<Color>();
disk_color[2]=new Stack<Color>();
for (int i = 0; i<val; i++) {
Rectangle2D.Double r=new Rectangle2D.Double();
double x = getWidth()/6 ;
x = (x == 0)?109 : x;
double wr = val*25-20*i;
r.setFrame(x-wr/2,190-i*20,wr,20);
s[0].push(r);
disk_color[0].push(c[i]);
}
top=null;
top_color=null;
ax=0.0; ay=0.0; w=0.0; h=0.0;
draggable=false;
repaint();
}
public void mouseClicked(MouseEvent ev){}
public void mousePressed(MouseEvent ev){
Point pos=ev.getPoint();
int n=current_tower(pos);
if(!s[n].empty()){
top=s[n].peek();
if(top.contains(pos)){
top=s[n].pop();
top_color=disk_color[n].pop();
ax=top.getX(); ay=top.getY();
w=pos.getX()-ax; h=pos.getY()-ay;
draggable=true; //allowing dragging if current mouse position is in top disk
}
else{
top=null;
top_color=Color.black;
draggable=false;
}
}
}
public void mouseReleased(MouseEvent ev){
if(top!=null && draggable==true){
int tower=current_tower(ev.getPoint());
double x,y;
if(!s[tower].empty()){
if(s[tower].peek().getWidth()>top.getWidth())
y=s[tower].peek().getY()-20; //calculating ay for dragged disk for placement
else{
JOptionPane.showMessageDialog(this,"Wrong Move","Tower Of Hanoi",JOptionPane.ERROR_MESSAGE);
tower=current_tower(new Point((int)ax,(int)ay));
if(!s[tower].empty())
y=s[tower].peek().getY()-20;
else
y=getHeight()-40;
//return; //cannot put bigger disk on a smaller one
}
}
else
y=getHeight()-40; //if no previous disk in tower
x=(int)(getWidth()/6+(getWidth()/3)*tower-top.getWidth()/2);
top.setFrame(x,y,top.getWidth(),top.getHeight());
s[tower].push(top);
disk_color[tower].push(top_color);
top=null;
top_color=Color.black;
draggable=false;
repaint();
}
}
public void mouseEntered(MouseEvent ev){}
public void mouseExited(MouseEvent ev){}
public void mouseMoved(MouseEvent ev){}
public void mouseDragged(MouseEvent ev){
int cx=ev.getX(); //getting current mouse position
int cy=ev.getY();
if(top!=null && draggable==true){
top.setFrame(cx-w,cy-h,top.getWidth(),top.getHeight());
repaint(); //repainting if dragging a disk
}
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(Color.black);
g2d.fillRect(0,0,getWidth(),getHeight());
int holder_x=getWidth()/6;
int holder_y1=getHeight()-10*20,holder_y2=getHeight()-20;
g2d.setColor(Color.white);
g2d.setStroke(new BasicStroke(5));
g2d.drawLine(holder_x,holder_y1,holder_x,holder_y2);
g2d.drawLine(3*holder_x,holder_y1,3*holder_x,holder_y2);
g2d.drawLine(5*holder_x,holder_y1,5*holder_x,holder_y2);
g2d.drawLine(0,holder_y2,getWidth(),holder_y2);
g2d.setStroke(new BasicStroke(1));
g2d.setColor(top_color);
if(draggable==true && top!=null)
g2d.fill(top); //drawing dragged disk
drawtower(g2d,0); //drawing disks of each tower
drawtower(g2d,1);
drawtower(g2d,2);
}
private void drawtower(Graphics2D g2d,int n){
if(!s[n].empty()){
for(int i = 0;i < s[n].size();i++){
g2d.setColor(disk_color[n].get(i));
g2d.fill(s[n].get(i));
}
}
}
private int current_tower(Point p){ //return current tower position with respect to Point p
Rectangle2D.Double
rA=new Rectangle2D.Double(),
rB=new Rectangle2D.Double(),
rC=new Rectangle2D.Double();
rA.setFrame(0,0,getWidth()/3,getHeight());
rB.setFrame(getWidth()/3,0,getWidth()/3,getHeight());
rC.setFrame(2*getWidth()/3,0,getWidth()/3,getHeight());
if(rA.contains(p))
return 0;
else if(rB.contains(p))
return 1;
else if(rC.contains(p))
return 2;
else
return -1;
}
}</pre>
Source Code for Run_Game.java
<br />
<pre class="brush: java">import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Run_Game implements ActionListener{
private static JFrame f = new JFrame();
private static Tower t;
private static JMenuBar menu_bar=new JMenuBar();
private JMenuItem
new_game=new JMenuItem("New Game"),
best_time=new JMenuItem("Best Time"),
exit=new JMenuItem("Exit"),
about=new JMenuItem("About.......");
private JMenu
help=new JMenu("Help"),
game=new JMenu("Game");
public Run_Game(String title) {
f.setTitle(title);
build();
}
public void actionPerformed(ActionEvent ev){
if(ev.getSource()==new_game){
Object values[]= { 3,4,5,6,7,8,9 };
Object val=JOptionPane.showInputDialog(f,"No. Of Disks : ","Input",
JOptionPane.INFORMATION_MESSAGE,null,values,values[0]);
if((int)val!=JOptionPane.CANCEL_OPTION)
t.init((int)val);
}
else if(ev.getSource()==exit)
System.exit(0);
}
private void build(){
game.add(new_game);
game.add(best_time);
game.add(exit);
help.add(about);
menu_bar.add(game);
menu_bar.add(help);
new_game.addActionListener(this);
exit.addActionListener(this);
f.setJMenuBar(menu_bar);
f.setSize(660, 280);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> {
Run_Game obj = new Run_Game("Tower Of Hanoi v1.0");
t=new Tower();
f.getContentPane().add(t);
});
}
}</pre>
-------------------------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/2odn4fioz2dcwr8/Tower+of+Hanoi+v1.0.zip" target="_blank">DOWNLOAD the project archive from Mediafire</a></b><br />
<a href="http://www.4shared.com/zip/NBmj-pf3ce/Tower_of_Hanoi_v10.html" target="_blank"><b>DOWNLOAD the project archive from 4shared</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com5tag:blogger.com,1999:blog-6584580098268567563.post-24857121212263194522014-06-08T00:05:00.001+05:302014-06-08T00:05:42.324+05:30Implementation of generic Binary Search Tree in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIHcmmfnfWSxCl9yXtvkucYTthU5aZgqHzgqSiNpCavgOmG8l9EetmUM8oFKd1QBNN99aNq_02_NXYa6zvzzxee6MZuwLLkOhKv5BqBkjxsjNa51GHl_JEXbRF99XGIWN08jZg2ywqhGPx/s1600/binarySearchTree.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIHcmmfnfWSxCl9yXtvkucYTthU5aZgqHzgqSiNpCavgOmG8l9EetmUM8oFKd1QBNN99aNq_02_NXYa6zvzzxee6MZuwLLkOhKv5BqBkjxsjNa51GHl_JEXbRF99XGIWN08jZg2ywqhGPx/s1600/binarySearchTree.png" height="192" width="320" /></a></div>
Today in this article I will tell you how to create a generic binary search tree (BST) in Java. A normal binary tree is any tree where each node can have a maximum of 2 nodes. But binary search tree is a special kind of binary tree which when traveresed using inorder traversal algorithm lists the nodes in ascending order. In this article we will not deal with traversal, and only concentrate on creating and generating the BST.<br />
The code is written to support generics. This means that only one code has to be written for binary search tree(BST). You can insert anything in the tree but the objects must be comparable. Comparable objects here means that classes of those objects must extend <b><i><span style="color: #3d85c6;">java.lang.Comparable</span></i></b> interface. The comments are also added to the code in Javadoc style<br />
<a name='more'></a><br />
Here in our code we have a class called BinarySearchTree, a generic class with type parameter T; which contains an inner class Node. The node class is used to define each node of the tree - containing two pointers for left and right sub-tree and a value parameter to contain value of the node. Next is <b><i><span style="color: #3d85c6;">insert(T)</span></i></b> method which is called by the user to insert new nodes. This function adds root if tree is empty, otherwise calls a private <b><i><span style="color: #3d85c6;">insert(Node,T)</span></i></b> method with root node and vakue passed as parameter. The private inner(Node,T) is a recursive one which adds node recursively depending on the value - added to left sub-tree if less than parent else added to right sub-tree. The other two methods are very trivial <b><i><span style="color: #3d85c6;">isEmpty()</span></i></b> to check if tree is empty and <b><i><span style="color: #3d85c6;">peek()</span></i></b> to return the value of root.<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">public class BinarySearchTree<T extends Comparable<T>> {
//T is the type parameter and comparable
Node root; //root node of the tree
//defines each node of tree
class Node{
T value; //value of node
Node right,left; //pointer to left and right sub-tree
Node(T value){
this.value = value;
}
}
/**
* This method inserts new node in tree
* @param value
*/
public void insert(T value){
if(isEmpty())
root = new Node(value); //root node added
else
insert(root, value); //if not empty then insert based on root
}
/**
* Recursive method is called internally to insert nodes at proper
places depending on their vakues.
* @param node
* @param value
*/
private void insert(Node node, T value){
if(value.compareTo(node.value) < 0){ //if new value less than parent node
if(node.left == null) //if left null then add
node.left = new Node(value);
else
insert(node.left,value); //if left not null then recursive call
}
else if(value.compareTo(node.value) >= 0){ //if new value same or greater than parent node
if(node.right == null) //if right null then add
node.right = new Node(value);
else
insert(node.right,value); //if right not null then recursive call
}
}
/**
* Returns the value of the root
* @return
*/
public T peek(){
return root.value;
}
/**
* Checks if tree is empty or not
* @return
*/
public boolean isEmpty(){
return (root == null)? true : false;
}
}</pre>
-------------------------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/9vmb7749vjisyt3/BinarySearchTree.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<b><a href="http://www.4shared.com/file/0DzAyMSDce/BinarySearchTree.html" target="_blank">DOWNLOAD the source from 4shared</a></b><br />
<br />
Happy coding :)</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-79683040099169551462014-06-05T20:55:00.002+05:302014-06-05T20:59:41.644+05:30How to create/declare and use annotations in Java - Part 1<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9O-XHViEyd0TNK-91ic53Iu5ZUYmUbhVKoWndGiqpLTBhi9VX7DSSW54e0emyZI_D347xKsZT63BO6Z8M3_Q9H1-sME4tGbmOxAp4j6cob4GbtJkR2P52H_RZqCYKXC2VxZpU84Y0xx5D/s1600/java-annotations.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9O-XHViEyd0TNK-91ic53Iu5ZUYmUbhVKoWndGiqpLTBhi9VX7DSSW54e0emyZI_D347xKsZT63BO6Z8M3_Q9H1-sME4tGbmOxAp4j6cob4GbtJkR2P52H_RZqCYKXC2VxZpU84Y0xx5D/s1600/java-annotations.jpg" height="258" width="400" /></a></div>
Today in this article I will show you how to create your own annotation. Here we will start with a very basic annotation and then slowly show you how to include arrays and also how to use default values. We will also show you how to yo use annotations. We have divided our tutorial on creating and using annotations in two parts. The first part meaning this one is a very basic and good one for beginners to start with.<br />
In our first annotation we will just start with an empty annotation specifying only <complete id="goog_1903482889">@target and @Retention.</complete></div>
<pre class="brush: java">import java.lang.annotation.*;
@Target(value={ElementType.FIELD})
@Retention(value=RetentionPolicy.RUNTIME)
public @interface Author {
}</pre>
In the next example you will see that when there is only one value for an annotation then we can omit the name as well as braces{} indicating arrays. The above sample is re-written as</div>
<pre class="brush: java">import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
}</pre>
In our next example you will see how to mention the target type when it is more than one say FIELD and METHOD.</div>
<pre class="brush: java">import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
}</pre>
In our next example we will deal with annotation which has annotation type elements. It looks almost like methods. We will also show you how to use this annotation in a class.</div>
<pre class="brush: java">import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
String name();
}
class MyClass {
@Author(name="Nirupam")
int i = 10;
}</pre>
In our next and last example of today, we will show you how to mention default values of annotation type elements. It is done using keyword <span style="color: #3d85c6; font-style: italic; font-weight: bold;">default </span>. If a default value is mentioned, then you can omit adding your own value. But it does not mean that you cannot add your own value, of course you can do it.</div>
<pre class="brush: java">import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
String name() default "Nirupam";
}
class MyClass {
@Author
int i = 10;
}</pre>
In our next and last part we will deal with creating and using advanced annotation. Till then keep coding and keep reading our articles.</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-39821394193187079762014-05-06T22:56:00.001+05:302014-07-22T16:54:00.256+05:30Infix to Postfix Conversion using Stack in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmtOI6BtHWpW19N-h-umiAlmIW8xc07NheriCM3dOhg2eoidTTRGRF-QnCoXkp-mzAIKMh8iPGNJCnt7cow97_i-DafQYUgMaaCI6TeBZJYpgwqnQ9tbTLd973u7thi-Slyr5ZARQ5xGPy/s1600/infix-postfix.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmtOI6BtHWpW19N-h-umiAlmIW8xc07NheriCM3dOhg2eoidTTRGRF-QnCoXkp-mzAIKMh8iPGNJCnt7cow97_i-DafQYUgMaaCI6TeBZJYpgwqnQ9tbTLd973u7thi-Slyr5ZARQ5xGPy/s1600/infix-postfix.jpg" /></a></div>
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important application of stack. Most of the codes that you will find dont take into considerations the exponent and parenthesis. Here in our example we will consider everything and it will be able to convert any infix expression to postfix containing exponent(^) and parenthesis("(",")"). In our example we have also shown the current symbol processed, stack status and current postfix expression. We have solved it in the following way<br />
<br />
<ul style="text-align: left;">
<li>First push a sentinel element # to denote end of stack</li>
<li>Scan each symbol of input infix expression</li>
<li>If symbol is operator then check precedence with operator on stack top and take necessary action</li>
<li>If left parenthesis then push it, and if right parenthesis then pop continously from stack till a left parenthesis is found</li>
<li>If all symbols are scanned then pop all elements from stack and ad to postfix till # found.</li>
</ul>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
</div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.util.Scanner;
import java.util.Stack;
public class InfixToPostfix {
/**
* Checks if the input is operator or not
* @param c input to be checked
* @return true if operator
*/
private boolean isOperator(char c){
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
return true;
return false;
}
/**
* Checks if c2 has same or higher precedence than c1
* @param c1 first operator
* @param c2 second operator
* @return true if c2 has same or higher precedence
*/
private boolean checkPrecedence(char c1, char c2){
if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-'))
return true;
else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
return true;
else
return false;
}
/**
* Converts infix expression to postfix
* @param infix infix expression to be converted
* @return postfix expression
*/
public String convert(String infix){
System.out.printf("%-8s%-10s%-15s\n", "Input","Stack","Postfix");
String postfix = ""; //equivalent postfix is empty initially
Stack<Character> s = new Stack<>(); //stack to hold symbols
s.push('#'); //symbol to denote end of stack
System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix);
for(int i = 0; i < infix.length(); i++){
char inputSymbol = infix.charAt(i); //symbol to be processed
if(isOperator(inputSymbol)){ //if a operator
//repeatedly pops if stack top has same or higher precedence
while(checkPrecedence(inputSymbol, s.peek()))
postfix += s.pop();
s.push(inputSymbol);
}
else if(inputSymbol == '(')
s.push(inputSymbol); //push if left parenthesis
else if(inputSymbol == ')'){
//repeatedly pops if right parenthesis until left parenthesis is found
while(s.peek() != '(')
postfix += s.pop();
s.pop();
}
else
postfix += inputSymbol;
System.out.printf("%-8s%-10s%-15s\n", ""+inputSymbol,format(s.toString()),postfix);
}
//pops all elements of stack left
while(s.peek() != '#'){
postfix += s.pop();
System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix);
}
return postfix;
}
/**
* Formats the input stack string
* @param s It is a stack converted to string
* @return formatted input
*/
private String format(String s){
s = s.replaceAll(",",""); //removes all , in stack string
s = s.replaceAll(" ",""); //removes all spaces in stack string
s = s.substring(1, s.length()-1); //removes [] from stack string
return s;
}
public static void main(String[] args) {
InfixToPostfix obj = new InfixToPostfix();
Scanner sc = new Scanner(System.in);
System.out.print("Infix : \t");
String infix = sc.next();
System.out.print("Postfix : \t"+obj.convert(infix));
}
}</pre>
-------------------------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Output</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<pre>Infix : A+(B*C-(D/E^F)*G)*H
Input Stack Postfix
#
A # A
+ #+ A
( #+( A
B #+( AB
* #+(* AB
C #+(* ABC
- #+(- ABC*
( #+(-( ABC*
D #+(-( ABC*D
/ #+(-(/ ABC*D
E #+(-(/ ABC*DE
^ #+(-(/^ ABC*DE
F #+(-(/^ ABC*DEF
) #+(- ABC*DEF^/
* #+(-* ABC*DEF^/
G #+(-* ABC*DEF^/G
) #+ ABC*DEF^/G*-
* #+* ABC*DEF^/G*-
H #+* ABC*DEF^/G*-H
#+ ABC*DEF^/G*-H*
# ABC*DEF^/G*-H*+
Postfix : ABC*DEF^/G*-H*+
</pre>
-------------------------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/5o2eozx8orqe2sr/InfixToPostfix.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/-YFny6KEce/InfixToPostfix.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com6tag:blogger.com,1999:blog-6584580098268567563.post-28913100880667365792014-05-04T14:04:00.000+05:302014-05-04T14:04:24.448+05:30Resize,Scale and Create thumbnail of an image<div dir="ltr" style="text-align: left;" trbidi="on">
To day in this article I will tell you how to resize or scale an image in Java. Many times while developing an application you maya need this. Most often you may require to create a thumbnail of an image in most web applications. This tutorial will guide you describing each steps in detail.<br />
<br />
<ul style="text-align: left;">
<li>First read an image from file or URL using ImageIO</li>
<li>Now create a BufferedImage with specified width, height and image type</li>
<li>Obtain a Graphics2D object from the destination object create in earlier step</li>
<li>Draw the original image using the Graphics object</li>
<li>Dispose the Graphics object</li>
<li>Return or save the final image</li>
</ul>
<div>
Here in our example we will have a class with 3 methods.<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCYCbQ7zoJ0gKKPXGM9Rg3h7aATCG09P5ZTVRgDkCdOSnfl3d6X7a9tWzEsypwDi9TNISf0u0RXl9Gwn2id5yzdw1gPvgmGsWqfZQd3nP9ksJF3LbqNsHbqcfOchSmIJ0w0MKazOnHdiGV/s1600/original.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCYCbQ7zoJ0gKKPXGM9Rg3h7aATCG09P5ZTVRgDkCdOSnfl3d6X7a9tWzEsypwDi9TNISf0u0RXl9Gwn2id5yzdw1gPvgmGsWqfZQd3nP9ksJF3LbqNsHbqcfOchSmIJ0w0MKazOnHdiGV/s1600/original.jpg" height="179" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Original image (930 x 520) to be resized or scaled</td></tr>
</tbody></table>
<br /></div>
<div>
<ul style="text-align: left;">
<li>resizeImage() : This method takes in a source image, the width and height of destination image. This is most simple method and follows the steps mentioned above<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRyBJZ4e3IT9BF96G0GYRVArbNJNInu-TssGBBXtp5arzeKcI-BJm6t0clo51OIIUa26qrLGbEXzC_ckFpSDyD92pxieUtwjSDRqjh_7gHcatwgE4PLSWWJTkKftEd1kUNpnRF96MllyS0/s1600/dest-resize.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRyBJZ4e3IT9BF96G0GYRVArbNJNInu-TssGBBXtp5arzeKcI-BJm6t0clo51OIIUa26qrLGbEXzC_ckFpSDyD92pxieUtwjSDRqjh_7gHcatwgE4PLSWWJTkKftEd1kUNpnRF96MllyS0/s1600/dest-resize.jpg" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Image resized (100 x 100) without hints</td></tr>
</tbody></table>
</li>
<pre class="brush: java">BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = dest.createGraphics();
g2d.drawImage(src, 0, 0, width, height, null);
g2d.dispose();
return dest;</pre>
<li>resizeImageWithHints() : This is a slightly modified version of the above method. Here rendering hints and alpha composite are added to the destination image as shown below<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpQSVfd-AoQ-XNcfZIA0nEoVdiduKrpys77Izau0nmhg-HtrIz4ZEEWynuDoR_Oqes1RGHpBQv-psPN2OBjCxbkEMoIW86UuR26-gIF62mz2Bs2i7cwgIfv0a9b3ObMeP4pG6myS7wZgCo/s1600/dest-resize-hints.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpQSVfd-AoQ-XNcfZIA0nEoVdiduKrpys77Izau0nmhg-HtrIz4ZEEWynuDoR_Oqes1RGHpBQv-psPN2OBjCxbkEMoIW86UuR26-gIF62mz2Bs2i7cwgIfv0a9b3ObMeP4pG6myS7wZgCo/s1600/dest-resize-hints.jpg" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Image resized (100 x 100) with hints</td></tr>
</tbody></table>
</li>
<pre class="brush: java">g2d.setComposite(AlphaComposite.Src);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);</pre>
<li>scaleImage() : This method takes input a source image and the scale factor varying from 0 to 1. The most important feature of this method is that it reserves i.e. maintains the aspect ratio of original image. Here an AffineTransform instance is created and the image is drwan with that instance<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJwBufDyyW-GTB9pn4SRXnKpeAQ8EikFCjFZy-ArkQ1A8zT1VhLeUuJlrE73JZzOKWd55lIZGB3LkEQFeRIhQiTd32sCrl9q0Od8HHhlsyCVxyeZoAmsG8ac24yEFGpR9ytuIxP6GIUu1v/s1600/dest-scale.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJwBufDyyW-GTB9pn4SRXnKpeAQ8EikFCjFZy-ArkQ1A8zT1VhLeUuJlrE73JZzOKWd55lIZGB3LkEQFeRIhQiTd32sCrl9q0Od8HHhlsyCVxyeZoAmsG8ac24yEFGpR9ytuIxP6GIUu1v/s1600/dest-scale.jpg" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Image scaled = 0.3 (279 x 156)</td></tr>
</tbody></table>
</li>
<pre class="brush: java">AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
g2d.drawRenderedImage(src, at);</pre>
</ul>
-------------------------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageResizer {
/**
* Resizes an image without rendering hints depending on input width, height
* @param src source image to be resized
* @param width width of destination image
* @param height height of destination image
* @return resized image
*/
public BufferedImage resizeImage(BufferedImage src,int width,int height){
BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = dest.createGraphics();
g2d.drawImage(src, 0, 0, width, height, null);
g2d.dispose();
return dest;
}
/**
* Resizes an image with rendering hints depending on input width, height
* @param src source image to be resized
* @param width width of destination image
* @param height height of destination image
* @return resized image
*/
public BufferedImage resizeImageWithHints(BufferedImage src,int width,int height){
BufferedImage dest = new BufferedImage(width, height, src.getType());
Graphics2D g2d = dest.createGraphics();
g2d.setComposite(AlphaComposite.Src);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(src, 0, 0, width, height, null);
g2d.dispose();
return dest;
}
/**
* Scales an image depending on sclae factor and maintains
* the aspect ratio of original image
* @param src source image to be scaled
* @param scale scale factor xscale = yscale
* @return scaled image
*/
public BufferedImage scaleImage(BufferedImage src, double scale){
int w = (int)(src.getWidth()*scale);
int h = (int)(src.getHeight()*scale);
BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = dest.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
g2d.drawRenderedImage(src, at);
return dest;
}
public static void main(String... args) throws Exception {
ImageResizer resizer = new ImageResizer();
BufferedImage src = ImageIO.read(new File("original.jpg"));
BufferedImage dest = resizer.resizeImage(src, 100, 100);
ImageIO.write(dest, "jpeg", new File("dest-resize.jpg"));
dest = resizer.resizeImageWithHints(src, 100, 100);
ImageIO.write(dest, "jpeg", new File("dest-resize-hints.jpg"));
dest = resizer.scaleImage(src, 0.3);
ImageIO.write(dest, "jpeg", new File("dest-scale.jpg"));
}
}</pre>
-------------------------------------------------------------------------------------------------------------------------
<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/bqvz52hguqkps9t/ImageResizer.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/IMHCM6pIce/ImageResizer.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-31868680374119226392014-04-26T22:46:00.002+05:302014-04-26T22:46:39.840+05:30Predefined annotations in Java - A short Discussion<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9O-XHViEyd0TNK-91ic53Iu5ZUYmUbhVKoWndGiqpLTBhi9VX7DSSW54e0emyZI_D347xKsZT63BO6Z8M3_Q9H1-sME4tGbmOxAp4j6cob4GbtJkR2P52H_RZqCYKXC2VxZpU84Y0xx5D/s1600/java-annotations.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9O-XHViEyd0TNK-91ic53Iu5ZUYmUbhVKoWndGiqpLTBhi9VX7DSSW54e0emyZI_D347xKsZT63BO6Z8M3_Q9H1-sME4tGbmOxAp4j6cob4GbtJkR2P52H_RZqCYKXC2VxZpU84Y0xx5D/s1600/java-annotations.jpg" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Today in this tutorial I am going to discuss with the annotations that are already defined in the Java language. Some of them are used by the Java compiler and some are used by other annotations.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Annotations used by compiler and declared in java.lang package</div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul style="text-align: left;">
<li><b><i>@Deprecated</i></b> : This annotation is used to indicate that the element marked with it should not be used any longer. The compiler will generate warning if any program uses class, field or method marked with this annotation. It should also be documented with Javadoc annotation @deprecated. Many people make mistakes between the use of @ sign in annotation and javadoc comment. They are completely different and most importantly the annotation has upper-case while the Javadoc comment has a lower-case.</li>
<pre class="brush: java">class DeprecationDemo{
/**
* @deprecated
* defines how to use deprecated annotation
*/
@Deprecated
public void deprecatedMethod(){}
}</pre>
<li><b><i>@Override</i></b> : This annotation is used to indicate that an element marked with it is meant to override an element of super-class. This is not necessary to override an element but helps to prevent runtime errors if Java fails to override during run-time. To know more why should you use this read our article <a href="http://javaingrab.blogspot.com/2012/09/is-it-possible-to-override-static.html" target="_blank">here</a></li>
<li><b><i>@SupressWarnings</i></b> : This annotation is used to supress some warnings that would be generated by the compiler if not used. In our example we will inherit a serializable class JPanel and not write the variable serialVersionUID which will generally result in warnings. But using this annotation will supress it.</li>
<pre class="brush: java">@SupressWarnings("serial")
class SupressWarningsDemo extends javax.swing.JPanel{
}</pre>
It can also be used to supress other warnings like deprecated using "deprecation" if using any deprecated elements. Also unchecked warnings using "unchecked" while interfacing with legacy codes before the inclusion of generics.
<li><b><i>@SafeVarargs</i></b> : This annotation when applied to a method confirms that there will be no unsafe operation with the variable argument parameter. When it is used unchecked warnings associated with varargs are supressed.</li>
<li><b><i>@FunctionalInterface</i></b> : This annotation is used to indicate that an interface is functional interface. this one is related to lambda expression and method references. This annotation is included in Java 8. It can only used with interfaces and if used with classes or enums it will create an error.</li>
</ul>
<div>
There are certain other annotations called meta-annotations that apply to other annotations. They are declared in java.lang.annotation package</div>
<div>
<ul style="text-align: left;">
<li><b><i>@Retention</i></b> : It is used to denote how the annotation should be stored. There are 3 ways</li>
<ul>
<li>RetentionPolicy.SOURCE : Retained at source level and ignored by compiler</li>
<li>RetentionPolicy.CLASS : Retained by compiler at compile-time but ignored by JVM</li>
<li>RetentionPolicy.RUNTIME : Used by JVM during run-time.</li>
</ul>
<li><b><i>@Documented</i></b> : This annotation is used to indicate that whenever the particular annotation is used it should be documented using Javadoc tool. By default they are not documented</li>
<li><b><i>@Target</i></b> : It is used to indicate which kind of Java elements it can be applied.</li>
<ul>
<li>ElementType.ANNOTATION : Can be applied to annotation type</li>
<li>ElementType.CONSTRUCTOR : Can be applied to constructors</li>
<li>ElementType.FIELD : Can be applied to a field</li>
<li>ElementType.LOCAL_VARIABLE : Can be applied to a local variable</li>
<li>ElementType.METHOD : Can be applied to a method</li>
<li>ElementType.PACKAGE : Can be applied to a package declaration</li>
<li>ElementType.PARAMETER : Can be applied to a parameter of a method</li>
<li>ElementType.TYPE : Can be applied to any element of a class.</li>
</ul>
<li><b><i>@Inherited</i></b> : It indicates that the annotation type can be inherited from the super-class. When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.</li>
<li><b><i>@Repeatable</i></b> : This annotation has been included in Java 8. It indicates that the annotation marked with this can be apllied more than once to the same declaration.</li>
</ul>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-37803886656477525632014-04-22T12:45:00.000+05:302014-04-22T12:45:10.515+05:30How to use JProgressBar - A Simple Demo<div dir="ltr" style="text-align: left;" trbidi="on">
Today I am going to show you how to use the swing component - JProgressBar in your GUI application. In this article , I will also focus on how to use lambda expression in swing application. You must have seen a progress bar in many applications. It actually is used to denote graphically the amount of task or work that is completed. The basic properties are :<br />
<ul style="text-align: left;">
<li>Max/Min value - A progress bar always has a maximum and a minimum value</li>
<li>Current value - This value is used to denote the current progress</li>
</ul>
<div>
The class definition of JProgressBar is</div>
<pre class="brush: java">public class JProgressBar
extends JComponent
implements SwingConstants, Accessible
</pre>
<div>
To know more about the JProgressBar class click <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JProgressBar.html" target="_blank">here</a><br />
Most often you need it while reading or writing afile. Here in our example, we will carry out a simple task where we just increase an integer value at a step of 10 and set that vakue to the progress bar. Before we assign the next value the thread sleeps for 100ms so that the progress can be viewed easily. Depending on that value a text area is updated.<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqsPqTFY7bjQA4U6bwQLMzpY1rBhqNCMp42Rm_ReqcNI1OcCuWmzBQ1KAigB-My_Ar0ufxYMvt-AiA2zB7gALpeIaiql2d-rTLsj2w9Dk8YgKb0Azsc2wPOt826a4TiqjvZ-N0U1YfvYia/s1600/JProgressBar.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqsPqTFY7bjQA4U6bwQLMzpY1rBhqNCMp42Rm_ReqcNI1OcCuWmzBQ1KAigB-My_Ar0ufxYMvt-AiA2zB7gALpeIaiql2d-rTLsj2w9Dk8YgKb0Azsc2wPOt826a4TiqjvZ-N0U1YfvYia/s1600/JProgressBar.jpg" height="320" width="282" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">The output of our demo code</td></tr>
</tbody></table>
<br />
Two most important things must be kept in mind whether its a simple or a complex task. In our example also we have followed that.<br />
<br />
<ul style="text-align: left;">
<li>You should always carry out the task in a seperate thread. In our case generating the integer value.</li>
<li>Always update the progress bar and other swing components in event-dispatch thread only. In our case we set the progress bar value with the integer and update text area.</li>
</ul>
<div>
Also here in our code instead of creating an anonymous inner class of ActionListener and Runnable we have used Lambda Expression.</div>
<div>
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b>Java Source Code</b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<pre class="brush: java">import java.awt.*;
import javax.swing.*;
public class JProgressBar_Demo {
//initializing components
private JFrame frame = new JFrame("Java Swing Examples");
private JLabel headerLabel = new JLabel("", JLabel.CENTER);
private JPanel
controlPanel = new JPanel(),
contentPanel = new JPanel();
private JProgressBar progressBar;
private Task task;
private JButton startButton;
private JTextArea outputTextArea;
public JProgressBar_Demo(){
buildGUI();
}
public static void main(String[] args){
JProgressBar_Demo swingDemo = new JProgressBar_Demo();
swingDemo.showDemo();
}
private void buildGUI(){
frame.setSize(350,400); //stting frame size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayouts();
//adding panels to the main panel
contentPanel.add(headerLabel);
contentPanel.add(controlPanel);
frame.getContentPane().add(contentPanel); //adding main panel to frame
frame.setVisible(true);
}
//sets layout of the panels
private void setLayouts(){
//deliberately choosing 3 rows though have 2 components
contentPanel.setLayout(new GridLayout(3,1));
//to add in a directional flow
controlPanel.setLayout(new FlowLayout());
}
public void showDemo(){
headerLabel.setText("Component in action : JProgressBar");
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
startButton = new JButton("Start");
outputTextArea = new JTextArea("",5,20);
//adding scroller to the text-area
JScrollPane scrollPane = new JScrollPane(outputTextArea);
//adding event listener
startButton.addActionListener(
//use of lambda expression intead new ActionListener()
e -> {
/* all tasks other tan component update in event listeners
should be carried out in seperate thread */
task = new Task();
task.start();
});
//adding components
controlPanel.add(startButton);
controlPanel.add(progressBar);
controlPanel.add(scrollPane);
frame.setVisible(true);
}
//This class carries out the task when start button is clicked
private class Task extends Thread {
public void run(){
for(int i =0; i<= 100; i+=10){
//lambda expression can use only final or pseudo-final variables
final int progress = i;
//update swing components in event-dispatch thread
SwingUtilities.invokeLater(
//lambda expression instead of new Runnable()
() -> {
progressBar.setValue(progress);
outputTextArea.append(String.format("%d%% of task completed.\n", progress));
}
);
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
}
}</pre>
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b>Download Links</b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<b><a href="http://www.mediafire.com/download/wcos0zh8ctjt4ti/JProgressBar_Demo.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/xTjODMsGce/JProgressBar_Demo.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-79465091582177078502014-04-18T21:22:00.001+05:302014-04-18T21:22:50.456+05:30Annotation in Java - An Introduction<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinipz4qEgr66qNO7-zE1WYTT2Pl11zFAl17MR9WL-PjJSx4GiZF6n8hJNmN0GO6Bu6e_L-tKyE6QPyQxhO631HJM42RB-jUA5baBJ_XZkLf4C9J1CuEfjv6erKh6lOlHv9ZcSYkzy1JZAv/s1600/java-annotations.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinipz4qEgr66qNO7-zE1WYTT2Pl11zFAl17MR9WL-PjJSx4GiZF6n8hJNmN0GO6Bu6e_L-tKyE6QPyQxhO631HJM42RB-jUA5baBJ_XZkLf4C9J1CuEfjv6erKh6lOlHv9ZcSYkzy1JZAv/s1600/java-annotations.jpg" height="207" width="320" /></a></div>
Today I am going to take you through the basics of annotation. This feature was introduce in JDK 5. Most of the time while writing programs you may have to provide some meta information along with your codes. In those cases annotations come into picture.<br />
<b>What is an annotation ?</b><br />
Annotation is a metadata that provides data or information about a program which is not a part of the program itself with no direct effect on the code it annotates.<br />
<br />
<b>Uses of annotation</b><br />
<br />
<ul style="text-align: left;">
<li>Information used by compiler : They can be used which carries special meaning to the compiler and helps in detecting any compile time errors.</li>
<li>Deployment-time processing : They can be used by softwares, servers to generate codes, files and also to deploy codes as in case of servlets.</li>
<li>Runtime processing : They can be used to carry information during runtime.</li>
</ul>
<div>
Annotations can be applied to declarations : declaration of classes, fields, methods etc. From Java 8, annotations can also be applied to use of types as below</div>
<div>
<ul style="text-align: left;">
<li>Class intance types</li>
<li>Type-Cast</li>
<li>implements clause</li>
<li>throes exception declaration</li>
</ul>
<div>
Depending on the usage of annotation, the retention policy and target of an annotation declared is mentioned.Before we create our own annotaions, these two things must be kept in mind</div>
</div>
<div>
<ul style="text-align: left;">
<li>Retention Policy - There is an enum to define named RetentionPolicy. The constants are used to define how long the annotations should be retained. It has three values : SOURCE, CLASS, RUNTIME .</li>
<li>Target - This is used to define which part of the program can be annotated with that particular annotation. There is an enum ElementType which has several constants PACKAGE, FIELD, METHOD, LOCAL_VARIABLE etc., to define which part should be targeted.</li>
</ul>
<div>
In our next tutorial we will deal with pre-defined annotations in java.</div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-28067791970167165092014-04-17T21:48:00.000+05:302014-04-19T14:54:35.041+05:30Java 8 feature - Lambda Expression An Introduction<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: left;">
Today I am going to deal with the new feature of Java 8 - <b>Lambda Expression</b>. Here we will go through a short introduction on lambda expression and follow up with a simple example to start with it before going into complex ones in our next articles.</div>
<b>Why Lambda Expressions ?</b><br />
Earlier befor Java 8, when we didn't have this awesome feature we had to use anonymous inner classes. Suppose you are writing a GUI application where you write anony mous class very often to specify what action is to be taken when a button is clicked. But now we can use lambdas in places of anonymous classes having a single method. Alternatively you can use them for functional interfaces.In those cases normally we try to pass funtionality as function arguments using anonymous classes. But those codes are cumbersome and look very unclear. So Lambda Expressions has been introduced which allows you to pass functionality as arguments with very simple syntax.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitccVnjKOtcFq3e2LjnexqpMf01uT1ftR0aJu_bxbtP1l-Ip52F8KqWUlWw9tzeCc-9C1wwW4l_AbeEZzAbUzwJBNX69Lxi6fT7HwmnE1vTV_Fpb40xj0nPox70QQcofjBNDPhdFqXC6eL/s1600/Lambda-Expression-in-Java-8.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitccVnjKOtcFq3e2LjnexqpMf01uT1ftR0aJu_bxbtP1l-Ip52F8KqWUlWw9tzeCc-9C1wwW4l_AbeEZzAbUzwJBNX69Lxi6fT7HwmnE1vTV_Fpb40xj0nPox70QQcofjBNDPhdFqXC6eL/s1600/Lambda-Expression-in-Java-8.jpg" /></a></div>
<div style="text-align: left;">
</div>
<b><br /></b>
<b>What is the syntax of Lambda Expression ?</b><br />
Suppose you have a functional interfacelike below which takes a string argument and returns void.</div>
<pre class="brush: java">interface IDemo{
public void action(String s);
}</pre>
Now your lambda expression syntax in place of anonymous class is</div>
<pre class="brush: java">(a) -> System.out.println(s)</pre>
Now if you have more than one parameter then give them seperated by commas as (a,b,c) and so on. As in our case we have only one parameter, you can omit the parenthesis.<br />
<br />
Here in our sample example we will create a Song class which will have different attrbutes like tile,album etc. There will be a functional interface that takes a Song object and returns a boolean value. Now there will be a method which takes in a Collection of songs and performs a particular action when they satisfy a particular criteria. Now earlier, you woula have to pass the criteria while calling that function as an anonymous class; but with Java 8 we will do it using Lambda Expression.<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">package lambda;
import java.util.List;
import java.util.ArrayList;
public class Song {
//instance variables
private String title,artist,album;
private short year,bitrate;
//constructor to set values
public Song(String title, String artist, String album, short year, short bitrate) {
super();
setTitle(title);
setArtist(artist);
setAlbum(album);
setYear(year);
setBitrate(bitrate);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public short getYear() {
return year;
}
public void setYear(short year) {
this.year = year;
}
public short getBitrate() {
return bitrate;
}
public void setBitrate(short bitrate) {
this.bitrate = bitrate;
}
@Override
public String toString() {
return "Music [title=" + title + ", artist=" + artist + ", album="
+ album + ", year=" + year + ", bitrate=" + bitrate + "]";
}
//prints all songs of the list which satisfies the criteria of tester
public static void printSongs(List<Song> tracks, CheckSong tester){
for(Song mt : tracks) //for-each loop
if(tester.test(mt)) //testing criteria
System.out.println(mt); //printing if satisfies
}
}
//functional interface to check the criteria
interface CheckSong{
boolean test(Song song);
}</pre>
Now earlier you had to mention the criteria by anonymous class like this while calling printSongs() method. Here we are trying to print all songs in list that are released after year 2010.<br />
<pre class="brush: java">printSongs(tracks,
new CheckSong() {
@Override
public boolean test(Song song) {
return song.getYear() > 2010;
}
});</pre>
But now with lambda expression the whole thing looks much simpler as shown below<br />
<pre class="brush: java">printSongs(tracks, mt -> mt.year > 2010);</pre>
The main method of the Song class where both approaches are shown
<br />
<pre class="brush: java">public static void main(String... args){
List<Song> tracks = new ArrayList<>();
Song m = new Song("Waka Waka","Shakira","FIFA",(short)2010,(short)320);
tracks.add(m);
m = new Song("La La La","Shakira","FIFA",(short)2014,(short)320);
tracks.add(m);
System.out.println("With anonymous class");
printSongs(tracks,
new CheckSong() {
@Override
public boolean test(Song song) {
return song.getYear() > 2010;
}
});
System.out.println("With lambda expression");
printSongs(tracks, mt -> mt.year > 2010);
}</pre>
<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
Download comlete source from below links which contains Song class with main method where both anonymous class and lambda expressions are used at the same time for better understanding.<br />
<b><a href="http://www.mediafire.com/download/ba77iql1pap5u7u/Song.java" target="_blank">DOWNLOAD the source from Mediafire</a></b><br />
<a href="http://www.4shared.com/file/HCFtYA6Lce/Song.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-72014720405736129642014-04-12T12:51:00.000+05:302014-04-12T12:56:02.101+05:30Is Java a pure object oriented programming language?<div dir="ltr" style="text-align: left;" trbidi="on">
One of the frequent question related to Java is whether Java a pure object oriented language or not is often asked in an interview. The answer is NO. There are many things in Java which are not objects e.g. primitive data types like boolean, int, float etc., different kinds of arithmetic, logical and bitwise operator e.g. +, -. *, /, &&, || etc. Few pure OO languages are <b>Smalltalk</b> and <b>Eiffel</b>. Though Java is one of the most successful Object oriented programming language, which also got some functional programming touch in Java 8 is never considered 100% or pure object-oriented programming language. If it were, all its primitives would be objects. It actually moves half-way in this direction with String and Array, but it doesn't quite go far enough.<br />
<br />
There are seven qualities to be satisfied for a programming language to be pure Object Oriented.<br />
<br />
<ul style="text-align: left;">
<li>Encapsulation/Data Hiding</li>
<li>Inheritance</li>
<li>Polymorphism</li>
<li>Abstraction</li>
<li>All predefined types are objects</li>
<li>All operations are performed by sending messages to objects</li>
<li>All user defined types are objects.</li>
</ul>
Java supports Encapsulation at class and package level, It supports Abstraction, Inheritance and Polymorphism, and all user defined types are also objects. What it doesn't support is #5 and #6.<br />
<div>
<br /></div>
<div>
<b>Why Java is not Pure Object Oriented language? </b></div>
<div>
<div>
Smalltalk is often considered one of the purest Object oriented language and comparing Java with Smalltak will give sufficient reasons, why Java is not pure OO language.</div>
<div>
<ul style="text-align: left;">
<li>Primitive data types are either stored directly in fields or on the stack rather than on the heap.</li>
<li>"Primitive types" in Smalltalk are actually "Primitive Classes" and in Smalltalk all "procedures" or "functions" are really messages</li>
</ul>
</div>
<div>
Though you can make your program pure object oriented by using <b>Autoboxing</b>, but Java compiler supports primitive data types, so Java cannot be Pure OO unless it makes everything objects.</div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-87163867564993720482014-04-04T14:30:00.000+05:302014-04-04T14:30:24.290+05:30AES - 256bits encryption and decryption of file<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiK8Y-TjNq6ZfrujZMEbcOUU5MtkR16ItdtlkMXVyHVK1enzcjQuvpBVVZr7QNC6t8D6hbaP22norTq1Sxe7hVM-zqg8Xtr4tAMH-RgTbCMF4gRiGKGgL4FGDcQ0VWr7wOEKq2Xmb5c7NFe/s1600/aes-logo.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiK8Y-TjNq6ZfrujZMEbcOUU5MtkR16ItdtlkMXVyHVK1enzcjQuvpBVVZr7QNC6t8D6hbaP22norTq1Sxe7hVM-zqg8Xtr4tAMH-RgTbCMF4gRiGKGgL4FGDcQ0VWr7wOEKq2Xmb5c7NFe/s1600/aes-logo.png" /></a></div>
Today I will show you how to do 256bits AES encryption and decryption of a file in Java. You can write codes for AES - 128bits without doing any extra configuration but to use AES - 256bits first of all you have to carry out the following steps. This is because when you install JDK it has default strength which is <i>Strong </i>but you will have to increase it to <i>Unlimited</i>.<br />
<br />
<ul style="text-align: left;">
<li>Download the <b>right </b>version of Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. For JDK7 download it from <a href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html" target="_blank">here</a></li>
<li>Extract the archive and copy the two JAR files (<b>local_policy.jar</b> and <b>US_export_policy.jar</b>) and paste it in the directory <b>JAVA_HOME/jre/lib/security </b>for example <i>C:/Program Files/Java/jdk1.7.0/jre/lib/security</i></li>
</ul>
<div>
In order to perform the encryption, first of all a KeYGenerator instance is created for AES key and the key length is set to 256 using init() method. Then the key is generated which is used for initializing Cipher instance. The generated key is saved to the output file(which will contain encrypted contents) to be used later. The cipher instance is used by the CipherOutputStream to encrypt and write the contents in encrypted format.</div>
<div>
In order to decrypt the encrypted file, initially the key that was saved is read from the file. Then that key is used for initializing Cipher for decryption. The cipher instance is used by CipherInputStream to read encrypted contents and generate the original contents which are then written to file using FileOutputStream.</div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
</div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
</div>
<pre class="brush: java">package com.javaingrab.security.encrypt;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class AESEncryptor {
public void encrypt(String fname) throws Exception{
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); //using AES-256
SecretKey key = keyGen.generateKey(); //generating key
Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES
aesCipher.init(Cipher.ENCRYPT_MODE, key); //initializing cipher for encryption with key
//creating file output stream to write to file
try(FileOutputStream fos = new FileOutputStream(fname+".aes")){
//creating object output stream to write objects to file
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(key); //saving key to file for use during decryption
//creating file input stream to read contents for encryption
try(FileInputStream fis = new FileInputStream(fname)){
//creating cipher output stream to write encrypted contents
try(CipherOutputStream cos = new CipherOutputStream(fos, aesCipher)){
int read;
byte buf[] = new byte[4096];
while((read = fis.read(buf)) != -1) //reading from file
cos.write(buf, 0, read); //encrypting and writing to file
}
}
}
}
public void decrypt(String fname)throws Exception{
SecretKey key =null;
//creating file input stream to read from file
try(FileInputStream fis = new FileInputStream(fname)){
//creating object input stream to read objects from file
ObjectInputStream ois = new ObjectInputStream(fis);
key = (SecretKey)ois.readObject(); //reading key used for encryption
Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES
aesCipher.init(Cipher.DECRYPT_MODE, key); //initializing cipher for decryption with key
//creating file output stream to write back original contents
try(FileOutputStream fos = new FileOutputStream(fname+".dec")){
//creating cipher input stream to read encrypted contents
try(CipherInputStream cis = new CipherInputStream(fis, aesCipher)){
int read;
byte buf[] = new byte[4096];
while((read = cis.read(buf)) != -1) //reading from file
fos.write(buf, 0, read); //decrypting and writing to file
}
}
}
}
public static void main(String[] args) throws Exception {
AESEncryptor obj = new AESEncryptor();
obj.encrypt("clear.txt");
obj.decrypt("clear.txt.aes");
}
}
</pre>
<b>NOTE </b>: You will need the clear.txt file which is the file to be encrypted to execute the code. The encrypted file will be placed in the same directory with same name as original file but with an extension ".aes". The decrypted file will have the same name as the encrypted file but with extension ".dec", this is done deliverately for you people to check whether the original conetents are same as the decrypted one.<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<a href="http://www.mediafire.com/download/jk7zpf7q89xow69/AESEncryptor.java" target="_blank">DOWNLOAD the source from Mediafire</a><br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com6tag:blogger.com,1999:blog-6584580098268567563.post-40895716485689960142014-03-24T13:35:00.000+05:302014-03-24T20:46:47.859+05:30Save(Write) and retrieve(Read) Java objects from file<div dir="ltr" style="text-align: left;" trbidi="on">
Today I will show you "how to save objects to file" and "how to read objects from file". This is a very important thing which you may need while writing an application in Java. You might have an application where you would like to save the state of an object which you may require later. You can think of using databases, but it is very odd to use it for saving small number of objects. Also it may be that you dont have access to databases. So it is best to use the local file systemand save objects in files. This will make the application more light and have freater performance.<br />
This is very easy to do. Just as you write and read all other things from file, similarly this can be done. You have to do just these two things<br />
<br />
<ul style="text-align: left;">
<li>The class whose object you want to save must implement the interface <b><i><span style="color: #3d85c6;">java.io.Serializable</span></i></b>. This interface is a tagging interface and has no abstract methods. As you knowobjects have existence only in JVM and they have no meaning in the external world. So making a class Serializable is quite like signing a contract with JVM that it can be taken outside it but it will be broken into bytes which will be actually saved in file. Similarly while reading the series of bytes from file will be read and the object will be reconstructed.</li>
<li>Wgile writing an object you need a stram to write it. The class <b><i><span style="color: #3d85c6;">java.io.ObjectOutputStream</span></i></b> will help to write objects while <b><i><span style="color: #3d85c6;">java.io.ObjectInputStream</span></i></b> will help to read objects.</li>
</ul>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Student implements Serializable{
private long roll;
private String name;
private static final long serialVersionUID = 1L;
public Student(long roll, String name){
this.roll = roll;
this.name = name;
}
@Override
public String toString() {
return "Student [roll=" + roll + ", name=" + name + "]";
}
}
class SerializableDemo{
public static void main(String[] args) throws ClassNotFoundException, IOException {
//creating instance of Student to save to file
Student s = new Student(11004L,"Aditya Goyel");
System.out.println("Before saving in file >>\n"+s);
//creating the stream to write to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("out.dat"));
oos.writeObject(s); //writing the object
oos.close(); //closing the stream
//creating the stream to read from file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("out.dat"));
Object o = ois.readObject(); //reading from file
if(o instanceof Student) //checking if it is a Student object
o = (Student)o; //type-cast to Student
System.out.println("\nAfter reading from file >> \n"+o);
ois.close(); //closing stream
}
}
</pre>
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Output</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<div>
Before saving in file >></div>
<div>
Student [roll=11004, name=Aditya Goyel]</div>
<div>
<br /></div>
<div>
After reading from file >></div>
<div>
Student [roll=11004, name=Aditya Goyel]</div>
<div>
<br /></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
</div>
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<a href="http://www.mediafire.com/download/oi9ias9qge7hhan/Student.java" target="_blank"><b>DOWNLOAD the source from Mediafire</b></a></div>
</div>Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-32118157584087243832014-03-23T11:42:00.000+05:302014-03-24T20:54:56.003+05:30How to convert java.sql.Date to java.util.Date and vice versa<div dir="ltr" style="text-align: left;" trbidi="on">
This is a very popular question often asked in an interview. You also might be in a situation where you have to store the current date retrieved by java.util.Date in a database table where the datatype of the column is DATE . In that case you have to convert it to java.sql.Date . Also you might have to fetch date from database and then store it in a java.util.Date object . So this is a very important topic. Since both of these classes store the value of date in long milliseconds, so it is very easy to convert from one type to the other. Both of these classes have a method called getTime() which is used for conversion.<br />
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">public class DateConverter {
public static void main(String[] args) {
//creating instances of java.util.Date representing current date and time
java.util.Date now = new java.util.Date();
System.out.println("Value of java.util.Date : " + now);
//converting java.util.Date to java.sql.Date in Java
java.sql.Date sqlDate = new java.sql.Date(now.getTime());
System.out.println("Converted value of java.sql.Date : " + sqlDate);
//converting java.sql.Date to java.util.Date back
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
System.out.println("Converted value of java.util.Date : " + utilDate);
}
}
</pre>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Output</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<div>
Value of java.util.Date : Sun Mar 23 11:35:46 IST 2014</div>
<div>
Converted value of java.sql.Date : 2014-03-23</div>
<div>
Converted value of java.util.Date : Sun Mar 23 11:35:46 IST 2014</div>
<div>
<br /></div>
</div>
<div>
<br /></div>
<div>
Hope this helps. Happy coding :)</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-3014474713425340902014-03-14T00:36:00.000+05:302014-03-24T21:03:23.321+05:30Different JDBC operations - SELECT, INSERT, UPDATE, DELETE<div dir="ltr" style="text-align: left;" trbidi="on">
In our last post we discussed about how to obtain a database connection.After we have it, we can carry out different JDBC operations. Here we will discuss about<br />
<br />
<ul style="text-align: left;">
<li>How to insert new records/rows in database tables (INSERT operation)</li>
<li>How to find a record/row in database tables (SELECT operation)</li>
<li>How to update records/rows in tables (UPDATE operation)</li>
<li>How to delete a record/row from tables (DELETE operation)</li>
</ul>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIB5vBTBzMWNp3wrpDo1HzBxueCapTn4Oe2Xg9zzZ3plXm4MPzxT6xyn9HxAOfNwsNKiPWqieJ7P_8R5t1vMFRq7QK-tWRI_wpEfB12YBBCxelZA95ulOddPcXmP3wirMa7QCZfNmRKbyV/s1600/JDBC+operations.JPG" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIB5vBTBzMWNp3wrpDo1HzBxueCapTn4Oe2Xg9zzZ3plXm4MPzxT6xyn9HxAOfNwsNKiPWqieJ7P_8R5t1vMFRq7QK-tWRI_wpEfB12YBBCxelZA95ulOddPcXmP3wirMa7QCZfNmRKbyV/s1600/JDBC+operations.JPG" height="268" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Different JDBC operations</td></tr>
</tbody></table>
<div class="separator" style="clear: both; text-align: left;">
SQL is written for carrying out the operations and it is either passed to a <b><i><span style="color: #3d85c6;">Statement </span></i></b>or a <b><i><span style="color: #3d85c6;">PreparedStatement</span></i></b>. The latter is used as DBMS has to only recompile and carry out the task. There is no need of parsing if PreparedStatement is used. Also it prevents SQL injection. You should use it everywhere when you have to pass parameters. It is recommended to use in all public applications.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
First create a database table Student as follows :</div>
<div class="separator" style="clear: both; text-align: left;">
CREATE TABLE student(id number primary key,name varchar(30));</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
-------------------------------------------------------------------------------------------------------------------------</div>
<div class="separator" style="clear: both; text-align: center;">
<b><i>Java Source Code</i></b></div>
<div class="separator" style="clear: both; text-align: left;">
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StudentService {
private Connection con;
public StudentService(Connection con){
this.con = con; //database connection object
}
//Inserting new row in table with given id and name
public void insertRecord(int id, String name) throws SQLException{
con.setAutoCommit(false);
String sql = "INSERT INTO student VALUES(?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.executeUpdate();
con.commit();
ps.close();
}
//Find a record based on id
public void findRecord(int id) throws SQLException{
String sql = "SELECT * FROM student WHERE id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if(rs.next())
System.out.println(rs.getInt("id")+"\t"+rs.getString("name"));
else
System.out.println("No records found");
ps.close();
}
//Find all the records
public void findAllRecord() throws SQLException{
con.setAutoCommit(false);
String sql = "SELECT * FROM student";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
System.out.println(rs.getInt("id")+"\t"+rs.getString("name"));
ps.close();
}
//Update a record with new name based on id
public void updateRecord(int id, String name) throws SQLException{
con.setAutoCommit(false);
String sql = "SELECT id,name FROM student WHERE id=?";
PreparedStatement ps=con.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ps.setInt(1, id);
ResultSet rs=ps.executeQuery();
rs.updateString("name", name);
rs.updateRow();
con.commit();
ps.close();
}
//Delete a record based on id
public void deleteRecord(int id) throws SQLException{
con.setAutoCommit(false);
String sql = "DELETE FROM student WHERE id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
con.commit();
ps.close();
}
}</pre>
<div class="separator" style="clear: both;">
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<a href="http://www.mediafire.com/download/y9z5t7ac6cau5dp/StudentService.java" target="_blank"><b>DOWNLOAD the source from Mediafire</b></a></div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-4687869012067626082014-03-13T13:16:00.002+05:302014-03-24T20:58:51.840+05:30Java program to connect to a database<div dir="ltr" style="text-align: left;" trbidi="on">
All those who are new to programming have dealt with data provided either from a file or command line. But you might ne in a situation where you have to store and access data from a persistent storage more easily and which is not a file, e.g. database. It fully depends on vendors and databse administrators how the data will be stored on the disk. It provides a much easier way to access and save data and coders dont have to think about storage. But before we go into saving and accessing data from a database, the first step is to create a connection with the databse from your java program. Here we will be using Oracle 11g Express edition as our database. We will use JDBC to obtain the connection.<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhU822yK1r1iap3E63BA-V4gIWvzil_o3LQAadqJVyLVHoa5_6x4t8qC7JQbay9ARiU01OygzKfBvWj3bbLABarYqyvAExaI5rwgwzz0dDc3iltMRpPQZLFk183OytkOw65_2Uof1sWFKFG/s1600/JDBC-Architecture.gif" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhU822yK1r1iap3E63BA-V4gIWvzil_o3LQAadqJVyLVHoa5_6x4t8qC7JQbay9ARiU01OygzKfBvWj3bbLABarYqyvAExaI5rwgwzz0dDc3iltMRpPQZLFk183OytkOw65_2Uof1sWFKFG/s1600/JDBC-Architecture.gif" height="262" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">JDBC Architecture</td></tr>
</tbody></table>
<br />
Just as we need a device driver to use a hardwarte from a software, similarly we will need a driver to access the database. There are different types of drivers : type 1, type 2 , type 3 and type 4. For more about this visit <a href="http://en.wikipedia.org/wiki/JDBC_driver" target="_blank">Wikipedia JDBC driver</a> . We will be using type 4 JDBC driver which is completely written in Java. If you have already installed Oracle you will find that in<br />
<div style="text-align: center;">
<i><span style="color: #674ea7;">C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar</span></i></div>
<div style="text-align: left;">
Place that jar file in your classpath. Below is the code which will return the Connection object to the database</div>
<div style="text-align: left;">
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
<div style="text-align: left;">
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public final class Provider {
static{
try {
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Driver loaded successfully");
} catch (ClassNotFoundException e) {
System.out.println("Failed to load driver");
}
}
public static Connection getCon(String userid, String pass) throws SQLException{
return DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", userid, pass);
}
}
</pre>
<br />
<div>
<br /></div>
<div>
This is the fisrt and foremost step of using JDBC. Happy coding :)</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-24461711842965677172014-02-16T12:56:00.000+05:302014-03-24T21:07:07.826+05:30Creating instances of a class having private constructor using reflection<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9VhICJa2gumtKhAr1908iX443uD21rsxo-Nf9pkfUCiycmBKA6nR2BtmLZWfkO4Vf-XusgoaF3i_zdL6JgaaRaAoEH8PjGv-Hg72kOVKlqdwuiXNpSTGbhCOrru40qo8jL5uVLkQoPuQu/s1600/java-reflection.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9VhICJa2gumtKhAr1908iX443uD21rsxo-Nf9pkfUCiycmBKA6nR2BtmLZWfkO4Vf-XusgoaF3i_zdL6JgaaRaAoEH8PjGv-Hg72kOVKlqdwuiXNpSTGbhCOrru40qo8jL5uVLkQoPuQu/s1600/java-reflection.jpg" height="128" width="200" /></a></div>
Today I will show that how the power of reflection can bypass encapsulation. This is excellent feature in Java. You must have read and experienced that you cannot create instances of class with private constructors using "new" keyword outside that class. But using reflection you can do mit very easily.And using that we can call any methods and do as we wish. To do that we have to follow these steps :<br />
<br />
<ol style="text-align: left;">
<li>Create the Class class instance of the specified class using <b style="color: #3d85c6; font-style: italic;">Class.forName() </b>or<b style="color: #3d85c6; font-style: italic;"> </b><span style="color: #3d85c6;"><Class-Name>.class</span></li>
<li>Create the Constructor instance from the Class instance using <b><i><span style="color: #3d85c6;">getDeclaredConstructor()</span></i></b></li>
<li>Call the <b><i><span style="color: #3d85c6;">setAccessible()</span></i></b> on constructor object and set to true. This is the most important step as failing it wont allow you to access the private constructor.</li>
<li>Call <b><i><span style="color: #3d85c6;">newInstance()</span></i></b> method on the constructor object which will return a reference to Object class. That's it. Dow what you wish with this reference.</li>
</ol>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<pre class="brush: java">import java.lang.reflect.Constructor;
class PrivateCons {
private String i;
private PrivateCons(String i){
this.i=i;
}
@Override
public String toString(){
return "I am "+i;
}
}
public class PrivateConsReflect{
public static void main(String[] args) throws Exception{
Class c=PrivateCons.class; //getting Class class instance
Constructor cons=c.getDeclaredConstructor(String.class); //getting constructor
cons.setAccessible(true); //setting true to access private feature
Object pc=cons.newInstance("5"); //creating instance of the class
System.out.println(pc); //printing object
}
}</pre>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<b><a href="http://www.mediafire.com/download/tg2gh313kzy24vu/PrivateConsReflect.java" target="_blank">DOWNLOAD the source from Mediafire</a></b></div>
<div>
<a href="http://www.4shared.com/file/V--k0YUQba/PrivateConsReflect.html" target="_blank"><b>DOWNLOAD the source from 4shared</b></a></div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0tag:blogger.com,1999:blog-6584580098268567563.post-29760425841773538992013-09-15T23:42:00.000+05:302014-03-25T13:06:01.042+05:30Generate and Validate captcha<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuCpBIGYL8IM8yhxupZys3QkXnNuLuKYDS7jzyWre3t7WPdC24kMvhPpSIB4oS0NLRCb4giWDmMZJpCY69jny6C1dfEropQcIXxMzdN7P8Gh9XbmLfnd2hiyAlw61zgOIhOoODO7Z5Jj5x/s1600/captcha.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuCpBIGYL8IM8yhxupZys3QkXnNuLuKYDS7jzyWre3t7WPdC24kMvhPpSIB4oS0NLRCb4giWDmMZJpCY69jny6C1dfEropQcIXxMzdN7P8Gh9XbmLfnd2hiyAlw61zgOIhOoODO7Z5Jj5x/s320/captcha.jpg" height="112" width="320" /></a></div>
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.<br />
Here we will be using <b><u>jcaptcha library</u></b> 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.<br />
<br />
<ul style="text-align: left;">
<li><b>login.jsp</b> : 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.</li>
<li><b>CaptchaService class </b>: This is a singleton class that is responsible for generating the instance that will help in generating the challenge image.</li>
<li><b>CaptchaGeneratorServlet class</b> : 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.</li>
<li><b>CaptchaVerifierServlet class </b>: 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.</li>
<li><b>results.jsp</b> : It extracts the session attribute and displays result according to that.</li>
</ul>
<div>
<br /></div>
<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<i>/* Code for login.jsp */</i><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-M_ChxH9Yc2b1P_PIXE_4innPBITTbwpBN1SB4zEaYIRvHrz4DArFRLWvTy1XegrzK28oTqSZIo7jwp0jtQ1701t2O0TFLwaXxHTbKnGnptguWJVflDnFP-zrPwrdBe32CcipA7xjeFVi/s1600/captcha-login.jpg" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-M_ChxH9Yc2b1P_PIXE_4innPBITTbwpBN1SB4zEaYIRvHrz4DArFRLWvTy1XegrzK28oTqSZIo7jwp0jtQ1701t2O0TFLwaXxHTbKnGnptguWJVflDnFP-zrPwrdBe32CcipA7xjeFVi/s320/captcha-login.jpg" height="219" width="320" /></a></div>
<pre class="brush: html"><!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></pre>
<b><br /></b>
<b><br /></b>
<i>/* Code for CaptchaService.java */</i><br />
<pre class="brush: 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;
}
}
</pre>
<br />
<b><br /></b>
<b><br /></b>
<i>/* Code for CaptchaGeneratorServlet.java */</i><br />
<pre class="brush: 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();
}
}
</pre>
<br />
<b><br /></b>
<i>/* Code for CaptchaVerifierServlet.java */</i><br />
<pre class="brush: 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;
}
}
</pre>
<br />
<div>
<br /></div>
<div>
<i>/* Code for results.jsp */</i><br />
<div class="separator" style="clear: both; text-align: center;">
<i><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEioaoWvy0onZ_SLm38Jg_TjsPebeUeIj7H7T3kRxeRmsjQqcOLfq0W0HDPp1pBiT5dVoC5uge39RahXhKRkyidzBjt6WavDkuiFc_B5VucEfGYLLp3c3VH0YiTiXhRTZtleNYCf-9FUXFNZ/s1600/captcha-results.jpg" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEioaoWvy0onZ_SLm38Jg_TjsPebeUeIj7H7T3kRxeRmsjQqcOLfq0W0HDPp1pBiT5dVoC5uge39RahXhKRkyidzBjt6WavDkuiFc_B5VucEfGYLLp3c3VH0YiTiXhRTZtleNYCf-9FUXFNZ/s320/captcha-results.jpg" height="217" width="320" /></a></i></div>
<i>
</i></div>
<div>
<div>
<b><!DOCTYPE html> </b></div>
<div>
<b><html></b></div>
<div>
<b><head></b></div>
<div>
<b><title>JCaptcha Demo - Result</title></b></div>
<div>
<b></head></b></div>
<div>
<b><body></b></div>
<div>
<b> <% Boolean b = (Boolean)session.getAttribute("result");</b></div>
<div>
<b> if ( b!=null && b.booleanValue() ){</b></div>
<div>
<b> %></b></div>
<div>
<b> Congrats! You passed the Captcha test!</b></div>
<div>
<b> <% } else { %></b></div>
<div>
<b> Sorry, you failed the Captcha test.</b></div>
<div>
<b> <% } %></b></div>
<div>
<b></body></b></div>
<div>
<b></html></b></div>
</div>
<div>
<b><br /></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<b><a href="http://www.mediafire.com/download/0ddswxedyxfm0a1/captcha.war" target="_blank">DOWNLOAD the war from Mediafire</a></b></div>
<div>
<b><a href="http://www.4shared.com/file/Mcgyp67P/captcha.html" target="_blank">DOWNLOAD the war from 4shared</a></b></div>
<div>
<b>NOTE</b> : 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.</div>
<div>
<br /></div>
<div>
Happy coding :)</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com8tag:blogger.com,1999:blog-6584580098268567563.post-78018919784088141682013-09-01T16:23:00.001+05:302013-09-01T16:31:11.114+05:30Getting and setting field values using reflection<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9VhICJa2gumtKhAr1908iX443uD21rsxo-Nf9pkfUCiycmBKA6nR2BtmLZWfkO4Vf-XusgoaF3i_zdL6JgaaRaAoEH8PjGv-Hg72kOVKlqdwuiXNpSTGbhCOrru40qo8jL5uVLkQoPuQu/s1600/java-reflection.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="128" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9VhICJa2gumtKhAr1908iX443uD21rsxo-Nf9pkfUCiycmBKA6nR2BtmLZWfkO4Vf-XusgoaF3i_zdL6JgaaRaAoEH8PjGv-Hg72kOVKlqdwuiXNpSTGbhCOrru40qo8jL5uVLkQoPuQu/s200/java-reflection.jpg" width="200" /></a></div>
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 <b><i><span style="color: #3d85c6;">getDeclaredField()</span></i></b> (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 <b><i><span style="color: #3d85c6;">getInt()</span></i></b> and <b><i><span style="color: #3d85c6;">setInt()</span></i></b> for int , <b><i><span style="color: #3d85c6;">getLong()</span></i></b> and <b><i><span style="color: #3d85c6;">setLong()</span></i></b> for long and so on. But for data types other than primiotive ones you have to use <b><i><span style="color: #3d85c6;">get()</span></i></b> and <b><i><span style="color: #3d85c6;">set()</span></i></b> methods.<br />
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.<br />
-------------------------------------------------------------------------------------------------------------------------<br />
<div style="text-align: center;">
<b><i>Java Source Code</i></b></div>
-------------------------------------------------------------------------------------------------------------------------<br />
<b>import java.lang.reflect.Field;</b><br />
<b>import java.util.Arrays;</b><br />
<b><br /></b>
<b>import static java.lang.System.out;</b><br />
<b><br /></b>
<b>class Person{</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>public int id=1521;</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>public String name="Luther";</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>public String hobbies[]={"cricket","music"};</b><br />
<b>}</b><br />
<b><br /></b>
<b>public class FieldChanger {</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>public static void main(String[] args) {</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>try{</b><br />
<span class="Apple-tab-span" style="font-weight: bold; white-space: pre;"> </span><b> Class c=Person.class; </b><i> //getting class reference</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> Person pobj=new Person();</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> </b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> Field id=c.getDeclaredField("id"); </b><i> //getting field reference</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> out.println("BEFORE : id = "+id.getInt(pobj)); /</b><i>/getting initial int value</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> id.setInt(pobj, 1926); </b><i>//setting a new int value</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> out.println(" AFTER : id = "+id.getInt(pobj));</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> </b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> Field name=c.getDeclaredField("name");</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> out.println("BEFORE : name = "+name.get(pobj)); </b><i>//getting initial String value</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> name.set(pobj, "Jennifer"); </b><i>//setting a new String value</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> out.println(" AFTER : name = "+name.get(pobj));</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> </b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> Field hobbies=c.getDeclaredField("hobbies");</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> </b><i>//showing initial array values</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> out.println("BEFORE : hobbies = "+Arrays.asList(pobj.hobbies));</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> String[] nhob={"football"};</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> hobbies.set(pobj, nhob); </b><i>//setting new values for array</i><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> out.println(" AFTER : hobbies = "+Arrays.asList(pobj.hobbies));</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span> </b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>}catch(NoSuchFieldException|</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>IllegalAccessException e){<span class="Apple-tab-span" style="white-space: pre;"> </span>}</b><br />
<b><span class="Apple-tab-span" style="white-space: pre;"> </span>}</b><br />
<b>}</b><br />
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Output</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<div>
BEFORE : id = 1521</div>
<div>
AFTER : id = 1926</div>
<div>
BEFORE : name = Luther</div>
<div>
AFTER : name = Jennifer</div>
<div>
BEFORE : hobbies = [cricket, music]</div>
<div>
AFTER : hobbies = [football]</div>
</div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div style="text-align: center;">
<b><i>Download Links</i></b></div>
<div>
-------------------------------------------------------------------------------------------------------------------------</div>
<div>
<b><a href="http://www.mediafire.com/download/4gvgaule5xp8lpx/FieldChanger.java" target="_blank">DOWNLOAD the source from Mediafire</a></b></div>
<div>
<b><a href="http://www.4shared.com/file/qh2nT09r/FieldChanger.html" target="_blank">DOWNLOAD the source from 4shared</a></b></div>
<div>
<br /></div>
<div>
Happy coding :)</div>
</div>
Anonymoushttp://www.blogger.com/profile/17242988539134445454noreply@blogger.com0