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

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,

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

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

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

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

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

HashSet Example in Java

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

Thread Pooling using Executors and ThreadPoolExecutor in Java

Thread Pool manages pool of threads waiting for job. They are called worker Threads.Initially threads are waiting in pool for job and once they will get job to process, it will be process that job and move back to thread pool and wait for another job.

As mentioned in below example, I have create fixed size of Thread Pool with 5 worker threads. Now I will submit 10 jobs which should be processed by worker threads in Thread Pool. But Since I have only 5 Threads available in Thread pool, how it will work?

Thread Interrupt Example in Java

Thread class provides method interrupt() using which one can Interrupt thread.

Before moving ahead, It's important to understand following scenarios :
  • If Thread is blocked in invocation of method like sleep(),join() or Object.wait then It's interrupted status will be cleared and InterruptedException will be thrown.
  • If Thread is blocked in IO Operation upon java.nio.channels.InterruptibleChannel then channel will be closed and interrupted status will be set. Here, Thread will receive ClosedByInterruptException

Thread Naming in Java

Thread class provides following methods using which You can set name to Thread and retrieve thread name.
  • public final void setName(String name) - Changes name of Thread equals to argument
  • public final String getName() - Return Thread name

JVM Shutdown Hook - addShutdownHook in Java

JVM Provides hook to register thread with shutdown init sequence. Meaning whenever shutdown will happen, this thread will run.You may require this to cleanup resources in case of unexpected JVM Shutdown.

Runtime.class provides method addShutdownHook whereYou can provide Thread instance.
public void addShutdownHook(Thread hook)

Thread Join Example in Java

Thread Class provides join() method Basically It will wait for Thread to die.Consider following scenario where we haven't used join and observe the output.

In Scenarion1, Output is not sequential and one Thread goes to sleep and Thread scheduler picks up another thread and start executing.

Scenario1 : Situation where there is no Join :

package com.anuj.threading;

/**
 * Thread Join Example
 * @author Anuj
 *
 */
class ThreadJoinExample extends Thread{

 @Override
 public void run() {
  for(int i=1;i<=5;i++){
   System.out.println(Thread.currentThread().getName() + " - "+i);
   
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ThreadJoinExample t1 = new ThreadJoinExample();
  ThreadJoinExample t2 = new ThreadJoinExample();
  t1.setName("Thread1");
  t2.setName("Thread2");
  
  t1.start();
  System.out.println(t1.getName() + " : " + t1.isAlive());
  
  /*try{
   t1.join();
   System.out.println(t1.getName() + " : " + t1.isAlive());
  }
  catch(Exception e){
   e.printStackTrace();
  }*/
    
  System.out.println(t2.getName() + " : " + t2.isAlive());
  t2.start();
 }
}
Output :Thread1 : true
Thread1 - 1
Thread1 - 2
Thread1 - 3
Thread1 - 4
Thread1 - 5
Thread1 : false
Thread2 : false
Thread2 - 1
Thread2 - 2
Thread2 - 3
Thread2 - 4
Thread2 - 5

Pausing Execution with Sleep - Thread.sleep in Java

If You want to suspend executing of Thread for particular period of time then Thread.sleep is for You.Once You suspend particular thread, Thread scheduler pickups other threads which are waiting for execution.

How to Set Priority of Thread - Thread Priority Example in Java

Each Thread has priority. Thread Scheduler schedules thread based on thread priority. You can set priority of thread. It's important to understand Preemptive Scheduling and Time Slicing before moving ahead.

Priorities are integer values from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY).
Default Priority is Thread.NORM_PRIORITY (Value 5)

What is Difference between Preemptive Scheduling and Time Slicing in Java

Preemptive Scheduling :
In Preemptive Scheduling , Highest Priority thread runs first until it enters into waiting states or dead states or higher priority tasks comes into picture.

Time Slicing:
In Time Slicing, Task executes for specific predefined slice of time and then enters into pool of read tasks. Then Scheduler decides which tasks should be executed next.

Data Encryption Decryption using DES Algorithm in Java

Encryption is process of converting plan text to cypher text using encryption algorithm and encryption Key.
Decryption is reverse process of encryption which recover original data from encrypted data using decryption key.

Here, One should understood Cryptography concept before moving into encryption and description world. It's basically making communication private - Protect Sensitive Information. Refer to wiki for more details.

Types of Cryptography :
  1. Symmetric
  2. ASymmetric

Common Aware Interfaces used in Spring

If You are developing application using Spring then sometime it's important that your beans aware about Spring IOC container resources. Here, Spring Aware comes into picture.

To use Aware Interfaces, You bean class should implement aware interfaces. and That's way they will be aware about container resources. I like to use these interfaces :)

Common Aware Interfaces used in Spring 3.2:
  1. BeanNameAware
  2. ApplicationContextAware
  3. BeanFactoryAware
  4. MessageSourceAware
  5. ApplicationEventPublisherAware
  6. ResourceLoaderAware

Spring @PostConstruct and @PreDestroy annotation Example

If You want to perform specific action or handling upon bean Initialization and Bean destruction then Implementing InitializingBean and Disposable Bean or init-method and destroy-method is for You !!

But there is another annotation approach available. You need to annotate methods with @PostConstruct and @PreDestroy annotation in you bean class and define in Spring Bean configuration file.

You can either add CommonAnnotationBeanPostProcessor (org.springframework.context.annotation.CommonAnnotationBeanPostProcessor) class in Spring bean xml or use context:annotation-config in spring bean configuration file

Init-method and Destroy-method Spring Bean example

If You want to perform specific action or handling upon bean Initialization and Bean destruction then Implementing InitializingBean and Disposable Bean is for You !!

But there is another approach also available if you don't want to implement those interfaces..You can add init-method and destroy-method into your spring bean configuration file at bean level.

Difference between context:component-scan and context:annotation-config in Spring

<context:component-scan/> scan packages and classes within given base packages then find and register beans into ApplicationContext.It does all things that <context:annotation-config/> is supposed to do.
So if you have used annotation for example, @Autowired in your code and <context:component-scan/> in xml then You do not require to use <context:annotation-config/>

What is ApplicationContext and BeanFactory in Spring?

ApplicationContext(org.springframework.context.ApplicationContext) is interface provided by Spring  and it's used for getting Configuration information about your application.Spring has many classes which implements this interface.

What are common Implementation of ApplicationContext ? - They are
  1. ClassPathXmlApplicationContext
  2. FileSystemXmlApplicationContext
  3. XmlWebApplicationContext

Apache Tika - Extract MetaData and Stractured Text Content Extraction

Apache Tika is used for detecting and extracting metadata and structured text content from different documents using existing parser libraries.

Apache Tika provides interface called Parser (org.apache.tika.parser) which provides api called parse whose job is to parses a document stream into a sequence of xhtml sax events.

Tika supports different formats like text,audio,image,video,word document,open document,pdf,xml,html etc. Please refer to Apache Tika Supported Documents Format for more details. You may want have a look at Apache Tika 1.4 API documentation

    Spring InitializingBean and DisposableBean Example

    In Spring, If You want to perform specific actions on Bean Initialization or Destruction then Spring abstract Interface InitializingBean and DisposableBean are for You !

    InitializingBean is abstract interface which has abstract method called afterPropertiesSet. If You have any bean which implements this interface then after all bean properties are set, this afterPropertiesSet method will be called.

    DisposableBean is abstract Interface which has abstract method called destroy. If You have any bean which implements this interface then after bean is released by Spring container, this method will be called.

    Java Program to Find Fibonacci Series of Given Number

    Fibonacci? Consider requirement that I want to display Fibonacci series of number 10.If You remember maths in school, we used to find Fibonacci number using below :

    Fibonacci is sum of previous two Fibonacci numbers fn= fn-1+ fn-2

    Fibonacci of 10 will be 0 1 1 2 3 5 8 13 21 34  ex. 0 1 (0+1) (1st+2nd)...

    How to Calculate Factorial of Number using Java with Recursion

    Factorial? let me show you how we calculate factorial of given number. Consider requirement that I want to find factorial of number 5.

    If you remembered Maths, in School we used to find factorial using below match function !
    n! = n * (n-1)!

    Ex. 5! = 5*(5-1)! = 5*4!
          4! = 4 *(4-1)! = 4*3!
          3! = 3*(3-1)! = 3*2!
          2!= 2*(2-1)! = 2*1!
          1! = 1*(1-0)! =  1

    How to Track Session Attribute - HttpSessionAttributeListener Example

    If You want to track session Attribute like whether there is new session attribute added,removed or replaced during application lifecycle then HttpSessionAttributeListener is for You !

    HttpSessionAttributeListener is abstract interface which comes as part of servlet-api.jar which has abstract method such as attributeAdded,attributeRemoved,attributeReplaced.

    How it works : 
    • When new session attribute is added using set then attributeAdded will be called.
    HttpSession session = request.getSession();
    session.setAttribute("sessionName","LoginIn");
    
    • If you try to set attribute value to some different value which is already present then attributeReplaced will be called. ex. session.setAttribute("sessionName","LoggedIn");

    How to Calculate Total Active Session - HttpSessionListener Example

    If you have web application and you want to count total number of active session then HttpSessionListener is for you !

    HttpSessionListener is abstract interface provided as part of servlet-api.jar which has abstract method such as sessionCreated and sessionDestroyed which get executed every time when we create new session using httpSession or invalidate session.

    By default one session is created. so when you use HttpSession session = request.getSession(); in HttpServlet then it will give you that session. You can invalidate session using session.invalidate();

    Listener - ServletContextListener Example

    If You want to do something before application starts, then ServletContextListener is for you.

    ServletContextListener is abstract interface provided as part of servler-api.jar which provides contextDestroyed and contextInitialized abstract method. One can create class which implements ServletContextListener and write implementation logic for example, logic that does something before web application starts.

    How to Download File using Servlet

    Consider that I have file containing project information available into server and I want to download that file. Using webservices you can also achieve same but Here, I am going to discuss "Download File using Servlet"

    Steps to be Performed to Download File using Servlet :
    1. Create Servlet File which will download file available in server
    2. Add Servlet entry into Web.xml or annotate with @WebServlet 

    Retrieve Key-Value Pairs of the Properties files in Java

    Java  Properties class represents a persistent set of properties.

    Properties class extends HashTable meaning Properties inherits from Hashtable, So put and putAll methods can be applied to a Properties object.

    Some of useful methods are metioned below which object of Properties class can call.

    Properties pro = new Properties();

    1. keySet() - Retrieve Set of Keys 
    2. keys() - Retrieves all keys of the properties files. Which stored in the Enumeration objects.

    javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found

    I was working on writing JSR 303 Custom Validation to validate Email Address and encountered with following exception.

    javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
        at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:271)
        at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110)
        at com.anuj.core.test.ValidEmailTest.setUp(ValidEmailTest.java:21)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)

    How to write Custom JSR 303 Validation using ConstraintValidator

    What is JSR 303?
    JSR 303 is Java Bean Validation framework which comes as part of J2EE 6. So in order to use classes specified by them, for Validation you need to include javaee-api jar Ex. javaee-api-7.0.jar

    Requirement :
    Consider that I want to write my own custom validation to validate email. Ya, there is already email validator provided by Hibernate as part of Hibernate 4.2 but this is just for eample. and you can create own validation to validate FileName or any other validation you like.

    Steps to create Custom Validation to validate Email :
    1. Create Interface - @interface
    2. Create Custom Validation Implementation class using ConstraintValidator
    3. Apply Custom Annotation to Bean(Pojo) but it can be any where on Constructor,Method,parameter,Field etc based on how you have added ElementType in @Target

    EJB 3.1 SessionBean Example with Remote Interface using WebLogic 12.1.1

    EJB stands for Enterprise Java Bean. If you are not fimilar with EJB, Please read below in order to move ahead with "Creating EJB 3.1 Application using WebLogic 12.1.1".
    1. What is EJB and Why Comes into Picture
    2. EJB Container and it's Feature
    EJB application requires to be run in Application Server like WebLogic, JBoss. As part of current EJB Demo, WebLogic Server 12.1.1 and  JDK 1.7 Update 03 is used.

    Suppose, I want to write Stateless Session Bean(Can be local or remote), in My case Remote Component which will provide customer Information upon request from Client.

    How to write JAX-WS WebServices and WebService Client in Java

    Today, I am going to explain about how to write JAX-WS Webservice providers(Endpoints) and how to create webservice client which uses published webservices.

    JAX-WS is Java Api for XML webservices. APIs for creating webservices in XML formats.

    Let's consider that I want to write JAX-WS Service which will publish customer Information and client will use this service and display requested customer Information.

    You require to develop following parts :
    1. Create WebService Endpoint Interfaces
    2. Create WebService Endpoint Implementation
    3. Endpoint Publisher
    4. Analyze Created wsdl file
    5. Create WebService Client which will use exposed services.

    Generate BeanName using Spring AnnotationBeanNameGenerator

    Developing application with Spring, sometimes require to retrieve bean name which you have either specified in @Bean annotation or bean id which is internally generated by Spring.

    Spring by Default generate Bean id same as Bean class name but with first letter in small caps.
    Using Spring AnnotationBeanNameGenerator class, one can achieve this using generateBeanName method.

    Ex. private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
    String beanName = this.beanNameGenerator.generateBeanName(definition, registry); 

    Here,
    (1) definition is Spring BeanDefinition. BeanDefinition describes bean instance which has property values, constructor argument values any many more.

    In order to retrieve BeanDefinition for bean, method resolveScopeMetadata(BeanDefinition definition) of Spring interface like ScopeMetadatResolver or AnnotationScopeMetadataResolver can be used.


    Spring provide interface called AnnotatedBeanDefinition which provide awesome bean information like getMetadata() for those beans which has annotation defined.

    (2) registry is of Spring BeanDefinitionRegistry.(Ex. BeanDefinitionRegistry registry)  it's basically interface for registries which holds bean Definition. It's only interface which encapsulate registries of bean Definition

    After struggling hours , I finally able to make things working. Hope you find this information useful

    Prefix mvc for element mvc:annotation-driven is not bound

    If you are planning to use <mvc:annotation-driven>  into your Spring MVC application, chances that you may be facing issue for "Prefix mvc for element mvc:annotation-driven is notbound " erorr. Root cause is that your bean definition XML doesn't have names-spaces mentioned below.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

    While developing SpringMVC application in Eclipse, All require dependencies has been added to maven dependencies in pom.xml. Yet running application encountered with Exception java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

    Solution : 
    Even though you have added all required dependencies into pom.xml for your J2EE WebProject you are require to reference maven dependencies to "Web Deployment Assembly"

    Right Click J2EE Web Project->Deployment Assembly->Add->Select Maven Dependencies.

    java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

    I was working on developing Spring MVC Application with Maven+Tomcat with Spring 3.2. While running application, encountered with Exception : java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

    Solution :
    I found that tomcat container doesn't contain jatl library and hence require to explicitly add it to maven dependencies in Pom.xml

    Maven Dependencies
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    After adding maven dependencies as mentioned above, issue is resolved. Hope it might help you.

    Unable to view Convert to Maven in Eclipse Juno IDE for J2EE

    While I was working on issue of converting my Java Project to Maven, I found that there is no options like configure-> "convert to Maven Project" on my current working project which is being discussed in existing forums.

    Solution :
    You need to add M2E(Maven Integration for Eclipse Plugin) to Eclipse Juno J2EE IDE from location http://download.eclipse.org/technology/m2e/releases

    Apache Solr and SolrJ Maven Dependancies

    While I was developing Solr application using Solrj, there was confusion (which is always :) ) of which maven dependencies to be included in Pom.xml. Hence thought to share here.
    Please don't miss to add M2_REPO classpath variable pointing to repository directory so you can easily import required library into your Java Project.

    Maven Dependencies for Developing application with Solr (version 4.1) are followed as :

    1. Solrj Dependencies
    <dependency>
               <artifactId>solr-solrj</artifactId>
               <groupId>org.apache.solr</groupId>
               <version>4.1.0</version>
               <type>jar</type>
        </dependency>

    2. Solr-core Dependencies
    <dependency>
               <artifactId>solr-core</artifactId>
               <groupId>org.apache.solr</groupId>
               <version>4.1.0</version>
               <type>jar</type>
        </dependency>
        <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>servlet-api</artifactId>
               <version>2.5</version>
        </dependency>

    Spring org.springframework.beans.BeanInstantiationException - Solved

    I was working on JAX-RS and encountered with BeanInstantiationException.

    Exception :
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.anuj.services.CountryServiceImpl]: Constructor threw exception; nested exception is com.anuj.common.errors.InternalServerException: Internal Server Error Occured
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:983)
        ... 41 more
    Caused by: com.anuj.common.errors.InternalServerException: Internal Server Error Occured
        at com.anuj.services.CountryServiceImpl.initialize(CountryServiceImpl.java:160)
        at com.anuj.services.CountryServiceImpl.(CountryServiceImpl.java:44)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
        ... 43 more