Search

Wednesday, February 25, 2015

How To Handle/Working With IFrame In Selenium WebDriver

Working with Iframes In webdriver was pending post from long time. Earlier we learnt, how to switch between windows In THIS POST. Also we learnt trick to switching between window tabs In THIS POST. If you are working with selenium IDE then you can use "selectframe" command to select and switch to IFrame as described In THIS POST.

Working with Iframe and page content
IFrame Is another web element and you can not locate Its element directly In selenium webdriver. To work with IFrame element In selenium webdriver, first of all you need to select that IFrame using syntax like bellow.

//switch to frame1. frame1 Is ID of frame.
driver.switchTo().frame("frame1");

Now you can work with any element which Is Inside frame1. Now supposing you wants to switch back to page content then you need to use syntax like bellow.
//Switch back to page content.
driver.switchTo().defaultContent();

After above syntax execution, You can work with page elements.

Working with multiple frames on same page
If there are multiple Iframes on single page then you can not directly navigate from Iframe1 to IFrame2. For that, You need to select page In between as bellow.
//switch to frame1
driver.switchTo().frame("frame1");
driver.findElement(By.xpath("//td[contains(text(),'Cow')]/preceding-sibling::td/input[@type='checkbox']")).click();

//Switch back to page content.
driver.switchTo().defaultContent();

//switch to frame2
driver.switchTo().frame("frame2");
driver.findElement(By.xpath("//input[@value='Boat']")).click();

Full example to switch from page to IFrame, Iframe to page and Iframe to Iframe Is as bellow.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Iframes {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2015/01/iframe1.html");
}

@Test
public void handleFrames(){
//Working with page element.
//Inserting some text In Town textbox of page.
driver.findElement(By.xpath("//input[@name='Town']")).sendKeys("Your town");

//Working with Iframe1 elements
//switch to frame1 and select cow checkbox from table. frame1 Is ID of frame.

driver.switchTo().frame("frame1");
driver.findElement(By.xpath("//td[contains(text(),'Cow')]/preceding-sibling::td/input[@type='checkbox']")).click();

//Switch back to page content.
driver.switchTo().defaultContent();

//Working with Iframe2 elements
//switch to frame2 and select I have a boat checkbox. frame2 Is ID of frame.

driver.switchTo().frame("frame2");
driver.findElement(By.xpath("//input[@value='Boat']")).click();

//switch back to page to Inserting some text In Country textbox of page.
driver.switchTo().defaultContent();
driver.findElement(By.xpath("//input[@name='Country']")).sendKeys("your country");
}
}

This way, you can handle IFrames In selenium webdriver.

Find the first non repeated character in a string : Technical interview question

In written exams or in technical interview  of Amazon , you can easily find this question . So in order to help you for the preparation of interview , we are answering this question in this post .

First we need to understand the question , we need to write an algorithm for  the first non repeated character in a string , for example :

Read Also :   Count number of words in the String

If the word "stress" is input  then it should print  't'   as output .

If the word "teeter" is input  then it should print  'r'   as output .

Now , we should understand the pseudo algorithm or logic to achieve this task , code is given in the end of this post .

Logic

As we know a non repeated character occurs only once in the string , so if we store the number of times
each alphabet appears in the string , it would help us identifying which characters are non repeated characters in the string .So we need to scan the whole string and determine the final counts of each character . Now scan the final values of each character in the string , the first character in the string with final count 1 is the first non repeated character in the string.

Pseudo Algorithm

1.   First create the  character count hash table .
 
          For each character
            If there is no value stored in the character
                     set it to 1 .
            else
                     increment the value of the character by 1 .

2.  Scan the string
           For each character
           return character if the count in hash table is 1 .
           If no character have count 1 , return null

Read Also :   Count total number of times each alphabet appears in the String


first non repeated character in the string java example













Code :



import java.util.HashMap;
import java.util.Scanner;


public class FirstNonRepeated {

public static void main(String[] args)
{
// TODO Auto-generated method stub

System.out.println(" Please enter the input string :" );
Scanner in = new Scanner (System.in);
String s=in.nextLine();
char c=firstNonRepeatedCharacter(s);
System.out.println("The first non repeated character is : " + c);
}

public static Character firstNonRepeatedCharacter(String str)
{
HashMap<Character,Integer> characterhashtable= 
                     new HashMap<Character ,Integer>();
int i,length ;
Character c ;
length= str.length(); // Scan string and build hash table
for (i=0;i < length;i++)
{
c=str.charAt(i);
if(characterhashtable.containsKey(c))
{
// increment count corresponding to c
characterhashtable.put( c , characterhashtable.get(c) +1 );
}
else
{
characterhashtable.put( c , 1 ) ;
}
}
// Search characterhashtable in in order of string str

for (i =0 ; i < length ; i++ )
{
c= str.charAt(i);
if( characterhashtable.get(c) == 1 )
return c;
}
return null ;
}
} 

Sunday, February 22, 2015

What is Apache Storm? How is it related to potato chips?

Logo of Apache Storm project

Previously, we have seen what is Big data, now let us look at a framework that lets you operate with big data. You might have known what is a framework, it is nothing but that which provides you the classes and interfaces to do a particular job easily. The term easily is very important here. It hides all the stuff that you don't need to worry about, by itself taking that burden.

Now, let us come to Storm. In general, a storm comes and goes at a blazing speed, perhaps in seconds. Such is the speed with which we need to process big data and Apache storm does exactly that. But what does it do and how does it do, is worth discussing about.

Apache storm processes a stream of data i.e. the data is continuous here. In simple terms, the data keeps on flowing.

Understanding Storm with potato chip factory  

Processing the potatoes in a factory
See how the potatoes are processed here

Just consider a potato chip factory. Here, first the potatoes are unloaded from the truck and sent into the factory. These potatoes are undergone to several stages.
1. The potatoes are cleaned.
2. Next, they are tested whether they are good or not.
3. Next, they are peeled.
4. Next, they are cut into the desired shape.
5. Next, they are fried
6. Next, a flavor is added to them.
7. Finally, they are sent into the packets.

The same potatoes undergo all these stages. In a similar way, the data is also undergone to several operations and each operation is called as a Bolt in storm. You got the potatoes from the truck, that means the truck here is the source of potatoes. So, the source of the data is called as a Spout in storm. After first stage is completed, the potatoes move to the 2nd stage. So, the 1st stage acts as a spout to the 2nd stage.
Now, all the spouts and the bolts are together called as topology in storm.

The important point you need to remember that process these potatoes. The machine to clean a potato is different, and the machine to test it is different, the peeler is different and so on. But all are connected to each other. Remember also, that these machines keep on running. They never stop because the potatoes keep on coming.
In a similar way, the data keeps on flowing and you do the operations. The programs that perform these operations keep on running. You only give them the data. They are not run when you provide the data and terminate when the operation is complete. If there is no data, then the program will be idle i.e. it will be in memory but doesn't do any job. So, the topology will be running always and when you give the data the operations are performed.

The birth of Storm

Apache storm is actually introduced by Twitter and is now an Apache project under incubation. But it is used in production environment. It is used by many companies like Twitter, Yahoo, Yelp, Groupon etc.

Apache storm as it is a big data framework, the bolts are executed in parallel i.e. bolts are distributed among several systems. So processing happens in sub-second latency. There is a terminology for storm which you need to master to understand it. Let us go through it.

Apache Storm terminology

Bolt: A program that performs an operation on the data. There can be any number of bolts in a topology. Each bolt does one operation. The operations can include anything, from modifying the data to performing calculations, logging or storing in the database.

Spout: The source of data is called as spout. It produces data to the bolts for processing. The spout can be anything, it can be a http request or a messaging queue. For example, if you want to process some tweets, then you need to listen to a Http port which takes in those tweets and these tweets will be stream of data.

Tuple: The part of the data that is processed by a bolt. As we have discussed before, Storm processes a stream of data i.e. the data keeps on flowing. A stream of data is a collection of several datum.
For example, if tweets are a stream of data that keeps on flowing, then every tweet is called as tuple. This tuple is processed by the bolt. The spout produces a series of tuples.

Topology: Bolts and spouts together are called as a topology. The topology contains spouts and bolts and also the connections between them. For example, in the above example, there is a sequence of processes, the potatoes cannot undergo those processes as they like. For example, they cannot be fried until they are peeled and cut. So, there is a flow of execution. In a similar way, you specify which bolt should execute first and which one next. Because, one bolt can depend on another.

Stream: It is a sequence of tuples which have no limits. It is a continuous flow of tuples.

Fields: Every tuple will have one or more fields. A field is nothing but a key-value pair. As, we have seen before, a tuple is a datum processed by the bolt. A tuple can be anything, from a simple String object or a Student object.
Consider, for example, that we need to process a Student information. Obviously, the student will contain many fields like sno, sname, age etc. Now, the fields will be sno, sname, age and they contain corresponding values.

There is more terminology, to be explored, but I don't want to clutter this post with all that. These are the basic terms.

A simple practical example

Consider that I want to store a student information. The student gives only name and age. Now, I need to generate sno. So, I have got two bolts as follows.

Spout: HTTP source
Bolt 1. To generate sno
Bolt 2. To store student object in database.

The spout will contain student objects where every object is a tuple and each tuple contains only sname and age since sno is to be generated by the bolt 1.
Now, bolt 1 generated a new sno. Now, we need to add the sno to the existing tuple and send it to bolt 2.
So, we add an additional field named sno with the generated value, say 101.

How To Open Tab And Switching Between Tabs In Selenium WebDriver

Earlier we have learnt about how to switching between windows In selenium webdriver as described on THIS PAGE. and work with multiple IFrames In THIS POST. As all of us are used to work with multuple tabs, some peoples don't like to work with multiple windows. So main question Is -> How to open new tab In selenium webdriver test and then how to switch between two tabs and take required actions. Also you can close all tabs using Robot class as described In THIS POST.

How to open new tab
WebDriver do not have any built In method using which we can open new tab. Normally we are using CTRL + t Keys to open new tab In Browser. We can do same thing In webdriver test for opening new tab In selenium webdriver, Bellow given syntat will open new tab In your driver browser Instance.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

How to switch between two tabs
For switching between tabs of browser, We are using CTRL + Tab keys. Same way, bellow given syntax will switch between tabs and select the content of selected tab.

//Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
//Switch to current selected tab's content.
driver.switchTo().defaultContent();

I have created simple example on tab switching for your better understanding. It will Open new tab and then switch between them to perform different actions on both tab's pages.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Tabs {

WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}

@Test
public void openTab() {
//Open tab 2 using CTRL + t keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Open URL In 2nd tab.
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");

//Call switchToTab() function to switch to 1st tab
switchToTab();
//perform required actions on tab 1.
driver.findElement(By.xpath("//input[@id='6']")).click();
driver.findElement(By.xpath("//input[@id='plus']"));
driver.findElement(By.xpath("//input[@id='3']"));
driver.findElement(By.xpath("//input[@id='equals']"));

//Call switchToTab() function to switch to 2nd tab.
switchToTab();
//perform required actions on tab 2.
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("hi");
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("test");

//Call switchToTab() function to switch to 1st tab
switchToTab();
//perform required actions on tab 1.
String str = driver.findElement(By.xpath("//input[@id='Resultbox']")).getAttribute("value");
System.out.println("Sum result Is -> "+str);
}

public void switchToTab() {
//Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
//Switch to current selected tab's content.
driver.switchTo().defaultContent();
}
}

This way, We can use keyboard actions to switch between tabs In selenium webdriver.

Friday, February 20, 2015

The "Earnings Gappers" Watchlist

Hi folks,

I wanted to share with you all a specific watchlist which i track closely in my daily routine. I call it the "Earnings Gappers" watchlist. The idea is pretty simple: I simply wait till AFTER a stock(company) reports their earnings and watch it closely and see how it closes on that day. If i see a STRONG candle on humongous volume on the close, i automatically add it to my "Earnings Gappers" watchlist.  This watchlist will essentially hold only the "winners". Stocks that reported outstanding earnings and the stock reacted very positively. Stocks that act well after earnings reports have a reliable tendency to keep running higher.

Some of these names end up as either "Trade Alerts" for ART OF TRADING members and/or actual setups which i email to AoT members as well. Some people might say, these stocks are 'too extended and hard to buy them now'; But I do not mind chasing stocks that reported great earnings and are now showing strong technical qualities as the chance of these stocks running even higher is very strong. Sometimes, you have to pay up for a quality name that has proven itself.

Here are a few examples I've added to this list recently.









ART OF TRADING  Member Reviews : HERE
 








Wednesday, February 18, 2015

Capturing Page JavaScript Errors Using Selenium WebDriver

It Is very Importnt to find Javascript errors on web page before any application's release. Generally Test engineer Goes to each and every page manually and check If there Is any java script error on page. It can take very much time. We can automate this task using selenium webdriver Instead of doing It manually.

How to Find JS errors using selenium webdriver
Selenium WebDriver do not have any built In method or function using which we can collect JS errors from page. For that you need to download "JSErrorCollector-0.5.jar" file from THIS PAGE and Include It In your project's build path. You can refer "Adding jar Files In Project's Build Path" section on THIS PAGE If you don't know how to add It.

Now you can create bellow given example In your eclipse. I have used page with javascript error.

package Testing_Pack;

import java.util.List;
import java.util.concurrent.TimeUnit;
import net.jsourcerer.webdriver.jserrorcollector.JavaScriptError;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class jsError {
WebDriver driver;

@BeforeTest
public void setup() throws Exception {
FirefoxProfile profile = new FirefoxProfile();
JavaScriptError.addExtension(profile);
driver = new FirefoxDriver(profile);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.com/2015/01/table-with-checkbox.html");
}

@Test
public void printPageErrors() throws Exception {
//Capture all errors and store them In array.
List<JavaScriptError> Errors = JavaScriptError.readErrors(driver);
System.out.println("Total No Of JavaScript Errors : " + Errors.size());
//Print Javascript Errors one by one from array.
for (int i = 0; i < Errors.size(); i++) {
System.out.println("Error Message : "
+ Errors.get(i).getErrorMessage());
System.out.println("Error Line No : "
+ Errors.get(i).getLineNumber());
System.out.println(Errors.get(i).getSourceName());
System.out.println();
}
}
}

Check the console output on test completion. It will print JSError as bellow In console.

Error Message : ReferenceError: adddlert is not defined
Error Line No : 729
http://only-testing-blog.blogspot.in/2015/01/table-with-checkbox.html

Tuesday, February 17, 2015

Meet Jack

I want to introduce you to my friend, Jack.


I’ve known Jack for quite some time. We met several years ago, when we were both very new to trading. We had the same style of trading for the first year or so, but as time passed, our methods changed, and we went our separate ways.


A few weeks ago, we got together and talked about our trading strategies. He has been trading decently well, and made a healthy $50k in 2014. Nothing amazing, but nothing to be ashamed of. He was proficient in just about every style of trading: buying and swinging beat down charts, shorting parabolics intraday and overextended daily charts, trading options, playing earnings, and doing some long term investing, such as buying a basket of small caps each year hoping one pays off big. He wouldn't say he is extremely well-versed in any of these styles, but he understands them well enough to make a little money with each.


He explained to me that each weekend, he has a list of tickers in EACH style of trading that he reviews, and makes a trade plan for each one on the list. So, 4 or 5 beat down daily charts, 4 or 5 parabolic daily charts to short, and so on. He said he works for 8-10 hours per weekend making these watchlists, and even then he doesn't feel prepared. There are so many to watch and keep track of, he said, that his mind can't keep up, and he feels exhausted each day because his brain has to switch gears constantly between the strategies. But he puts up with the exhaustion because he knows that in the end, he will still make money. Maybe not $1M a year, but enough to pay the bills.


He then went on to explain his trading strategy within each skill set. He said that he usually has 4 or 5 setups every day for each category, such as parabolic charts to short. He can always identify which one is the best opportunity, and sometimes he thinks to himself, ‘Maybe I should only focus on that one play.’ But instead, he plays each of those 4 or 5 setups with the same size, and devotes equal mental energy to each, afraid of missing a play. He admits that at the end of the day he almost always feels mentally drained, because he invariably has 4 or 5 charts up at the same time, and keeping track of each position is very stressful, especially when not all of them are in the green. But he puts up with the exhaustion because he knows that in the end, he will still make money. Maybe not $10k a day, but enough to pay the bills.


He then went on to explain his intraday trading strategy. He said that when there are parabolic daily charts that he knows he wants to short, he will scalp them for every single move they've got. Why not milk it for everything it's got, right? At the end of each day that those setups occur, he said he usually has between 50-200 tickets with his broker. He is mentally exhausted, his eyes are strained, and he has a headache from staring at every tick the entire day. It's very stressful to be scalping a stock all day! But he puts up with the exhaustion because he knows that in the end, he will still make money. Maybe not $10k a day, but enough to pay the bills


Every day Jack is burned out and doesn't have enough energy to do anything except lay down on the couch and eat some greasy potato chips. But he doesn't care!!! He makes a decent salary each year, remember!? He has to live up to what his name destined him to be: the Jack of All Trades, Master of NONE.


After respectfully listening to his story, I told him my style of trading.


Every night before the next day in the markets, I spend anywhere from 15 minutes to 3 hours scanning and researching tickers. But I don't give a pig’s snout about trying to scan and research the next stock to be a big earnings winner. I don't care about trying to nail the bounce on some bottoming chart. Why not? Because I am not comfortable with that trading style, and I have found my niche. Sure, I could probably become proficient in any of those styles of trading if I put in the effort. But would I love and enjoy it as much as I do my current trading style? Definitely not. I focus on my niche setups only. And once I narrow them down from my scans (as I wrote about HERE), I evaluate which I have the most conviction with. There aren't trades like VGGL every day. But when there are, I size the hell in. By focusing on one style of trading and really learning everything about it, I can build the conviction I need to feel comfortable holding a larger-than-normal position for me (and make MORE than just “enough to pay the bills”).


(I'm not saying trying to nail the bounce of a bottoming daily chart is a bad style of trading and you can't make that your niche. I'm saying that its not for me. Would I be able to constantly push myself to the next level and make $1M a year trading those setups? For me personally, the answer is no.)


I focus on 1 or 2 main plays a day for scalping or "swinging" intraday, and 1 or 2 plays in my swing account that do not need to be monitored constantly. The swings don't take up very much mental energy; I just check the 15-minute charts a few times a day to make sure they aren't doing anything crazy. Of the 1 or 2 stocks I am day-trading, I typically let them play out for at least 10-15 minutes into the open. Could I make money scalping those first few minutes? Sure, probably, but it's not worth my mental energy. I don't want to catch every single minuscule move on a stock just to make a quick buck. I want to take a chunk out of the stock, not just a .02 scalp on FB or TWTR. I don't need to milk every single move a stock makes. I only need to take the ones that I have strong conviction in, and can size the hell in. And I can still make more than Jack makes trying to scalp the same stock all day.


Just about every day, I get to walk away from my computer with plenty of mental energy, satisfied with my trading, and not stressing about how I missed a big move in a stock. This is a big problem that I noticed when I was struggling trading, and with a lot of newer traders. People constantly complain about how they missed a big move in a stock, or covered too early/sold too soon. This is unhealthy for your mindset and makes you feel bad about yourself, which then makes it much harder to feel confident in your next trade or next trading day. At first I just tricked my brain into enjoying missing moves on a stock. Always feel confident in every move you make. If it keeps tanking, just think of all the stupid chasers who are long and losing their ass. Think of something that can get your mind off of the negativity you feel about yourself for missing. Sometimes if I am waiting for the next pop on a stock to get short, but instead it just takes another leg down without me, I literally get up that moment and walk out of the room. Then I’ll take some deep breaths, gaze out of the window, and clear my mind. Then when I sit back down at my computer, I feel centered and not upset for missing a play.


Jack ended every day drained, so he had no energy left to motivate himself to push to the next level in trading. He was stuck in the mud, complacent, which is a very bad thing in trading regardless of whether or not you’re profitable. I want to conserve my energy, trade less stocks, and always have enough energy to do whatever I want the rest of the day. I always have more to learn, and have the energy to push myself to the next level in trading. I'm not a slave to my computer and the stocks I trade. I own them, they do not own me.


------------------------------------------------------------------------


I was inspired to write this story because of the problem I used to have and the problem I see many others going through right now. In my opinion, you will never make it in trading if you don't have a niche. And you will never make it if you are obsessed with trying to be in every single move of every single stock, every single day. This causes a ridiculous amount of unnecessary stress internally. It's of the utmost importance to have control over your emotions and mental energy before you can expect yourself to be a consistent trader. I don't touch setups I don't have extreme conviction and confidence in. They are a complete and utter waste of my time, money, and mental energy. I leave those setups to the vultures.


   But, what does "make it" mean to me? Jack has never made it. Sure he makes $50k a year, but the money doesn't matter. I want to have no limit to how far I can go, no matter what I do. I always want enough energy to keep pushing and get myself to the next step on the endless staircase of life. Have I made it? No. I still have a long way to go and a near-infinite amount of knowledge left to absorb. But I can feel confident and successful each and every day, and not worry about missing the next big piker convention in town.


No matter how many chart patterns you've studied, books you’ve read, or styles of trading you are proficient in, the first thing one must master is the emotions.


Other food for thought:


Whenever I have a GREAT day/week/month or rather when I feel that I have had a great day/week/month, I look back at my trades and find all the places where I can improve. Yes I did well, but I always tell myself I can do better, because I can! There is no limit to how well a trade can go or how much you can make, so there will always be a way to critique yourself. The point here is, humble yourself before the market does it for you. Every time I feel on top of the world and my trading is going extremely well, I start to get cautious. Although I will still be aggressive and push size, I will not let the ego-boost get to my head and cause me to be irrationally stubborn and let a trade go far against me and break my rules for no reason. Many times, traders will have a huge win, then the next trade they have a sloppy entry and play more size than normal for the sole reason that they nailed the last trade, so they can risk their profits. It is a big mistake to think like this.


Thanks
Nikkos (IU: Nikkorico)


P.S.
Future Blog Post Ideas
-My thoughts on fundamental vs. technical trading
-How I pushed myself to the next level (playing larger size and feeling comfortable)


If you have suggestions/ideas you would like me to talk about in future blog posts, let me know in the comment section below! I can’t guarantee I will write a blog on all of them but I will certainly try to.


Sunday, February 15, 2015

How to Parse JSON to/from Java Object using Jackson Example

In this example You will learn how to parse a  JSON String to Java and  how to convert Java Object to JSON format using Jackson. JSON stands for JavaScript Object notation is a subset of JavaScript object syntax, which allows all JavaScript client to process it without using any external library. Because of its compact size, compared to XML and platform independence nature makes JSON a favorite format for transferring data via HTTP. Though Java doesn't have any inbuilt support to parse JSON response in core library, Java developers are lucky to have couple of good and feature rich JSON processing libraries such as GSON, Jackson and JSON-simple.  Jackson in a high performance, one of the fasted JSON parsing library, which also provides streaming capability. It has no extenal dependency and solely depends on JDK. It is also powerful and provides full binding support for common JDK classes as well as any Java Bean class, e.g. Player in our case. It also provides data binding for Java Collection classes e.g. Map as well Enum.
Read more »

How To Wait For Page To Load/Ready In Selenium WebDriver

Generally selenium WebDriver handles page loading or wait for page to load by It self If you have used Implicit Wait In your test. But many on development sites have a page loading Issues and It Is taking more or less time for page to load on every test iteration. So some times your test will run without any Issue and some times It will be unable to found some elements due to the page loading Issue.

I have a solution for such Issue If any one facing It. We can use bellow given javascript syntax In our test to check (loading) status of page. It will return "complete" when page Is loaded completely.
document.readyState

We have already learnt how to execute javascript In selenium test earlier.You will find few of the examples on THIS LINK. Javascript execution syntax to get page loading status In webdriver Is as bellow. It will check Page ready status for us.

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("return document.readyState").toString().equals("complete");

So we can check page ready status after every 1 second using for loop as shown In bellow example.
Once page Is ready, It will start taking actions on page.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class checkPageReady {

WebDriver driver;

@BeforeTest
public void setup() throws Exception {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/04/calc.html");
}

@Test
public void calc() {
//Call this function to wait for page to ready.
checkPageIsReady();

//Once page Is ready/loaded, Bellow given steps will be executed.
driver.findElement(By.xpath("//input[@id='1']")).click();
driver.findElement(By.xpath("//input[@id='plus']")).click();
driver.findElement(By.xpath("//input[@id='5']")).click();
driver.findElement(By.xpath("//input[@id='equals']")).click();
}


public void checkPageIsReady() {

JavascriptExecutor js = (JavascriptExecutor)driver;


//Initially bellow given if condition will check ready state of page.
if (js.executeScript("return document.readyState").toString().equals("complete")){
System.out.println("Page Is loaded.");
return;
}

//This loop will rotate for 25 times to check If page Is ready after every 1 second.
//You can replace your value with 25 If you wants to Increase or decrease wait time.

for (int i=0; i<25; i++){
try {
Thread.sleep(1000);
}catch (InterruptedException e) {}
//To check page ready state.
if (js.executeScript("return document.readyState").toString().equals("complete")){
break;
}
}
}
}

This way, You can check or wait for page to load In selenium webdriver test.

How ConcurrentHashMap Internally Works in Java with Example

How ConcurrentHashMap works or internal implementation of ConcurrentHashMap is one of the most popular java interview questions under the category concurrency. We have already discussed the other popular java interview questions like  internal working of HashSet or How  HashMap works in java .

ConcurrentHashMap utilizes the same principles of HashMap, but is designed primarily for a multi-threaded application and hence it does not require explicit synchronization.   The only thread safe collection objects were Hashtable and synchronized Map prior to JDK 5.

Before learning How ConcurrentHashMap works in Java , we need to look at why ConcurrentHashMap is added to the Java SDK.

Interviewer : Why we need ConcurrentHashMap when we already had Hashtable ?

Hashtable provides concurrent access to the Map.Entries objects by locking the entire map to perform any sort of operation (update,delete,read,create). Suppose we have a web application , the overhead created by Hashtable  (locking the entire map) can be ignored under normal load. But under heavy load , the overhead of locking the entire map may prove fatal and may lead to delay response time and   overtaxing of the server.
 
This  is where ConcurrentHashMap comes to rescue. According to ConcurrentHashMap Oracle docs,
ConcurrentHashMap class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details. So the main purpose of this class is to provide the same functionality as of Hashtable but with a performance comparable to HashMap.

ConcurrentHashMap achieves this by a simple tweak. So this leads to our main question



How ConcurrentHashMap works in Java

According to ConcurrentHashMap Oracle docs,

The constructor of ConcurrentHashMap looks like this :

public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel)

So the above line  creates a new, empty map with the specified initial capacity, load factor and concurrency level.
where,
Important Parameters to consider from ConcurrentHashMap Constructor:

initialCapacity - the initial capacity. The implementation performs internal sizing to accommodate this many elements.
concurrencyLevel - the estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads.

In the ConcurrentHashMap Api , you will find the following constants.

static final int DEFAULT_INITIAL_CAPACITY = 16;
static final int DEFAULT_CONCURRENCY_LEVEL = 16;

initial capacity parameter and concurrency level parameters of ConcurrentHashMap constructor (or Object) are  set to 16 by default.

Thus, instead of a map wide lock, ConcurrentHashMap maintains  a list of 16 locks by default ( number of locks equal to the initial capacity , which is by default  16) each of which is used to lock on a single bucket of the Map.This indicates that 16 threads (number of threads equal to the concurrency level , which is by  default 16) can modify the collection at the same time , given ,each thread works on different bucket. So unlike hashtable, we perform any sort of operation ( update ,delete ,read ,create) without locking on entire map in ConcurrentHashMap.

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset.

The allowed concurrency among update operations is guided by the optional concurrencyLevel constructor argument (default 16), which is used as a hint for internal sizing. The table is internally partitioned to try to permit the indicated number of concurrent updates without contention. Because placement in hash tables is essentially random, the actual concurrency will vary. Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention

Interviewer : Can two threads update the ConcurrentHashMap simultaneously ?

                                                     
Yes it is possible that two threads can simultaneously write on the ConcurrentHashMap. ConcurrentHashMap default implementation allows 16 threads to read and write in parallel.
But in the worst case scenario , when two objects lie in the same segment or same partition, then parallel write would not be possible.

Interviewer : Why ConcurrentHashMap does not allow null keys and null values ?

According to the author of the ConcurrentHashMap (Doug lea himself)

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated. The main one is that if map.get(key) returns null, you can't detect whether the key explicitly maps to null vs the key isn't mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between 
calls.

In simple words,

The code is like this : 
 
if (map.containsKey(k)) {
return map.get(k);
} else {
throw new KeyNotPresentException();
}

It might be possible that key k might be deleted in between the get(k) and containsKey(k) calls. As a result , the code will return null as opposed to KeyNotPresentException (Expected Result if key is not present).

Interviewer : What is the difference between HashMap and ConcurrentHashMap?

The HashMap was not thread safe and therefore could not be utilized in multi-threaded applications.  The ConcurrentHashMap was introduced to overcome this shortcoming and also as an alternative to using HashTable and synchronized Maps for greater performance and uses the standard Hashing algorithms to generate hash code for storing the key value pairs.For more difference between HashMap and ConcurrentHashMap check this popular interview question HashMap vs ConcurrentHashMap in java.



Interviewer : Can multiple threads read from the Hashtable concurrently ?

No multiple threads can not read simultaneously from Hashtable. Reason, the get() method of  Hashtable is synchronized. As a result , at a time only one thread can access the get() method .
It is possible to achieve full  concurrency for reads (all the threads read at the same time) in  ConcurrentHashMap by using volatile keyword.

Interviewer: Does ConcurrentHashMap Iterator behaves like fail fast iterator or fail safe Iterator?

ConcurrentHashMap iterator behaves like fail safe iterator. It will not throw ConcurrentModificationException . We have already discussed Fail Fast Iterator vs Fail Safe Iterator.


Interviewer : Why does Java provide default value of partition count as 16 instead of very high value ?

According to Java docs ,
How ConcurrentHashMap works in java interview question



Ideally, you should choose a value to accommodate as many threads as will ever concurrently modify the table. Using a significantly higher value than you need can waste space and time, and a significantly lower value can lead to thread contention.




Interviewer : Can you write the simple  example which proves ConcurrentHashMap class behaves like fail safe iterator?


ConcurrentHashMap Example :


import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;


public class ConcurrentHashMapExample
{


public static void main(String[] args)
{
ConcurrentHashMap<String,String> premiumPhone = new ConcurrentHashMap<String,String>();
premiumPhone.put("Apple", "iPhone6");
premiumPhone.put("HTC", "HTC one");
premiumPhone.put("Samsung","S6");

Iterator iterator = premiumPhone.keySet().iterator();

while (iterator.hasNext())
{
System.out.println(premiumPhone.get(iterator.next()));
premiumPhone.put("Sony", "Xperia Z");
}

}

}

Output :


S6
HTC one
iPhone6



Please mention in the comments in case you have any doubts regarding the internal implementation of ConcurrentHashMap.