Friday, 26 February 2016

Thread vs Timers

One of the most basic uses of threads is to perform some periodic task at set intervals. In fact, this is so basic that there is a specialized class for performing this task—and you’ve already worked with it. The Timer class, in package javax.swing, can generate a sequence of ActionEvents separated by a specified time interval. Behind the scenes, a Timer uses a thread. The thread sleeps most of the time, but it wakes up periodically to generate the events associated with the timer. Before timers were introduced, threads had to be used directly to implement a similar functionality. In a typical use of a timer for animation, each event from the timer causes a new frame of the animation to be computed and displayed. In the response to the event, it is only necessary to update some state variables and to repaint the display to reflect the changes. A Timer to do that every fifty milliseconds might be created like this:

Timer timer = new Timer( 30, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
} );

Suppose that we wanted to do the same thing with a thread. The run() method of the thread would have to execute a loop in which the thread sleeps for 50 milliseconds, then wakes up to do the updating and repainting. This could be implemented in a nested class as follows using the method Thread.sleep().

 private class Amar extends Thread {
 public void run() {
while (true) {
try {
catch (InterruptedException e) { 

To run the animation, you would create an object belonging to this class and call its start() method. As it stands, there would be no way to stop the animation once it is started. One way to make it possible to stop the animation would be to end the loop when a volatile boolean variable, terminate, becomes true.
              There is a subtle difference between using threads and using timers for animation. The thread that is used by a Swing Timer does nothing but generate events. The event-handling code that is executed in response to those events is actually executed in the Swing event-handling GUI thread, which also handles repainting of components and responses to user actions. This is important because the Swing GUI is not thread-safe. That is, it does not use synchronization to avoid race conditions among threads trying to access GUI components and their state variables. As long as everything is done in the Swing event thread, there is no problem. A problem can arise when another thread manipulates components or the variables that are also used in the GUI thread. In the Animator example given above, this could happen when the thread calls the updateForNextFrame() method. The variables that are modified in updateForNextFrame() would also be used by the paintComponent() method that draws the frame. There is a race condition here: If these two methods are being executed simultaneously, there is a possibility that paintComponent() will use inconsistent variable values—some appropriate for the new frame, some for the previous frame.
             One solution to this problem would be to declare both paintComponent() and
updateForNextFrame() to be synchronized methods. A better solution in this case is to
use a timer rather than a thread.
This is a simple article which showed you that how thread and timers differs in their processing. 
Thank you guys.

Thursday, 25 February 2016

How to play videos in JAVA

In previous articles i showed you that JAVA having broad working areas. Today i will show you how to play videos in JAVA using javafx api.
For playing videos in JAVA we need following things :
  • JAVA 7 JDK or greater
  • Eclipse or Netbeans IDE 
Install all of these in your system. After that start eclipse IDE and make a JAVA project. After it add a class file named as you want.  Now make the following program. Here i am showing you a simple MP4 video play without any other controls on media player window.

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;



public class video extends Application{

    private Media media;
    private MediaPlayer player;
    private MediaView view;
    private Scene scene;
    private Group root;
    public void start(Stage stage) throws Exception {
        root = new Group();
        scene = new Scene(root,800,600);
        media = new Media(new File("/media/amar/Disk 3/my softwares/dhoom3.mp4")     

        player = new MediaPlayer(media);;

        view = new MediaView(player);


        stage = new Stage();

After it save the program and run as JAVA application. You will see the video is playing normally. The drawback of media player in JAVA that it is unable to support all video formats. 
Good Luck guys.

Wednesday, 24 February 2016

Image Slideshow in Java

Image slide show in java  can made by several methods. There are many ways to implement these methods. But here i am going to show you how we can make a simple image slide show from images which are present in our computer. First rename the images which will be used in the slide show as a1, a2, a3, a4, a5 and so on. We will also use a jframe as window, timer for introducing delay in slide show and jlabel for showing image. Now see the simple slide show program created by me.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class slide extends JFrame {

    JPanel panel;
    JLabel label;
    ImageIcon img;
    Timer timer;
    int i=0;
    public slide() {
        setLayout(new FlowLayout());

        panel = new JPanel();
        label = new JLabel();
        timer = new Timer(0, null);
        timer.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(i>4) {
                    label.setIcon(new ImageIcon("/home/amar/Desktop/a"+i+".jpg"));
                }else {

                    label.setIcon(new ImageIcon("/home/amar/Desktop/a"+i+".jpg"));
    public static void main(String[] args) {
        slide amar = new slide();


Run the program and you will see the slide show. Here delay is 1000ms, you can make it as you want.
Good Luck guys. Follow my blog.

Tuesday, 23 February 2016

How to read data from URL in java

Java is a best programming language i known. It is complete and easy. Java networking can used for making chat programs, browsers, email sender and many more applications. Here i am going to show you how we can read website data using URL. Java uses URL class for this purpose.
                                                            The URL class is used to represent resources on the World-Wide Web. Every resource has an address, which identifies it uniquely and contains enough information for a Web browser to find the resource on the network and retrieve it. The address is called a “url” or “universal resource locator”.  (URLs can actually refer to resources from other sources besides the web; after all, they are “universal”.)
                                                             An object belonging to the URL class represents such an address. Once you have a URL object, you can use it to open a URLConnection to the resource at that address. A URL is ordinarily specified as a string, such as “”. There are also relative URL’s. A relative URL specifies the location of a resource relative to the location of another URL, which is called the base or context for the relative URL. 
                                                              Once you have a valid URL object, you can call its openConnection() method to set up a connection. This method returns a URLConnection. The URLConnection object can, in turn, be used to create an InputStream for reading data from the resource represented by the URL. This is done by calling its getInputStream() method. The openConnection() and getInputStream() methods can both throw exceptions of type IOException. Once the InputStream has been created, you can read from it in the usual way, including wrapping it in another input stream type, such as BufferedReader, or using a Scanner. Reading from the stream can, of course, generate exceptions.
                                                               Let’s look at a short example that uses all this to read the data from a URL. This subroutine opens a connection to a specified URL, checks that the type of data at the URL is text, and then copies the text onto the screen. 

import java.util.Scanner;

public class amar {

    public static void main(String[] args) {
        String url;   
        String urlLC; 
        if (args.length == 0) {
            Scanner stdin = new Scanner(;
            System.out.print("Enter a url: ");
            url = stdin.nextLine();
        else {
            url = args[0];
        urlLC = url.toLowerCase();
        if ( ! (urlLC.startsWith("http://") || urlLC.startsWith("ftp://") ||
                urlLC.startsWith("file://"))) {
            url = "http://" + url;
            System.out.println("Using: " + url);
        try {
        catch (IOException e) {
            System.out.println("\n*** Sorry, an error has occurred ***\n");

    static void readTextFromURL( String urlString ) throws IOException {

        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
        InputStream urlData = connection.getInputStream();

        String contentType = connection.getContentType();
        System.out.println("Stream opened with content type: " + contentType);
        if (contentType == null || contentType.startsWith("text") == false) throw new               IOException("URL does not seem to refer to a text file.");
        System.out.println("Fetching context from " + urlString + " ...");

        BufferedReader in; 
        in = new BufferedReader( new InputStreamReader(urlData) );

        while (true) {
            String line = in.readLine();
            if (line == null)


In this program a prompt will come and ask to enter the URL starting with "http://", "ftp://", or "file://". If it does not start with one of these protocols, "http://" is added to the beginning of the input line. 
                                                  If everything will we fine then the text from the URL is copied to the console window of eclipse.
Good Luck guys.

Monday, 22 February 2016

How to install PHP and MySQL in LINUX

PHP, MySQL and Apache are most important for web developers. Here i am going to show you how to install all of these in your LINUX machine. So let's start and follow my steps carefully.

Step 1 : First of all we need to install apache or any other web server. here we will install apache. Apache is a free open source software which runs over 50% of the world’s web servers. For installing apache on your machine open the terminal in your LINUX machine and type following commands one by one.

sudo apt-get update
sudo apt-get install apache2

Now open your browser and type "localhost" or "". It will show you the following page.

Step 2 : Now install MySQL on your machine. To install MySQL, open terminal and type in these commands.

sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql

In the middle of your installation it will ask you set the root password, If you missed then set the password later within the MySQL shell.
Once you have installed MySQL, we should activate it with this command: 

sudo mysql_install_db

Now type the following command:

sudo /usr/bin/mysql_secure_installation

After this a prompt will ask you for entering the current root password. Type the password. Now prompt will ask you to change the password, So type N.
After that type 'Y' in all upcoming prompts. At last MySQL will reload and implement the new changes. 
Now MySQL installed successfully. For checking it open the terminal and type the following command :

sudo mysql root your_password

Step 3 : Now we are going to install PHP. To install PHP, open terminal and type in this command.

sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt

Type 'Y' in two prompts after it. It will install PHP automatically.
Now add php to the directory index by the following command:

sudo nano /etc/apache2/mods-enabled/dir.conf

Now add the index.php in beginning of the index files. It should be see like this :

<IfModule mod_dir.c>

          DirectoryIndex index.php index.html index.cgi index.php index.xhtml index.htm


Now type the command for adding the libraries and modules:

apt-cache search php5-

The terminal will show you the all modules. Select one of them and type the command:

sudo apt-get install name of the module

Now setup is almost complete. create a new file named "phpinfo.php" in '/var/www' folder and type the following lines.


Save it and open the browser and type "localhost/phpinfo.php"  the following address in address bar. It will show you the following screen.

Good luck guys. 

Sunday, 21 February 2016

Cryptographic Techniques and Protocols

There are many cryptographic techniques and protocols, they mostly
fall into one of three categories:

Bulk Encryption : This is the modern equivalent of secret writing . A bulk encryption algorithm uses a key to scramble (or encrypt ) data for transmission or storage. It can
then only be unscrambled (or decrypted ) using the same key. Bulk encryption is so called because it is effective for securing large chunks of data. Some common algorithms are Data Encryption Standard (DES), Data Encryption Algorithm (DEA) and RC4. This is also called the symmetric encryption.

Public Key Encryption :This is also a technique for securing data but instead of using a single key for encryption and decryption, it uses two related keys, called public key and private key , which together form what is known as a key pair . As the word suggests, public keys are made available to everyone, but each entity that holds a key pair should keep the private key as secret. If data is encrypted using one of the keys, it can only be decrypted using the other, and vice-versa.
                                                Public key encryption is a form of asymmetric encryption, because the key that is used to encrypt is different from the key used to decrypt. With this technology, the sender in a secure communication can use the receiver’s public key to encrypt the data, because at that point in time only the receiver can decrypt the data, by using its own private key.
                                                 Compared to bulk encryption, public key encryption is more secure, because it does not require the transmission of a shared key that both the parties must hold. However, public key encryption is computationally expensive and is therefore not suited to large amounts of data.
                                                 The most commonly-used algorithm for public key encryption is the Rivest,Shamir and Adleman (RSA) system.

Hashing : A secure hash is an algorithm that takes a stream of data and creates a
fixed-length digest of it. This digest is a fingerprint for the data. A digest has two main properties:
1. If even one single bit of data is changed, then the message digest changes as well. Notice, however, there is a very remote probability that two different arbitrary messages can have the same fingerprint.
2. Even if someone was able to intercept transmitted data and its fingerprint, that person would not be practically able to modify the original data so that the resulting data has the same digest as the original one.

                                                 Hashing functions are often found in the context of digital signatures. This is a method for authenticating the source of a message, formed by encrypting a hash of the source data. Public key encryption is used to create the signature, so it effectively ties the signed data to the owner of the key pair that created
the signature.

                                                  This all about Cryptographic Techniques and Protocols. We will discuss further in future articles in my blog. Thanks for reading friends.

Saturday, 20 February 2016

What is Cryptography?

Cryptography is the science of secret writing. It's a branch of mathematics, part of cryptology . Cryptology has one other child, cryptanalysis , which is the science of breaking (analyzing)cryptography. 

The main security concerns of applications are addressed by cryptography. First, applications need assurance that users are who they say they are. Proving identity is called authentication . In the physical world, a driver's license is a kind of authentication. When you use a computer, you usually use a name and password to authenticate yourself. Cryptography provides stronger methods of authentication, called signatures and certificates.

Computer applications need to protect their data from unauthorized access. You don't want people snooping on your data (you want confidentiality), and you don't want someone changing data without your knowledge (you want to be assured of your data's integrity). Data stored on a disk, for example, may be vulnerable to being viewed or stolen. Data transmitted across a network is subject to all sorts of nefarious attacks. Again, cryptography provides solutions.

So what can you do with cryptography? Plenty. Here are just a few examples:

Secure network communications : Cryptography can protect your data from thieves and impostors. Most web browsers now support SSL , a cryptographic protocol that encrypts information before it is transmitted over the Internet. SSL allows you to buy things, using your credit card number, without worrying too much that the number will be stolen.

Secure hard disk : You can encrypt the files on your hard disk so that even if your enemies gain physical access to your computer, they won't be able to access its data.

Secure email : Email is notoriously easy to steal and easy to forge. Cryptography can make it hard to forge email and hard to read other people's messages.

Although cryptography is heavily mathematical. One of the really nice things about the Java Security API is that, like any good software library, it hides a lot of complexity. The Security API exposes concepts, like Signature and Cipher , and quietly deals with the underlying details. You can use cryptography effectively in a Java application without knowing too much about what's going on underneath the hood.

Friday, 19 February 2016

Networking in JAVA

Networking in JAVA is best thing i used in JAVA. Those who are new with networking in JAVA should use only three basic things first. These things are Socket, Host name, and I/O streams. Socket is used for making connection, Host name is address and I/O streams for sending and receiving information. So here is our first and simplest example in JAVA networking.

package socket;
import java.util.*;


* This program makes a socket connection to the atomic
   clock in Boulder, Colorado, and prints

* the time that the server sends.


public class SocketTest {

public static void main(String[] args) throws IOException {

try (Socket s = new Socket("", 13)) {

InputStream inStream = s.getInputStream();

Scanner in = new Scanner(inStream);

while (in.hasNextLine())


String line = in.nextLine();




The first line opens a socket, which is a network software abstraction that enables communication out of and into this program. We pass the remote address and the port number to the socket constructor. If the connection fails, an UnknownHostException is thrown. If there is another problem, an IOException occurs. Since UnknownHostException is a subclass of IOException and this is a sample program, we just catch the superclass.
Once the socket is open, the getInputStream method in returns an
InputStream object that you can use just like any other stream. Once you have grabbed the stream, this program simply prints each input line to standard output. This process continues until the stream is finished and the server disconnects.

Note: The Java platform also supports the User Datagram Protocol (UDP), which can be used to send packets (also called datagrams) with much less overhead than that of TCP. The drawback is that packets need not be delivered in sequential order to the receiving application and can even be dropped altogether. It is up to the recipient to put the packets in order and to request retransmission of missing packets. UDP is well suited for applications in which missing packets can be tolerated —for example, for audio or video streams or continuous measurements.