Tuesday, April 08, 2014

Building Application with Spring Boot

Spring Boot makes very easy to build standalone as well as production grade Spring based application. I found features like "Embedded Tomcat and Jetty. no need to deploy war. also XML based configuration eliminated" - interesting !

Spring Boot Features :
  • Create Stand Alone Spring based Application
  • No need for XML Configuration
  • Embedded Tomcat and Jetty (no need to deploy war)
  • Configure Spring Automatically whenever possible
  • Maven Configuration simplified
  • Provide production ready features like health check and externalized Configuration.

If you are using Maven then add following into pom.xml

    org.springframework.boot
    spring-boot-starter-parent
    1.0.1.RELEASE


    
        org.springframework.boot
        spring-boot-starter-web
    


If You are using Gradle then Add following dependencies into build.gradle
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.0.1.RELEASE")
}

Build Sample Spring Application using Spring Boot :

Home Controller
package com.anuj.controllers;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@RestController
public class HomeController {
    
    @RequestMapping("/home")
    public String handleHome() {
        return "Welcome to Spring Boot!";
    }
    
}

Here, @RestController is newly introduced in Spring 4 while previously using @Controller in spring 3.2. @RestController combines @Controller and @ResponseBody hence due to same, then we hit request from browser, it returns data rather than View.

Application
package com.anuj;
import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
    
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        
        System.out.println("Beans provided by Spring Boot:");
        
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }
}
Here, @EnableAutoConfiguration tells Spring to start adding beans based on classpath settings,other beans etc.
@ComponentScan tells Spring to look/scan components/services/config into package "com.anuj"
@Configuration marks class as Config class, Source of bean definations

build.gradle
buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-snapshot" }
        mavenLocal()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.1.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'SpringBoot'
    version =  '1.0'
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty")
    // end::jetty[]
    // tag::actuator[]
    compile("org.springframework.boot:spring-boot-starter-actuator")
    // end::actuator[]
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
 gradleVersion = '1.9'
}

Run Application from eclipse and hit http://localhost:8080/home into Browser

Output :










See, The beauty is that no need to start or deploy, everything is handled :)


Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

Sunday, March 30, 2014

Hibernate Named Queries Example

Hibernate provides @NamedQueries template using which you can associate unique query name to query.
Since Named Queries are global access , their name should be unique. You can use Named Queries in XML Mappings or using Annotation.

If You are using XML instead of annotation then you can add Named Queries as below in Hibernate hbm.xml file. It should be after Class tags.

       <![CDATA[from Customer cust where cust.customerType = :customerType]]>


Hibernate Names Queries Tutorial using Annotation:

Customer.java
package com.anuj.core.entities;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@NamedQueries({
 @NamedQuery(
   name="retrieveCustomerByType",
   query="from Customer cust where cust.customerType = :customerType"
 )
})

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
@Entity
@Table(name = "customer")
public class Customer implements Serializable{

 private String customerId;
 private String customerName;
 private String customerType;

 public Customer(){
  
 }
 
 public Customer(String customerName,String customerType){
  this.customerName = customerName;
  this.customerType = customerType;
 }
 
 @Id
 @GeneratedValue
 @Column(name="CustomerId",nullable=false,unique=true)
 public String getCustomerId() {
  return customerId;
 }

 public void setCustomerId(String customerId) {
  this.customerId = customerId;
 }

 @Column(name="CustomerName",nullable=false)
 public String getCustomerName() {
  return customerName;
 }

 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }

 @Column(name="CustomerType",nullable=false)
 public String getCustomerType() {
  return customerType;
 }

 public void setCustomerType(String customerType) {
  this.customerType = customerType;
 }

}


HibernateUtils :
package com.anuj.hibernate.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class HibernateUtils {

 private static SessionFactory sessionFactory = buildSessionFactory();
 
 private static SessionFactory buildSessionFactory(){
  try {
   return new AnnotationConfiguration().configure().buildSessionFactory();
  } catch (Throwable ex) {
   // TODO: handle exception
   System.err.println("Initialization of Session Factory Failed");
   throw new ExceptionInInitializerError(ex);
  }
 }
 
 public static SessionFactory getSessionFactory(){
  return sessionFactory;
 }
}


Hibername Configuration Xml :

 
  com.mysql.jdbc.Driver
  PASSWORD
  jdbc:mysql://localhost/DBNAME
  USERNAME
  org.hibernate.dialect.MySQLDialect
  false
  
 


Note that Transaction commit and rollback mentioned below will be useful when query will be insert/update/delete.

CustomerApp :
package com.anuj.main;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.anuj.core.entities.Customer;
import com.anuj.hibernate.utils.HibernateUtils;

/**
 * 
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class CustomerApp {

 private static Session session = null;
 
 public static void main(String[] args) {
  
  CustomerApp customerApp = new CustomerApp();
  customerApp.retrieveCustomer("Business");
 }
 
 /**
  * Retrieve Existing Customer
  * @param customerType
  */
 public void retrieveCustomer(String customerType){
  Transaction transaction = null;
  
  try {
   session = HibernateUtils.getSessionFactory().openSession();
   transaction = session.beginTransaction();
   
   Query query = session.getNamedQuery("retrieveCustomerByType");
   query.setParameter("customerType",customerType);
   
   List customer = query.list();
   Iterator itr = customer.iterator();
   
   while(itr.hasNext()){
    Customer cust = (Customer)itr.next();
    System.out.println("CustomerId : "+cust.getCustomerId());
    System.out.println("Customer Name : "+cust.getCustomerName());
    System.out.println("Customer Type : "+cust.getCustomerType());        
   }
   
   transaction.commit();
   
  } catch (HibernateException e) {
   transaction.rollback();
   e.printStackTrace();   
  }
  finally{
   if(session != null){
    session.close();
   }
  }
 } 
}


Output :
CustomerId : 1
Customer Name : Anuj
Customer Type : Business
CustomerId : 10
Customer Name : Zvika
Customer Type : Business
CustomerId : 11
Customer Name : David
Customer Type : Business
CustomerId : 6
Customer Name : Prithvi
Customer Type : Business

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

Sunday, February 02, 2014

What is Javaassist?

Javaassist stand for Java Programming Assistance. It's java library providing means to manipulate java bytecode. 
  • It enables java program to create new java classes at runtime and to modify classes before JVM loads it.
  • It's sub project of Jboss.

Now Question is "Why we require to manipulate java bytecode"?
  • You want to create subclasses at runtime which intercepts methods invocations. Meaning "Generating Proxies" which intercepts methods invocations.
  • Hibernate uses proxies to intercept methods invocation on entities to implement lazy loading. ie. fetching objects from database once it's accessed. 
  • Spring also uses proxies to implement it's AOP Support. 

We should know :
  • There are many third parties libaries like Javaassist, CGLib, ASM etc but I perfer Javaassist.
  • It seems that Hibernate 3.6 deprecated CGlib for some reasons. Hibernate 3.6 Deprecated List  shows that support for cglib as bytecode provider has been deprecated.
  • Difference between JDK Dynamic Proxy and Cglib/javaasssit is that JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which will also be implemented by the proxy class).CGLIB and javassist can create a proxy by subclassing. Here, proxy becomes a subclass of the target class. No need for interfaces.
    So Java Dynamic proxies can proxy: public class Aimplements iA where CGLIB can proxy: public class A

You can use following dependencies for  Javaassist in pom.xml:

  javassist
  javassist
  3.12.1.GA


For More Details Visit:

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

Tuesday, October 08, 2013

RSA Public Key Encryption and Private Key Decryption using Java

In Previous Post, I have discussed about What is Cryptography, What are Types of it and How we can encrypt and decrypt data using DES Algorithm in Java

Asymmetric Cryptography :
  • Here, We share Public Key with others so they can encrypt data using Public Key
  • We can only decrypt data using Private Key associated with Public Key. Private key is secret one and we don't share with anyone.
  • Most common used algorithm is RSA ALGORITHM. named after Rivest,Shamir and Adleman
Understanding and making working example for RSA encryption and decryption using public and private key takes lots lots of time for me. Believe me, It's complex stuff :)

Steps 1 :

Let's Break down tasks which helps us to encrypt and decrypt data using RSA Algorithm.
  1. Generate Public Key and Private Key
  2. Pull out parameters for Public Key and Private Key which help us in saving Keys to File
  3. Save Public Key and Private Key to file so public key can be distributed and private key can be kept secret.
  4. Encrypt Data using Public Key (use public key from stored file as above)
  5. Decrypt Data using Private Key (use private key from stored file as above)
Now,
Procedure to encryt and decrypt data using Cipher remains similar as we have done in DES Algorithm having some differences.

Steps 2 :  Encrypt Data

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey); //pubKey stored earlier
cipher.doFinal(dataToEncrypt);

Steps 3 : Decrypt Data
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey); //privKey stored earlier
byte[] descryptedData = cipher.doFinal(data);
System.out.println("Decrypted Data: " + new String(descryptedData));

If you would like to correct any issue then let me know your views and suggestions ! You can fork on my GitHub RSA Algorithm Repository

Java Program - RSA Public Key Encryption and Private Key Decryption :
package com.anuj.security.encryption;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;

/**
 * 
 * @author Anuj
 * Blog www.goldenpackagebyanuj.blogspot.com
 * RSA - Encrypt Data using Public Key
 * RSA - Descypt Data using Private Key
 */
public class RSAEncryptionDescription {

	private static final String PUBLIC_KEY_FILE = "Public.key";
	private static final String PRIVATE_KEY_FILE = "Private.key";
	
	public static void main(String[] args) throws IOException {

		try {
			System.out.println("-------GENRATE PUBLIC and PRIVATE KEY-------------");
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			keyPairGenerator.initialize(2048); //1024 used for normal securities
			KeyPair keyPair = keyPairGenerator.generateKeyPair();
			PublicKey publicKey = keyPair.getPublic();
			PrivateKey privateKey = keyPair.getPrivate();
			System.out.println("Public Key - " + publicKey);
			System.out.println("Private Key - " + privateKey);

			//Pullingout parameters which makes up Key
			System.out.println("\n------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------\n");
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
			RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
			System.out.println("PubKey Modulus : " + rsaPubKeySpec.getModulus());
			System.out.println("PubKey Exponent : " + rsaPubKeySpec.getPublicExponent());
			System.out.println("PrivKey Modulus : " + rsaPrivKeySpec.getModulus());
			System.out.println("PrivKey Exponent : " + rsaPrivKeySpec.getPrivateExponent());
			
			//Share public key with other so they can encrypt data and decrypt thoses using private key(Don't share with Other)
			System.out.println("\n--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------\n");
			RSAEncryptionDescription rsaObj = new RSAEncryptionDescription();
			rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
			rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());
			
			//Encrypt Data using Public Key
			byte[] encryptedData = rsaObj.encryptData("Anuj Patel - Classified Information !");
			
			//Descypt Data using Private Key
			rsaObj.decryptData(encryptedData);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * Save Files
	 * @param fileName
	 * @param mod
	 * @param exp
	 * @throws IOException
	 */
	private void saveKeys(String fileName,BigInteger mod,BigInteger exp) throws IOException{
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		
		try {
			System.out.println("Generating "+fileName + "...");
			fos = new FileOutputStream(fileName);
			oos = new ObjectOutputStream(new BufferedOutputStream(fos));
			
			oos.writeObject(mod);
			oos.writeObject(exp);			
			
			System.out.println(fileName + " generated successfully");
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(oos != null){
				oos.close();
				
				if(fos != null){
					fos.close();
				}
			}
		}		
	}
	
	/**
	 * Encrypt Data
	 * @param data
	 * @throws IOException
	 */
	private byte[] encryptData(String data) throws IOException {
		System.out.println("\n----------------ENCRYPTION STARTED------------");
		
		System.out.println("Data Before Encryption :" + data);
		byte[] dataToEncrypt = data.getBytes();
		byte[] encryptedData = null;
		try {
			PublicKey pubKey = readPublicKeyFromFile(PUBLIC_KEY_FILE);
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, pubKey);
			encryptedData = cipher.doFinal(dataToEncrypt);
			System.out.println("Encryted Data: " + encryptedData);
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
		
		System.out.println("----------------ENCRYPTION COMPLETED------------");		
		return encryptedData;
	}

	/**
	 * Encrypt Data
	 * @param data
	 * @throws IOException
	 */
	private void decryptData(byte[] data) throws IOException {
		System.out.println("\n----------------DECRYPTION STARTED------------");
		byte[] descryptedData = null;
		
		try {
			PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			descryptedData = cipher.doFinal(data);
			System.out.println("Decrypted Data: " + new String(descryptedData));
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
		
		System.out.println("----------------DECRYPTION COMPLETED------------");		
	}
	
	/**
	 * read Public Key From File
	 * @param fileName
	 * @return PublicKey
	 * @throws IOException
	 */
	public PublicKey readPublicKeyFromFile(String fileName) throws IOException{
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(new File(fileName));
			ois = new ObjectInputStream(fis);
			
			BigInteger modulus = (BigInteger) ois.readObject();
		    BigInteger exponent = (BigInteger) ois.readObject();
			
		    //Get Public Key
		    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
		    KeyFactory fact = KeyFactory.getInstance("RSA");
		    PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);
		    		    
		    return publicKey;
		    
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(ois != null){
				ois.close();
				if(fis != null){
					fis.close();
				}
			}
		}
		return null;
	}
	
	/**
	 * read Public Key From File
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException{
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(new File(fileName));
			ois = new ObjectInputStream(fis);
			
			BigInteger modulus = (BigInteger) ois.readObject();
		    BigInteger exponent = (BigInteger) ois.readObject();
			
		    //Get Private Key
		    RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
		    KeyFactory fact = KeyFactory.getInstance("RSA");
		    PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
		    		    
		    return privateKey;
		    
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			if(ois != null){
				ois.close();
				if(fis != null){
					fis.close();
				}
			}
		}
		return null;
	}
}

Output :
-------GENRATE PUBLIC and PRIVATE KEY-------------
Public Key - Sun RSA public key, 2048 bits
modulus: 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
public exponent: 65537
Private Key - Sun RSA private CRT key, 2048 bits
modulus: 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
public exponent: 65537
private exponent: 16818884445379350882395107598729290416080593813537574464745772338710078438111715082067390966047001054301440184313465125210240366320168055190663664601447788444717915899473729065013582226025416358245476925153555960357354022421635853002786514216572883778571785289225804534119366907605083654230390210185843516320290211843466509006336799394129511533245623813347345392660622411996306876517607316550963240563612473897071827862623073628753325937287805770949617787789425780112692109708570540461688127920714311987581602948589935567788167325085963891768759393262829208398129726072686050759571366259756340489722725543813760017473
prime p: 169306732673760790355930286583843583805308330869543277096562778910166303721930997866328982804816821819049730113874193091618529576910909406581209778870502424642394784256694354812411284399682213039455474743549204317489176290410742719482125745160659824679134175050540597373872559990275244248263694864065118289029
prime q: 127467990746102133899249581938138767929216080178107251583999590555445542238038489740168537885259598373126437993872087614678308989656079509601390372258522297126080029882334388941627788832329332096331303686348060808722035897823890209585664124526602293844519631122458634394071272791623445251919411933626571407281
prime exponent p: 119333901496849599293704132446823728072975688967404864411271868504773060528055275408385106164501021564724723181564468948550204262420398221130137530179366136709128313306521237344549101427812082746106271950635036621111395400810892143995572494105716759714409340496355063773002962656679194311000577640962509866565
prime exponent q: 87599841848325282034397392631823732681751728567706372035518219616807479391168584759867720185760822911137855574805147536162722715185622854768100782400042506374437622501342120383019881612208077700942453678524044597159341666571405330569429887003580278506237997865700511687666143632786492373791879306019609527633
crt coefficient: 7792255011181278160725143182305151172136668404207729019083906871364836764302818205034762517433549401848970490160009739693902133369434504868735056960398036976540900479169732396057070661243627622278554530394073212878117541087837917760429802642524231978699857141434244570696796138207734744378146597148568299985

------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------

PubKey Modulus : 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
PubKey Exponent : 65537
PrivKey Modulus : 21581189033711728218884545603483534136048436157764307737563263470622465209956484999186502236746398592183132361416574917491992616495836589976123829407441678145892864499340377518038083961762657109551322980788812471344883222074336738095812428432922899347944377728829986328978579520777569602492356009886434195381263189086322743017222283576658366049322746591279563891358961018804857343098186437284431498111857540148953385584647472608550518878892606670675504722021939011562806733746871866813023994221533891973381208433651324985362129897175578902143642720519685766703550582631650738544841113850242327026858745837631433020149
PrivKey Exponent : 16818884445379350882395107598729290416080593813537574464745772338710078438111715082067390966047001054301440184313465125210240366320168055190663664601447788444717915899473729065013582226025416358245476925153555960357354022421635853002786514216572883778571785289225804534119366907605083654230390210185843516320290211843466509006336799394129511533245623813347345392660622411996306876517607316550963240563612473897071827862623073628753325937287805770949617787789425780112692109708570540461688127920714311987581602948589935567788167325085963891768759393262829208398129726072686050759571366259756340489722725543813760017473

--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------

Generating Public.key...
Public.key generated successfully
Generating Private.key...
Private.key generated successfully

----------------ENCRYPTION STARTED------------
Data Before Encryption :Anuj Patel - Classified Information !
Encryted Data: [B@749436
----------------ENCRYPTION COMPLETED------------

----------------DECRYPTION STARTED------------
Decrypted Data: Anuj Patel - Classified Information !
----------------DECRYPTION COMPLETED------------

PLEASE NOTE that current program is for learning purpose only and one should not use it as part of production or project. Also one must check with Sun/Oracle/any other licenses if associated before using.

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

Friday, October 04, 2013

Calibration Data Missing in Netbeans 7.3

While I was doing profiling using netbeans 7.3,I encountered with Issue "Calibration Data Missing" when we are using profiling first time and after reading netbeans documentation found solutions which is mentioned as below.

To Solve, "Calibration Data Missing" Issue,

1. Go to Profile->Advance Commands->Run Profiler Calibration->and Select Java Platform-> Next-> Finish.
2. Click on Profile Main Project from Netbeans bar -> Select either from below

Monitor Application :


Analyze Memory :


Analyze performance :


Output After Profiling :


Tuesday, September 24, 2013

TreeMap Example in Java

TreeMap maintains ascending order and does not allows null as Key which differs in HashMap and LinkedHashMap.

About TreeMap:
  • It extends AbstractMap class and Implements NavigableMap Interface
  • It maintain ascending order
  • It does not allow null as Key
  • Contains unique elements Only

If You observe output of TreepMap example as below, Output is in Ascending order. If You try to put null as Key then NullPointerException throws as below.

Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.put(TreeMap.java:556)
at com.anuj.basic.TreeMapOperations.main(TreeMapOperations.java:23)

You may want to refer to :

Java TreeMap Example:
package com.anuj.basic;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 
 * @author Anuj
 * Maintain Accending Order
 * Does not allow null as Key
 */
public class TreeMapOperations {

 public static void main(String[] args) {
  TreeMap hashMap = new TreeMap();
  
  hashMap.put("Anuj","1");
  hashMap.put("Zvika","2");
  hashMap.put("David", "3");
  hashMap.put("David", "3");
  //hashMap.put(null,null); //Exception
  
  Set set = hashMap.entrySet();
  Iterator iterator = set.iterator();
  
  while(iterator.hasNext()){
   Map.Entry entry = (Map.Entry)iterator.next();
   System.out.println("Key:"+entry.getKey() + " Value:"+entry.getValue());
  }
 }

}

Output:
Key:Anuj Value:1
Key:David Value:3
Key:Zvika Value:2

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

LinkedHashMap Example in Java

LinkedHashMap is used for Key-Value concepts. when we require to store values based on Key then LinkedHashMap is for You !But It maintains insertion order while HashMap does not.

About LinkedHashMap:
  • It extends HashMap class and Implements Map Interface
  • It maintain insertion order
  • Allows null as Key and Values also
  • Contains unique elements Only
You may want to refer to :

If You observe output of LinkedHashMap example as below, Output is same in sequence we inserted elements because LinkedHashMap does maintain Insertion Order while HashMap does not.

Java LinkedHashMap Example :
package com.anuj.basic;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @author Anuj
 * Maintain Insertion Order
 * Allow Null
 */
public class LinkedHashMapOperations {

 public static void main(String[] args) {
  LinkedHashMap hashMap = new LinkedHashMap();
  
  hashMap.put("Anuj","1");
  hashMap.put("Zvika","2");
  hashMap.put("David", "3");
  hashMap.put("David", "3");
  hashMap.put(null,null);
  
  Set set = hashMap.entrySet();
  Iterator iterator = set.iterator();
  
  while(iterator.hasNext()){
   Map.Entry entry = (Map.Entry)iterator.next();
   System.out.println("Key:"+entry.getKey() + " Value:"+entry.getValue());
  }
 }

}


Output :
Key:Anuj Value:1
Key:Zvika Value:2
Key:David Value:3
Key:null Value:null

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

HashMap Example in Java

HashMap is used for Key-Value concepts. when  we require to store values based on Key then HashMap is for You !

About HashMap :
  • HashMap is class which extends AbstractMap and Implements Map Interface
  • HashMap does not maintain insertion order
  • Allows null as Key and Values also - No Exception is thrown
  • Contains unique elements Only

If You observe output of HashMap example as below,  Output is not same in sequence we inserted elements because HashMap does not maintain Insertion Order while LinkedHashMap does.

You may want to refer to :

Java HashMap Example :
package com.anuj.basic;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @author Anuj
 * Does not maintain Insertion Order
 * Allow Null
 */
public class HashMapOperations {

 public static void main(String[] args) {
  HashMap hashMap = new HashMap();
  
  hashMap.put("Anuj","1");
  hashMap.put("Zvika","2");
  hashMap.put("David", "3");
  hashMap.put("David", "3");
  hashMap.put(null,null);
  
  Set set = hashMap.entrySet();
  Iterator iterator = set.iterator();
  
  while(iterator.hasNext()){
   Map.Entry entry = (Map.Entry)iterator.next();
   System.out.println("Key:"+entry.getKey() + " Value:"+entry.getValue());
  }
 }

}


Output :
Key:null Value:null
Key:David Value:3
Key:Anuj Value:1
Key:Zvika Value:2

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

TreeSet Example in Java

About TreeSet:
  • TreeSet is class which extends AbstractSet and Implements NavigableSet Interface
  • It does maintain ascending order
  • It does not allow null
  • Contains unique elements Only, same as HashSet and LinkedHashSet

If You observe output of TreeSet example as below, Output is ascending order and NullPointer Exception will be thrown if You try to add null into TreetSet.

You may want to refer to :

Java TreeSet Example :
package com.anuj.basic;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * 
 * @author Anuj
 * allows unique elements only
 * maintain ascending order
 */
public class TreeSetOperations {

 public static void main(String[] args) {
  TreeSet treeSet = new TreeSet();
  
  treeSet.add("Anuj");
  treeSet.add("Zvika");
  treeSet.add("David");
  treeSet.add("David");
  //treeSet.add(null); //Exception
  
  Iterator iterator = treeSet.iterator();
  while(iterator.hasNext()){
   System.out.println(iterator.next());
  }
 }

}


Output :
Anuj
David
Zvika

//Exception when adding null
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.put(TreeMap.java:556)
at java.util.TreeSet.add(TreeSet.java:255)
at com.anuj.basic.TreeSetOperations.main(TreeSetOperations.java:21)

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

LinkedHashSet Example in Java

About LinkedHashSet :
  • LinkedHashSet is class which extends HashSet and Implements Set Interface
  • It maintain insertion order
  • Allows null
  • Contains unique elements Only

If You observe output of LinkedHashSet  example as below, Output is not same in sequence we inserted elements because LinkedHashSet does maintain Insertion Order while HashSet does not.

You may want to refer to :

Java LinkedHashset Example :
package com.anuj.basic;

import java.util.Iterator;
import java.util.LinkedHashSet;

/**
 * 
 * @author Anuj
 * maintain insertion order
 * store unique elements only
 */
public class LinkedHashSetOperations {

 public static void main(String[] args) {
  LinkedHashSet hashSet = new LinkedHashSet();
  
  hashSet.add("Anuj");
  hashSet.add("Zvika");
  hashSet.add("David");
  hashSet.add("David");
  hashSet.add(null);
  
  Iterator iterator = hashSet.iterator();
  while(iterator.hasNext()){
   System.out.println(iterator.next());
  }
 }

}

Output :
Anuj
Zvika
David
null

Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/