Sunday, July 30, 2017

Puzzles

Question:- Three ants are sitting at the three corners of an equilateral triangle. Each ant starts randomly picks a direction and starts to move along the edge of the triangle. What is the probability that none of the ants collide?

Answer:- So let’s think this through. The ants can only avoid a collision if they all decide to move in the same direction (either clockwise or anti-clockwise). If the ants do not pick the same direction, there will definitely be a collision.

Well, each ant can move in 2 different directions. Because there are 3 ants, this means that there are 2*2*2 (which equals eight) possible ways that the ants can move.

And since we already know that there are only 2 ways in which the ants can avoid collision entirely :- 2/8 = 0.25

this means that there are 8-2 = 6 scenarios where the ants will collide. And 6 out of 8 possible scenarios, means that the probability of collision is 6/8 = .75. Thus, the probability of the ants colliding is .75.

Question:- A bird fly 200km/hr.Two trains coming oppositely one 100km/hr, other 50km/hr. Total distance between the trains starting point is 450km.So the bird is flying to and fro in the train line. How long distance the bird travel when the trains meet each other.

Answer:-

<---------------------------------- 450 km ---------------------------------------------------------------------------->
|-----------------------------------------------------------------------------|-------------------------------------------------|
X(100km/h) <----- (450-x) -------------------------------> meet  <---------- x --------->(50km/h) Y

 speed = distance /time

100 = 450-x / t1
50 = x / t2

as they meet at same time so

t1 = t2 => 450-x/100 = x/50 = x => 150 km

time = 150 / 50 = 3 hrs
Distance bird traveled is = 200 * 3 = 600 km


Question:- A train leaves City X for City Y at 15 mph. At the very same time, a train leaves City Y for City X at 20 mph on the same track. At the same moment, a bird leaves the City X train station and flies towards the City Y train station at 25 mph. When the bird reaches the train from City Y, it immediately reverses direction. It then continues to fly at the same speed towards the train from City X, when it reverses its direction again, and so forth. The bird continues to do this until the trains collide. How far would the bird have traveled in the meantime?

Answer:-
The concept of relative speed can work handy here. Let’s assume that the distance between City X and City Y is d miles. The trains are approaching each other at a relative speed of (20 + 15) = 35 mph. The sum of the distances covered by the trains when they collide is d (i.e. the distance between the cities). Since distance/speed gives us time, we know that the trains collide d/35 hours after they start.

Since the speed of the bird is constant at 25 mph, we know that the bird would have covered

25 * (d/35) miles = 5d/7 miles before the trains collide.

Question:- You have 10 boxes of balls (each ball weighing exactly10 gm) with one box with defective balls (each one of the defective balls weigh 9 gm). You are given an electronic weighing machine and only one chance at it. How will find out which box has the defective balls?

Answer:- For convenience sake, let’s name the boxes from 1 to 10. In order to solve this problem, you have to leverage the fact that you know exactly what each good ball is supposed to weigh and what each defective ball is supposed to weigh. Many of us instinctively will take one ball out of each box and try to find a way to make it work but the trick to take different number of balls from each box.

The number of balls you pick from each bag is equal to the box number. For example, pick 1 ball from box 1, 2 balls from box 2 and so on. In total you will have 55 balls. If all of the boxes have good balls, then the total weight of these balls would be 550gm.

If box 1 has defective balls, then the total weight should be 1gm less than expected (only one ball weighing 9 gm). If box 2 has defective balls, then the total weight should be 2gm less than expected (two balls weighing 9 gm). So once you weigh the set of chosen balls, find out the difference between the total weight and the expected weight. That number represents the box number which contains the defective balls.

Question:-  You have 9 balls, equally big, equally heavy - except for one, which is a little heavier. How would you identify the heavier ball if you could use a pair of balance scales only twice?

Answer:-
Divide the 9 balls into 3 groups of 3. Compare the weight of two of those groups. The heavier group should then be obvious, it will either tip the scales, or, if the scales stay balanced, then it is the group you didn't include. Now, choose 2 balls from this group and compare their weights, and using the same logic as before, the heavier ball will be obvious.

Question:-  You have 100 doors to be painted and 2 painters. 1 starts at one end and paints every other door. The other painter starts at the other end and paints every 3rd door. What door number will they meet at?

Answer:-

1st painter: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
2nd painter: 97 94 91 88 85 82 79 76 73 70 67 64 61 58 55 52 49 46 43 40 37 34 31 28 25

the meeting point is 25th door

Plus, find out relative steps that would be 1st door = x, every 3rd door = 3x
relative doors = x+3x = 4x
total doors = 100
4x = 100
x = 100/4 = 25th door

Question:- The owner of a banana plantation has a camel. He wants to transport his 3000 bananas to the market, which is located after the desert. The distance between his banana plantation and the market is about 1000 kilometer. So he decided to take his camel to carry the bananas. The camel can carry at the maximum of 1000 bananas at a time, and it eats one banana for every kilometer it travels.

What is the largest number of bananas that can be delivered to the market?

Answer:-
First of all, the brute-force approach does not work. If the Camel starts by picking up the 1000 bananas and try to reach point B, then he will eat up all the 1000 bananas on the way and there will be no bananas left for him to return to point A.

So we have to take an approach that the Camel drops the bananas in between and then returns to point A to pick up bananas again.

Since there are 3000 bananas and the Camel can only carry 1000 bananas, he will have to make 3 trips to carry them all to any point in between.




<---p1---><--------p2-----><-----p3---->
A---------------------------------------->B
 

When bananas are reduced to 2000 then the Camel can shift them to another point in 2 trips and when the number of bananas left are <= 1000, then he should not return and only move forward.

In the first part, P1, to shift the bananas by 1Km, the Camel will have to

    1. Move forward with 1000 bananas – Will eat up 1 banana in the way forward
    2. Leave 998 banana after 1 km and return with 1 banana – will eat up 1 banana in the way back
    3. Pick up the next 1000 bananas and move forward – Will eat up 1 banana in the way forward
    4. Leave 998 banana after 1 km and return with 1 banana – will eat up 1 banana in the way back
    5. Will carry the last 1000 bananas from point a and move forward – will eat up 1 banana

Note: After point 5 the Camel does not need to return to point A again.

So to shift 3000 bananas by 1km, the Camel will eat up 5 bananas.

After moving to 200 km(P1) the Camel would have eaten up 1000 bananas and is now left with 2000 bananas.

Now in the Part P2, the Camel needs to do the following to shift the Bananas by 1km.

    1. Move forward with 1000 bananas – Will eat up 1 banana in the way forward
    2. Leave 998 banana after 1 km and return with 1 banana – will eat up this 1 banana in the way back
    3. Pick up the next 1000 bananas and move forward – Will eat up 1 banana in the way forward

Note: After point 3 the Camel does not need to return to the starting point of P2.

So to shift 2000 bananas by 1km, the Camel will eat up 3 bananas.

After moving to 333 km(P2) the camel would have eaten up 1000 bananas and is now left with the last 1000 bananas.

The Camel will actually be able to cover 333.33 km, I have ignored the decimal part because it will not make a difference in this example.

Hence the length of part P2 is 333 Km.

Now, for the last part, P3, the Camel only has to move forward. He has already covered 533 (200+333) out of 1000 km in Parts P1 & P2. Now he has to cover only 467 km and he has 1000 bananas.

He will eat up 467 bananas on the way forward, and at point B the Camel will be left with only 533 Bananas.

Question:- There are 4 persons (A, B, C and D) who want to cross a bridge in night.

A takes 1 minute to cross the bridge.
B takes 2 minutes to cross the bridge.
C takes 5 minutes to cross the bridge.
D takes 8 minutes to cross the bridge.

There is only one torch with them and the bridge cannot be crossed without the torch. There cannot be more than two persons on the bridge at any time, and when two people cross the bridge together, they must move at the slower person’s pace. Can they all cross the bridge in 15 minutes?

Answer:-
A and B cross the bridge. A comes back. Time taken 3 minutes. Now B is on the other side.
C and D cross the bridge. B comes back. Time taken 8 + 2 minutes. Now C and D are on the other side.
A and B cross the bridge. Time taken is 2 minutes. All are on the other side.

Total time spent is 3 + 10 + 2 = 15 minutes.

Question:- You have 1000 wine bottles, one of which is poisoned. You want to determine which bottle is poisoned by feeding the wines to the rats. The poisoned wine takes one hour to work. How many rats are necessary to find the poisoned bottle in one hour?

Answer:-
Let's  take something simpler to explain: Suppose you have 8 bottles to test.   You can test this with 3 rats.  Each rat gets fed some of 4 bottles:

Rat A: #2, #5, #6, #8
Rat B: #3, #5, #7, #8
Rat C: #4, #6, #7, #8

If no rats die, then you know that #1 is poisoned.
If A dies, then you know #2 is poisoned.
If B dies, then you know #3 is poisoned.
If C dies, then you know #4 is poisoned.
If both A and B die, then you know #5 is poisoned.
If both A and C die, then you know #6 is poisoned.
If both B and C die, then you know #7 is poisoned.
If all the rats die, then you know #8 is poisoned.

So, for 8 bottles, you need 3 rats.

Turns out, with 1 rat, you can test 2 bottles.  With 2 rats, you can test up to 4 bottles.  With 3 rats, you can test up to 8 bottles.  With N rats you can test 2N bottles.  So for 1000 bottles, you need log21000, round up, which is ~9.965784 rats, rounded up to 10 rats.
N= rats
2N= 1000 =>
N = log2(1000) => ~ 9.9 = 10

Another Answer:-
The idea is to number bottles from 1 to 1000 and write their corresponding binary numbers on the bottle. Each rat is assigned a position in the binary numbers written on bottles. Let us take an example. Rat 1 represents first bit in every bottle, rat 2 represents second bit and so on. If rat numbers 5, 7 and 9 die, then bottle number 42 (Binary 0000101010) is poisoned.


We number the bottles from 1 to 1000 and write their corresponding binary numbers on the bottle.
Each bottle will have a binary number with 10 place digits since 2 to the power 10 = 1024.

Now, each rat is assigned a placeholder in the binary numbers so formed.
Rat 1 is assigned binary place 1.
Rat 2 is assigned binary place 2.
Rat 3 is assigned binary place 3.
and so forth and so on...

Each rat is given a sip from the bottle if the number on the bottle at the binary place assigned to him is 1 otherwise if it is 0, it doesn't take a sip.

Now for a bottle numbber 28 i.e 0000011100, Rat 3, Rat 4 and Rat 5 take a sip from that bottle. This way each rat takes(or not takes) a sip from many bottles depending upon binary number (0 or 1) appearing against his assigned binary place on that bottle.

Then we wait for an hour and to let rats die.

Imagine Rat 3,5,6 & 8 died. It means poisoned bottle would be:

(10) (9) (8) (7) (6) (5) (4) (3) (2) (1)
 0 0 1 0 1 1 0 1 0 0 = 0010110100 = 180

Hence bottle no. 180 was poisoned.

Question:- A man has a medical condition that requires him to take two kinds of pills, call them A and B. The man must take exactly one A pill and exactly one B pill each day, or he will die. The pills are taken by first dissolving them in water.

The man has a jar of A pills and a jar of B pills. One day, as he is about to take his pills, he takes out one A pill from the A jar and puts it in a glass of water. Then he accidentally takes out two B pills from the B jar and puts them in the water. Now, he is in the situation of having a glass of water with three dissolved pills, one A pill and two B pills. Unfortunately, the pills are very expensive, so the thought of throwing out the water with the 3 pills and starting over is out of the question. How should the man proceed in order to get the right quantity of A and B while not wasting any pills?

Answer:-
Add one more A pill to the glass and let it dissolve. Take half of the water today and half tomorrow. It works under following assumptions.

The dissolved Pills can be used next day.

The man has to take pills at least for one more day.

Question:-
You have 5 jars of pills. Each pill weighs 10 grams, except for contaminated pills contained in one jar, where each pill weighs 9 grams. Given a scale, how could you tell which jar had the contaminated pills in just one measurement?

Answer:-
Take out 1 pill from jar 1, 2 pills from jar 2, 3 pills from jar 3, 4 pills from jar 4 and 5 pills from jar 5. Put all these 15 pills on scale. The correct wight is 150 (15*10). But one of the jars has contaminated pills. So the wight will definitely less than 150. If the wight is 149 then jar 1 has contaminated pills because the there is only one contaminated pill. If the wight is 148 then jar 2, if the wight is 147 then jar 3, if 146 then jar 4, if 145 then jar 5.

Question:-
There is a room with a door (closed) and three light bulbs. Outside the room there are three switches, connected to the bulbs. You may manipulate the switches as you wish, but once you open the door you can’t change them. Identify each switch with its bulb.

Answer:-
Let the bulbs be X, Y and Z

Turn on switch X for 5 to 10 minutes. Turn it off and turn on switch Y. Open the door and touch the light bulb.

1. if the light is on, it is Y
2. if the light is off and hot, it is X
3. if the light is off and cold, it is Z

Question:-
There are 3 person in a forest, when they slept at night someone from outside colored their faces black(all three). Now when they wake up in the morning all three started laughing at each other thinking that the other two persons have black faces.
But after some time they realized that their own faces are also black and then they stop laughing at each other.
Here, you have to give a valid LOGICAL REASON that how they realized that their own faces are also black, i.e. all three faces are black.

Answer:-
Case 1: Only one guy is painted Assume C, Obviously C won't laugh. A and B will laugh.
Case 2 : Two guys were painted assume B and C, Then A will laugh for sure as B and C are painted.
if B is laughing it means C has painted pace as A doesn't have painted face.
if C is laughing it means, B has painted pace then he immediately stops laughing.
if both B and C are laughing, it means both B and C have painted face as they are aware that A doesn't have painted face. Immediately both B and C will stop laughing and A will continue to laugh.
Case 3 : All three are painted
A thinks that B and C are laughing by seeing each other. Similarly for B and C. So when All three are painted only All three will laugh.

Question:-
Two dice are thrown simultaneously. What is the probability of getting two numbers whose product is even?

Answer:-
In a simultaneous throw of two dice, we have n(S) = (6 x 6) = 36.

Then, E     = {(1, 2), (1, 4), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 2), (3, 4), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 2), (5, 4), (5, 6), (6, 1),
(6, 2), (6, 3), (6, 4), (6, 5), (6, 6)}

n(E) = 27.

P(E) =     n(E) / n(S)   =     27 / 36    =     3 / 4

Question:-
In a lottery, there are 10 prizes and 25 blanks. A lottery is drawn at random. What is the probability of getting a prize?

Answer:-
P (getting a prize) =     10 / (10 + 25)    =     10/35     =     2 / 7


Question:-
In a throw of dice what is the probability of getting number greater than 5.

Answer:-
Number greater than 5 is 6, so only 1 number
Total cases of dice = [1,2,3,4,5,6]

So probability = 1/6

Question:-
Three unbiased coins are tossed, what is the probability of getting at least 2 tails ?


Answer:-
Total cases are = 2*2*2 = 8, which are as follows
[TTT, HHH, TTH, THT, HTT, THH, HTH, HHT]

Favoured cases are = [TTH, THT, HTT, TTT] = 4

So required probability = 4/8 = 1/2

Saturday, July 29, 2017

Data Structure - Array

Q:- Find largest element in an array?
A:- The solution is to initialize max as first element, then traverse the given array from second element till end. For every traversed element, compare it with max, if it is greater than max, then update max.
Time complexity of the above solution is O(n).

Q:- Find Second largest element in an array?
A:-  A simple solution will be first sort the array in descending order and then return the second element from the sorted array. The time complexity of this solution is O(n Log n).

A Better Solution is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n*n).

A more Efficient Solution can be to find the second largest element in a single traversal. The time complexity of this solution is O(n).

1) Initialize two variables first and second to INT_MIN as,
   first = second = INT_MIN
2) Start traversing the array,
   a) If the current element in array say arr[i] is greater
      than first. Then update first and second as,
      second = first
      first = arr[i]
   b) If the current element is in between first and second,
      then update second to store the value of current variable as
      second = arr[i]
3) Return the value stored in second.


Q:- Find the smallest and second smallest elements in an array?
A:- A Simple Solution is to sort the array in increasing order. The first two elements in sorted array would be two smallest elements. Time complexity of this solution is O(n Log n).

A Better Solution is to scan the array twice. In first traversal find the minimum element. Let this element be x. In second traversal, find the smallest element greater than x. Time complexity of this solution is O(n * n).

The above solution requires two traversals of input array.

An Efficient Solution can find the minimum two elements in one traversal. Below is complete algorithm. Time complexity of this solution is O(n).

1) Initialize both first and second smallest as INT_MAX
   first = second = INT_MAX
2) Loop through all the elements.
   a) If the current element is smaller than first, then update first
       and second.
   b) Else if the current element is smaller than second then update
    second

Q:- Recursive program to linearly search an element in a given array?

class Test
{
     static int arr[] = {12, 34, 54, 2, 3};
     

/* Recursive Method to search x in arr[l..r] */
     static int recSearch(int arr[], int l, int r, int x)
     {
          if (r < l)
             return -1;
          if (arr[l] == x)
             return l;
          return recSearch(arr, l+1, r, x);
     }
     
     public static void main(String[] args)
     {
        int x = 3;
        int index = recSearch(arr, 0, arr.length-1, x);
        if (index != -1)
           System.out.println("Element " + x + " is present at index " +
                                                    index);
        else
            System.out.println("Element " + x + " is not present");
     }
 }


Q:- Find the largest three elements in an array?
A:- Expected time complexity is O(n) and extra space is O(1).

1) Initialize the largest three elements as minus infinite.
    first = second = third = -∞

2) Iterate through all elements of array.
   a) Let current array element be x. int x= arr[0];
   b) If (x > first)
      {
          // This order of assignment is important
          third = second
          second = first
          first = x  
       }
   c)  Else if (x > second)
      {
          third = second
          second = x
      }
   d)  Else if (x > third)
      {
          third = x 
      }

3) Print first, second and third


Q:- Program to cyclically rotate an array by one?
Input:  arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}

A:-
Following are steps.
1) Store last element in a variable say x.
2) Shift all elements one position ahead.
3) Replace first element of array with x.

Time Complexity: O(n)
Auxiliary Space: O(1)

Q:- Segregate 0s and 1s in an array?
Input array   =  [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output array =  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 
 
A:- Method 1 (Count 0s or 1s)
1) Count the number of 0s. Let count be C.
2) Once we have count, we can put C 0s at the beginning and 1s at the remaining n – C positions in array.

Time Complexity: O(n)

The method 1 traverses the array two times. Method 2 does the same in a single pass.

Method 2 (Use two indexes to traverse)
Maintain two indexes. Initialize first index left as 0 and second index right as n-1.

Do following while left < right
a) Keep incrementing index left while there are 0s at it
b) Keep decrementing index right while there are 1s at it
c) If left < right then exchange arr[left] and arr[right]


Q:- Find duplicates in O(n) time and O(1) extra space?
A:- 
 

Java Concurrency

Cyclic barrier :-  A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

When each thread reaches the barrier (common point) you need to call await() method on the CyclicBarrier object. This will suspend the thread until all the thread also call the await() method on the same CyclicBarrier object.
Once all the specified threads have called await() method that will trip the barrier and all threads can resume operation.
The barrier is called cyclic because it can be re-used after the waiting threads are released.

When using a CyclicBarrier, the assumption is that you specify the number of waiting threads that trigger the barrier. If you specify 5, you must have at least 5 threads to call await().

In a CyclicBarrier, if a thread has a problem (timeout, interrupted...), all the others that have reached await() get an exception.

Consider the same IT world scenario where manager divided modules between development teams (A and B). He goes on leave and asked both team to wait for each other to complete their respective task once both are done assign it to QA team for testing.

Here manager thread works as main thread and development team works as worker thread. Development team threads wait for other development team threads after completing their task.

Countdown latch :- A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.


When using a CountDownLatch, you specify the number of calls to countDown() that will result in all waiting threads being released. This means that you can use a CountDownLatch with only a single thread.

How CountDownLatch works in Java
CountDownLatch works in latch principle,  main thread will wait until Gate is open. One thread waits for n number of threads specified while creating CountDownLatch in Java. Any thread, usually main thread of application,  which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any more. So CoundDownLatch enables you to make a thread wait till all other threads are done with their execution.

Pseudo code can be:

// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution

Usage:-

Consider a scenario where we have requirement where we have three threads "A", "B" and "C" and we want to start thread "C" only when "A" and "B" threads completes or partially completes their task.

Consider a IT world scenario where manager divided modules between development teams (A and B) and he wants to assign it to QA team for testing only when both the teams completes their task.

Here manager thread works as main thread and development team works as worker thread. Manager thread waits for development teams thread to complete their task.

CountDownLatch is a synchronization aid, introduced in Java 5. Here the synchronization does not mean restricting access to a critical section. But rather sequencing actions of different threads. The type of synchronization achieved through CountDownLatch is similar to that of Join. Assume that there is a thread "M" which needs to wait for other worker threads "T1", "T2", "T3" to complete its tasks Prior to Java 1.5, the way this can be done is, M running the following code
        T1.join();
        T2.join();
        T3.join();
   

The above code makes sure that thread M resumes its work after T1, T2, T3 completes its work. T1, T2, T3 can complete their work in any order. The same can be achieved through CountDownLatch, where T1,T2, T3 and thread M share same CountDownLatch object.
"M" requests :  countDownLatch.await();
where as "T1","T2","T3" does  countDownLatch.countdown();

One disadvantage with the join method is that M has to know about T1, T2, T3. If there is a new worker thread T4 added later, then M has to be aware of it too. This can be avoided with CountDownLatch. After implementation the sequence of action would be [T1,T2,T3](the order of T1,T2,T3 could be anyway) -> [M]

Difference between CyclicBarrier and CountDownLatch
1. In CoundownLatch, the countdown value could not be reset, that can happen in the case of CyclicBarrier.

2. In CountDownLatch, there is one or more threads, that are waiting for a set of other threads to complete. In this situation, there are two types of threads, one type is waiting, another type is doing something, after finishes their tasks, they could be waiting or just terminated.

In CyclicBarrier, there are only one type of threads, they are waiting for each other, they are equal.

3. CountDownLatch is used for one-time synchronization. While CyclicBarrier is used for multiple synchronization points The barrier is called cyclic because it can be re-used after the waiting threads are released. Once the countdown reaches zero any further call to await() method won't block any thread. It won't throw any exception either.

4. One obvious difference is, only N threads can await on a CyclicBarrier of N to be release in one cycle. But unlimited number of threads can await on a CountDownLatch of N. The count down decrement can be done by one thread N times or N threads one time each or combinations.

5. In CountDownLatch, main threads waits for other threads to complete their execution. In CyclicBarrier, worker threads wait for each other to complete their execution.

Eg. CountDownLatch: Suppose a stone can be lifted by 10 people so you will wait for all 10 to come. Then only you can lift the stone.
CyclicBarrier: If you are going to a picnic, and you need to first meet at some common point from where you all will start your journey.

Phaser :- A Phaser is a synchronizer that can be used to synchronize a batch of threads (parties) where each party can register in the batch with phaser and then use the phaser to have them blocked until every thread in the batch has arrived (notified) the phaser and at that point any blocked thread will resume execution.

As we know CountdownLatch is not reusable whereas a CyclicBarrier is reusable but not very flexible. In both of them, number of registered parties (threads) for waiting cannot vary whereas they can vary in Phaser.

A Phaser is best of both worlds so we can say:

Phaser = CountdownLatch + CyclicBarrier

Phaser is more suitable for use where it is required to synchronize threads over one or more phases of activity. Though Phaser can be used to synchronize a single phase, in that case it acts more like a CyclicBarrier. But it is more suited where threads should wait for a phase to finish, then advance to next phase, wait again for that phase to finish and so on.

CyclicBarrier vs CountdownLatch vs Phaser



CountdownLatchCyclicBarrierPhaser
Fixed number of partiesFixed number of partiesDynamic number of parties
Non-cyclic in nature hence not reusablecyclic in nature hence reusableReusable
Can be advanced using countDown (advance) and await (must wait)Cannot be advancedCan be advanced using relevant methods.

http://niklasschlimm.blogspot.in/2011/12/java-7-understanding-phaser.html
http://flex4java.blogspot.in/2015/03/why-and-how-to-use-phaser-in-java.html


Exchanger :- makes it easy for two threads to exchange data between themselves.

Exchanger provides a synchronization point at which two threads can pair and swap elements. Exchanger waits until two separate threads call its exchange() method. When two threads have called the exchange() method, Exchanger will swap the objects presented by the threads.

Usage of Exchanger
Exchanger can be used in a Producer-Consumer scenarios where one thread will produce the data and exchange it with the consumer thread. Consumer thread in turn will pass the empty buffer to the producer thread.


Semaphore :- use to limit the number of threads that can proceed through a section of code, in this case we use a good old sleep to simulate a long lived operation

How Semaphore works

Thread that wants to access the shared resource tries to acquire a permit using acquire() method. At that time if the Semaphore's count is greater than zero thread will acquire a permit and Semaphore's count will be decremented by one.

If Semaphore's count is zero, when thread calls acquire() method, then the thread will be blocked until a permit is available.

When thread is done with the shared resource access, it can call the release() method to release the permit. That results in the Semaphore's count incremented by one.

ConcurrentHashMap

BlockingQueue:-
A blocking queue is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more items or clearing the queue completely.


ArrayBlockingQueue -
It uses an internal array in which the elements are kept, and the Queue interface imposes certain rules (like the FIFO rule, which is essential to any queue). Because it uses an array, it has a fixed size which is given in the constructor.
ArrayBlockingQueue keeps the elements in an array it needs only one lock to keep everything synchronized.

DelayQueue

LinkedBlockingQueue -
It uses nodes (like a linked list), to keep track of the order of the elements, which increases the complexity of the data structure. It can have a fixed-size limit as well, but if we don’t define one the limit is Integer.MAX_VALUE by default. LinkedBlockingQueue uses two locks, one for insertion and one for extraction.


https://examples.javacodegeeks.com/core-java/util/concurrent/linkedblockingqueue/java-util-concurrent-linkedblockingqueue-example/


PriorityBlockingQueue

SynchronousQueue

 

Wednesday, July 26, 2017

RESTful Services

Spring 4 MVC RESTful Service

Spring 4 provides support for developing RESTful services using Spring 4 @RestController annotation.

Spring 4 MVC based RESTful JSON service - Jackson library [jackson-databind.jar]

Spring 4 MVC based  RESTful XML service - Jackson XML extension library [jackson-dataformat-xml.jar]
Additionally, We will go a step further by annotating the domain class with JAXB annotations to support XML in case Jackson’s XML extension library is not available for some reason.

We are using @RestController annotation, which marks this class as a controller where every method returns a domain object/pojo instead of a view. It means that we are no more using view-resolvers, we are no more directly sending the html in response but we are sending domain object converted into format understood by the consumers. In our case, due to jackson library included in class path, the Message object will be converted into JSON format[ or in XML if either the jackson-dataformat-xml.jar is present in classpath or Model class is annotated with JAXB annotations].

In order to test it, you can use either the browser or a true-client.POSTMAN is a nice tool to test your REST Endpoints as in a real scenario. Advantage of Postman is that you can send the “Accept” header along with request which will then be used by Spring while sending the response in required format. With browsers it is not so straight-forward to send the “Accept” Header but you can suffix the URL with format[.json/.xml] to get similar results.

The key difference between a traditional Spring MVC @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML by registered HttpMessageConverters.

Traditional Spring MVC Workflow


    Step 1: The browser or client sends a request to the web application.
    Step 2: The request lands to the dispachter servlet and consult with handler mapping.
    Step 3: The Handler mappings defined in the application context file, this has information about which is controller need to be invoked.
    Step 4: The controller will be invoked and it can request the model for some information using DAOs and Services.
    Step 5: After Requests are processed by the Controller and the response is returned to the DispatcherServlet with logical view name
    Step 6: Then return to the view resolver prepared the view based on your configuration decide the which configuration (JSP, Velocity, PDF etc.) to be invoked.


@Controller
public class AccountController {
  @RequestMapping(value="/account", method=RequestMethod.GET)
  public ModelAndView get(Long accountId) {
   //Process model object
    return new ModelAndView("account-detail", model) ;
  }
}


Spring MVC REST Workflow



    Step 1: The client sends a request to a web service in URI form.
    Step 2: The request lands to the dispachter servlet and consult with handler mapping.
    Step 3: The Handler mappings defined in the application context file, this has information about which is controller need to be invoked.
    Step 4: The controller will be invoked and process model.
    Step 5: Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.


@Controller
public class restClassName{

  @RequestMapping(value={"/uri"})
  @ResponseBody
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}


In Traditional Spring MVC Workflow, notice that controller return the ModelAndView object with logical view name to dispactcher servlet, it is forwarded to the ViewResolver in step 6. But in the Spring MVC REST Workflow, Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. As of Spring Version 4.0, this process has been more simplified by the @RestController annotation.

Using the @ResponseBody Annotation
If any handler method of controller class is annotated with @ResponseBody, Spring converts the return value of this method and writes it to the http response automatically. @ResponseBody is treated as the view here among MVC and it is dispatched directly instead being dispatched from Dispatcher Servlet and the respective converters convert the response in the related format like text/html, application/xml, application/json .

What is Behind the @ResponseBody
There is a list of HttpMessageConverters registered in the background when we enable Spring web mvc feature to the web application by using @EnableWebMvc or <mvc:annotation-driven> namespace. HTTPMessageConverter is responsible to convert the request body to a specific class and back to the response body again, depending on a predefined mime type.

Spring 4 MVC REST Controller Service

 

@RestController annotation is introduced as of Spring 4.0, it is actually combination of @Controller and @ResponseBody. It is a convenience way to use this annotation instead of using @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default.



@RestController
public class restClassName{

  @RequestMapping(value={"/uri"})
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

So @RestController let's you expose Rest APIs in Spring 4.0 and above.

Can @Controller annotation be used for both Web MVC and REST applications?
If yes, how can we differentiate if it is Web MVC or REST application.

Monday, July 24, 2017

MVC Framework

In the beginning there was darkness (and simplicity). The only things that existed were static html pages. They would have html and text, and that's it.
Soon after, Servlets were created to allow dynamic pages to be written using the Java language.

public class ABCServlet extends HttpServlet
{
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
   PrintWriter out = response.getWriter();
   out.println("<html><head><title>A Nice Servlet</title></head><body>");
   out.println("The nice body of this servlet displays the date for you: "+(new java.util.Date()));
   out.println("</body></html>");
   out.close();
 }
}

But things became complicated, because creating large dynamic html page content with lots of data required many lines of out.println() statements. So something else came along.

With the creation of JSP pages, you could now write a Scriptlet or Expression, Standard Actions, EL (JSP Expression Language), JSTL and the Servlet Container (eg. Tomcat) would dynamically generate all the servlet code for you automatically (eg. all the out.println() statements).

MVC is a systematic way to use the application where the flow starts from the view layer, where the request is raised and processed in controller layer and sent to model layer to insert data and get back the success or failure message.

Servlet/JSP MVC architecture :-

1. A form(html/jsp) with two variables "email" and "password" which is our view layer.
2. Once the user enters email, and password and clicks on submit then the action is passed in MVCServlet where email and password are passed.
3. This MVCServlet is controller layer(servlet). Here in MVCServlet the request is sent to the bean object which act as model layer(bean).
4. The email and password values are set into the bean and stored for further purpose.
5. From the bean, the value is fetched and shown in the view layer(jsp).


form.jsp(View)
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!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">
    </head>
    <body>
    <form action="MVCServlet" method="POST">
    Email: <input type="text" name="email">
    <br />
    Password: <input type="text" name="password" />
    <input type="submit" value="Submit" />
    </form>
    </body>
    </html>

browser sends http request to web server, container create httpServletRequest and httpServletResponse objects for this http request. Now container see requested url and maps to specific servlet
reuest.getURL() -> server:port/hello
/hello -> mapping HelloServlet (Controller)
Model
View


MVCServlet.java(Controller)
public class MVCServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String email=request.getParameter("email"); 
        String password=request.getParameter("password");
       
        TestBean testobj = new TestBean();
        testobj.setEmail(email);
        testobj.setPassword(password);
        request.setAttribute("testbean",testobj);
        RequestDispatcher rd=request.getRequestDispatcher("mvcsuccess.jsp"); 
        rd.forward(request, response);
    }

}

TestBean.java(Model)
public class TestBean implements Serializable{
   
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    private String email="null";
    private String password="null";
}

mvcsuccess.jsp(View)
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@page import="demotest.TestBean"%>
    <!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">
    </head>
    <body>
    <% 
    TestBean testguru=(TestBean)request.getAttribute("testbean"); 
    out.print("Welcome, "+testguru.getEmail()); 
    %>
    </body>
    </html>



Spring MVC Framework :-
Spring MVC is based on servlet and jsp technology implement model-view-controller design pattern.


Spring MVC framework is designed around a central Servlet called DispatcherServlet that handles all the HTTP requests and responses. It is completely integrated with the Spring IoC container so it allows you to use every feature that Spring has.

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −

1. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.

2. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.

3. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.

4. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.

<web-app>
  <display-name>Archetype Created Web Application</display-name>
 
  <servlet>
        <servlet-name>spring</servlet-name>
            <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>

    <init-param>
        <param-name>contextConfigLocation</param-name> //setter method
        <param-value>/WEB-INF/webApplicationContext.xml</param-value> //custom name
    </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
   
</web-app>


By default,
DispatcherServlet loads its configuration file using <servlet-name>-servlet.xml.
E.g. with above web.xml file, DispatcherServlet will try to find spring-servlet.xml file in classpath.

DispatcherServlet (actually a servlet) is the front controller in Spring MVC that intercepts every request and then dispatches/forwards requests to an appropriate controller. 

Listener class - Listens on an event

ContextLoaderListener -
    1. Listens during server start up/shutdown
    2. Reads the spring configuration file (with value given against “contextConfigLocation” in web.xml), parse it and loads the beans defined in that config file(destroys the bean during shutdown)
    3. Configuration files can be provided in web.xml
    
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>


Basically you can isolate your root application context and web application context using ContextLoaderListner.

The config file mapped with context param will behave as root application context configuration. And config file mapped with dispatcher servlet will behave like web application context.

We should define our common services, entities, aspects etc in root application context. And controllers, interceptors etc are in relevant web application context.

OR When you want to put your Servlet file in your custom location or with custom name, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.

Sunday, July 23, 2017

Dependency Injection

DI:- passing needed dependencies into the object externally instead of having it construct them itself OR asking a factory object to make one of them.

class SomeClass{

MyObject myObject;
   public SomeClass(){
     myObject = factory.getObject();
   }

}

class SomeClass{

   public SomeClass(MyObject myObject){
     this.myObject = myObject;
   }

}

It allows us to remove hard-coded dependencies and make application loosely coupled, extendable and maintainable.

Eg. 
without DI:-
Switch needs to know beforehand which bulb I am connected to (hard-coded dependency). So,
Switch -> PermanentBulb //switch is directly connected to permanent bulb, testing not possible easily
with DI:-

Switch only knows I need to turn on/off whichever Bulb is passed to me. So,
Switch -> Bulb1 OR Bulb2 OR NightBulb (injected dependency)



Two types of Dependency Injection:

    Constructor Injection
    Setter Injection

1. Constructor-based dependency injection:
Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.


public class Triangle {

private String type;

public String getType(){
    return type;
 }

public Triangle(String type){   //constructor injection
    this.type=type;
 }
}
<bean id=triangle" class ="com.test.dependencyInjection.Triangle">
        <constructor-arg value="20"/>
</bean>

2. Setter-based dependency injection:
Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.


public class Triangle{

 private String type;

 public String getType(){
    return type;
  }
 public void setType(String type){          //setter injection
    this.type = type;
  }
 }

<!-- setter injection -->
 <bean id="triangle" class="com.test.dependencyInjection.Triangle">
        <property name="type" value="equivialteral"/>
</bean> 
 

NOTE: It is a good rule of thumb to 
Use Constructor Injection when object must be created with all of its dependency(mandatory dependencies).
Use Setter injection when a number of dependencies are more or you need readability(optional dependencies). 

Note that the if we use annotation based than @Required annotation on a setter can be used to make setters as a required dependencies.

If Object A and B are dependent on each other i.e A is depends on B and vice-versa. Spring throws ObjectCurrentlyInCreationException while creating objects of A and B because A object cannot be created until B is created and vice-versa. So spring can resolve circular dependencies through setter-injection. Objects constructed before setter methods invoked.

Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.

One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible with constructor injection because every time you call the constructor, a new object is gets created.


How do we implement DI in Spring Framework?

We can use Spring XML based(defined above) as well as Annotation based configuration to implement DI in spring applications.

@Autowired annotation is used to let Spring know that DI is required. This can be applied to field, constructor and methods level.

    //field-based dependency injection
    @Autowired
    private MessageService service;

    //constructor-based dependency injection  
    @Autowired
    public MyApplication(MessageService svc){
        this.service=svc;
    }
   
    //setter-based dependency injection
    @Autowired
    public void setService(MessageService svc){
        this.service=svc;
    } 


So, Dependency Injection is a design pattern, and @autowired is a mechanism for implementing it.
The DI idea is that, instead of your object creating an object it needs (say by using new to instantiate it), this needed object - a dependency - is handed to your object, typically using the constructor or a setter method.
If you autowire, you're injecting a dependency. In this case, Spring uses reflection to make this work, so you're not using the constructor or a setter method, but you're still injecting the dependency.

Saturday, July 22, 2017

Session Management

HTTP Protocol/Web Server both are stateless by design, meaning that for web server, every request is a new request to process and they can’t identify if it’s coming from client that has been sending request previously. So you connect to the server, talk back and forth, then disconnect.

But real-world applications often do require state, we should know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client.

So, idea behind session management is to put requests from the same client in the same context, the concept of the HTTP Session exists.

All the HTTP Session is is the application state information relating to one particular client. A client being a single instance of an HTTP client application program. Or simply illustrated, if my desktop computer has IE and FireFox both communicating with the server, that's 2 clients. Regardless of how many windows and tabs they are using.

In order to associate a client's identify with a particular state-set on the server, you need some sort of identity. Hardware MAC addresses won't do it - they cannot be seen outside the local LAN segment. IP addresses won't do it either.

So lacking a reliable third-party identity mechanism, J2EE uses HTTPSession and jSessionId. The HTTPSession lives exclusively on the server and its most important feature is Map mechanism that holds objects stored in Session context and the User's login context - if the user has logged in via Container Security Services. So, Session management is server responsibility.

When the session is created, a session token(identifier/jSessionId) is generated and sent to the client (stored in a cookie). After that, in next subsequent requests between client and server, the client sends the session token(jSessionId) as an HTTP cookie in every HTTP request header, so that server can identify it. All session data is stored on the server, the client only stores the session token.

==> server is basically doing fetching the HTTPSession object from the session map via its key (jsessionid)

Server session map => (key, value) => (jSessionId, HTTPSession object)

This is an abstract Map - a really heavy-duty server might be paging sessions out in and out of files, databases or other persistent storage - or bouncing it between servers in a cluster, but from the application developer's point of view, it's there when it needs to be.

The jsessionid may NOT be the same value on every request/response cycle. It is not the case that the jsessionid is sent to the client, cached there and re-used on all subsequent requests. The jsessionid is whatever jsessionid was returned from the previous request response.In particular, for security reasons, when you switch to https (secure) transmission, the old jsessionid becomes invalid. A new jsessionid is returned from the secure response. Since the jsessionid is a "random" value with absolutely no information carried in it other than its own value, what the server is basically doing is fetching the HTTPSession from the session map via its old key (jsessionid), generating a new jsessionid, storing the session in the session map under the new key (jsessionid), and removing the old key/value from the map. Actual order and mechanism may vary, but that's the net effect.

There are several ways through which we can provide unique identifier in request and response.

User Authentication – This is the very common way where user can provide authentication credentials from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it won't work if the same user is logged in from different browsers.

HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session.

URL Rewriting – We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters.

Cookies – Cookies are small piece of information(key/value pair) that is sent by web server in response header and gets stored in the browser cookies. When client make further request, it adds the cookie to the request header and we can utilize it to keep track of the session. We can maintain a session with cookies but if the client disables the cookies, then it won’t work.

Session Management API – Session Management API is built on top of above methods for session tracking. Some of the major disadvantages of all the above methods are:

    Most of the time we don’t want to only track the session, we have to store some data into the session that we can use in future requests. This will require a lot of effort if we try to implement this.
    All the above methods are not complete in themselves, all of them won’t work in a particular scenario. So we need a solution that can utilize these methods of session tracking to provide session management in all cases.

Understanding JSESSIONID Cookie

A "JSESSIONID" is the unique id of the http session. "Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another another."

So when you first hit a site, a new session is created and bound to the SevletContext. If you deploy multiple applications, the session is not shared.

JSESSIONID cookie is created/sent when http session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want to get the session, but not create it if it doesn't exist, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent.

Note: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the session='false' page directive, in which case session variable is not available on JSP page at all.

Friday, July 21, 2017

Spring Security

Spring Security is a lightweight security framework that provides authentication and authorization support in order to secure spring-based applications. It integrates well with Spring MVC and comes bundled with popular security algorithm implementations.

Two major areas of application security are “authentication” and “authorization” (or “access-control”). These are the two main areas that Spring Security targets.

"Authentication" is the assurance that the user is actually the user he is claiming to be, for example, when the user logs into any application and gives his credentials, he authenticates himself. At the authentication level, spring supports various authentication models such as Http Basic authentication, Form Based authentication.

"Authorization" is the assurance that the user is allowed to access only those resources that he is authorized to use. For example, in a corporate application, there are some parts of an application where only admin have access and to some parts all the employees have access. These access rules are determined by the access rights given to each user of the system. At the authorization level, spring targets three main areas: authorizing web request, authorizing whether methods can be invoked and authorizing access to individual domain object instances.

Security Namespace Configuration-
To start using the security namespace in your application context, you first need to make sure that the spring-security-config jar is on your classpath. Then all you need to do is add the schema declaration to your application context file:

    <beans xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
              http://www.springframework.org/schema/security
              http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
        ...
    </beans>

web.xml Configuration-
    <filter>
      <filter-name>springSecurityFilterChain</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security(protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc). Note that you should not use this bean name yourself.

We can now configure the security XML for different security related options like authentication model, login page, access denied page etc..

Authentication Model:
Here we decide which authentication model you will use for your web application. Option could be any of the above(LDAP, Open ID..). Once decided same could be configured via “<authentication-manager></authentication-manager>” tag.

1.
<authentication-manager>
     <authentication-provider>
     <user-service>
     <user name="user1" password="password" authorities="ROLE_USER, ROLE_ADMIN" />
     <user name="user2" password="password" authorities="ROLE_USER" />
     </user-service/>
     </authentication-provider>

</authentication-manager>

Here user and their roles have been hard coded in XML itself and user will be authenticated and authorized on given basis. Two user has been created with password as “password” and there are roles are “ROLE_USER, ROLE_ADMIN”.

2.
<authentication-manager>
     <authentication-provider ref="ldapActiveDirectoryAuthProvider"></authentication-provider>
</authentication-manager>
    
<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
     <constructor-arg value="abc.xyz.com"/>
     <constructor-arg value="ldaps://abc.xyz.com:636"/>
     </bean>

Here user will be authenticated and authorized via LDAP server(In current Situation Active Directory).

3.
     <authentication-manager>
     <authentication-provider>
     <jdbc-user-service data-source-ref="dataSource" />
     </authentication-provider>
     </authentication-manager>


Here user will be authenticated and authorized on the basis of table(USERS & AUTHORIZATION) in DB. datasource will be used to access the given tables in DB. Structure of the tables should be.

<code class="language-css">
CREATE TABLE USERS (USERNAME VARCHAR2, PASSWORD VARCHAR2,ENABLED VARCHAR2); 
CREATE TABLE AUTHORITIES(USERNAME VARCHAR2, AUTHORITY VARCHAR2);
</code>

A Minimal <http> Configuration-
We might have to configure login, logout page and role based URL access.

<http auto-config="true">
<intercept-url pattern="/**" access="ROLE_USER" />
</http>

Which says that we want all URLs within our application to be secured, requiring the role ROLE_USER to access them.
The <http> element is the parent for all web-related namespace functionality.
The <intercept-url> element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax.
The access attribute defines the access requirements for requests matching the given pattern.

With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.
The prefix "ROLE_" is a marker which indicates that a simple comparison with the user's authorities should be made.

In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes).

The attribute "auto-config=true" defines three elements

    <http>
     <form-login />
     <http-basic />
     <logout />
     </http>


The default configuration always chooses http-basic authentication model. If the model needs to be changed to the form-login model, then the following configuration is needed.

Login page configure

<form-login login-page='/login.jsp' default-target-url='/home.jsp' always-use-default-target='true' />

Here we have configured login page as “login.jsp” and user will be redirected to “home.jsp” after login(By default-target-url) always-use-default-target is used to set if user will be redirected to “default-target-url” at all time or not?

If true user will be redirected to home.jsp even user was on any other page when session timed-out.

If false user will not be redirected to home.jsp always means user will be on the same page where users session has timed out or on home.jsp when login for the first time.

Role based URL access configure

<intercept-url pattern="/**" access="ROLE_USER" />

Note*: Now all the URl can be accessed by only those who have the authority of “ROLE_USER”. Static part configuration to bypass all security.

<http pattern=”/login.jsp*” security=”none”/>


Access denied page configuration

<access-denied-handler error-page="/accessdenied.jsp" />

Logout page & logout link configuration
 
 <logout logout-url="/logout" logout-success-url="/logoutPage.jsp" />


Session Management Configuration

     <session-management>
     <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
     </session-management>


Here we have defined that user can have 1 session at max.

error-if-maximum-exceeded is used to define what should be happend when user tries to create more then one session.

If it is true : User will get error page stating that user can not have more then one session if it already has one active session.
If it is false: User will not get any error while trying to login to application(Creating another session) but other session will get invalidated and user will have only have new session.


The architecture of secured web requests

How requests are processed?
The Spring Security architecture relies heavily on the use of delegates and servlet filters to provide layers of functionality around the context of a web application request.

The automatic configuration attribute(<http auto-config="true">) in the Spring Security XML configuration file sets up a series of 10 servlet filters, which are applied in a sequence through the use of a Java EE servlet filter chain. The filter chain is a Java EE Servlet API concept specified by the javax.servlet.FilterChain interface that allows a web application to direct that a chain of servlet filters should apply to any given request.

Request travel along the chain, being processed by each filter in turn, finally arriving at the destination servlet(dispatcher servlet).

You may also configure the filter chain entirely from scratch. Although this is tedious, as there are many dependencies to wire, it can provide a high level of flexibility in configuration and application suitability matching.

What does auto-config do behind the scenes?
Provides 3 authentication-related functions:
• HTTP basic authentication
• Form login authentication
• Logout

How users are authenticated?
When a user provides credentials in our login form, these credentials must be verified against a credential store in order to proceed any further in our secured system. Verification of the credentials presented involves a series of logical components that are used to encapsulate aspects of the authentication process.


What is spring_security_login and how did we get here?
when you attempted to hit http://localhost:8080/ you were redirected to the URL http://localhost:8080/spring_security_login

The spring_security_login portion of the URL represents a default login page as named in the DefaultLoginPageGeneratingFilter class. We can use configuration attributes to adjust the name of this page to be something unique to our application.
Let's look at the HTML source of this form to figure out what the UsernamePasswordAuthenticationFilter is expecting:

<form name='f' action='/j_spring_security_check' method='POST'>
User:<input type='text' name='j_username' value=''>
Password:<input type='password' name='j_password'/>
<input name="submit" type="submit"/>
<input name="reset" type="reset"/>
</form>



'/j_spring_security_check' This is a special URL that is watched for by the UsernamePasswordAuthenticationFilter to handle form-based login.

Where do the user's credentials get validated?
In our simple three-step configuration file, we used an in-memory credential store to get up and running quickly:
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user authorities="ROLE_USER" name="guest" password="guest"/>
</user-service>
</authentication-provider>
</authentication-manager>


The DaoAuthenticationProvider is an AuthenticationProvider that provides a thin wrapper to implement the AuthenticationProvider interface and then delegates to an implementation of the o.s.s.core.userdetails. UserDetailsService interface. The UserDetailsService is responsible for returning an implementation of o.s.s.core.userdetails.UserDetails.

Exceptions and others propagate up the filter chain, and are typically expected and handled gracefully by request-processing filters, either by redirecting a user to an appropriate page (login or access denied), or by returning appropriate HTTP status codes, such as HTTP 403 (Access Denied).


How requests are authorized?
The final servlet filter in the default Spring Security filter chain, FilterSecurityInterceptor, is the filter responsible for coming up with a decision on whether or not a particular request will be accepted or denied. At this point the FilterSecurityInterceptor filter is invoked, the principal has already been authenticated, so the system knows that they are valid users. Remember that the Authentication interface specifies a method ( List<GrantedAuthority> getAuthorities() ), which returns a list of authorities for the principal. The authorization process will use the information from this method to determine, for a particular request, whether or not the request should be allowed.

Remember that authorization is a binary decision—a user either has access to a secured resource or he does not. There is no ambiguity when it comes to authorization.
Smart object-oriented design is pervasive within the Spring Security framework, and authorization decision management is no exception. Recall from our discussion earlier in the chapter that a component known as the access decision manager is responsible for making authorization determinations.
 

In Spring Security, the o.s.s.access.AccessDecisionManager interface specifies two simple and logical methods that fit sensibly into the processing decision flow of requests:

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...