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

Total Pageviews

Followers


Labels

Popular Posts

free counters