Wednesday 16 April 2014

Add site authentication in tomcat


Browser Authentication in tomcat server

If we are in development phase of our application and want to deploy application for testing purpose. We need to provide some authentication for accessing our web application, want for make sure that, testing team only can access application. If give browser authentication , unauthorized user not able to access application (even our home page).

 Step for creating Browser authentication.

1.      Create user in tomcat server.

   For creating user we need to mention username, password and role in tomcat-users.xml file. Location of file is  :- */conf/tomcat-users.xml .

Example :-

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager"/>
  <user username="manager" password="m@n@g3r" roles="manager"/>
  <user username="admin" password="admin_1234" roles="manager"/>
            </tomcat-users>

2.      Put authentication entry on web.xml (either in application web.xml or server web.xml)

   Add following code inside of  <web-app> tag in web.xml file.

<security-constraint>
       <web-resource-collection>
             <web-resource-name>Rentokil Web App</web-resource-name>
             <url-pattern>/*</url-pattern>
       </web-resource-collection>
       <auth-constraint>
              <role-name>manager</role-name>
       </auth-constraint>
       <user-data-constraint>
                <!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
                <transport-guarantee>NONE</transport-guarantee>
       </user-data-constraint>
</security-constraint>
<login-config>
                <auth-method>BASIC</auth-method>
                <realm-name>Rentokil Web App</realm-name>
</login-config>


While we accessing our application one prompt will come and asking for entering username and password. If we enter current password it will navigate to our application. If we click cancel button error msg will show in white page.


     



    

Handling mobile and desktop application with single URL in java.

This summary is not available. Please click here to view the post.

Sunday 18 November 2012

usefull linux command

sudo : for executing command by using admin privilage .

find command

   

Find a file "foo.bar" that exists somewhere in the filesystem

    $ find / -name foo.bar -print
    If the file is found the path to the file will be printed as output. On most platforms the -print is optional, however, on some Unix systems nothing will be output without it. Without specifications find searches recursively through all directories.

Find a file without searching network or mounted filesystems

    $ find / -name foo.bar -print -xdev
    This is useful if you have mounted network drives or filesystems that you do not want searched. This can increase search speed greatly if the mounted filesystem is large or over a slow network. "-mount" does the same thing as "-xdev" for compatibility with other versions of find.

Find a file without showing "Permission Denied" messages

    $ find / -name foo.bar -print 2>/dev/null
    When find tries to search a directory or file that you do not have permission to read the message "Permission Denied" will be output to the screen. The 2>/dev/null option sends these messages to /dev/null so that the found files are easily viewed.

Find a file, who's name ends with .bar, within the current directory and only search 2 directories deep

    $ find . -name *.bar -maxdepth 2 -print

Search directories "./dir1" and "./dir2" for a file "foo.bar"

    $ find ./dir1 ./dir2 -name foo.bar -print

Search for files that are owned by the user "joebob"

    $ find /some/directory -user joebob -print
    The files output will belong to the user "joebob". Similar criteria are -uid to search for a user by their numerical id, -group to search by a group name, and -gid to search by a group id number.

Find a file that is a certain type. "-type l" searches for symbolic links

    $ find /some/directory -type l -print
    Several types of files can be searched for:
      b    block (buffered) special
      c    character (unbuffered) special
      d    directory
      p    named pipe (FIFO)
      f     regular file
      l     symbolic link
      s    socket
      D   door (Solaris)

Search for directories that contain the phrase "foo" but do not end in ".bar"

    $ find . -name '*foo*' ! -name '*.bar' -type d -print
    The "!" allows you to exclude results that contain the phrases following it.

The power of find

find becomes extremely useful when combined with other commands. One such combination would be using find and grep together.
    $ find ~/documents -type f -name '*.txt' \
    -exec grep -s DOGS {} \; -print
    This sequence uses find to look in /users/home/directory/documents for a file (-type f) with a name ending in .txt. It sends the files it finds to the grep command via the -exec option and grep searches the file found for any occurrences of the word "DOG". If the file is found it will be output to the screen and if the word "DOG" is found, within one of the found files, the line that "DOG" occurs in will also be output to the screen.
The ordering of find's options are important for getting the expected results as well as for performance reason.
Visit POWER TOOLS:A Very Valuable Find, by Jerry Peek, for creative ways to use find and important tips about constructing the command's options.

Saturday 17 November 2012

ubuntu root password


ubuntu root account

This is the mystery for most users - you didn't set a root password, so what is it? The root user (also known as superuser), is a user on Ubuntu Linux and Unix-like systems with full administrative privileges (full access). So using root account for daily work can be very dangerous and you may damage your working system.

Ubuntu and root account

By default root account is locked under Ubuntu Linux. Therefore, you cannot login as root or use 'su -' command to become a superuser. To run all administrative command use sudo command. sudo allows a permitted user to execute a command as the superuser or another user. Ubuntu setup your default account (the one created during installation) to run all administrative commands.
For example create a new user called bar, you need to type sudo command as follows:
$ sudo adduser bar
Password:
When sudo asks for a password, you need to supply YOUR OWN password. In other words a root password is not needed. Here are few more examples.

Task: Start / stop / restart services stored in /etc/init.d/ directory

$ sudo /etc/init.d/ssh stop
$ sudo /etc/init.d/networking restart

Task: Avoid typing sudo each and every time

Note that this is not recommended until and unless you are an expert and aware of what you are typing:
$ sudo -i
Above command will start /bin/bash as a root shell so that you can enter a root user command without using sudo command.

How do I login as root user?

Open terminal and simply type the following command:
$ sudo bash
OR
$ sudo -s
Supply your password and you will become a root user.

Thursday 27 September 2012

Thread Complete guid

Java thread complete guid


Complete reference  of java thread

1.       Introduction
        A thread is a flow of control within a program . Thread is a sequential path of code execution with in a program .Each thread has its own local variable and programing counter and life cycle.  Thread sharing the same address space means that share instance variables , not local variables.
                Process:- A process is an instantce of computer program that is execute sequentially. It is a collection of instruction which are execute simultaneously at the run time . several process may cotain in a same program . process consis of memeory space allocated by the operation system. It remain running  util all the non daemon thread are done executing.
                Thread:- thread is light weight process which within a program and perform a sepcial task. Several thread may contain in a process. Sigle thread process contain only one thread but in multi thread process contain more than one thread within a process.
2.         Main thread
 Main()  method runs in a one thread , this thread is konow as main thread.of main thread create child thread program will keep runing util the all thread have complete its execution. 
3.       Life cycle of a thread
Different state of thread :-


                New state :- After the creations of thread instance and before  the invocation of start() method .thread concider as not alive
                Ready-to-run state :-  thread start it life from runnable state . after invocation of start() method thread enter to runnable state .in this state thread wait for a turn on the processer . thread can return to this state either running,waiting,sleeping or coming back from blocked state.
                Running state :-  thread currently executiong state that means thread executing. Only way to enter running state is scheduler swelect thread for running  from runnable pool.
                Dead state :- once run method completes thread become dead state. Cant run again.
                Blocked :- waiting the resources that are hold by another thread.


In java (Detail)



New :- remain in this state util program start the thread.
Runnable :- start executing the thread . mean executing start()method in thread
Waiting :- Thread stop there execution temporarly and allow another thread to start execution . once the running thread single to waiting thread to start execution that thread’s state transilate back to running state. 
Timed Waiting :- enter timed waiting state for specific time . thread transilate back to running state when time intervel expired or event it is waiting for is occure .



Multithreading
   Java built-in support for multithreading programming.it contain two or more thread can run concurrently.each thread defaines separate execution path.
Multitasking
                Execute more than one task at a time , task being a progrm.only one cpu involove that switch s from one program to another this switching is so quik that’s why  the apperance of executing all of the programs at same time .

               
Two thread have more than one task(operation) execute cuncorrently , here cpu switch task of each thread.
Advantages of multi threading over multi tasking
 Reduce computation time
Improve performance
Thread share same address space
Context switching between thread is less expensive than process
Cost of communication between threads is relativly low.

Different stage for multi threading

Thread goes to other non-runnable state depend on circumstance.cannot goes to running state from non-runnable state . frist goes to runinng state. Some nonrunnable state.
                Sleeping :- it might be return to runnable state later . if particular event occure.sleep for paricular amount of time.use sleep() to stop the running state of thread.
    Waiting for notification :- Thread send back to runnable state after reciving  notification from another thread.
Blocked on I/O:- wait for completion of blocked operation. Send back to runnable state after availity of resourse
Blocked for joint completion:- come this state because of waiting the completion of another thread.
Blocked for lock acquisition :-come this state because of waiting to acquring the lock of an object .

Java thread methods
currentThread() :- Return object reference to the thread in which it is invoke
getName() :- retrive the name of the thread object or instance.
Start() :- used to start the thread, by calling run Method
Run():- this is entry point to execute thread.
Sleep():-suspend the thread for specific time intervel
isAlive():-determine thread is running or not
activeCount():-  return number of active threads in a particular thread group and all its sub group
interrupt() :- interupt the the thread
yield():- current  thread pause execution and allow other thread to execute.
Join() :- join() / join(long millisecond) these not return until either the thread has completed or it is timed out respectivly.
Thread creation
An objecty of  thread class repersent a thread. 
2 ways of thread creation
1.       Extending the java.lang.thread Class
2.       Implementing the java.lang.runnable interface
In both case override the run() method

Eg: - 
  Class MyThread extends Thread{
                     String s =null;
MyThread (String  s1) {
                                     s=s1;
                                     start();
}
Public void run(){
                System.out.println(s);
}
  }
Public class RunThreadd{
     Public static void main(String arg[]){
                myThread m1 = new Mythread(“”Thread started ….”);
}
}

Implementing  Java.lang.runnaqble interface
Eg:-  Class MyThread implements runnable{
                Thread  t;
                String s =null;
MyThread(String s1){
                s= s1;
                t =new Thread(this);
                t.start();
}
Public void run(){
                System.out.println(s);
}
}
Public  Class Runnable {
                Public static void main(String arg[]) {
                                MyThread m = new  MY=ythread(“thread statrted…..”)
                }
}

Implementation of runnable interface is better :-
1.       Can extend another class .
2.       Can avoid the overhead of thread class which can be excessive
Thread Constructors :-
        Thread(), thread(String) , thread(Runnable),thread(Runnable,String),Thread(ThreadGroup,String) , Thread(ThreadGroup,Runnable) , Thread(ThreadGroup,Runnable,String) , Thread(ThreadGroup,runnable,String,long)
                ThreadGroup :- reperesent a gruoup of thread.it show in hierarchical manner . root thradGroup can contain all other  threadGroup nad thread each subgroup contain other group and thread. Threads can access only belonging thread group.
When new threadGroup is created it added member of existing thread group.
If thread X in group1 aand execute the code
ThreadGroup group2 = new ThreadGroup(group2);
Group2 2 it created under group1.
Change default parent group :- ThreadGroup group2 =n ew ThreadGroup(group2,group3);
Here newly formed group under group2
Functions
getName():-return name of particular group
getParent():- return parent threadGroup
activeGroupCount():- number of active threadGroup in particular threadGroup and all iths subgroup.
getThreadGroup():-  return thread group of a particular thread.

Creating multiple thread
                At the time of execution of the program all threads are registeed with the thread scheduler and cpu scheduler executes them one by one .
Different method for creating multi thread application
Exstend thread class
Implement Runnable interface
Class MyThread exstends Thread {                                 
                Mythread  ( String s) {
                Super(s);
                Satrt();
}
Public void run(){
                For(int i=0;i<5;i++) {
                                Syso(“thread name : ”
+Thread.currentThread().getName());
Try{
                Thread.sleep(1000);
}catch (Exception e){
}
}
Public Class Multithread {
                Public statyic void main(String args[]){
Syso(“Thread name:”+Thread.currentthread().
getName);
Mythread m1 = new Mythread(“My thread  1”);
Mythread m23 =new Mythread(“My thread 2”);
}
}
Class MyThread implements runnable {
         Thread t;  
         Mythread (String s){
                       t = new Thread(thuis, s);
                     t. Start();
            }
            Public void run() {
                      For(int i=0;i<5;i++){
                          Syso(“Thread name :”+Thread.currentThread().getName());
                            Try{
                                    Thread.sleep(1000);
                             }catch (Exception e){
                             }
                       }
             }
            Public class MultiThread {
                     Public static void main(String args[]){
                         Mythread m1 = new Mythread(“Mythread 1”)
                         Mythread m2 = new  Mythread(“My thread 2”)
              }
             }
}

Thread Priorities
       Thread scheduler use thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread goes to ready to run state based on priority value. Thread scheduler provide cpu time to thread ofhiger priority during ready-to-run sate.
Priority integer value from(1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY)) . default 5(Thread.NORM_PRIORITY).
setPriority() :-To set priority value to a thread
getPriority() :- to get priority value from thread.

When thread is created it inherite the priority of its parent thread. Higher priority thread select for exection.use preemptive schedule algorithm(If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.) . if two thread with same priority roun-robin algorithum (A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.)is applied

Deadlocak
    Deadlock is infinit waiting  for resource. Athread is waiting for an object that hold by second thread and this second thread waiting for object that hoold by frist thread. This situvation is known as deadlock.

  Here cpu this ideal no one thread executed util the holding up resource are free.
Dead locak example :-

      Class MyThread extends Thread {
                String  s1;
                String  s2;
                MyThread (String s1,String s2) {
                                This.s1 = s1;
                                This.s2 = s2;
                                Start();
                }
Public void run(){
                While (true){
                                Sychronized(s1){
                                                Sychronized(s2){
                                                                Syso(s1+s2);
                                                }
                                }             
                }
                }
}

Class Mythread2  extend Thread {
                String s1;
                String s2;
MyThread2(String s1,String2){
This.s1 =s1;
This.s2=s2;
Start();
}
Public void run(){
                While(true){
                                Sychonized(s2){
                                                Sychronized(s1){
                                                                Syso(s2+s1);
}
}
}
}
}

public static void main(string arg[] ){
                                String s1 =”dead”;
                                String s2 = “Lock”;
MyThread m1 = new Mythread(s1,s2);
Mythread2 m2 = new Mythread2(s1,s2);
                }
               
                               
     }

Rules for avoiding dead lock :-
1.       Simplest way to avoid dead lock is follow the heuristic that a synchronized method should never call another synchronized method. This not offern partical.
2.       Allow a top level class to handle the synchronization for all the method of the classes it call . only the method of top level class are synchronized freeing the lower order method do not worry about sychoronization
3.       Make sure locks are always acquired in the same order . this is best solution . very difficult to sketch the locking order . so you can ensure that you are getting and releasing locks in the best order .

Lock starvation.
  It means thread waiting for lock grab long time . because another thread already grab the lock for entire lock time.

Lock acquisition doesn’t queue. Threads don’t check other threads trying to also acquire locks.
Releasing a thread does not affect thread scheduling .processor is responsible for thread scheduling .

Lock starvation happening due to :-

                Multiple threads compete for the same lock
                Important result can occur during this time period
Thread all have same priority
Processor is using round robin scheduling

  

Sychronized Thread
Independed  thread are known as asynchronous thread. Problems of asychronous thread
                Two or more thread share the same resources only one can access the resource at a time
Two thread access the same data . one try to read and one trying write . some inconsitacy will happened . two avoid this java use monitor also known as semaphore by using sychroniozed . this is type of locking only one thread is in critical region once the thread is in critical section no ther thread can enter to that crtical region. So another thread will have to wait for entering critical region.

Synatx:- sychronized (object) {
                                // statement to be sychoronized
                 }

Lock :-
 Lock refers to access granted to a particular thread that can access the shared resources. At a time only one thread can hold the lock.every object has built in lock that is usefull when object has sychoronized method code . mean only one thread can access the resource guarded by the object lock.

                                Only methods or blocks can be sychoronized . A class and variable cannot be sychronized .
                                Each object has just one lock
                                Class can have both sychronized and non syschoronized method
                                 Two thread wants to execute a same syachoronized method in same instance class , only one thread can execute the method at a time
                                Mutiple thread can  access the class’s non sychoronized methods. If your application really not needed sychoronization avoid it beacase it may cause deadlock so should be carefull about syschoronize not to overuse it.
                                Thread hold its lock even it goes to sleep
                                Thread can aquire more than one lock.
                                Construcuctor can not be suchoronized .
Sychoronized methods
If any method want to execute the sychoronize method frist it has to obtain the object lock.if lock is already held then calling thread has to wait.
Example code :-
                                Class Share extends Thread {
                                                Static String msg[] = {“this”,”is ”,”a”,”sychoronized”, “variable”};
                                                Share(String threadName){
                                                                Super(threadName )
}
                                                Public void run(){
                                                                Display(getName());
                                                }
                                                Public sychronize display(String threadN){
                                                                For(int  i=0;i<=4;i++)
                                                                                Syso(ThreadN+msg[i]);
                                                                Try{
                                                                                This.sleep(1000);
                                                                }Catch(Exception e){
                                                                }
                                                }
                                }

                                Public calss sycThread{
                                                Public static void main(String[] args){
                                                                Share t1 = new Share(“Thread One: ”)
                                                                T1.start();
                                                Share t2 = new Share(“Thread Two”);
                                                T2.start();
                                                }
                                }

Sychronize block(statement)
                                Sychoronized  satements must specify the object that provides the native lock.
Example code :-  Class share extends thread{
                                                Static String msg[] = {“This”, “is”,”a”,”Sychoronized”, “variable”};
                                                Share(String threadName){
                                                                Super(threadName);
                                                }
                                                Public void run(){
                                                                Display (getName());
}
Public  void display(String ThreadN){
                Sychronized (this){
                                For(int i=0;i<=4;i++)
                                                Syso(theradN+msg[i]);
                                Try{
                                                This.sleep(1000);             
                                }catch (Exception e){}
                }
}
}
Public calss synstatement {
                Public static void main (String[] args) {
                                Share ti = new Share(“thread one : ”);
                                T1.start();
Share t2 = new Share(“thread Two: “);
T2.start();
                }
}
 Inter-thread Communication
                        Inter-thread communication reduce cpu’s idle time. For inter-thread communication implemented by some methods.these methods defined in “java.lang” package and can only called with in sychronized code .

Methods
 Description
Wait()
Called thread to give up the monitor and go to sleep until some other thread enters the same monitor and call method notifyAll()
Notify()
It call first thread that call wait() on the same object
notifyAll()
Wake up all the thread that called wait()on the same object. Highest prority thread will run first .


Daemon Thread
  Any thread can be daemon thread .it like service provider for others threads or object running in same process as the daemon thread. Used for back ground supporting tasks. If normal thread are not running and remaining thread are daemon threads then interpreter exits.
                                    SetDaemon(true/false) :- specify that thread is daemon thread
                                    Public Boolean isDaemon(): this method used to determine the thread is daemon thread or not .

Locking

Building your own locking class(Mutex)
                        Mutex object serve the locking mechanism.many os implement mutex lock as threading locking mechanisum.in java every object contain a lock . built in in object calss.

                        Example code:- public class buzyLocj{
Protected Thread buztyLock = null;
Protected int lockCount = 0;
Public synchronized void getBusyLock(){
            While(!tryGetBuzyLock())
                        Try {
                                    Wait();
                        }catch(exception ignored){}
}
}

Public synchronized tryGetBuzyLock(){
            If(busylock == null){
                        buzyLock = thread.currentThread();
                        lockCount = 1;
                        return true;
                }
            If(buzyLock == Thread.currentThread()){
            If(buzyLock == null){
lockCount++;
return true;
            }
Return false;

}’
Public sychoronized void freeLockFlag(){
            If(getbuzyLockOwner() == tread.currentThread()){
                        LockConunt--;
                        If(lockCount == 0){
                        BUZYlOCK == 0;
Notify();
}

                        }
}public sysnchronized Thread getBuzyLockOwner(){
            Return buzyLock
   }
}
Thread safe
Two separate thread can access the control at the same time without developer can worry about the threads interface with one another.
OptimizeIt is invaluable tool for thread checking