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'?>
  <role rolename="manager"/>
  <user username="manager" password="m@n@g3r" roles="manager"/>
  <user username="admin" password="admin_1234" roles="manager"/>

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.

             <web-resource-name>Rentokil Web App</web-resource-name>
                <!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
                <realm-name>Rentokil Web App</realm-name>

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.

Recent trend is to create two separate application that compatible for desktop browser and mobile browser.So user automatically switch to their URL according to the device from which they access the site .

Normally in mobile site we are include only necessary information due to space constrain. So data layer and business layer of the application also have some minor changes.that means we need to handle this separate.Checking user-agent and change logic according to user-agent in each page is very difficult.

We can create one application that switch URL according to the user-agent (field in HTTP request contain the client information like browser name ,device name,OS etc ) . Point this application to the domain name.

Example:- we have two application one for mobile device and another for desktop
Mobile URL :- IP:port/mobile/*
desktop URL :- IP:port/*
URL switching applicaion :- IP1:port
Domain name :-
Our Domain name pointing to the IP1:port that switch URL according to the user-agent. if the user type URL as it goes to the IP1:port and switch the user to different URL according to the user-agent.

Problem is if user trying to access mobile site (IP:port/mobile/*) from desktop browser, mobile site will render in desktop browser. this is a bad practice in user point of view (look and feel of application will awful if we render mobile site in desktop browser).

To handling this scenario we can write filter for IP:port application.

1. Create filter that check user-agent field in HTTP request and if it is from mobile will goes to IP:port/mobile/
Example :-

public class DesktopFilter implements Filter{

* properties
private static Properties properties = new Properties();

private static final String IPAD_URL = "abac.ipad.url";

public void destroy() {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
String userAgent = ((HttpServletRequest)request).getHeader("User- Agent");
if(userAgent == null){
userAgent = "";
properties.load(getClass().getResourceAsStream (""));
chain.doFilter(request, response);
} catch (Exception ex){
chain.doFilter(request, response);
public void init(FilterConfig arg0) throws ServletException {

2. Create filter lib file and place this file either in application(IP:port) lib / server lib.

3.We can include filter mapping either in application web.xml or server web.xml, if your server dedicate to you application then you can freely use server web.xml . otherwise you should careful add filter mapping in web.xml.

If user access application from desktop by using
1. :- it will redirect to IP:port/*
2. IP:port/mobile/* :- it will redirect to IP:port/mobile/*

Sunday, 18 November 2012

usefull linux command

sudo : for executing command by using admin privilage .

find command


Find a file "" that exists somewhere in the filesystem

    $ find / -name -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 -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 -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 ""

    $ find ./dir1 ./dir2 -name -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
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
$ 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 .

   Java built-in support for multithreading contain two or more thread can run concurrently.each thread defaines separate execution path.
                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) {
Public void run(){
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);
Public void run(){
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 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
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) {
Public void run(){
                For(int i=0;i<5;i++) {
                                Syso(“thread name : ”
}catch (Exception e){
Public Class Multithread {
                Public statyic void main(String args[]){
Syso(“Thread name:”+Thread.currentthread().
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());
                             }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

    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;
Public void run(){
                While (true){

Class Mythread2  extend Thread {
                String s1;
                String s2;
MyThread2(String s1,String2){
This.s1 =s1;
Public void run(){

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(){
                                                Public sychronize display(String threadN){
                                                                For(int  i=0;i<=4;i++)
                                                                }Catch(Exception e){

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

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){
                                                Public void run(){
                                                                Display (getName());
Public  void display(String ThreadN){
                Sychronized (this){
                                For(int i=0;i<=4;i++)
                                }catch (Exception e){}
Public calss synstatement {
                Public static void main (String[] args) {
                                Share ti = new Share(“thread one : ”);
Share t2 = new Share(“thread Two: “);
 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 .

Called thread to give up the monitor and go to sleep until some other thread enters the same monitor and call method notifyAll()
It call first thread that call wait() on the same object
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 .


Building your own locking class(Mutex)
                        Mutex object serve the locking mechanism.many os implement mutex lock as threading locking 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(){
                        Try {
                        }catch(exception ignored){}

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

Public sychoronized void freeLockFlag(){
            If(getbuzyLockOwner() == tread.currentThread()){
                        If(lockCount == 0){
                        BUZYlOCK == 0;

}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