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 java.io.File;
import java.net.URL;

import javax.imageio.ImageIO;

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

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

String imageUrl = "http://img.gettyimageslatam.com/public/userfiles/redesign/images/landing/home/img_entry_002.jpg";

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

// 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());
e.printStackTrace();
}

}
}

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.

Example:

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
                        test1.start();
                        test2.start();
                        test3.start();
                        test4.start();
                        test5.start();
            }
}

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

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

Output:

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

Tuesday, December 9, 2014

How to extract a JSON value from a BASH script



Requirement : I was working on shell script where I need to get Id value from JSON and I tried so many thing but unable to get it without using any other tools. So, After trying so many failure attempt, I end up with this site (A big thanks to you) which resolved my issue.


Here is how I fetched value from JSON,


JSON = <YOUR_JSON>
PROPERTY_TO_FETCH="<VALUE>" (In my case, it was "id")

ID = `echo $JSON| sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w $PROPERTY_TO_FETCH`

echo ${ID ##*|}


Which will print the value of 'id' from JSON.

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...