Wednesday 14 March 2012

Daemon thread

Daemon is used in multitasking operating system . Daemon  is  a computer program that run as a background  process . it meas that it doesn't have direct control of an interactive user. in UNIX environment init   process is the parent process ( not always ) .  System often start Daemon at boot time ,  they often serve the function of responding to network requests, hardware activity, or other programs by performing some task  .

In java Daemon thread  are like service provider for other thread or object run in the same process as daemon thread . this thread used as back ground process. This thread only needed if  normal thread executing . all normal thread are not running and renaming thread are Daemon then interpreter exists.

            setDaemon(true/false)   :- used for setting a thread as Daemon .

           public boolean isDaemon()  :- Used for testing this thread is daemon or not .


example code :-


    public class BackGround extends Thread {
    public void run() {
       System.out.println("Entering Run Method");

       try {
         System.out.println("Current Thread : currentThread() is"
         + Thread.currentThread());

         while (true) {
           try {
             Thread.sleep(500);
           catch (InterruptedException x) {
           }

           System.out.println("Start thread again again");
        }
        

       } finally {
              System.out.println("Exiting run Method");
       }
   }

 
  public static void main(String[] args) {
     System.out.println("Entering main Method");

     DaemonThread t = new DaemonThread();
     t.setDaemon(true);
     t.start();

     try {
        Thread.sleep(3000);
    catch (InterruptedException x) {
    }

    System.out.println("Exiting main method");
  }

}



Output:- 

Entering main Method
Entering Run Method
Current Thread : currentThread() is [Thread-0,5,main]  
Start thread again again
Start thread again again
Start thread again again
Start thread again again
Start thread again again
Start thread again again  
Exiting main method


Difference between User Thread and Daemon thread

 The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread. Threads created by a user thread are user thread. JVM doesn't terminates unless all the user thread terminate.

We can change user thread to daemon thread by setting setDaemon(true) on thread object.

Newly created thread get inherited the thread property("daemon-status") from the  parent thread (on this thread new thread is created eg:- main() ). So explicitly change the thread property .

Should call setDaemon(true) before thread start (call before run() method) .

If the Java runtime determines that the only threads running in an application are daemon threads (i.e., there are no user threads in existence) the Java runtime promptly closes down the application, effectively stopping all daemon threads dead in their tracks. In order for an application to continue running, it must always have at least one live user thread. In all other respects the Java runtime treats daemon threads and user threads in exactly the same manner.



Advance Concept of Daemon :-

Daemons are usually instantiated as process (is running instant of a program , it managed by kernel each process have unique processId (PID) .) .

there are 3 type of process  in Linux .

1. Intactive :- Inactive process interactivity by a user at the command line .
2. Batch  :- This process are submitted from a queue of process that will not intact with command line .
3. Daemon :-     This process recognize any process as whose parent process have PID 1 .



Tuesday 13 March 2012

Image Uploading With Auto thumbnail generation In PHP

     Here i demonstrate how to create a form with file field , And upload image though this file field and automatically generate thumbnail for that particular image . Uploaded image stored in fullImage folder in root path and thumbnail images stored in thumbnail folder in root folder.
 
Step 1

   Create a HTML form for uploading image . 
   HTML form for uploading image .   profile.html

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
         <head>
                 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
                 <title>mobile Application</title>
          </head>
          <body>

          <form action="AccountAdd.php" method="post" enctype="multipart/form-data" >
              <div>Frist Name</div><div><input type="text"  id="firstname" name="firstName"/></div>
              <div>Last Name</div><div><input type="text"  id="lastName" name="lastName"/></div>
              <div>Age</div><div><input type="text"  id="age" name="age"/></div>
              <div>Image</div><div><input type="file"  id="user" name="fullImage"/></div>
               <div style="margin: 14px 0 0 25px "><input type="submit" id="login" name="login" value="register"></div>
          </form>
          </body>    
</html> 


 Step 2:-

          Function for creating thumbnails. This function create thumbnails from source file ( name pass as $source argument ) and will create thumbnail image in the destination folder ( destination Folder name pass on $destination argument ) .

AccountAdd.php

function create_thumbnail($source,$destination , $thmb_width){
              $size = getimagesize($source);
              $width = $size[0];
              $height = $size[1];
              $x = 0;
              $y = 0;
              if($width > $height){
                  $x = ceil(($width-$height)/2);
                  $width = $height;
              } elseif ($height > $width){
                  $y = ceil(($height - $width)/2);
                  $height = $width;
              }
              $new_image = imagecreatetruecolor($thmb_width, $thmb_width) or die("cannot initialize new GD image stream");
              $extension = get_image_extension($source);
              if ($extension=='jpg' || $extension == 'jpeg'){
                  $image = imagecreatefromjpeg($source);
              }
              if ($extension == 'gif'){
                  $image = imagecreatefromgif($source);
              }
              if ($extension == 'png'){
                  $image = imagecreatefrompng($source);
              }
             
              imagecopyresampled($new_image,$image, 0, 0, $x, $y, $thmb_width, $thmb_width, $width, $height);
              if ($extension=='jpg' || $extension == 'jpeg'){
                  imagejpeg($new_image , $destination);
              }
              if ($extension == 'gif'){
                  imagegif($new_image, $destination);
              }
              if ($extension == 'png'){
                  imagepng($new_image , $destination);
              }
         
          }



Step 3:- Define variables like maxi_size of image , width of  thumb nail image , Actual image location , thumbnail image location . Here both width and height of image are take on same variable $thumb_width and use this value set as both width and height of the thumb image  (means square image are generate.)

 AccountAdd.php

              $image_location = "fullImage/";
              $thumbs_location = "thumbnail/";
              $thumb_width =100;
              $maximum_size = 50000;


Step 4:- Create function for taking extension for image for validating  image 

            AccountAdd.php

              function get_image_extension($name){
                
                  $name =strtolower($name);
                  $i = strpos($name, ".");
                  if(!$i){return ""; }
                $l = strlen($name) - $i;
                $exstension = substr($name, $i+1 , $l);
                return $exstension;
          }   



Step 5 :- Create function for generating random name for avoiding name conflict .

     AccountAdd.php

            function random_name($length){
              $character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
              $name = "";
              for($i = 0; $i <$length ; $i++){
                  $name .= $character[mt_rand(0, strlen($character)-1)];
              }
              return "image-".$name;
             
          }



Step 6:-  Take information from HTML page and upload Actual image in  fullImage folder in the root path.
            
            
           AccountAdd.php

             if($_FILES['fullImage']['name'] == ''){
                       $results = "Image source cant not be empty. please
                       click the 'browse' button locate an image then click the 'upload Image'
                       button!!";
               } else{
                   $size = filesize($_FILES['fullImage']['tmp_name']);
                   $filename = stripslashes($_FILES['fullImage']['name']);
                   $extension = get_image_extension($filename);
                   if($size > $maximum_size){
                       $results = "Your file size exceeds the maximum size limit
                       please try again!";
                   }
                   else
                   if(($extension != "jpg") &&
                      ($extension != "jpeg") &&
                      ($extension != "png") &&
                      ($extension != "gif") ) {
                         
                          $results = "Image can only be with jpg, jpeg, png or gif exstension .
                          please try again !</center>";
                      
                    }else{
                        $image_random_name = random_name(15).".".$extension;
                        $copy = @copy($_FILES['fullImage']['tmp_name'], $image_location.$image_random_name);
                       
                        if(!$copy){
                            $results = "Error while uploading image! Please try again !";
                        } else {
                            create_thumbnail($image_location.$image_random_name, $thumbs_location.$image_random_name, $thumb_width);
                            $results = "Image has been uploaded";
                        }
                    }
               }



 


 Note:- I found these code when i search for my requirement on internet .