Friday, May 10, 2013
The heapsort algorithm starts by using BUILD-MAX-HEAP to build a max-heap on the input array A[1 : : n ],where n=A:length. Since the maximum element of the array is stored at the root A[1] , we can put it into its correct final osition by exchanging it with A[n] . If we now discard node n from the heap - and we can do so by simply decrementing A:heap-size-- we observe that the children of the root remain max-heaps, but the new root element might violate the max-heap property. All we need to do to restore the max-heap property, however, is call MAX-HEAPIFY(A, 1), which leaves a max-heap in A[1 : : n -1] . The heapsort algorithm then repeats this process for the max-heap of size n- 1 down to a heap of size 2.
     The program written below has build_max_heap() to build the max-heap, max_heapify() to retain the max-heap property and heap_sort() for sorting. The most important thing of the code is that you can use this to sort anything. Just pass an array of any object which is comparable i.e. implements Comparable interface or any array of wrapper class objects like Integer, Float etc. This is only beacause we have done this using Java's generics feature to make this code generic and general and no need for different implementations.
Heapsort operation
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.util.Scanner;

/*This code can take in any array of Comparable i.e whose data can be compared and generates the sorted elements using heap sort*/
public class HeapSort<E extends Comparable<? super E>>{
    private int heap_size;
private E A[];

public HeapSort(E a[]){
  A=a;
}

private void build_max_heap(){  //building max-heap
   heap_size=A.length-1;
   for(int i=heap_size/2;i>=0;i--)
  max_heapify(i);
}

private void swap(int i,int j){
   E tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}

private void max_heapify(int i){
   int l=2*i,r=2*i+1;  //left and right child
int largest;
   if(l<=heap_size && A[l].compareTo(A[i])>0)
  largest=l;
else largest=i;
if(r<=heap_size && A[r].compareTo(A[largest])>0)
  largest=r;
if(largest!=i){    //finding largest, swapping and then reheapify
  swap(i,largest);
  max_heapify(largest);
}
}

public E[] heap_sort(){
   build_max_heap();
for(int i=A.length-1;i>=0;i--){
  swap(0,i);  //swapping with first
  heap_size--;  //decreasing size
  max_heapify(0);  //reheapify
}

return A;
}

public static void main(String[] args)throws Exception{
Scanner sc=new Scanner(System.in);
System.out.print("Enter size : ");
int n=sc.nextInt();
Integer a[]=new Integer[n];
System.out.println("Enter elements to be sorted -->");
for(int i=0;i<n;i++)
  a[i]=sc.nextInt();
  
HeapSort<Integer> obj=new HeapSort<Integer>(a);
a=obj.heap_sort();
System.out.println("Sorted array -->");
for(int i=0;i<n;i++)
  System.out.print(a[i]+"  ");
    }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------

Saturday, May 4, 2013
Today I will tell you how you can get the parameter values submitted by a client to a server using servlets. Here you will see different process of extracting the form parameters depending on your requirements. Here we will use getParameter() , getParameterValues() , getParameterNames() and getParameterMap() methods.
 getParameter() : This method returns only a single value associated with the parameter name. This is generally used when you have only one value for a parameter.
getParameterValues() : It returns an array of all values associated with a parameter name. This is used when you have multiple values for a parameter.
getParameterNames() : It returns an Enumeration<String> which are the different parameter names. Now you can use individual name and extract the values. This is used when you dont know the param names. But in reality you will always know them from beforehand.
getParameterMap() : It returns a Map of parameter names mapped to all values associated with each parameter. This is the most general case.
--------------------------------------------------------------------------------------------------------------------------
Servlet Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/paramReader")
public class ParamReader extends HttpServlet{
   public void doGet(HttpServletRequest req,HttpServletResponse res){
        //used when one parameter has only one value
String fn=req.getParameter("fn");

//used when one parameter has more than one vakue
String str[]=req.getParameterValues("fn");  //getting all values

//used when parameter names are unknown
Enumeration<String> en=req.getParameterNames();  //getting all names
while(en.hasMoreElements())
          req.getParameter(en.nextElement());  //getting vakue
     
      //used to get whole map
Map<String,String[]> m=req.getParameterMap();
Set<String> s=m.keySet();  //key set means param names
Iterator<String> it=s.iterator();
while(it.hasNext())
          m.get(it.next());  //param values
   }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Tuesday, April 9, 2013
Today I will tell you how you can send a HTTP request from your simple Java program and then read the data(HTML) sent from the server. This is actually the process which is carried out by browsers when you type the url in its address bar. The browser receives the data and then parses and displays it. Here we will omit the parsing and only print the data received from server on the console. The request to the url here is a HTTP GET request. The following classes are used
java.net.URL : This class represents the Uniform Resource Locator and points to a resource. Here we will use openConnection() method to connect to the url and get a URLConnection reference.
java.ney.URLConnection : The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. We will call getInputStream() to get a stream to that url which is used for reading data from url or server.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.net.URL;
import java.net.URLConnection;
import java.io.*;

public class URLConnectionReader {
  public static void main(String[] args) throws Exception {
    URL url = new URL(args[0]);  //url read from command line
    URLConnection c = url.openConnection();  //connecting to url
    BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));  //stream to resource
    String str;
    while ((str = in.readLine()) != null)   //reading data
       System.out.println(str);  //printing data read from url to console
    in.close();  //closing stream
  }
}
Sunday, March 31, 2013
-------------------------UPDATE-------------------------
I have updated the code on request of some followers so that they can directly use this code for their project without requiring to make any changes.
Following changes have been made
  • A copy method has been introduced to copy the streams. I reduces unnecessary duplicate codes for copying files.
  • Another important update added is that the file decrypted will have the same name it had before encryption along with its extension.
  • The last feature added is try with resources. This reduces extra bit of coding to flush and close the streams.
--------------------------------------------------

Today I am going to discuss how you can encrypt any file in Java.For encryption we need a key based on which the encryption will be done. Not only that, I will also show how you can decrypt that file and get back the original one. The encryption algorithm can be chosen by the user. Here we will use some classes Cipher,CipherInputStream,CipherOutputStream,SecretKeySpec. One thing you have to always remember is that the same key must be used both for encryption and decryption. We will use Cipher stream classes as only one function call is required for both either reading/writing and encryption/decryption. Otherwise we would have to call update() method for encryption/decryption and then write() for writing to file.
SecretKeySpec class : This class specifies a secret key in a provider-independent fashion and is only useful for raw secret keys that can be represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.
Cipher class : This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework. Its getInstance() method is called to get the object based on algorithm. Then the init() method is called for initializing the object with encryption mode and key.
CipherInputStream class : It is composed of an InputStream and a Cipher so that read() methods return data that are read in from the underlying InputStream but have been additionally processed by the Cipher. The Cipher must be fully initialized before being used by a CipherInputStream. It is used for decryption and does read and then update operation.
CipherOutputStream class : Just like above it is also composed of a stream and cipher and the cipher must be fully initialised before using this stream. It is used for encryption purpose.

So below is the code which solves your question how to encrypt a file in Java and also how to decrypt a file. This code actually shows you how to encrypt and decrypt a file using DES or Triple DES in Java.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
The code after update applied
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class FileEncryptor{
    
 private String algo;
 private String path;
 
    public FileEncryptor(String algo,String path) {
     this.algo = algo; //setting algo
     this.path = path;//setting file path
    }
    
    public void encrypt() throws Exception{
         //generating key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher encrypt =  Cipher.getInstance(algo);  
         encrypt.init(Cipher.ENCRYPT_MODE, key);
         //opening streams
         FileOutputStream fos =new FileOutputStream(path+".enc");
         try(FileInputStream fis =new FileInputStream(path)){
            try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
                copy(fis,cout);
            }
         }
     }
     
     public void decrypt() throws Exception{
         //generating same key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher decrypt =  Cipher.getInstance(algo);  
         decrypt.init(Cipher.DECRYPT_MODE, key);
         //opening streams
         FileInputStream fis = new FileInputStream(path);
         try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){  
            try(FileOutputStream fos =new FileOutputStream(path.substring(0,path.lastIndexOf(".")))){
               copy(cin,fos);
           }
         }
      }
     
  private void copy(InputStream is,OutputStream os) throws Exception{
     byte buf[] = new byte[4096];  //4K buffer set
     int read = 0;
     while((read = is.read(buf)) != -1)  //reading
        os.write(buf,0,read);  //writing
  }
  
     public static void main (String[] args)throws Exception {
      new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt();
      new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt();
  }
}
The original code before update
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class FileEncryptor{
    
    private String algo;
    private File file;
 
    public FileEncryptor(String algo,String path) {
     this.algo=algo; //setting algo
     this.file=new File(path); //settong file
    }
    
     public void encrypt() throws Exception{
         //opening streams
         FileInputStream fis =new FileInputStream(file);
         file=new File(file.getAbsolutePath()+".enc");
         FileOutputStream fos =new FileOutputStream(file);
         //generating key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher encrypt =  Cipher.getInstance(algo);  
         encrypt.init(Cipher.ENCRYPT_MODE, key);  
         CipherOutputStream cout=new CipherOutputStream(fos, encrypt);
         
         byte[] buf = new byte[1024];
         int read;
         while((read=fis.read(buf))!=-1)  //reading data
             cout.write(buf,0,read);  //writing encrypted data
         //closing streams
         fis.close();
         cout.flush();
         cout.close();
     }
     
     public void decrypt() throws Exception{
         //opening streams
         FileInputStream fis =new FileInputStream(file);
         file=new File(file.getAbsolutePath()+".dec");
         FileOutputStream fos =new FileOutputStream(file);               
         //generating same key
         byte k[] = "HignDlPs".getBytes();   
         SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);  
         //creating and initialising cipher and cipher streams
         Cipher decrypt =  Cipher.getInstance(algo);  
         decrypt.init(Cipher.DECRYPT_MODE, key);  
         CipherInputStream cin=new CipherInputStream(fis, decrypt);
              
         byte[] buf = new byte[1024];
         int read=0;
         while((read=cin.read(buf))!=-1)  //reading encrypted data
              fos.write(buf,0,read);  //writing decrypted data
         //closing streams
         cin.close();
         fos.flush();
         fos.close();
     }
     
     public static void main (String[] args)throws Exception {
         new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt();
         new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt();
  }
}

NOTE : The generated decrypted file name is not the same as that of original so that you can check whether same contents have been generated or not. You can change this part.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire

DOWNLOAD the complete file encryptor project from Mediafire
NOTE : the project archive contains the java source file, the sample file for encryption and the encrypted file produced after encryption of sample file.
--------------------------------------------------------------------------------------------------------------------------
Related Posts
--------------------------------------------------------------------------------------------------------------------------
AES - 256bits encryption and decryption of file

Search keywords : how to, encrypt, decrypt, files, using DES, for encryption and decryption, java

Happy coding :)
Wednesday, March 20, 2013
Today I am going to tell how you can save your application preferences, settings and configuration. You must have always wondered that how different softwares save the user data for that particular application. We can do this very easily in Java using the class java.util.prefs.Preferences .
Preferences class : This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store. A node is created using node() method.
         There are two separate trees of preference nodes, one for user preferences (method used is userRoot()) and one for system preferences (method used is systemRoot()). Each user has a separate user preference tree, and all users in a given system share the same system preference tree. The precise description of "user" and "system" will vary from implementation to implementation. Typical information stored in the user preference tree might include font choice, color choice, or preferred window location and size for a particular application. Typical information stored in the system preference tree might include installation configuration data for an application. The put() method has two arguments of key-value pair. There are different put() methods for different data types. There is also a get() method for retreiving values of keys. The two parameters are key and default value. The default value is returned if key is not found. The keys and  nodes are removed using remove() and removeNode().
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.util.prefs.Preferences;

public class AppPreferences{
  public static void main (String[] args) throws Exception{
    Preferences p=Preferences.userRoot().node("myapp");
    System.out.println(p); //display current preference
    p.put("user","nirupam"); //adding a user key
    System.out.println(p.get("user","Hello World")); //shows default value if 
key not found
    p.remove("user"); //removing key
    p.removeNode();  //removing node
    }
}
--------------------------------------------------------------------------------------------------------------------------
Oitput
--------------------------------------------------------------------------------------------------------------------------
Screenshot of the windows registry
Windows Registry
To see the above outout in your registry you must comment the last two lines of code as they removes the node. So keep this in mind.

Output on Console

User Preference Node: /myapp
nirupam

--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

Total Pageviews

Followers


Labels

Popular Posts

free counters