Search

Wednesday, December 31, 2014

How To Handle HTTP Proxy Authentication Using AutoIt In Selenium WebDriver

Use of AutoIt with selenium webdriver Is very useful because selenium webdriver Is not able to handle windows dialog like file upload dialog, file download dialog, HTTP proxy authentication dialog etc. But AutoIt Is desktop application testing tool and It Is very stable with handling all these kind of dialog. Let's try to work with HTTP proxy authentication dialog.

Before reading more In this post, I am suggesting you to visit bellow given pages. It will helps you to understand more about AutoIt script creation and Integration with selenium webdriver.
  1. What Is AutoIt
  2. How to download and Install AutoIt
  3. How to create script In AutoIt to upload file.
  4. How to Integrate AutoIt script with selenium webdriver to upload file.
  5. How to create AutoIt + Selenium WebDriver script to download file.
Create AutoIt Script To Handle HTTP Authentication
Sometimes when you access site, It will show you HTTP proxy authentication popup as shown In bellow Image.


To handle such popups, We can use AutoIt script with selenium webdriver script. Now you are already aware about how to create AutoIt script.

AutoIt script to handle HTTP proxy authentication Is as bellow.
; Used Title property of authntication dialog window. It will wait for 8 seconds.
WinWaitActive("Authentication Required", "", 8)

; Send User ID In Used name text field.
Send("Your User Name")

; Press keyboard TAB key to move cursor on password text field.
Send("{TAB}")

; Send Passoword In Password text field.
Send("Password")

; Press Keyboard ENTER key to select OK button.
Send("{ENTER}")

You need to replace your actual user name and password In above script and then save It with .au3 extension using AutoIt script editor. Then you can convert your script In .exe format by compiling using AutoIt. You can Integrate that .exe file with selenium webdriver script to handle HTTP authentication Using AutoIt.

Tuesday, December 30, 2014

2014 Wrap-Up and Thoughts into 2015

As a whole, 2014 was a fantastic year for me and my trading. The goals I set for myself at the beginning of 2014 were blown out of the water. Sure, I made a good amount of money in the end, but that doesn't necessarily mean I traded well the whole time. There were plenty of avoidable mistakes throughout the year and I hope to learn from those mistakes and apply those in 2015. Also, I met some absolutely amazing traders and people throughout the year in IU and couldn't be more thankful for that.

After my swing short on APT in October, I was ready to take a break. I had just rebounded significantly from my lows and decided that after that rollercoaster ride, it would be smart to stop trading until 2015, just to play it safe. However, I found that I couldn't stop trading altogether; I was still addicted and didn't want to get out of the loop. But I had realized something after my large win on Ebola stocks: I don't need to trade every single stock, nor do I need to catch every single move in a stock, in order to make money. I see so many people get caught up in the 'need' to be a day-trader, and the obsession of being in a play at all times. After my big loss and recovery, I snapped out of that phase. I realized it was much more of a thrill to be the sniper in the hills, staying low in disguise and waiting patiently for the target to expose itself. I could watch all of the soldiers down on the battlefield fight hand-to-hand, where the odds are close to 50-50. But up on the hill, the odds are swayed in my favor, perhaps 75-25. Then, when the timing is right, I load my one bullet, aim carefully, and take the shot. If you practice enough, one shot is all you need.

Sometimes I will miss the shot, but that doesn't mean I need to go run down to the bottom of the hill and try to attack the target with my fists (chasing the stock). Instead, I stay on the hill, wait patiently for the target to get back in my crosshairs, and take another shot (wait for the lower high with good r/r). I might miss again, but there's no reason to get too upset about it. There will always be others.

So, I spent the rest of October, November, and December playing the perfect setups ONLY. Compared to how often I was trading before, I was barely trading, yet I was making more money, executing the plays much better, and feeling very satisfied. How could this be?

It seems so obvious to me now, and I'm not sure why it took me this long to finally figure it out: adjust your size based on your conviction and how ideal/perfect the setup is. This also brings me to another big lesson this year, which is the importance of finding your niche. During the last 3 months I finally had a clear vision of what my niche is: shorting the pigs. Primarily swinging short until the bacon is sizzling off the grill. Find the setups that you naturally feel comfortable with, in which you feel right at home. Identify the setups that you are NOT comfortable with, in which you feel as though you are walking on eggshells. For example, VGGL was right in my sweet spot. The company was garbage, riddled with fishy deals and dilution, and it was extremely overextended. I felt right at home, so I sized in accordingly. Although it was one of the biggest positions I had ever taken, it felt like any other trade, because I was comfortable with the setup and had conviction. I would never take that kind of position when, for example, trying a bounce play on the oil stocks. I have no comfort with those kind of daily charts at all, and I cannot get a good read on them. That doesn't mean I won't play them necessarily: it just means I will play maybe 5-10% of the size I would on a setup like VGGL. I don't believe there is any coincidence that the last 3 months, during which I was extremely patient and only traded setups in my niche, were the best 3 months of my trading career.

After closing my VGGL position, along with a few other smaller swing shorts, I asked myself a few questions. Is it worth it to wait a few weeks until one of your niche setups appears? And if it happens to be a PERFECT setup, is it worth trading with decent size? I decided that the answer to both of these questions is yes. I swung VGGL short for about three weeks, and made $50k. I will gladly wait another three weeks to make another $50k.

    For 2015, I plan on putting more focus towards improving my execution of my niche setups. I plan on being very patient on my entries and only entering if the setup is PERFECT. There is no reason to chase stocks, as there will always be others. I'm setting up a spreadsheet with my goals on different time frames (yearly, monthly, weekly) and am going to keep track of whether or not I hit the goals. If I don't, I'll evaluate why I didn't and learn from it. Almost none of my goals are money-based. They are based on the quality with which I execute my trades. Another thing I've learned is that if you trade well, the money will naturally follow. Focusing too much effort on the money and not the quality of execution leaves one with an account blown to shreds and confidence levels down the drain.

Cheers to a great 2014, and looking forward to next year!
Nikkos (IU: Nikkorico)

Sunday, December 28, 2014

Downloading File Using AutoIt In Selenium WebDriver

Downloading file using selenium webdriver Is also tricky task. I have already described how to handle file download functionality In selenium webdriver by creating custom firefox profile In THIS POST. It Is really very long task. At place of using custom profile approach, We can use AutoIt script with selenium webdriver to download file from any web page.

You will find different test files download links on THIS PAGE which we will use to learn how to download file using AutoIt In selenium webdriver. We have to perform bellow given steps to create selenium webdriver + AutoIt script.

Identify objects properties of file download and save dialog
In Firefox browser, Go to THIS PAGE and click on "Download Text File" link. It will open Save file dialog with Open with and Save File radio options.

Now you can Identify save file dialog properties using AutoIt Window Info tool as described In THIS POST. In this case you will get only dialog's property (Title and class) using AutoIt Window Info tool as shown In bellow Image. It Is not able to retrieve property of Save File radio option and OK button. So we have to use some alternative method In our AutoIt script to select Save File radio option and click OK button.


So we have only dialog property In this case as bellow.
  • File Save dialog : Title = Opening Testing Text.txt, Class = MozillaDialogClass
We will use class property In our script to select dialog.

Write AutoIt script to save file
If you see In above Image, Save File option has shortcut to select It. We can select It using ALT + S keyboard shortcut keys. Also focus Is set by default on OK button. So we can press ENTER key to select OK. We can do both these Keystroke action In AutoIt very easily using Send() command as shown In bellow script.

; wait for 8 seconds to appear download and save dialog. Used class property of download dialog.
WinWait("[CLASS:#MozillaDialogClass]","",8)

; Perform keyboard ALT key down + s + ALT key Up action to select Save File Radio button using keyboard sortcut.
Send("{ALTDOWN}s{ALTUP}")

; Wait for 3 seconds
Sleep(3000)

; Press Keyboard ENTER button.
Send("{ENTER}")

Save above script In "Script To Download File.au3" format at "E:\AutoIT" location. Above script will perform bellow give actions.
  1. wait for 8 seconds to appear file saving dialog.
  2. Press ALT down + s + ALT up key to select Save File radio.
  3. Press Enter key to select OK button.
Convert script In executable format

Now you can create executable file of above script as described In THIS POST. After conversion, you will get executable file "Script To Download File.exe".

CLICK HERE to download ready made "Script To Download File.au3" and "Script To Download File.exe" files of AutoIt.

Integrate AutoIt script with selenium webdriver to download file
As described In THIS POST, We will use java Runtime.getRuntime().exec(); method to execute AutoIt script In selenium webdriver.

So our Selenium webdriver + AutoIt script to download file from web page Is as bellow.

Note : "Script To Download File.exe" file should be located at E:\\AutoIT folder.
package AutoIt;

import java.io.IOException;
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 AutoIt_Test {
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/2014/05/login.html");
}

@Test
public void testCaseOne_Test_One() throws IOException, InterruptedException {
//Click on Download Text File link to download file.
driver.findElement(By.xpath("//a[contains(.,'Download Text File')]")).click();
//Execute Script To Download File.exe file to run AutoIt script. File location = E:\\AutoIT\\
Runtime.getRuntime().exec("E:\\AutoIT\\Script To Download File.exe");
}
}

Now If you run above script, It will download Text file automatically. At the end of script execution, file will be downloaded as shown In bellow Image.


This way you can download any file from web page.

5 ways to Reverse a String in Java with Example

In this tutorial we will discuss  how to reverse a string in java . Although there are many ways to get the solution but we are sharing 5 different ways to  reverse a string. This question is frequently asked in the technical interview of java.This question is easy , but please mark this question in your to do list before attending any technical interview in java. First we will understand the question by writing example.

Input :   Alive is awesome
Output: emosewa si evilA

Input : Be in present
Output : tneserp ni eB

Read Also :  Difference between String , StringBuilder and StringBuffer

Points to Keep in Mind Before attempting the Solution:

1. String class in java do not have reverse() method , StringBuilder class does have built in reverse() method.
2. StringBuilder class do not have toCharArray() method , while String class does have toCharArray() method.

Pseudo Code for Reverse String Method 1:

1. The user will input the string to be reversed.
2. First we will convert String to character array by using the built in java String class method toCharArray().

3. Then , we will scan the string from end  to start,  and print the character one by one.


import java.io.*;
import java.util.*;

public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}

Pseudo Code for Reverse String Method 2:

1.  In the second method , we will use the built in reverse() method of the StringBuilder class ,.
Note :  String class does not have reverse() method . So we need to convert the input string to StringBuilder , which is achieved by using the append method of the StringBuilder.

2.  After that print out the characters of the reversed string  by scanning from the first till the last index.


import java.io.*;
import java.util.*;

public class reverseString {
public static void main(String[] args) {
String input="AliveisAwesome";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1=input1.reverse();
for (int i=0;i<input1.length();i++)
System.out.print(input1.charAt(i));
}}




Pseudo Code for Reverse String Method 3:

1. Convert the input string into character array by using the toCharArray() built in method of the String Class .
2. In this method we will scan the character array from both sides , that is from the start index (left) as well as from last index(right) simultaneously.
3. Set the left index equal to 0 and right index equal to the length of the string -1.
4. Swap the characters of the start index scanning with the last index scanning  one by one .After that  increase the left index by 1 (left++) and decrease the right by 1 i.e (right--) to move on to the next characters in the character array .
5. Continue till left is less than or equal to the right .


import java.io.*;
import java.util.*;

public class reverseString {
public static void main(String[] args) {
String input = "Be in present";
char[] temparray= input.toCharArray();
int left,right=0;
right=temparray.length-1;
for (left=0; left < right ; left++ ,right--)
{
// Swap values of left and right
char temp = temparray[left];
temparray[left] = temparray[right];
temparray[right]=temp;
}
for (char c : temparray)
System.out.print(c);
System.out.println();
}}


Pseudo Code for Reverse String Method  4:

1. Convert the input string into the character array by using toCharArray() built in method.
reverse a string in java with example
2. Then add the characters of the array into the LinkedList object . We used LinkedList because it maintains the insertion order of the input values.
3. Java also has  built  in reverse() method for the Collections class . Since Collections class reverse() method takes a  list object , to reverse the list , we will pass the LinkedList object which is a type of list of characters.
4. We will create the ListIterator object by using the listIterator() method on the LinkedList object.
ListIterator object is used to iterate over the list.
5. ListIterator object will help us to iterate over the reversed list and print it one by one to the output screen.


import java.io.*;
import java.util.*;

public class reverseString {
public static void main(String[] args) {
String input = "Be in present";
char[] hello=input.toCharArray();
List<Character> trial1= new LinkedList<>();
for(char c: hello)
trial1.add(c);
Collections.reverse(trial1);
ListIterator li = trial1.listIterator();
while(li.hasNext())
{System.out.print(li.next());}
}}


Pseudo Code for Reverse String Method 5 :

1. The last method is converting string into bytes .  getBytes()  method  is used to convert the input string into bytes[].
2. Then we will create a temporary byte[]  of length equal to the length of the input string.
3. We will store the bytes(which we get by using getBytes() method) in reverse order   into the temporary byte[] .


package ctci;
import java.io.*;
import java.util.*;

public class reverseString {
public static void main(String[] args) {
String input = "Be in present";
byte [] strAsByteArray = input.getBytes();
byte [] result = new byte [strAsByteArray.length];

for(int i = 0; i<strAsByteArray.length; i++){
result[i] = strAsByteArray[strAsByteArray.length-i-1];
}
System.out.println( new String(result));
}}


Read Also :   5 ways to Determine if String has all Unique Characters

Please mention in the comments in case if you know any  way to reverse the string other then the above mentioned ways or in case you have any doubts.

Upload File In Selenium WebDriver Using AutoIt

As you know, File uploading Is very hard In selenium webdriver because It Is not able to handle file uploading dialog. So we will use AutoIT with selenium webdriver to upload file In web applications. We have already created AutoIt script (Script To Upload File.exe) In previous post which can select file from File Upload dialog. We will learn how to Integrate that AutoIt script with selenium webdriver In this section.

In java, It Is very easy to execute any executable file. We can run any executable script file using Runtime.getRuntime().exec("File Path") method. We will use this java method In our selenium webdriver test script to handle file upload dialog.

So now final selenium webdriver with AutoIt Integration test script Is as bellow.

Note : "Script To Upload File.exe" and "Test.txt" files should be located at "E:\\AutoIT" folder.
package AutoIt;

import java.io.IOException;
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 AutoIt_Test {
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/2014/01/textbox.html");
}

@Test
public void testCaseOne_Test_One() throws IOException, InterruptedException {
//Click on browse button.
driver.findElement(By.name("img")).click();
//To execute autoIt script .exe file which Is located at E:\\AutoIT\\ location.
Runtime.getRuntime().exec("E:\\AutoIT\\Script To Upload File.exe");
}
}

Run above script In eclipse. 
  • It will click on browser button to open File Upload dialog using selenium webdriver.
  • Then Runtime.getRuntime().exec("E:\\AutoIT\\Script To Upload File.exe"); syntax will execute AutoIt generated "Script To Upload File.exe" file. It will select file and click on open button of File Upload dialog.
On completion of script, you will see that Test.txt file Is uploaded as shown In bellow given Image.


This way we can upload file using AutoIt In selenium webdriver.

Read next post to know how to download file using AutoIT + Selenium webdriver.

Wednesday, December 24, 2014

How to Synchronize ArrayList in Java with Example

ArrayList is a very useful Collection in Java, I guess most used one as well but it is not synchronized. What this mean? It means you cannot share an instance of ArrayList between multiple threads if they are not just reading from it but also writing or updating elements. So how can we synchronize ArrayList? Well, we'll come to that in a second but did you thought why ArrayList is not synchronized in first place? Since multi-threading is core strength of Java and almost all Java programs has more than one thread, why Java designer not makes it easy for ArrayList to be used in such environment? Answer lies in performance, there is performance cost associated with synchronization and making ArrayList synchronized would have made it slower. So, they definitely thought about it and left ArrayList as non-synchronized to keep it fast, but at the same time they have provided easy ways to make it synchronized and this is what we are going to learn in this tutorial. Collections class has several method to create synchronized List, Set and Map and we will use Collections.synchronizedList() method to make our ArrayList synchronized. This method accepts a List which could be any implementation of List interface e.g. ArrayList, LinkedList and returns a synchronized (thread-safe) list backed by the specified list. So you can also use this technique to make LinkedList synchronized and thread-safe in Java.
Read more »

Tuesday, December 23, 2014

Create Script In AutoIt To Upload File

Before creating and running file upload script In AutoIT, You must be aware about what Is AutoIT and how to Install It. I have already described about AutoIT In THIS POST and how to download and Install It In THIS POST. Now let us learn how to create script In AutoIT to upload file using selenium webdriver.

In this section, We will learn how to create and run AutoIt script stand alone. Next post will describe you how to Integrate AutoIT script with selenium webdriver.

Identify objects properties of File Upload dialog
First of all you need to Identify objects of file upload dialog. Navigate to THIS PAGE where you will find file uploading functionality. Click on Browse button. It will open file uploading dialog as shown In bellow Image.

To Identify objects of dialog, AutoIt has Windows Info tool. You can open It from Start -> All Programs -> AutoIt V3 -> AutoIt Windows Info.


To Identify object properties of Upload dialog, Simply drag and drop "Finder Tool" from AutoIT v3 windows Info tool to "File name" field as shown In above Image. It will automatically Identify object properties of File Upload dialog and File name field. Same way you can Identify properties of any object of any dialog. We will use that object property In auto It script. In this example, Our object properties are as bellow.
  • File upload dialog : Title = File Upload, Class = #32770
  • File name field : Edit1 (Class + Instance combination)
  • Open button : Button1 (Class + Instance combination)
Write AutoIt script to select file In dialog
File "Test.txt" (which I wants to upload) Is located at E:\AutoIT location. To write file upload script, you need to use SciTE Script Editor. Open script editor from Start -> All Programs -> AutoIt V3 -> SciTE Script Editor and write bellow given script In to It and save It as "Script To Upload File.au3". Script explanation Is given with each line.

Note : Test.txt file should be located at "E:\AutoIT" folder.

; It will wait for 8 seconds to appear File Upload dialog.
; Used Title property of File upload dialog window.


WinWait("File Upload","",8)

; Set control focus to File name Input box of File Upload dialog.
; Used Class property of File upload dialog window and Class+Instance property for File name Input box.

ControlFocus("[CLASS:#32770]","","Edit1")

Sleep(3000)

; Set the name of file In File name Edit1 field.
; "Test.txt" file Is located In AutoIT folder of E drive. So we have to provide full path like E:\AutoIT\Test.txt.

ControlSetText("[CLASS:#32770]", "", "Edit1", "E:\AutoIT\Test.txt")

Sleep(3000)

; Click on the Open button of File Upload dialog.

ControlClick("[CLASS:#32770]", "","Button1");

In above script, We have used total five different AutoIT commands. Explanation Is as bellow.
  • WinWait : Used to wait for given time to appear targeted dialog window.
  • ControlFocus : Set the focus on targeted dialog window.
  • Sleep : Wait for given time.
  • ControlSetText : Write text In targeted Input text field of dialog.
  • ControlClick : Click on targeted button of win. dialog.
Your script will looks like bellow In AutoIt editor.



Convert script In executable format
To run this script, We need to convert It In executable .exe format. It Is very simple because AutoIT has built In function to convert script In .exe format.

To convert script, 
  • Simply go to the folder where "Script To Upload File.au3" file Is stored.
  • Right click on file and select Compile Script as shown In bellow Image. It will create "Script To Upload File.exe" file In same folder.


CLICK HERE to download ready made "Script To Upload File.au3" and "Script To Upload File.exe" files of AutoIt.

Test AutoIt script
Now you can test script to verify Is It working fine or not.

To test script, 
  • File Upload dialog should be opened. Go to THIS TEST PAGE In Firefox browser and click on "Browse" button to open File Upload dialog.
  • Double click on "Script To Upload File.exe" file to execute script and observe actions on File Upload dialog. It will enter file path In File name field of dialog and then click on Open button automatically.
If this works then your script Is fine. Read next post to learn how to use "Script To Upload File.exe" file In selenium WebDriver test to upload file.

Monday, December 22, 2014

How To Download And Install Auto IT Step By Step

As I described In PREVIOUS POST, Auto IT Is opensource automation tool and can help us to handle windows element In our selenium webdriver test cases. We need AutoIT and AutoIT script editor to write test scripts.

Steps To Download AutoIT

You can download AutoIT from Its official website. Click Here to go AutoIT to download page. On that page, Click on Download AutoIt button as shown In bellow given Image. It will start downloading "autoit-v3-setup.exe" file.




Steps To Download AutoIT Script Editor

To download AutoIT Script editor, Go to same Downloading Page and click on Download editor button as shown In bellow Image. It will download file with name "SciTE4AutoIt3.exe".


Installing AutoIT
You need to Install AutoIT first and then you can Install AutoIT Script editor. To Install AutoIT, Double click on "autoit-v3-setup.exe" file. It will open Installation dialog as shown In bellow Image.


Click on Next button and follow the Installation guide by keeping default settings as It Is. On completion of Installation, You can see AutoIT In your Start menu -> All Programs options as shown In bellow Image.

Install AutoIT Script Editor
AutoIT script editor which Is Installed with AutoIT Is Lite version as shown In bellow Image.


To get full editor version, You need to Install It separately. To Install AutoIT script editor, Double click on "SciTE4AutoIt3.exe" source file. It will open Installation dialog as shown In bellow Image.


Follow script editor Installation guide by keeping default settings as It Is. At the end of Installation, You will see AutoIT Installed In Start -> All Programs as shown In bellow Image.


Now you can open editor and verify Its version. It will looks like bellow.


That's All.. Now you are all set to write and run scripts In Auto IT. View next post to learn how to create script In Auto IT to upload file on web page.

Sunday, December 21, 2014

What Is AutoIT V3 And Why We Need It In Selenium WebDriver

As you know, It Is very hard to automate windows popup dialog box like file upload dialog, file download and save dialog, windows authentication dialog etc In selenium webdriver because It Is designed to automate web applications. Surly there are few work around to do all these things In selenium webdriver but do not have any strong and stable feature using which we can do all these things easily. In this section, We will learn something about Auto IT automation and Its usage with webdriver.

What Is AutoIT V3?
We can say, Auto IT Is Automation tool using which we can automate windows GUI. It Is freeware automation tool. Best use of auto It Is to simulate mouse and keyboard events like keystroke, mouse movement, working with windows native popup dialog etc. It Is mostly used for automating desktop applications.

Why AutoIT V3?
Main reasons behind using auto IT are as bellow.
  • Open Source Tool : It Is freeware automation tool with many features.
  • Easy to download and Install - It Is very easy to Install Auto IT. You can download .exe file from It official website.
  • Easy to learn and use - It uses very simple scripting language. Anyone can understand Its different methods and functions very easily. In help section of Auto IT, Each function Is described with detailed description and example.
  • Simulates keystrokes and mouse events - This Is the main reason behind using It. It Is very stable with keystrokes and mouse movement events.
  • Standalone compile and execution - It has built In feature to compile script and generate .exe executable file. You not need any extra add-on to do all these things.
  • Easy to handle windows elements : It Is very easy to handle windows elements like dialog, popup, buttons, text box and all other elements.
Why Need AutoIT V3 With Selenium WebDriver?
Many web applications contains forms with file uploading feature, Some times you need to test file downloading feature, Sometimes you need to handle windows authentication popups. Sometimes It Is not possible or I can say hard to handle all these things using only selenium webdriver. To handle all these situations easily, We can use AutoIT generated .exe file with selenium webdriver. Because AutoIT handles all these things very easily.

Read my next post to know how to download and Install AutoIT.

Wednesday, December 17, 2014

WebDriver Interview Questions With Answers

Part 19

88 : In XPath, I wants to do partial match on attribute value from beginning. Tell me two functions using which I can do It.

Answer : We can use bellow given two functions with XPath to find element using attribute value from beginning.
  1. contains()
  2. starts-with()
89 : I have used findElements In my test case. It Is returning NoSuchElementException when not element found. Correct me If I am wrong.

Answer : It Is Incorrect. findElements will never return NoSuchElementException. It will return just an empty list.

90 : My Firefox browser Is not Installed at usual place. How can I tell FirefoxDriver to use It?

Answer : If Firefox browsers Is Installed at some different place than the usual place then you needs to provide the actual path of Firefox.exe file as bellow.
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\Firefox.exe");
driver =new FirefoxDriver();

91 : How to create custom firefox profile and how to use It In selenium webdriver test?

Answer : You can view detailed answer for firefox custom profile on THIS PAGE.

92 : What versions of Internet Explorer are supported by selenium WebDriver?

Answer : Till date, Selenium WebDriver supports IE 6, 7, 8, 9, 10 and 11 with appropriate combinations of Windows 7, Vista or XP.

How to break from nested loop in Java

There are situations we need nested loops in Java, one loop containing another loop e.g. to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in two dimensional array. There are couple of more situations where you need nested looping e.g.  printing pascal triangle and printing those star structures exercises from school days. Sometime depending upon some condition we also like to came out of both inner and outer loop. For example while searching a number in a two dimensional array, once you find the number, you want to come out of both loop. Question is how can you break from nested loop in Java. You all know about break right? you have seen break in switch statements, or terminating for, while and do while loop, but not many Java developer know but there is a feature called labeled break, which you can used to break from nested loop. All the places, where you have used break before is example of unlabeled break, but once you use label with break you can terminate a particular loop in nested loop structure. In order to use labeled for loop, you first need to label each loop as OUTER or INNER, or whatever you want to call them. Then depending upon from which loop you want to exit, you can call break statement as shown in our example. By the way, there is a better way to do the same thing, by externalizing the code of nested loop into a method and using return statement for coming out of the loop. This improves readability of your algorithm by giving appropriate name to your logic.
Read more »

Monday, December 15, 2014

Reading Font Properties In Selenium WebDriver Using .getCssValue() Method

Sometimes you need to read font properties like font size, font color, font family, font background color etc.. during WebDriver test case execution. Selenium WebDriver Is very wast API and It has many built In methods to perform very small small operations on web page. Reading font property manually Is very simple task using firebug as shown In bellow given Image.


If you wants to read above shown font property In selenium webdriver then you can do It using .getCssValue() Method. You can provide property name (Example : font-family, font-size, font-weight, etc.) with .getCssValue() method to read Its value.

READ MORE TUTORIALS on selenium WebDriver.

Bellow given example will read values of font-size, color, font-family and text-align properties of "Example Login Page" text.
package Testing_Pack;

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

public class fontTest {
WebDriver driver = null;

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

@Test
public void readFontProperty(){
//Locate text string element to read It's font properties.
WebElement text = driver.findElement(By.xpath("//h1[contains(.,'Example Login Page')]"));

//Read font-size property and print It In console.
String fontSize = text.getCssValue("font-size");
System.out.println("Font Size -> "+fontSize);

//Read color property and print It In console.
String fontColor = text.getCssValue("color");
System.out.println("Font Color -> "+fontColor);

//Read font-family property and print It In console.
String fontFamily = text.getCssValue("font-family");
System.out.println("Font Family -> "+fontFamily);

//Read text-align property and print It In console.
String fonttxtAlign = text.getCssValue("text-align");
System.out.println("Font Text Alignment -> "+fonttxtAlign);
}
}

Output of above example Is as bellow.
Font Size -> 26.4px
Font Color -> rgba(102, 102, 102, 1)
Font Family -> "Trebuchet MS",Trebuchet,Verdana,sans-serif
Font Text Alignment -> left

You can use .getCssValue() method to get any other property value of any element.

Sunday, December 14, 2014

Interview Questions With Detailed Answers On Selenium

Part 18

83 : What are the benefits of parallelism over normal execution?

Answer : Using parallelism facility of TestNG In selenium webdriver,
  • Your software test execution time will be reduced as multiple tests will be executed simultaneously.
  • Using parallelism, We can verify multithreaded code In software application.
84 : I wants to run test cases/classes In parallel. Using which attribute and value I can do It?

Answer : You have to use parallel = classes attribute In testng.xml to run software web app tests parallel. VIEW EXAMPLE.

85 : What Is dependency test In TestNG?

Answer : Dependency Is very good feature of testng using which we can set software test method as dependent test method of any other single or multiple or group of test methods. That means depends-on method will be executed first and then dependent test method will be executed. If depends-on software test method will fail then execution of dependent test method will be skipped automatically. TestNG dependency feature will works only If depends-on test method Is part of same class or part of Inherited base class. DETAILED DESCRIPTION ON DEPENDENCY.

86 : What Is the syntax to set test method dependency on multiple test methods.

Answer : We can set test method's dependency on multiple test methods as bellow.
@Test(dependsOnMethods={"Login","checkMail"})
public void LogOut() {
System.out.println("LogOut Test code.");
}

Above test method Is depends on Login and checkMail test methods. VIEW EXAMPLE.

87 : What Is the syntax to set test method disabled.

Answer : We can use attribute enabled = false with @Test annotation to set test method disabled. Syntax Is as bellow.

@Test(enabled = false)
public void LogOut() {
System.out.println("LogOut Test code.");
}

Disabled software test methods will be excluded automatically during execution. VIEW PRACTICAL EXAMPLE.

Friday, December 12, 2014

How I Find My Prey (Scans/Watchlist)

My style of trading is almost completely short-biased. The concept of short selling has intrigued me since day one, and I have been perfecting my strategy intensively for the past six to eight months. Of course, at first, I was very naive in thinking that gravity must takes its toll on all stocks going up. That's a very dangerous game to play, and one I choose not to play anymore. Stocks can, and will, go up. I step up to the plate when perception of value and reality of value diverge in a serious way.


What causes Mr. Perception of Value to suddenly diverge from its cynical friend, Mr. Reality of Value?


Some of the most common are:

  • A promotion/pump (paid or unpaid)
  • An overreaction to news or some event relating to the company
  • Sympathy to other stocks moving up in the same sector


These can occur alone or in any combination. There have been some prime examples of this divergence in the last year: Marijuana/Pot stocks, Body Cam stocks, and Ebola stocks, to name a few. Each of these groups of stocks that ran had some combination of the above reasons. Let's take a peek at how these charts ended.


HEMP (Marijuana/Pot Stock)


ISNS (Body Cam Stock)


and my favorite...
APT (Ebola Stock)


   These are extreme examples of what I look for in stocks, but I think the concept is clear: ridiculously overextended charts that I have a high degree of conviction will come back down. It is simply a matter of being patient and letting the backside of the move commence. How and when I identify (or have to conviction to believe) that the backside of the move has begun is beyond the scope here, and to be honest, I don't think it would be of great value to explain that . The real way to grow as a trader is to experience things first-hand and learn. Success is gained by practice, trial-and-error, and self-perfection. Come up with your OWN ways to fix problems, your own innovations. Of course you can learn a general concept and "borrow" a style of trading from someone else for a while, but you won't OWN it until you add your own personal touch. There is nothing--NOTHING--wrong with trading based on someone else's style of trading, and I did just that for about a year. But if you want to get to the next level, you have to find your niche.


Creating a Watchlist


I have tried several different websites and platforms to scan for stocks, and my personal favorite is TD Ameritrade's ThinkorSwim (ToS). Not only are the charts great, but the built-in scanner is very customizable and fairly easy to use. It took me a little while to go through all the features and parameters but it was well worth the time. ToS is free for anyone who has an account open with TD Ameritrade. You don't even need to fund the account.


Once you install it, you can open it up and go to the Scan tab, as shown below.



I run several different scans, one for each price range (.01-$1, $1-$20, and $20+), and then one "safety net" scan that checks all of these price ranges. Each of these scans searches for stocks up over a certain % over certain time frames. They are all simple scans, and they do provide plenty of worthless set-ups. But I would rather sift through a few more charts and be more generic in my scan than be very specific in my scan and potentially let a good play slip through the cracks.


Here are the scans I use most often. If you have ToS installed, you should be able to open these scans in your platform. (UPDATE: If you cannot open these in your ToS, try clearing your cookies/cache, or use a different browser to click these links. Also, try opening the links with ToS closed, and with ToS already open. If they still won't open, I wrote another post HERE with the criteria so you can manually make these scans.)

  • Short Scan for $1-$20 (most of my plays come from here)
  • Short Scan for .01-$1 (I rarely play these, but every once in a while a great play comes out of it so its worth the extra effort to go through this)
  • Short Scan for $20+ (rarely do I play these, as most of the results here are just slow, grinding daily charts that are up a lot. But like the .01-$1 scan, occasionally there are great parabolic charts.)
  • Short Scan "Safety Net" Scan (this looks for stocks up a large amount in the last 1-20 weeks. It catches all the stocks that hit my other scans several weeks ago but just consolidated or stuck around near their highs. I use this for finding potential longer term shorts)


The majority of the results from my scans are charts that I'm either not interested in playing at all, or charts that might be decent in the future because I want to wait for them to go higher. If I think they might set up in the next couple of days or weeks, I pull up the charts and set price alerts with my broker. I just eyeball price points where if the stock somehow got to that price, I would be very interested in shorting it. That way, if I am monitoring other setups and the stock gets to that area of interest, I get an alert sent to my phone and can pull the chart up right away.


As an example, say my scan gives me 50 results. About 20-30 of them are charts I'm not interested in at all. Of the remaining tickers, 5-10 of them are ones I feel are getting very overextended. After narrowing it down to this amount, I pull the chart up and run through the recent company PRs and SEC filings to see if I can get a general idea of why the stock is up. If I see no PRs or filings at all, then its very likely that the stock is being pumped and there is no legitimate reason for it to be up at all. If there are PRs/filings that seem generally positive and explain why the stock is up, I try to evaluate if the PR is fluff or not. For me, it is always very important to know and understand WHY a stock is up. It helps me form my idea of where the reality of value lies, approximately. If I don't understand why, I have no problem avoiding the play. (Side note: as a general rule of thumb, over-extended earnings winner charts tend to take much longer to pullback and won't pull back as far, so they usually aren't my main watches.)


-------------------------------------------------------------------
Here are some hypothetical examples of charts I come across. The blue line (perception of value) is always going to be where the stock is actually trading at. A stock’s price depends entirely on what people are willing to pay for it. In other words, it depends on what their perception of the value of the stock is. With all these charts, the potential profit is represented by the distance between the blue and the red line. The greater the distance, the more I salivate at the thought of shorting the pig.
----------------------------------------------------------------




1) The arrow represents a catalyst for this stock. It could be a worthless PR, or a paid promotion, but clearly it caused the price to skyrocket. Yet the reality of value didn't move up AT ALL in response to this catalyst. This means that the catalyst was completely worthless and the stock will inevitably fall back down: it's just a matter of time. Float rotation and a lot of trapped shorts might cause the stock to stay up much longer, but it will inevitably come back down. The potential profit here is enormous, and it is a play I cannot and will not pass up.


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




2) The arrow, again, represents a catalyst for this stock. This time it is slightly different, because although the price did skyrocket due to this catalyst, the reality of value moved up slightly as well. The potential profit here is still very large in this example, but not as large as the previous example. I would definitely keep this kind of chart at the top of my watchlist.


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




3) In this example, the stock has been in a clear uptrend for several months. This uptrend is, for the most part, legitimate because the reality of value is rising as well. But in late April, the perception of value diverged from its reality of value. The potential profit isn't too big here, but it is probably worth a scalp, as the stock will most likely return to its previous average distance from the reality of value line. These are good stocks to watch as well, and I play them just to fill the time while I wait for charts like example 1 and 2 to set-up. These are solid target-practice setups.


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




4) In this example, the stock had some major catalyst in early April that caused it to skyrocket and make new highs on the daily chart. But notice that the two lines didn't diverge much, even though the stock shot up. This is where shorts can get trapped. They believe, as I once did, that just because a stock is up, it must go back down, regardless of the reason that it is up. That line of thinking just doesn't work in this case, as the catalyst in this instance was VERY legitimate and the stock may continue higher and higher. IMPORTANT: this example CAN turn into example 3 due to a squeeze of the shorts who thought it must go down right away. I always keep these tickers on my watchlists and check on them every few days to see if they squeezed much higher and the 'lines' did diverge.


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


Quick summary - Example 1 Charts are my absolute favorite. They don't come around often, but when they do, they are at the top of my list. Example 2 Charts are my next priority on the list. Example 3 Charts are the lowest priority, and I will play those only if there are no Ex. 1 or Ex. 2's to play. For the most part I just avoid Example 4 charts, which are frequently earnings winners the first day or two following earnings. But if you throw in enough stubborn shorts in the early days of an earnings winner and a pumper/guru for good measure, they might just morph into an Example 2 Chart.


How can you be sure where the reality of value lies? Can I just give all the answers away? No, that defeats the purpose. You have to learn that by experience. Observe several overextended charts and see which pattern they fit into. Keep them on watch for a few months and see what they do. Then go back and study the initial catalyst for the stock, and see if you can make any connections. It takes time and a lot of effort, and I am by no means finished in my journey of understanding how to find the reality of value of stocks.


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


After narrowing the list down even further from the quick "research", I put the tickers into my "Monitor" Grid, which is just a grid of 15-minute charts for 8 tickers. It gives me a bigger picture of what the stocks are doing, and if they start to set up for a play I just put the ticker into my 1-minute charts. (You can download this Flexible Grid if you want HERE)




In addition to the scans I run after the market closes, I also keep an eye on the Largest %-Gainers during the day. The top one is for stocks $1+ and the bottom is for stocks .01-$1.




All of these tools I use in ThinkorSwim are really just free alternatives. EquityFeed has all these features for scanning and more, as do many other paid platforms, I'm sure.


Keep in mind that this is just my style of trading. Maybe it will help you, maybe it won't. But the key to getting to the next level in trading is finding who you want to be. Evaluate what kind of trader you want to become. Just because this style of trading works for me doesn't mean it will work for you. I've tried to mold myself to fit other styles of trading just because I saw others be successful in that style, and it didn't work. In fact, I probably lost more money trying to become someone who I am not than trying to find who I really want to be.

Thanks,

Nikkos (IU: Nikkorico)