Sunday, August 3, 2014
In an earlier post here , 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.
     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 X509EncodedKeySpec object. Then use the KeyFactory to reconstruct the public key. Next we have to create the Signature object with the same algorithm as earlier and initialize with the public key.
Sunday, July 27, 2014
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).
What is 0/1 Knapsack problem ?
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 :
   1. You can either choose an item completely or reject it. (0 or 1)
   2. The total weight of bag must not exceed its maximum capacity W. i.e. (Sum of w[i]) <= W
   3.  The total value or profit of items chosen must be maximum. i.e. Sum of p[i] is maximum
where 0 <  i <=n.
How to solve 0/1 Knapsack problem in Java ?
Step1: Structure: Characterize the structure of an optimal solution.
    – 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.
Tuesday, July 22, 2014

Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we 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 -
Saturday, July 12, 2014
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
Saturday, July 5, 2014
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.
    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.
Sunday, June 29, 2014
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.

How to sign data with digital signature ?
1. Form the message to be signed.
2. Generate a public-private key pair
3. Calculate hash of the message and encrypt it with sender's private key
4. Send the dugutally signed message with the signature along with the public key.

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.
Sunday, June 15, 2014
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.
Below are the steps you must follow to implement watch service
   1. Get the path of the folder - The first step is to get the Path object associated with the folder. This is done using Paths.get() method.
   2. Get file system of the path - Next step is to get the FileSystem object associated with the Path object. This is done using getFileSystem() method.
   3. Get watch service - Next you have to get WatchService from FileSystem object using newWatchService() method.
Monday, June 9, 2014
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.
    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.
Sunday, June 8, 2014
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.
     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 java.lang.Comparable interface. The comments are also added to the code in Javadoc style
Thursday, June 5, 2014
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.
In our first annotation we will just start with an empty annotation specifying only @target and @Retention.
import java.lang.annotation.*;

@Target(value={ElementType.FIELD})
@Retention(value=RetentionPolicy.RUNTIME)
public @interface Author {
}
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
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
}
In our next example you will see how to mention the target type when it is more than one say FIELD and METHOD.
import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
}
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.
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
 String name();
}

class MyClass {
 @Author(name="Nirupam")
 int i = 10;
}
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 default . 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.
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
 String name() default "Nirupam";
}

class MyClass {
 @Author
 int i = 10;
}
In our next and last part we will deal with creating and using advanced annotation. Till then keep coding and keep reading our articles.
Tuesday, May 6, 2014
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

  • First push a sentinel element # to denote end of stack
  • Scan each symbol of input infix expression
  • If symbol is operator then check precedence with operator on stack top and take necessary action
  • If left parenthesis then push it, and if right parenthesis then pop continously from stack till a left parenthesis is found
  • If all symbols are scanned then pop all elements from stack and ad to postfix till # found.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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));
 }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
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*+

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Sunday, May 4, 2014
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.

  • First read an image from file or URL using ImageIO
  • Now create a BufferedImage with specified width, height and image type
  • Obtain a Graphics2D object from the destination object create in earlier step
  • Draw the original image using the Graphics object
  • Dispose the Graphics object
  • Return or save the final image
Here in our example we will have a class with 3 methods.
Original image (930 x 520)  to be resized or scaled

  • 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
    Image resized (100 x 100) without hints
  • 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;
  • 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
    Image resized (100 x 100) with hints
  • 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);
  • 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
    Image scaled = 0.3 (279 x 156)
  • AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
    g2d.drawRenderedImage(src, at);
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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"));
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Saturday, April 26, 2014
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.

Annotations used by compiler and declared in java.lang package
  • @Deprecated : 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.
  • class DeprecationDemo{
       /**
       * @deprecated
       * defines how to use deprecated annotation
       */
       @Deprecated
       public void deprecatedMethod(){}
    }
  • @Override : 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 here
  • @SupressWarnings : 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.
  • @SupressWarnings("serial")
    class SupressWarningsDemo extends javax.swing.JPanel{
       
    }
    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.
  • @SafeVarargs : 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.
  • @FunctionalInterface : 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.
There are certain other annotations called meta-annotations that apply to other annotations. They are declared in java.lang.annotation package
  • @Retention : It is used to denote how the annotation should be stored. There are 3 ways
    • RetentionPolicy.SOURCE : Retained at source level and ignored by compiler
    • RetentionPolicy.CLASS : Retained by compiler at compile-time but ignored by JVM
    • RetentionPolicy.RUNTIME : Used by JVM during run-time.
  • @Documented : 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
  • @Target : It is used to indicate which kind of Java elements it can be applied.
    • ElementType.ANNOTATION : Can be applied to annotation type
    • ElementType.CONSTRUCTOR : Can be applied to constructors
    • ElementType.FIELD : Can be applied to a field
    • ElementType.LOCAL_VARIABLE : Can be applied to a local variable
    • ElementType.METHOD : Can be applied to a method
    • ElementType.PACKAGE : Can be applied to a package declaration
    • ElementType.PARAMETER : Can be applied to a parameter of a method
    • ElementType.TYPE : Can be applied to any element of a class.
  • @Inherited : 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.
  • @Repeatable : 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.
Tuesday, April 22, 2014
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 :
  • Max/Min value - A progress bar always has a maximum and a minimum value
  • Current value - This value is used to denote the current progress
The class definition of JProgressBar is
public class JProgressBar
extends JComponent
implements SwingConstants, Accessible
To know more about the JProgressBar class click here
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.

The output of our demo code

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.

  • You should always carry out the task in a seperate thread. In our case generating the integer value.
  • 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.
Also here in our code instead of creating an anonymous inner class of ActionListener and Runnable we have used Lambda Expression.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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) {}
      }
     }
    }   
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Friday, April 18, 2014
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.
What is an annotation ?
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.

Uses of annotation

  • Information used by compiler : They can be used which carries special meaning to the compiler and helps in detecting any compile time errors.
  • Deployment-time processing : They can be used by softwares, servers to generate codes, files and also to deploy codes as in case of servlets.
  • Runtime processing : They can be used to carry information during runtime.
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
  • Class intance types
  • Type-Cast
  • implements clause
  • throes exception declaration
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
  • 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 .
  • 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.
In our next tutorial we will deal with pre-defined annotations in java.
Thursday, April 17, 2014
Today I am going to deal with the new feature of Java 8 - Lambda Expression. 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.
Why Lambda Expressions ?
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.


What is the syntax of Lambda Expression ?
Suppose you have a functional interfacelike below which takes a string argument and returns void.
interface IDemo{
   public void action(String s);
}
Now your lambda expression syntax in place of anonymous class is
(a) -> System.out.println(s)
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.

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.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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);
}
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.
printSongs(tracks, 
               new CheckSong() {
   @Override
   public boolean test(Song song) {
    return song.getYear() > 2010;
   }
});
But now with lambda expression the whole thing looks much simpler as shown below
printSongs(tracks, mt -> mt.year > 2010);
The main method of the Song class where both approaches are shown
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); 
}

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
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.
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Saturday, April 12, 2014
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 Smalltalk and Eiffel. 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.

There are seven qualities to be satisfied for a programming language to be pure Object Oriented.

  • Encapsulation/Data Hiding
  • Inheritance
  • Polymorphism
  • Abstraction
  • All predefined types are objects
  • All operations are performed by sending messages to objects
  • All user defined types are objects.
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.

Why Java is not Pure Object Oriented language? 
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.
  • Primitive data types are either stored directly in fields or on the stack rather than on the heap.
  • "Primitive types" in Smalltalk are actually "Primitive Classes" and in Smalltalk all "procedures" or "functions" are really messages
Though you can make your program pure object oriented by using Autoboxing, but Java compiler supports primitive data types, so Java cannot be Pure OO unless it makes everything objects.
Friday, April 4, 2014
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 Strong but you will have to increase it to Unlimited.

  • Download the right version of Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. For JDK7 download it from here
  • Extract the archive and copy the two JAR files (local_policy.jar and US_export_policy.jar) and paste it in the directory JAVA_HOME/jre/lib/security for example C:/Program Files/Java/jdk1.7.0/jre/lib/security
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.
    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.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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");
 }

}
NOTE : 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.
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire

Monday, March 24, 2014
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.
     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

  • The class whose object you want to save must  implement the interface java.io.Serializable. 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.
  • Wgile writing an object you need a stram to write it. The class java.io.ObjectOutputStream will help to write objects while java.io.ObjectInputStream will help to read objects.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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
 }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Before saving in file >>
Student [roll=11004, name=Aditya Goyel]

After reading from file >>
Student [roll=11004, name=Aditya Goyel]

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Sunday, March 23, 2014
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.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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);
    }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Value of java.util.Date : Sun Mar 23 11:35:46 IST 2014
Converted value of java.sql.Date : 2014-03-23
Converted value of java.util.Date : Sun Mar 23 11:35:46 IST 2014


Hope this helps. Happy coding :)
Friday, March 14, 2014
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

  • How to insert new records/rows in database tables (INSERT operation)
  • How to find a record/row in database tables (SELECT operation)
  • How to update records/rows in tables (UPDATE operation)
  • How to delete a record/row from tables (DELETE operation)
Different JDBC operations
SQL is written for carrying out the operations and it is either passed to a Statement or a PreparedStatement. 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.

First create a database table Student as follows :
  CREATE TABLE student(id number primary key,name varchar(30));

-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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();
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Thursday, March 13, 2014
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.
JDBC Architecture

     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 Wikipedia JDBC driver . 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
C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar
Place that jar file in your classpath. Below is the code which will return the Connection object to the database
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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);
 }
}


This is the fisrt and foremost step of using JDBC. Happy coding :)
Sunday, February 16, 2014
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 :

  1. Create the Class class instance of the specified class using Class.forName() or <Class-Name>.class
  2. Create the Constructor instance from the Class instance using getDeclaredConstructor()
  3. Call the setAccessible() on constructor object and set to true. This is the most important step as failing it wont allow you to access the private constructor.
  4. Call newInstance() method on the constructor object which will return a reference to Object class. That's it. Dow what you wish with this reference.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
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
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------

Total Pageviews

Subscribe via Email

Followers


Popular Posts

Blog Archive

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.