Sunday, 30 June 2013

Synchronization of threads in JAVA

Welcome folks ,

Here's an important topic in the field of programming - Synchronization of threads .

Thread - A thread is a single sequence stream within in a process. Threads have some  properties of processes, therefore they are also  called as lightweight processes .

Thread synchronization is very important because unsynchronized threads lead to race condition .

Lets see how to synchronize the execution of threads in JAVA.

Execute the below program and check the output

class WeTechies
{
    public static void main(String args[])
    {
        WeTechies1 t1 = new WeTechies1("t1: ");
        WeTechies1 t2 = new WeTechies1("t2: ");
        t1.start();
        t2.start();
        boolean t1IsAlive = true;
        boolean t2IsAlive = true;
        do {
           if (t1IsAlive && !t1.isAlive()) {
               t1IsAlive = false;
    System.out.println("t1 is not alive.");
           }
           if (t2IsAlive && !t2.isAlive()) {
               t2IsAlive = false;
               System.out.println("t2 is not alive.");
           }
        } while(thread1IsAlive || thread2IsAlive);
    }
}

class WeTechies1 extends Thread
{
static String message[] = { "Welcome", "to", "we", "techies ."};

    public WeTechies1(String th)
    {
        super(th);
    }

    public void run()
    {
        String threadname = getName();
        for (int i=0;i<message.length;++i) {
           letsWait();
           System.out.println(threadname + message[i]);
        }
    }

    void letsWait()
    {
        try {
           sleep((long)(3000*Math.random()));
        } catch (InterruptedException ex) {
           System.out.println("Thread has been Interrupted!" + ex);
        }
    }
}

This is the output obtained from the above program

t1: Welcome
t1: to
t1: we
t2: Welcome
t2: to
t1: techies .
t1 is not alive.
t2: we
t2: techies .
t2 is not alive.

But the expected output is      Welcome
                                                to
                                                we
                                                techies


We get this un expected output due to the non synchronization between the threads t1 and t2.

In the above program we have created a multi threaded program by creating the WeTechies1 as a  subclass of  the Thread class , which is done using the keyword extend.

Now lets create a program with similar behavior, but we create our threads as objects of the class WeTechies1, which is not a subclass of Thread. WeTechies1 will implement the Runnable interface and objects of WeTechies1 will be executed as threads by passing them as arguments to the Threadconstructor.

class WeTechies
{
    public static void main(String args[])
    {
        Thread t1 =  new Thread(new WeTechies2("thread1: "));;
        Thread t2 =  new Thread(new WeTechies2("thread2: "));;
        t1.start();
        t2.start();
        boolean t1IsAlive = true;
        boolean t2IsAlive = true;
        do {
           if (t1IsAlive && !t1.isAlive()) {
               t1IsAlive = false;
    System.out.println("t1 is not alive.");
           }
           if (t2IsAlive && !t2.isAlive()) {
               t2IsAlive = false;
               System.out.println("t2 is not alive.");
           }
        } while(t1IsAlive || t2IsAlive);
    }
}

class WeTechies2 implements Runnable
{
static String message[] = { "Welcome", "to", "we", "techies ."};
String threadname;
    public WeTechies2(String id)
    {
        threadname = id;
    }

    public void run()
    {
     
        for (int i=0;i<message.length;++i) {
           letsWait();
           System.out.println(threadname + message[i]);
        }
    }

    void letsWait()
    {
        try {
           Thread.currentThread().sleep((long)(3000*Math.random()));
        } catch (InterruptedException ex) {
           System.out.println("Thread has been Interrupted!" + ex);
        }
    }
}

The output of the above program is


thread1: Welcome
thread2: Welcome
thread1: to
thread2: to
thread1: we
thread2: we
thread2: techies .
t2 is not alive.
thread1: techies .
t1 is not alive.

You will find the output to be similar to the previous program but the difference lies in the way the threads are created , this program does not extend the Thread class to create the thread like the previous program did ,  rather it implements the Runnable interface in order to create the thread.


Now lets synchronize the threads in order to get our expected output.

This can be done using the synchronized keyword.

Consider the below program where we synchronize the execution of the threads 1 and 2 using the keyword synchronized in the output() method

class WeTechiesSynchronization
{
    public static void main(String args[])
    {
        WeTechies thread1 = new WeTechies("thread1: ");
        WeTechies thread2 = new WeTechies("thread2: ");
        thread1.start();

        thread2.start();
        boolean thread1IsAlive = true;
        boolean thread2IsAlive = true;
        do {
           if (thread1IsAlive && !thread1.isAlive()) {
               thread1IsAlive = false;
               System.out.println("Thread 1 is dead.");
           }
           if (thread2IsAlive && !thread2.isAlive()) {
               thread2IsAlive = false;
               System.out.println("Thread 2 is dead.");
           }
        } while(thread1IsAlive || thread2IsAlive);
    }
}

class WeTechies extends Thread
{
static String message[] = { "Welcome", "to", "we", "techies ."};

    public WeTechies(String id)
    {
        super(id);
    }

    public void run()
    {
        WeTechiesSynchronizedOutput.output(getName(),message);
    }

    void randomWait()
    {
        try {
           sleep((long)(3000*Math.random()));
        } catch (InterruptedException x) {
           System.out.println("Interrupted!");
        }
    }
}

class WeTechiesSynchronizedOutput
{
           public static synchronized void output(String name,String list[])
          {
                   for(int i=0;i<list.length;++i) {
                   WeTechies t = (WeTechies) Thread.currentThread();
                    t.randomWait();
                    System.out.println(name+list[i]);
                   }
          }
}

The ouput of the above program is

thread1: Welcome
thread1: to
thread1: we
thread1: techies .
Thread 1 is dead.
thread2: Welcome
thread2: to
thread2: we
thread2: techies
Thread 2 is dead.

Now we have got the expected output by making use of the synchronized keyword.

This way the race conditions can be handled hence leading to synchronized execution of the threads.

Please feel free to leave your comments or doubts

thank you :)

Saturday, 29 June 2013

How to Create Progress Indicator in JavaFX

Hi,

  Wondering how to use Progress Indicator in JavaFX

    like to have a progress bar which shows the progress of program/task completed ?

    Well, thats quite simple using JavaFX!!

    First thing we need to create a JavaFX FXML project,If you dont know follow this post.
  
    Once the project is created first step is to design the User Interface, for this demo i have created
    like this

createworker(), dynamic UI, FXML, javaFX, progress bar in javafx, Progress Indicator in javafx, progress property, task in javafx, user interface in javafx,


   Replace your code in .fxml file with this one

<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxprogressindicator.SampleController">

  <children>
    <Button fx:id="start" layoutX="26.0" layoutY="14.0" onAction="#handleButtonAction"
      text="Start" />

    <Label fx:id="label" layoutX="55.0" layoutY="73.0" minHeight="16.0" minWidth="69.0" />

    <ProgressIndicator fx:id="progress" layoutX="83.0" layoutY="113.0" prefHeight="62.0"
      prefWidth="138.0" progress="0.0" />

    <Button fx:id="stop" layoutX="200.0" disable="true"  layoutY="14.0" onAction="#stopAction"
      mnemonicParsing="false" text="cancel" />
  </children>

</AnchorPane>

This creates a Anchor pane and adds

2 Buttons start and cancel
1 Progress Indicator refered as progress
1 Label just to inform you that your program has started.

Now your done with UI creation next is creating event handler for it.

Creating event handler? where did we registered our event?

I know you got these question check above code when we created a button we used onAction="#eventname"

This attribute specifies the eventhandler to be called when a action is performed on it.

Now creating the event handlers

@FXML
    private void handleButtonAction()
 {
      // this will be executed when button is clicked, if you have registered this handler as above
 }

Now for this demo

Paste the following code in your controller file for using progress indicator

//Two button handlers for stop and start respectively

 @FXML
    private void stopAction()
    {
       //when cancel button is clicked it will end the task created and
        worker.cancel(true);
      //unbinds progress indicator from that task
         progress.progressProperty().unbind();
     //set it to 0
         progress.setProgress(0);
        start.setDisable(false);
    }
    @FXML
    private void handleButtonAction() {
        //setDisable() is used to enable or disable the elements
        stop.setDisable(false);
        start.setDisable(true);
        label.setText("Now your program is progressing!!");
        progress.progressProperty().unbind();
        progress.setProgress(0);
      //creating a new task
        worker = createWorker();
        //binding it with that task
        progress.progressProperty().bind(worker.progressProperty());
         //you can pass any value while task is executing and it can printed on console or set to label
                worker.messageProperty().addListener(new ChangeListener<String>() {
                    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                        System.out.println(newValue);
                    }
                });
                // task started on new thread
                 new Thread(worker).start();
               
    }
    public Task createWorker() {
        return new Task() {
            // call() should be overridden

            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(2000);
                  //updateMessage() is used to pass the values to be printed on screen or console
                    updateMessage("2000 milliseconds");
                  //this is used to show the progress
                    updateProgress(i + 1, 10);
                }
                 worker.cancel(true);
                return true;
            }
        };
    }

OMG!! what is this code, if you dint understood anything dont worry I will explain about Task in my next post

For now Task is used to do some work in background and  which may change our UserInterface dynamically (while running the programm) its similar to Threads , but using threads we can't change the UI when running the program.

Check comments for above code explaination and what ever you want to perform in background do it
 in createworker() .

Thats all you can run your program and you will see progress indicator showing the progress of
your program.


your final output will be this

createworker(), dynamic UI, FXML, javaFX, progress bar in javafx, Progress Indicator in javafx, progress property, task in javafx, user interface in javafx,

Download the complete source code from here

Please feel free to leave your comments or doubts

thank you :)

Tuesday, 25 June 2013

Here is an example to Upload Multiple Files(.jpg, .txt, .pdf, .doc etc) to Remote Server:



Hi, welcome,

        FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface. As with all classes derived from SocketClient, you must first connect to the server with connect before doing anything, and finally disconnect after you're completely finished interacting with the server. Then you need to check the FTP reply code to see if the connection was successful.

package mobileapplicatio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


//the following packages has to be downloaded in order to work with APIs supported by FTP
//LINK to download the packages Zip file

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
package UploadApplication;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//To use FTP methods you have to download the following libraries
//Zip

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
  1. public class TestUpload {
  2.     public static void main(String[] args) {
  3.         String server = "RemoteServer.com";
  4.         int port = 21;
  5.         String user = "User";
  6.         String pass = "password";
  7.         FTPClient ftpClient = new FTPClient();
  8.         try {
  9.             ftpClient.connect(server, port);
  10.             ftpClient.login(user, pass);
  11.             ftpClient.enterLocalPassiveMode();

  12.             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  13.             File firstLocalFile = new File("PATHTOFOLDER");
  14.             for (final File fileEntry : firstLocalFile.listFiles()) {
  15.                 if (fileEntry.isDirectory()) {
  16.                     //do your operatons;
  17.                 } else {
  18.                     String firstRemoteFile = fileEntry.getName();
  19.                     InputStream inputStream = new FileInputStream(fileEntry);

  20.                     System.out.println("Start uploading file-->"+fileEntry.getName());
  21.                     boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
  22.                     inputStream.close();
  23.                     if (done) {
  24.                         System.out.println("The first file is uploaded successfully.");
  25.                     }
  26.                 }
  27.             }
  28.         } catch (IOException ex) {
  29.             System.out.println("Error: " + ex.getMessage());
  30.             ex.printStackTrace();
  31.         } finally {
  32.             try {
  33.                 if (ftpClient.isConnected()) {
  34.                     ftpClient.logout();
  35.                     ftpClient.disconnect();
  36.                 }
  37.             } catch (IOException ex) {
  38.                 ex.printStackTrace();
  39.             }
  40.         }
  41.     }
  42. }

/*  Steps to add libraries

-->Goto projects
-->right click on Libraries         
            -->Select Add jar file/folders
            --->Browse to downloaded files and click ok

*/


***********************************************************************************************
Explanation for the client program


Line 3:Specify The Remote server address(URL) to which the file has to be uploaded.

Line 4:Default port number for FTP clients

Line 5:Specify User name

Line 6:Specify PASSWORD

Line 7: Creating instance of FTPClient in next three lines we will connect to the Server

Line 14: Specify the path of the folder from which the files will be selected and uploaded.

Line 15:Loop through each file present in  the specified library
              Upload each file with the same name.

Line 23:Uploads file to Remote server with the specified name.

*************************************************************************




Leave your doubts or suggestions in comments section...

Monday, 17 June 2013

client and server interaction

Hi, welcome,

Ever wondered how does your server identify you and provide the service you request for? 

             Its very simple. In this post you will learn about a simple interaction between the client and the server.

To start off,  lets look at one of the simplest things that you can do - we will initialize a stream connection and receive a message from a remote server.

Consider the below c program - a simple code for the client .

Here socket connection is established between the client and the server and the client receives the message sent by the server, note that for demonstration purpose we use the same system as the client and the server .

Well lets start coding the client machine

Here it goes !!!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

 #define MAX_SIZE_OF_MESSAGE 500
#define PORT_NUMBER 2343

int main(int argc, char *argv[])
{

     1 } char buffer[MAX_SIZE_OF_MESSAGE + 1];

     2 } int len, wetechies_socket;

     3 } struct sockaddr_in destination_machine;

     4 } mysocket = socket(AF_INET, SOCK_STREAM, 0);

     5 } memset(&dest, 0, sizeof(dest));      
         
     6 } dest.sin_family = AF_INET;

     7 } destination_machine.sin_addr.s_addr = inet_addr("127.0.0.1"); 

     8 }  dest.sin_port = htons(PORTNUM);         
       
     9 } connect(wetechies_socket, (struct sockaddr *)&destination_machine, sizeof(struct sockaddr));

   10 }  len = recv(wetechies_socket, buffer, MAX_SIZE_OF_MESSAGE, 0);

   11 }   buffer[len] = '\0';

   12 } printf("Received %s (%d bytes).\n", buffer, len);

   13 }  close(wetechies_socket);

   14 } return EXIT_SUCCESS;

}

***********************************************************************************************
Explanation for the client program

Line 1 - An array by name buffer of type char is created with the size MAX_SIZE_OF_MESSAGE + 1 (+1 is used so that we can add the null terminator too).

Line 2 - Initialization of the variables len  (used to hold the length of the message received from the server (line 10) ) and mysocket .

Line 3 - Creates a variable destination_machine which is a struct of type sockaddr_in , This struct stores information about the machine we want to connect to.

Line 4 - The socket() function tells our OS that we want a file descriptor for a socket which we can use for a network stream connection; what the parameters mean is mostly irrelevant for now. But if your are interested you can always explore it by using the man page by hyst typing the command man socket.

Line 5memset() is used to zero the struct variables. you can again use the man page by typing the command man memset to know more about the memset function

Line 6 - Sets the address family. This should be the same value that was passed as the first parameter to socket(); for most purposes AF_INET will serve.

Line 7 - Here is where we set the IP address of the machine we need to connect to(here we use 127.0.0.1 which is know as the loopback address and refers to your own machine). The variable destination_machine.sin_addr.s_addr is just an integer stored in Big Endian format, but we don't have to know that as the inet_addr() function will do the conversion from string into Big Endian integer for us. 

Line 8 - This line sets the destination port number. The htons() function converts the port number into a Big Endian short integer. If your program is going to be run solely on machines which use Big Endian numbers as default then destination_machine.sin_port = 21 would work just as well. However, for portability reasons htons() should always be used. 

Line 9 - Establishes a connection with the server machine.

Line 10 - Receives up to MAX_SIZE_OF_MESSAGE bytes of data from the connection and stores them in the buffer string. The number of characters received is returned by recv()

Line 11 - The data received will not automatically be null terminated when stored in the buffer, so we need to do it ourselves with buffer[inputlen] = '\0'

*************************************************************************

Now lets start coding the server machine

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORTNUM 2343

int main(int argc, char *argv[])
{

    char msg[] = "wetechies !\n";

    struct sockaddr_in destination_machine;

    struct sockaddr_in server;

    int wetechies_socket;          

    socklen_t socksize = sizeof(struct sockaddr_in);

    memset(&server, 0, sizeof(server));        

    server.sin_family = AF_INET;              

    server.sin_addr.s_addr = htonl(INADDR_ANY);

    server.sin_port = htons(PORTNUM);          
    wetechies_socket = socket(AF_INET, SOCK_STREAM, 0);

    bind(wetechies_socket, (struct sockaddr *)&server, sizeof(struct sockaddr));

    listen(wetechies_socket, 1);
    int connection_socket = accept(wetechies_socket, (struct sockaddr *)&destination_machine, &socksize);

    while(connection_socket)
    {
        printf("Incoming connection from %s - sending welcome\n", inet_ntoa(destination_machine.sin_addr));
        send(connection_socket, msg, strlen(msg), 0);
       connection_socket = accept(wetechies_socket, (struct sockaddr *)&destination_machine, &socksize);
    }

    close(connection_socket);
    close(wetechies_socket);
    return EXIT_SUCCESS;
}

***********************************************************************************************
Explanation for the server program

In fact, this is very similar to the client program. The main difference is that rather than creating a sockaddr_in with information about the machine we are trying to connect, we create it with information about the server, and then we bind() it to the socket. 

The listen() function then tells our program to start listening using the given socket.

The second parameter of listen() allows us to specify the maximum number of connections that can be queued.

Each time a connection is made to the server it is added to the queue.We take connections from the queue using the accept() function. The accept() function returns another socket. This socket is essentially a "session" socket, and can be used solely for communicating with connection we took off the queue. The original socket (mysocket) continues to listen on the specified port for further connections.
 ***************************************************************


Leave your doubts or suggestions in comments section...

Getting started with augmented reality

Augmented Reality

Hi folks ,

you would have been very tired reading the other posts which is  technical now in this post lets see something thats not just technical but also v v v CooooooooL

YES !!!! you don't believe?? Check this out http://www.youtube.com/watch?v=jKIv3Pt6zjI 

 Surprised?? wondering how it happens???? 
well its not a magic.....its very simple .
                                                      its just

                        Augmented Reality
Wanna develop something like this?? Congratulations your in the right place !!!!!!!

Follow the below steps

1 } Download the android  sdk from http://developer.android.com/sdk/index.html (this is used  in case you are developing application  for the android platform )


2 } Download the qualcommm sdk from https://developer.vuforia.com
(this is the sdk tat supports the augmentation of objects , it has the complete set of tools required for AR apps ) .


3 } To design you are app , you can use one of the best game engine called " unity 3D engine " it can be downloaded from http://unity3d.com/unity/download/

The main advantage of using qualcomm sdk is tat its open source and the sample apps itself gives a clear idea of everything .


The most important part of developing your application is the creation of the image target .

The below fig shows the workflow for creating the image target.



You can create the image target either on your device or on the cloud database


Device databases allows your  applications to  access local database of image targets. 
Cloud databases allows your  applications to work with a large number of targets.  Cloud databases are stored in the Internet and support over a million image targets.

Once your done with it , you can just drag and drop the objects provided by the unity game engine and bulid and run your application on your device .  

Here is the development area of the unity engine , the camera preview of unity helps you to visualize the output of your application before you deploy it . 

3d ar app, android ar app, augmentation, augmented reality, image target, qualcomm, unity engine, vuforia,


As the augmented reality concept is vast i end the discussion here , please feel free to ask your questions(if any ) in the comments section :-)