Thursday, 27 October 2016

How to get uniq value from array

package java_practice;

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class Uniqvaluesfromarray {

public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] numbers = {1, 1, 2, 1, 3, 4, 5};
Set<Integer> uniqKeys = new TreeSet<Integer>();
uniqKeys.addAll(Arrays.asList(numbers));
System.out.println("uniqKeys: " + uniqKeys);
}

}


Output: uniqKeys: [1, 2, 3, 4, 5]

Thursday, 16 June 2016

Collections in java

Java Collections:
Collection: Collection represents a single unit of object/group.
Java Collections framework is collection of interfaces and classes which helps in storing and procesing data efficiently.

                        Collection(interface)
Set(interface)                        List(interface)                Queue(interface)
Hashset,LinkedHashSet,Treeset(sortedSet)        ArrayList,Vector,LinkedList        LinkedList,PriorityQueue

1) List:
List is an ordered collection(sequence).
List may contains duplicate elements
List index is starts with Zero

1a) ArrayList:
ArrayList is resizable implemented from List interface
Java ArrayList class can contain duplicate elements.
ArrayList class maintain insertion order.
ArrayList class is non synchronized.

Methods of ArrayList class:

add("String")
add(index, "String")
remove("String")
set(int index,Object)
indexOf(Object)
get(int index)
size()
contains("String")
clear()



Sample code using ArrayList:


package collections;

import java.util.ArrayList;

public class ArrayList_Example {

    public static void main(String[] args) {
        ArrayList<String> arr=new ArrayList<String>();
        arr.add("padi");
        arr.add("pravanjan");
        arr.add("reddy");
        System.out.println("printing arrayList: " + arr);
        System.out.println("Printing size of array:" + arr.size());
        System.out.println("Element at index 0 :" + arr.get(0));
        System.out.println("Does arrayList contains padi: "+arr.contains("padi"));
        arr.add(2, "REDDDY");
        System.out.println("printing arrayList: " + arr);
        System.out.println("Index of PERL is "+arr.indexOf("reddy"));
        System.out.println("Printing size of array:" + arr.size());
       
    }
}

Output:
printing arrayList: [padi, pravanjan, reddy]
Printing size of array:3
Element at index 0 :padi
Does arrayList contains padi: true
printing arrayList: [padi, pravanjan, REDDDY, reddy]
Index of PERL is 3
Printing size of array:4

1b) LinkedList:
Java v class uses doublly linked list to store the elements
LinkedList class can contain duplicate elements
LinkedList class maintains insertion order
LinkedList is non synchronized

Sample Code:
package collections;

import java.util.LinkedList;
import java.util.*;

public class LinkedList_Example {
   
    public static void main(String[] args) {
       
   
    LinkedList<String> ll=new LinkedList<String>();
    ll.add("pabbu");
    ll.add("reddy");
    ll.add("aaaaaaaaaa");
    System.out.println("Printin all linked list values : " + ll);
    Iterator<String> itr=ll.iterator();
    while (itr.hasNext()) {
    System.out.println("printing values using iterator :" + itr.next());
       
    }
    }
}

Output:
Printin all linked list values : [pabbu, reddy, aaaaaaaaaa]
printing values using iterator :pabbu
printing values using iterator :reddy
printing values using iterator :aaaaaaaaaa

+++++++++++++++++ Hash Set Class++++++++++++++
HashSet class uses hashtable to store the elements, It extends AbstartctSet class implements Set interface
HashSet contains only unique elemets.
HashSet contains only Values
 Difference between List and Set:
 - List can contains duplicate elements whereas Set contains unique elemenets only.

++++++++++ Sample code using HashSet class +++++++++
package collections;

import java.util.HashSet;
import java.util.Iterator;

public class HashSet_Example {
public static void main(String[] args) {
    HashSet<String> hset=new HashSet<String>();
    hset.add("pabbu");
    hset.add("pabbu");
    hset.add("reddy");
    hset.add("abcd");
    System.out.println("Printin all values from HaseSet: " + hset);
    Iterator<String> itr=hset.iterator();
    while (itr.hasNext()) {
    System.out.println("printin vaue using iterator : " + itr.next());
       
    }
   
}
}

Output :
Printin all values from HaseSet: [pabbu, reddy, abcd]
printin vaue using iterator : pabbu
printin vaue using iterator : reddy
printin vaue using iterator : abcd

++++++++++++++++ Tree Set Class ++++++++++
- Contains uniqe elements like HashSet
 - Maintains ascending order

Sample code for TreeSet :

package collections;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSet_Example {
public static void main(String[] args) {
    TreeSet<String> ts=new TreeSet<String>();
    ts.add("pabbu");
    ts.add("abcd");
    ts.add("reddy");
    ts.add("reddy");
    System.out.println(" Printin all values from TreeSet: " + ts);
    Iterator<String> itr=ts.iterator();
    while(itr.hasNext())
    {
        System.out.println("printin all values using iterator :" + itr.next());
    }
   
   
}
}

Output :
 Printin all values from TreeSet: [abcd, pabbu, reddy]
printin all values using iterator :abcd
printin all values using iterator :pabbu
printin all values using iterator :reddy

+++++++++++++    HashMap               +++++++++++
 - HashMap contains values based on the key. It implements the Map interface and extends the AbstractMap class.
 - It contains only Uniq elements
 - It may have one null key and multiple null values.
 - It maintains no order.

Sample code for HashMap:
package collections;
import java.util.*;
import java.util.HashMap;
import java.util.Map;


public class HashMapTest {
    public static void main(String[] args) {
       
   
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"pabbu");
hm.put(200, "reddy");
hm.put(200, "reddy");

    for(HashMap.Entry m:hm.entrySet())
    {
        System.out.println(m.getKey() + " "+m.getValue());
       
    }
   
    }
}


Output:

100 pabbu
200 reddy

+++++++++++++++
What is difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key and value).

++++++    Hash Table    ++++++++++++++
- HashTable is an array of list. Each list is know as bucket. The position of bucket is identified by calling the hascode() method.
- HashTable contains values based on the Key.
- it contains only Uniq elements.
- It may not have any null key or value.
- It is Synchronized

Sample Code for HashTable:
package collections;

import java.util.Hashtable;
import java.util.Map;

public class HashTable_Test {
    public static void main(String[] args) {
        Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
        ht.put(100,"pabbu");
        ht.put(200, "reddy");
        ht.put(300,"pabbu");
        ht.put(100,"abcd");
        ht.put(400," ");
       
       
        for(Map.Entry m:ht.entrySet())
                {
            System.out.println(m.getKey()+" "+m.getValue());
                }
    }

}

Output:
400 
300 pabbu
200 reddy
100 abcd


++++++++++     Diffrence between HashMap and Hashtable     ++++

    HashMap                                Hashtable
1) HashMap is non synchronized. It is not thread safe.        1) Hashtable is synchronized.It is thread safe and can be shaed with manu threads.
2) HashMap allows one null key and multiple null values        2) Hashtable doesnt allow any null key or value
3) HashMap is a new class introduced in JDK 1.2            3) Hashtable is legacy class
4) HashMap is fast                        4) hASHTABLE is slow
5) We can make HashMap as synchronized by calling
   Map m=Collections.synchronizedMap(hashMap)            5) Hashtable is internally syncronized






Sorting in assending order using java

package java_interview;

public class Sort_AssendingOrder {
    public static void main(String[] args) {

        int[] arr={22,33,11,31,34};
        int t=0;
        for(int i=0;i<arr.length;i++){
        for(int j=i+1;j<arr.length;j++){
        if(arr[i]>arr[j]){
        t=arr[i];
        arr[i]=arr[j];
        arr[j]=t;

        }
        }
        }

        for(int k=0;k<arr.length;k++){
        System.out.println(arr[k]);
        }
    }
}
Output:
11
22
31
33
34

How to get repeated string in java

package java_interview;

public class RepetedStringCount {
    public static void main(String[] args) {

        String s="regression";
        int repeated;

        for(int i=0;i<s.length();i++)
        {
        for(int j=i+1;j<s.length();j++)
        {
        if(i!=j && s.charAt(i)==s.charAt(j)){
        System.out.println(s.charAt(i));
        break;
        }
        }
        }}
}

Output:
r
e
s

Wednesday, 15 June 2016

How to print minimum number and maximum number in java


public class Print_Min_Max_Value {
   

public static void main(String[] args)
{
    int i;  //loop counter
    int[] arr=new int[]{10,20,90,50}; //arrays
    int min=arr[0]; //set values for comparison from start to end of the array
    int max=arr[0]; //set values for comparison from start to end of the array
    for (i=0;i<arr.length;i++)
    {
        if(arr[i]>max)
        {
            max=arr[i];
        }
        else if(arr[i]<min)
        {
            min=arr[i];
        }
    }
    System.out.println(max);
    System.out.println(min);
   
}




}
output:
90
10

How to check whether the given number is prime number or not


public class PrimeNumber_Or_Not {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
int x;
{
    for(x=2;x<=10;x++)
        if(x%2==0)
        {
            System.out.println("not prime" + x);
           
        }
    else {
        System.out.println("prime " + x);
    }
}
    }

   
   
}
Output:
not prime2
prime 3
not prime4
prime 5
not prime6
prime 7
not prime8
prime 9
not prime10

fibonacci example program


public class Fibonacy {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
int a=0;
int b=1;
for(int i=0;i<10;i++)
{
   
    a=a+b;
    //System.out.println("a data"+a);
    b=a-b;
    System.out.println("b data "+b);
}
    }

}

Output:
b data 0
b data 1
b data 1
b data 2
b data 3
b data 5
b data 8
b data 13
b data 21
b data 34

Handling popups using AutoIt


Tuesday, 7 June 2016

How to compare string with and withod using equals

+++String comparison with using equals ++++
package java_interview_logics_practice;

public class CompareStringWithEqual {

    public static void main(String[] args) {
        String s1="abcd";
        String s2="abcd";
        if(s1.equals(s2))
        {
            System.out.println("s1 is equals with s2 :");
        }
        else
        {
            System.out.println("s1 is not equals with s2 :");
        }

    }

}

+++++++++String comparison without using Equals  ++++++

package java_interview_logics_practice;

public class CompareStringWithoutEquals {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
String s1="abcd";
String s2="abcd";
if(s1.length()==s2.length())
{
    for(int i=0;i<s1.length();i++)
    {
        if(s1.charAt(i)!=s2.charAt(i))
        {
            System.out.println("String "+s1+" is not equal to string "+s2);
            break;
        }
    }
     System.out.println("String "+s1+" is equal to string "+s2);
}
else
{
   
    System.out.println("String "+s1+" is not equal to string "+s2);
}

}


    }




How to print values (drop down) using mouse over in selenium(nop ecommerce application)

package pageFactory_POM;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;

public class Example {
    static WebDriver driver;
    //WebDriver driver=new FirefoxDriver();
   
    public List<WebElement> elements;
    @Test
    public void verifyDashboradTabOnAdminpage() throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","D:\\selenium_NEW_PRACTICE\\softwares\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();       
       
        driver.get("http://admin-demo.nopcommerce.com/admin/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*[@id='Email']")).sendKeys("admin@yourstore.com");
        driver.findElement(By.xpath("//*[@id='Password']")).sendKeys("admin");
        driver.findElement(By.xpath("//input[@class='button-1 login-button']")).click();
        Thread.sleep(2000);
       
        //click on catalog button
        WebElement ele=driver.findElement(By.xpath("//img[@src='/Administration/Content/images/ico-catalog.png']"));
        ele.click();
        Thread.sleep(2000);
        System.out.println("Catalog is clicked");
        int catalogMenuSize = driver.findElements(By.xpath("//ul[@id='admin-menu']/li[2]/div/ul/li")).size();
        System.out.println("totall option from dd:" + catalogMenuSize);
        Actions action = new Actions(driver);
        Actions dd = new Actions(driver);
       
        for(int i=1;i<=catalogMenuSize;i++){
            if (i!=2){
                action.moveToElement(driver.findElement(By.xpath("//ul[@id='admin-menu']/li[2]/span"))).build().perform();
                dd.moveToElement(driver.findElement(By.xpath("//ul[@id='admin-menu']/li[2]/div/ul/li[" + i + "]/span"))).build().perform();
                System.out.println( i + ":: " + driver.findElement(By.xpath("//ul[@id='admin-menu']/li[2]/div/ul/li[" + i + "]/span")).getText());
                List<WebElement> elem2 = driver.findElements(By.xpath("//ul[@id='admin-menu']/li[2]/div/ul/li["+i+"]/div/ul/li/a"));
                for(int j=1;j<=elem2.size();j++){
                String subxpath ="(//ul[@id='admin-menu']/li[2]/div/ul/li["+i+"]/div/ul/li/a)["+j+"]";
                System.out.println(" :::: " + driver.findElement(By.xpath(subxpath)).getText());
                }
                }
                else {
                action.moveToElement(driver.findElement(By.xpath("//ul[@id='admin-menu']/li[2]/span"))).build().perform();
                dd.moveToElement(driver.findElement(By.xpath("//ul[@id='admin-menu']/li[2]/div/ul/li[" + i + "]/a"))).build().perform();
                System.out.println( i + ":: " + driver.findElement(By.xpath("//ul[@id='admin-menu']/li[2]/div/ul/li[" + i + "]/a")).getText());
                }
           
            }
    }
}
       
   
       
       
       
       
       
       

Friday, 3 June 2016

How to handle JavaScript alerts or window based popups using Robot keys and selenium

package rough;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.chainsaw.Main;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

import com.mysql.jdbc.Driver;

public class WindowAlertPopup_Handling {
static WebDriver driver;
public static void main(String[] args) throws AWTException, InterruptedException {
    int n = 9;
    //driver=new FirefoxDriver();
    System.setProperty("webdriver.chrome.driver","D:\\selenium_NEW_PRACTICE\\softwares\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.get("http://www.jtable.org/");   
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    driver.findElement(By.xpath("//*[contains(text(),'Export to Excel')]")).click();
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    Thread.sleep(1000);
    /*
    //working fine using Robot keys
    Robot robot=new Robot();
    robot.keyPress(KeyEvent.VK_ALT);
     robot.keyPress(KeyEvent.VK_S);
     robot.keyRelease(KeyEvent.VK_S);
     robot.keyRelease(KeyEvent.VK_ALT);
     robot.keyPress(KeyEvent.VK_ENTER);
      System.out.println("File is downloaded");
      */
   
    //working fine using selenium
    Alert al=driver.switchTo().alert();
    String aleartText=al.getText();
    al.accept();
    System.out.println("clicking alert popup");
   

}
}

How to perform actions on table by using perticular text

package rough;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.chainsaw.Main;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

import com.mysql.jdbc.Driver;

public class If_PerticularTextContains_PerformActions {
static WebDriver driver;
public static void main(String[] args) {
    int n = 9;
    //driver=new FirefoxDriver();
    System.setProperty("webdriver.chrome.driver","D:\\selenium_NEW_PRACTICE\\softwares\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.get("http://www.jtable.org/");   
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    WebElement table=driver.findElement(By.xpath("//*[@id='StudentTableContainer']/div/table"));
    List<WebElement> th=driver.findElements(By.tagName("th"));
    int col_position=0;
    for(int i=0;i<th.size();i++)
    {
    System.out.println(th.get(i).getText());
     if("City".equalsIgnoreCase(th.get(i).getText())){
         col_position=i+1;
         break;
     }
    }
     List<WebElement> FirstColumns = table.findElements(By.xpath("//tr/td["+col_position+"]"));
    String firstNameOnTable=FirstColumns.get(0).getText();
     System.out.println("first :" + firstNameOnTable);
        for(WebElement e: FirstColumns){
         String ss = e.getText();
            System.out.println(ss);
           
            if(ss.equalsIgnoreCase(firstNameOnTable))
                System.out.println("one");
            {
                    driver.findElement(By.xpath("//*[@id='StudentTableContainer']/div/table/tbody/tr[1]/td[9]/button")).click();
           }    
          
    }
   
   
driver.close();
   
}
}

Tuesday, 17 May 2016

Handling page scroll & Actions & Slider bar using selenium

package linkedIn_Interview;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.OutputType.*;

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.screentaker.ViewportPastingStrategy;
public class Question1 {

    static WebDriver d;
    @BeforeMethod
    public void setUp()
    {
        System.setProperty("webdriver.chrome.driver", "D:\\selenium_NEW_PRACTICE\\jars\\chromedriver_win32\\chromedriver.exe");
        d=new ChromeDriver();
        d.manage().window().maximize();
    }
    @Test
    public void verifyLinkedInExam() throws InterruptedException, IOException
    {       
        d.get("http://www.ia.ca");
        getScreenshot();
        //take the screenshot of the entire home page and save it to a png file
        //Screenshot screenshot = new AShot().shootingStrategy(new ViewportPastingStrategy(1000)).takeScreenshot(d);
        //ImageIO.write(screenshot.getImage(), "PNG", new File("D:\\selenium_NEW_PRACTICE\\screenshots\\home"+System.currentTimeMillis()+".png"));
        d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        d.findElement(By.xpath("//span[contains(text(),'Loans')]")).click();
        d.findElement(By.xpath("//a[contains(text(),'Mortgages')]")).click();
        String mortgateTtl=d.getTitle();
        Assert.assertEquals(mortgateTtl, "Mortgage - Mortage rates | iA Financial Group");
        System.out.println("Verify title is pass : ");
        JavascriptExecutor js=(JavascriptExecutor)d;
        js.executeScript("window.scrollBy(0,700)", "");
        System.out.println("page is scrolling to down : " );       
        d.findElement(By.xpath("//a[contains(text(),'Calculate your payments')]")).click();
        JavascriptExecutor js1=(JavascriptExecutor)d;
        js1.executeScript("window.scrollBy(0,700)", "");
        System.out.println("page is scrolling to down : " );
        WebElement slider = d.findElement(By.xpath("//div[contains(@class,'slider slider-horizontal')]"));
        int width=slider.getSize().getWidth();
        System.out.println("printing size width of slider : " + width);
       
        Actions act=new Actions(d);
        act.click(slider).build().perform();
        Thread.sleep(1000);
        for(int i=0;i<2;i++)
        {
            act.sendKeys(Keys.ARROW_RIGHT).build().perform();           
        }
        for(int i=0;i<1;i++)
        {
        d.findElement(By.xpath("//*[@id='MiseDeFondPlus']")).click();
        }
        Select years=new Select(d.findElement(By.xpath("//*[@id='Amortissement']")));
        years.selectByVisibleText("15 years");       
        Select timeFrequency=new Select(d.findElement(By.xpath("//*[@id='FrequenceVersement']")));
        timeFrequency.selectByVisibleText("weekly");
        d.findElement(By.xpath("//*[@id='TauxInteret']")).clear();
        WebElement interestRate=d.findElement(By.xpath("//*[@id='TauxInteret']"));
        interestRate.sendKeys("5");
        d.findElement(By.xpath("//*[@id='btn_calculer']")).click();
        Thread.sleep(1000);
        String weekPayment=d.findElement(By.xpath("//*[@id='paiement-resultats']")).getText();
        System.out.println("printin weekely payment info : " + weekPayment);
        Assert.assertEquals(weekPayment, "$ 836.75");
       
    }
    @Test
    public void getScreenshot()
    {
        //take the screenshot of the entire home page and save it to a png file
                Screenshot screenshot = new AShot().shootingStrategy(new ViewportPastingStrategy(1000)).takeScreenshot(d);
                try
                {
                    ImageIO.write(screenshot.getImage(), "PNG", new File("D:\\selenium_NEW_PRACTICE\\screenshots\\home"+System.currentTimeMillis()+".png"));
                }
                catch(IOException e)
                {
                    System.out.println(e.getMessage());
                   
                }
    }
   
    @AfterMethod
    public void tearDown()
    {
        d.close();
        System.out.println("closing bowser : ");
    }
    }

Get entire page screenshot in selenium


 - Download the ashot.jar file

package linkedIn_Interview;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.OutputType.*;

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.screentaker.ViewportPastingStrategy;
public class Question1 {

    static WebDriver d;
    @BeforeMethod
    public void setUp()
    {
        System.setProperty("webdriver.chrome.driver", "D:\\selenium_NEW_PRACTICE\\jars\\chromedriver_win32\\chromedriver.exe");
        d=new ChromeDriver();
        d.manage().window().maximize();
    }
    @Test
    public void verifyLinkedInExam() throws InterruptedException, IOException
    {       
        d.get("http://www.ia.ca");
        getScreenshot();  //add this method at where u want take screenshot
        //take the screenshot of the entire home page and save it to a png file
        //Screenshot screenshot = new AShot().shootingStrategy(new ViewportPastingStrategy(1000)).takeScreenshot(d);
        //ImageIO.write(screenshot.getImage(), "PNG", new File("D:\\selenium_NEW_PRACTICE\\screenshots\\home"+System.currentTimeMillis()+".png"));
        d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
           @Test
    public void getScreenshot()
    {
        //take the screenshot of the entire home page and save it to a png file
                Screenshot screenshot = new AShot().shootingStrategy(new ViewportPastingStrategy(1000)).takeScreenshot(d);
                try
                {
                    ImageIO.write(screenshot.getImage(), "PNG", new File("D:\\selenium_NEW_PRACTICE\\screenshots\\home"+System.currentTimeMillis()+".png"));
                }
                catch(IOException e)
                {
                    System.out.println(e.getMessage());
                   
                }
    }
   
    @AfterMethod
    public void tearDown()
    {
        d.close();
        System.out.println("closing bowser : ");
    }
    }

Monday, 16 May 2016

Working on window based popups using robot keys with Selenium

package interview;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class Window_Popups_Handling {

    /**
     * @param args
     * @throws AWTException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws AWTException, InterruptedException {
        // TODO Auto-generated method stub

        WebDriver driver=new FirefoxDriver();
               
        driver.get("http://seleniumhq.org/download/");
        driver.manage().timeouts().implicitlyWait(9000,TimeUnit.SECONDS);
        driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/p[6]/a")).click();
        System.out.println("hiiii");
        Robot robot=new Robot();
        Thread.sleep(2000);
          robot.keyPress(KeyEvent.VK_ALT);
          robot.keyPress(KeyEvent.VK_S);
          robot.keyRelease(KeyEvent.VK_S);
           robot.keyRelease(KeyEvent.VK_ALT);
           robot.keyPress(KeyEvent.VK_ENTER);
           System.out.println("File is downloaded");

       
       
       
        //driver.close();
   
    }
   

}

How to select alternate Check box and select all check boxes using selenium

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CheckBox_Alternate_click
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver=new FirefoxDriver();
driver.get("http://www.flipkart.com/mobiles/apple~brand/pr?sid=tyy%2C4io&otracker=ch_vn_mobile_filter_Top+Brands_Apple");
driver.manage().window().maximize();
Thread.sleep(2000);
//List<WebElement> chkboxes = driver.findElements(By.xpath("//input[@type='checkbox']"));////input[contains(@class,'compare-checkbox')]
List<WebElement> chkboxes = driver.findElements(By.xpath("//input[contains(@class,'compare-checkbox')]"));//
for(int i = 0; i<chkboxes.size(); i=i+2)
{
   
chkboxes.get(i).click();
System.out.println("clicking check boxes : ");
}
driver.quit();
}
}

++++++++++++++++++++++++++++++++
public void verifyHandlingCheckBox()
{
    driver.get("http://toolsqa.com/automation-practice-form/?firstname=&lastname=&sex=Female&photo=&continents=Asia&submit=");
    //get and click select check boxes
      List<WebElement> checkBox=driver.findElements(By.cssSelector("input[name=profession]"));
   
    for(int i=0;i<checkBox.size();i++)
    {
         checkBox.get(i).click();
    }
    int checkedCount = 0;
    int uncheckedCount = 0;
    for(int i=0;i<checkBox.size();i++)
    {
        System.out.println(i + " : check box is selected" + checkBox.get(i).isSelected());
        if(checkBox.get(i).isSelected())
        {
            checkedCount++;
        }
        else
        {
            uncheckedCount++;
        }
    }
    System.out.println("number of selected checkbox: "+checkedCount);
    System.out.println("number of unselected checkbox: "+uncheckedCount);
}

Monday, 8 February 2016

What is difference between Hybrid, Native & Web apps(Android/iPhone).



Ans : a) Native app  : Apps which does not need web connectivity. 
  b) Web app   :  App which runs in mobile web browser.
  c) Hybrid app :  App having inbuilt web browser & native app components

Write code to reverse an array(int) of 1 to 10



Ans: a) Using commons.lang java library
public static int arr[]={1,4,2,3,7,6};
public static void revAnArray(int arr[]){
ArrayUtils.reverse(arr);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}

b) Reverse loop

public static void reverseByloop(int[] arr){
int length=arr.length-1;
for(int i=length;i>=0;i--){
System.out.println(arr[i]);
}

What is difference absolute & relative xpath? Write one xpath manually?



Ans:  XPATH is a language that describes how to locate specific elements, attributes, etc. in a xml document. It allows you to locate specific content within an XML document. 
1) Absolute XPath : Relative XPath starts with / ( Note : ‘/’ is used for root path)
b) html/body/div[23]/div[4]/div[1]/div[2]/div/div
2) Relative XPath : Relative XPath starts with // (Note :‘//’ is used for current path)
Syntax//element_type[@attribute_name =’value’]
e.g. a) //*[@id='gbqfba']
b)//div[4]/div[1]/div[2]/div/div
  

Thursday, 4 February 2016

How to execute testng.xml file from main() method or from class/programm



Project Folder structure:




Testng.xml code:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="methods">

  <test name="Sanity">
  
      <classes>
         <class name="interview.Auto_Suggetins_Pass"/>
         
     </classes>
  </test>
     
</suite>

My class file :  to run testng.xml file from class or main method
package interview;

import java.util.List;

import org.testng.TestListenerAdapter;
import org.testng.TestNG;
import org.testng.collections.Lists;

public class Run_TestNGxml_from_main_method {

public static void main(String[] args) {

// //working fine way 1
/*List<String> suites = Lists.newArrayList();
          TestListenerAdapter tla = new TestListenerAdapter();
            TestNG testng = new TestNG();
            Class[] classes = new Class[]{interview.Auto_Suggetins_Pass.class};
             testng.setTestClasses(classes);
            testng.addListener(tla);
             testng.run();*/
             //working fine way 2 
             
  List<String> suites = Lists.newArrayList();         
       TestListenerAdapter tla = new TestListenerAdapter();
       TestNG testng = new TestNG();
       suites.add("testng.xml");
       testng.setTestSuites(suites);
       testng.addListener(tla);
       testng.run();
}
}