Friday, February 20, 2015

How to generate JavaDoc jar using Maven

The maven-javadoc plugin can be used to generate a javadoc jar file, It uses JDK's javadoc.exe tools to generate javadocs, pack in jar file and deploy along with your project.
To add support of javadoc in your Maven, Just add 'maven-javadoc' plugin into your pom.xml file and specify goal as 'jar'.
Example :
<!-- Generates JAVADOC -->
Run it as mvn:install or mvn:package, It will generate javadoc and package it as a jar file.



Thursday, February 19, 2015

Introduction to Lambda Expression with Examples

Java 8 comes up with one great features called Lambda Expressions. It's first step to the functional programming. With Lambda expression we can treat functionality as method arguments i.e. you can pass a method as argument to another method.
Previously we use to write anonymous class if we wanted to pass some method as argument to another method but with lambda expression, we can pass a plain method as argument. Lambda expressions is a anonymous function i.e. It has arguments, a body and return type.

Syntax of Lambda Expression :
(Argument(s)) → {Body}
Eg :
(int x, int y, int z) - > {return x+y+z};
(String msg) - > {System.out.println(msg);}
() - > { return 100;}

Structure of Lambda Expression :

  • It can have zero, one or more number of parameters.
  • For empty set of parameters, Empty parentheses are used. e.g () -> 100
  • Type of the passed parameter can be explicitly declared or can be taken from context. e.g. (int x) is same as (x).
  • One important difference between anonymous inner class and lambda expression is, if we use ‘this’ it resolves to anonymous class but in the case of lambda expression, it resolves to the enclosing class where lambda is written.
Functional Interfaces :
A functional interface is an interface having one abstract method declared in it. It is similar to Marker interface just Marker interface has no methods or field declaration in it. java.lang.Runnable is one example of functional interface as It has only one method void run().

@FunctionalInterface :
It’s a new annotation which  indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. As functional Interfaces  can have only one abstract method, If you declare more than one then it will throws compile time error.

Eg :  
Valid Functional interaface

public interface IFunctional1 {
public void display();
Invalid Functional interaface

public interface IFunctional {
public void display();
public void printResult();

It will throw compile time error as @functionalInterface contains two abstract methods.

Examples of Lambda Expression :

package in.techblog.waheed.lambda;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

* This class demostrate few examples of lambda expression
* @author abdul
public class LambdaExample {

* @param args
public static void main(String[] args) {

// ****************Example1********************************//

// Old way of calling..
new Thread(new Runnable() {
public void run() {
System.out.println("Old way of calling..Anonymous.");

// New way of calling....
new Thread(
() -> System.out
.println("New way of calling..Lambda Expression"))

// ****************************Example2******************//

List<Integer> list = Arrays.asList(101, 102, 103, 104, 105, 106, 107);

list.forEach(n -> System.out.print(" " + n));

// Double colon operator, Will cover in next tutorial..

// *****************************Example3*****************//

// Print Even number
System.out.println("\n\nEven numbers:");
evaluate(list, (n) -> n % 2 == 0);

* Evaluate the list on the basis of Predicate function. Check
* .com/javase/8/docs/api/java/util/function/Predicate.html
* @param list
*            list of integer array that need to be evaluated
* @param predicate
*            boolean-valued function
public static void evaluate(List<Integer> list, Predicate<Integer> predicate) {
for (Integer l : list) {
if (predicate.test(l)) {
System.out.println(l + " ");

Please feel free to comment, Suggestion/Feedback are most welcome :)


Thursday, February 12, 2015

How to download and save image from URL

The 'javax.imageio.ImageIO' is a handy class which provides lots of utility methods related to images processing in Java. Using this class we can read and write images into disk.

In below example, We will see how to use 'javax.imageio.ImageIO' to read an image from URL and save it into different formats.

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

* This class will download the image from the specified URL and download it in
* different format.
* @author
public class ImageDownloader {

* @param args
public static void main(String[] args) {

String imageUrl = "";

try {
System.out.println("Downloading Image...");
URL url = new URL(imageUrl);
BufferedImage image =;

// Save it in PNG format.
ImageIO.write(image, "png", new File("image.png"));

// Save it in JPEG format
ImageIO.write(image, "jpg", new File("image.jpg"));

// Save it in BMP format
ImageIO.write(image, "bmp", new File("image.bmp"));

// Save it in GIF format
ImageIO.write(image, "gif", new File("image.gif"));
System.out.println("Downloaded all the images");
} catch (Exception e) {
System.out.println("Error while downloading Image "
+ e.getMessage());


References :

Sunday, February 8, 2015

What is Semaphore with example ?

What is Semaphore?

Semaphore is used to control access to common resource for completing multiple resources. It guards a critical section against entry by more than N threads at a time. The java.util.concurrent.Semaphore  class was first introduced by Java in V 1.5.

It has two main methods():
·         acquire()
·         release()

Semaphore is initialized with a given number of "permits” i.e. counter which keeps track of the number of resources available. When a request comes to resources, Semaphore checks the counter and if it is less than total count then it grant access to resources and subsequently reduces the counter. Similarly while releasing a resources, it increments the count.

Thus, at most N threads can access the acquire method without any release() calls where N is number of permits the semaphore was initialized with.

If the permits is in ON|OFF mode i.e. just one count then it is called binary semaphore.


Suppose there are 5 threads who wants to access particular resources which is guard by Semaphore having permits is 2, i.e. three threads has to wait for a semaphore to be released.

package in.waheed.semaphore.example;
import java.util.concurrent.Semaphore;

 * @author abdul waheed
public class SemaphoreExample {

             * @param args
            public static void main(String args[]) {

                        // Semaphore having counter as 2
                        Semaphore semaphore = new Semaphore(2);

                        // Creating 5 threads
                        SemaphoreTest test1 = new SemaphoreTest(semaphore);
                        SemaphoreTest test2 = new SemaphoreTest(semaphore);
                        SemaphoreTest test3 = new SemaphoreTest(semaphore);
                        SemaphoreTest test4 = new SemaphoreTest(semaphore);
                        SemaphoreTest test5 = new SemaphoreTest(semaphore);

                        // Starting all the threds

class SemaphoreTest extends Thread {
            Semaphore semaphore;
            SemaphoreTest(Semaphore semaphore) {
                        this.semaphore = semaphore;

            public void run() {
                        try {
                                    System.out.println("Acquired : " + this.getName());
                        /*         System.out.println("Available permits : "
                                                            + semaphore.availablePermits());*/
                                    try {
                                    } catch (Exception e) {
                        } catch (InterruptedException ie) {
                        } finally {
                                    System.out.println("Released : " + this.getName());


Acquired: Thread-1
Acquired: Thread-0
Released: Thread-1
Acquired: Thread-4
Acquired: Thread-2
Released: Thread-0
Acquired: Thread-3
Released: Thread-4
Released: Thread-2
Released: Thread-3

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...