Wednesday, 30 December 2015

How to write xpaths in selenium with example

// if class= z-radio-content' in html usinf contains

//label[contains(@class,'z-radio-content')]



How to get newly created file from multiple files in java

//Opening newly created/updated file


import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;


public class Getting_Newly_Added_File_Runnable {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws IOException {
        File dir = new File("D:\\my_sys_backup\\imp_all_data_combined\\imp_all_data_combined\\wednesdayTask04"); //here wednesdayTask04 is folder name it has so many files abc.xls,def.xls.ghi.xls
from this we need get which one is created first

        File [] files  = dir.listFiles();
         Arrays.sort(files, new Comparator(){
            public int compare(Object o1, Object o2) {
                return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                long result = f2.lastModified() - f1.lastModified();
                if( result > 0 ){
                    return 1;
                } else if( result < 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
         //Prints the file names according to modific
      System.out.println( Arrays.asList(files));
      //Prints the Newly created/updated file name and it open the file based on Index number
        System.out.println(Arrays.asList(files).get(0));
        File latestExcelFile=Arrays.asList(files).get(0);
        System.out.println(latestExcelFile.getAbsolutePath());
       //Opening the file at run time
        Desktop.getDesktop().open(new File(latestExcelFile.getAbsolutePath()));
    }

}


















































Find the Radio Button count and get its text using selenium / how to work on radio buttons using selenium


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.firefox.FirefoxDriver;
public class Radiobuttontotal_Pass {

 public static void main(String[] args) throws InterruptedException {
 WebDriver myTestDriver = new FirefoxDriver();
 myTestDriver.get("http://tinyurl.com/cn5pum8");
 myTestDriver.manage().window().maximize();
 myTestDriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

List<WebElement> RadioNamelist = myTestDriver
 .findElements(By
 .xpath("//label[contains(@class,'z-radio-content')]"));

 System.out.println(RadioNamelist.size());

 for(int i=0;i<RadioNamelist.size();i++){
 //System.out.println(RadioNamelist.get(i).getAttribute("name"));
     System.out.println(RadioNamelist.get(i).getText());
   
 }
 myTestDriver.quit();
 }
}

+++++++++++++++++++++++++


package pageFactory_POM;

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

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ToolsQA_Practice_Page {
static WebDriver driver;
@BeforeTest
public void setUp()
{
    System.setProperty("webdriver.chrome.driver","D:\\selenium_NEW_PRACTICE\\softwares\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void verifyRadioBtnFunctionality()
{
    driver.get("http://toolsqa.com/automation-practice-form/?firstname=&lastname=&sex=Female&photo=&continents=Asia&submit=");
    WebElement userName=driver.findElement(By.cssSelector("input[name=firstname]"));
    userName.sendKeys("pabbu");
    WebElement lastname=driver.findElement(By.cssSelector("input[name=lastname]"));
    lastname.sendKeys("reddy");
    //get radio button count
    //List<WebElement> radioBtnCount= driver.findElements(By.cssSelector("input[name=sex]")); //it also works fine
    List<WebElement> radioBtnCount= driver.findElements(By.cssSelector("input[name=sex][type=radio]"));
    System.out.println("print radio button count ::  " + radioBtnCount.size());
    int count=radioBtnCount.size();
    Assert.assertEquals(count, 2, " :: verify radio button count should be 2");
    //get radio button names
    for(int i=0;i<radioBtnCount.size();i++)
    {
        String radioValue = radioBtnCount.get(i).getAttribute("value");
        // Select the Check Box it the value of the Check Box is same what you are looking for
                if (radioValue.equalsIgnoreCase("Male")){
                    radioBtnCount.get(i).click();
                // This will take the execution out of for loop
                break;
                }
    }
    boolean val= driver.findElement(By.cssSelector("input[name=sex][type=radio]")).isSelected();
    Assert.assertTrue(true, "verify male check box is checked: ");
}
@AfterTest
public void tearDown()
{
    driver.close();
}
}
 

Get all header name(Hyper link names) if changing using start with and ends with



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DisplayHeaderLinkNames {

public static String StartString=null;
 public static String EndString=null;


 public static void main(String[] args) {

 WebDriver myTestDriver = new FirefoxDriver();
 myTestDriver.manage().window().maximize();

myTestDriver.navigate().to("http://www.imdb.com/list/GyzpQ_PZLcg/");

 StartString = "//*[@id='main']/div/div[7]/div[";
 EndString = "]/div[3]/b/a";

 for(int i=1;i<=35;i++){
 System.out.println(myTestDriver.findElement(By.xpath(StartString + i + EndString)).getText());
 System.out.println(myTestDriver.findElement(By.xpath(StartString + i + EndString)).getAttribute("href"));;

 }

 myTestDriver.quit();

 }

}

Working with multiple browser instances using JavaScript



import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.openqa.selenium.JavascriptExecutor;

import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;

public class Mul_Browser_Instance {
WebDriver d;
//WebDriver d1=new ChromeDriver();
//d1=System.setProperty("webdriver.chrome.driver", "C:\\v2autoW5.0\\Test\\chromedriver\\chromedriver.exe");
//WebDriver actDriver = new ChromeDriver();
@BeforeTest 
public void start(){ 
  d = new FirefoxDriver();
}
 


         @Test 
          public void SearchSuggestion() throws InterruptedException { 
           
  d.get("http://google.com");     
System.out.println("google from FF");
System.out.println(d.getTitle());

Set<String> listoffirstbrowserwindows=d.getWindowHandles();
System.out.println(listoffirstbrowserwindows);
String firsrbrowser=d.getWindowHandle();
System.out.println(d.getTitle());
((JavascriptExecutor)d).executeScript("window.open();");
Set<String> listofsecondbrowserwindows=d.getWindowHandles();
System.out.println(listofsecondbrowserwindows);
listofsecondbrowserwindows.removeAll(listoffirstbrowserwindows);
System.out.println(listofsecondbrowserwindows);
String secondBrowser=((String)listofsecondbrowserwindows.toArray()[0]);
System.out.println(secondBrowser);
d.switchTo().window(secondBrowser);
//System.setProperty("webdriver.chrome.driver", "C:\\v2autoW5.0\\Test\\chromedriver\\chromedriver.exe");
//WebDriver actDriver = new ChromeDriver();
d.get("https://yahoo.com");
Thread.sleep(2000);
d.switchTo().window(firsrbrowser);
Thread.sleep(2000);
d.switchTo().window(secondBrowser);

Thread.sleep(2000);
d.switchTo().window(firsrbrowser);
System.out.println("last aaa");
Thread.sleep(2000);
d.switchTo().window(secondBrowser);
System.out.println("last bbbb");
//System.setProperty("webdriver.chrome.driver", "C:\\v2autoW5.0\\Test\\chromedriver\\chromedriver.exe");
//WebDriver actDriver = new ChromeDriver();
//actDriver.get("https://webmail.in.v2solutions.com/owa");

//actDriver.get("http://yahoo.com");
//System.out.println("yahoo in chrome");
//System.out.println(actDriver.getTitle());


/*Set<String> mumbro=d.getWindowHandles();
Iterator<String> ii=mumbro.iterator();
String pwin = null;
String cwin= null;
while(ii.hasNext())
    {
    d.switchTo().window(pwin);
    System.out.println("now am in parent browser-1");
    }
d.switchTo().window(cwin);
System.out.println("now am in child browser-1");*/
         }

}

Get or Print the web table data

package interview;

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 WebTable_3 {
static WebDriver driver;
   
    public static void main(String[] args) throws InterruptedException
    {
       
         driver=new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("http://money.rediff.com/");
           
    WebElement element=driver.findElement(By.id("allpage_links"));
    Thread.sleep(5000);
    List<WebElement> rowCollection=element.findElements(By.xpath("//*[@id='allpage_links']/tbody/tr"));


    System.out.println("Numer of rows in this table: "+rowCollection.size());
    //Here i_RowNum and i_ColNum, i am using to indicate Row and Column numbers. It may or may not be required in real-time Test Cases.      
    int i_RowNum=1;
    for(WebElement rowElement:rowCollection)
    {
          List<WebElement> colCollection=rowElement.findElements(By.xpath("td"));
          int i_ColNum=1;
          for(WebElement colElement:colCollection)
          {
               System.out.println("Row "+i_RowNum+" Column "+i_ColNum+" Data "+colElement.getText());
               i_ColNum=i_ColNum+1;
           }
        i_RowNum=i_RowNum+1;
     }
    }
}

=========other way ==========
//Printing the webTable content with using iterator
package interview;

import java.util.Iterator;
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 Print_WebTableContent_With_Iterator {

    static WebDriver driver;
    public static void main(String[] args) {
    driver=new FirefoxDriver();
    driver.get("http://www.w3schools.com/html/html_tables.asp");
    System.out.println("Browser Opened:");
    List<WebElement> we= driver.findElements(By.xpath("//*[@id='main']/table[1]"));
   
    Iterator<WebElement> itr=we.iterator();
    while(itr.hasNext())
    {
        System.out.println(itr.next().getText());
    }
       
   
    }

}

==========Other way+++++++++++
//Runable code to read data from web table
package interview;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;

public class Webtable_4_fb_run {

public static void main(String[] args) {
ProfilesIni pr = new ProfilesIni();
FirefoxProfile fp = pr.getProfile("FirefoxProfile_Selenium");
FirefoxDriver driver = new FirefoxDriver(fp);

driver.get("http://www.timeanddate.com/worldclock/");
driver.manage().window().maximize();

WebElement table = driver.findElement(By.xpath("html/body/div[1]/div[7]/section[2]/div[1]/table"));
List<WebElement> rows = table.findElements(By.tagName("tr"));

for(int i = 0; i<= rows.size(); i++)
{
List<WebElement> cols = rows.get(i).findElements(By.tagName("td"));

for(int j = 0; j < cols.size();j++)
{
System.out.print(cols.get(j).getText() + "---------");
}

System.out.println();
}

}

}

++++++++++++++++++++++++++++++++++++++++++
 package Other;
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;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class Table_Data_Test {
  public String baseURL = "http://accessibility.psu.edu/tablecomplexhtml";
  public WebDriver driver = new FirefoxDriver();

  @BeforeMethod
  public void setup()
  {
   driver.get(baseURL);
  }

  @AfterMethod
  public void tear()
  {
   driver.quit();
  }

  @Test
  public void testTableExample()
  {
   List<WebElement> rows = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr")); // Returns the number of Rows
   List<WebElement> cols = driver.findElements(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td")); // Returns the number of Columns
 
   // Static XPath of a single TR and TD is ".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr[1]/td[1]"
 
   // code to fetch each and every value of a Table
 
   for(int rowNumber = 1; rowNumber <= rows.size(); rowNumber++)
   {
    for(int colNumber = 1; colNumber <= cols.size(); colNumber++)
    {
     System.out.print(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rowNumber+"]/td["+colNumber+"]")).getText()+"  ");
    }
    System.out.println("\n");
   }
 
   System.out.println("###############################################################################\n");

  // nth element value of a table
 
   System.out.println(driver.findElement(By.xpath(".//*[@id='node-281']/div/div[1]/div[2]/table/tbody/tr["+rows.size()+"]/td["+cols.size()+"]")).getText());
 
  }
}

How to get cookie names and delete cookies




import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Cookies {
 public static void main(String[] args){

  WebDriver driver= new FirefoxDriver();
  driver.get("https://gmail.com");
  Set<Cookie> cookee= driver.manage().getCookies();
  Iterator<Cookie> it = cookee.iterator() ;
  while(it.hasNext())
  {
   Cookie c= it.next();
   System.out.println(c.getDomain() + c.getName() );
 
  }

  driver.manage().deleteAllCookies() ;

 }


}
++++++++++++++++++


import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class FindAllCookiesInaWebSite
{
    public static void main(String[] args) 
    {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://in.yahoo.com/");
        
        Set<Cookie> cookies=driver.manage().getCookies();
        
        //To find the number of cookies used by this site
        System.out.println("Number of cookies in this site "+cookies.size());
        
        for(Cookie cookie:cookies)
        {
            System.out.println(cookie.getName()+" "+cookie.getValue());
            
            //This will delete cookie By Name
            //driver.manage().deleteCookieNamed(cookie.getName());
            
            //This will delete the cookie
            //driver.manage().deleteCookie(cookie);
        }
        
        //This will delete all cookies.
        //driver.manage().deleteAllCookies();   
    }
}
 

Select Multiple Options from dropdown


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.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class Select_Multiple_Options_from_dropdwon {
    private static WebDriver driver = null;
    public static void main(String[] args) throws InterruptedException {

        // Create a new instance of the Firefox driver
        driver = new FirefoxDriver();

        // Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        // Launch the URL
        driver.get("http://www.toolsqa.com/automation-practice-form");

        // Step 3: Select 'Selenium Commands' Multiple select box ( Use Name locator to identify the element )
        Select oSelection = new Select(driver.findElement(By.name("selenium_commands")));

        // Step 4: Select option 'Browser Commands'  and then deselect it (Use selectByIndex and deselectByIndex)
        oSelection.selectByIndex(0);
        Thread.sleep(2000);
        oSelection.deselectByIndex(0);

        // Step 5: Select option 'Navigation Commands'  and then deselect it (Use selectByVisibleText and deselectByVisibleText)
        oSelection.selectByVisibleText("Navigation Commands");
        Thread.sleep(2000);
        oSelection.deselectByVisibleText("Navigation Commands");

        // Step 6: Print and select all the options for the selected Multiple selection list.
        List oSize = oSelection.getOptions();
        int iListSize = oSize.size();
        // Setting up the loop to print all the options
        for(int i =0; i < iListSize ; i++){

            // Storing the value of the option   
            String sValue = oSelection.getOptions().get(i).getText();
            // Printing the stored value
            System.out.println(sValue);
            // Selecting all the elements one by one
            oSelection.selectByIndex(i);
            Thread.sleep(2000);
            }

        // Step 7: Deselect all
        oSelection.deselectAll();

        // Kill the browser
        driver.close();
    }
}
 

Select values from drop down one by one (Handling ajax based applications)

import java.util.List;

import java.util.concurrent.TimeUnit;

import org.apache.xalan.trace.SelectionEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


public class Dropdown_2 {
    WebDriver d1;
    @BeforeMethod
     public void start(){ 
           d1 = new FirefoxDriver();  
         } 
    @Test
    public void Ajaxdropdown(){
               
        d1.get("http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx");
        d1.manage().timeouts().implicitlyWait(40,TimeUnit.MINUTES);
        d1.findElement(By.xpath("//*[@id='sourceTab']")).click();
       
       
        Select s1=new Select(d1.findElement(By.xpath("//*[@id='SelectedBranch']")));
        List<WebElement> droplist=s1.getOptions();
        int count=droplist.size();
        System.out.println(count);
        for (WebElement we:droplist)
        {
            System.out.println("dropdown values are:"+we.getText());
        }
        for(int i=0;i<count;i++)
        {
            WebElement countrydropdown1=d1.findElement(By.xpath("//*[@id='SelectedBranch']"));
            countrydropdown1.click();
            Select s2=new Select(countrydropdown1);
            s2.selectByIndex(i);
            WebElement dBox1= (new    WebDriverWait(d1,50)).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='SelectedBranch']")));
            //System.out.println(dBox1);
        }

Tuesday, 29 December 2015

Working with multiple browsers or Multiple windows

package selenium;

import java.util.Set;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class MultipleBrowser  {
    WebDriver driver;
  @Test
  public void multipleBrowsers() throws InterruptedException {
           driver=new FirefoxDriver();
     
          driver.get("https://www.google.co.in/");
          System.out.println(driver.getTitle());
         
//Get a list window handles which are currently opened (the list will contain more than one handle if there are any child windows (popups) opened from parent window, otherwise it will contain only 1 set)
          Set<String> listofallfirstbrowserrelatedwindows = driver.getWindowHandles();
          System.out.println(listofallfirstbrowserrelatedwindows);

//Get the Parent window handle for the firstbrowser window and assgine to firstbrowser
          String firstbrowser = driver.getWindowHandle();
          System.out.println(driver.getTitle());

//open a new window using "executeScript"JavaScript but under same driver umbrella (Means same driver will be able to communicate with this browser also as it is opend under same driver instance)
          ((JavascriptExecutor)driver).executeScript("window.open();");

//Get latest list of the currently open windows (this is supposed to return all the browser handles which are openend under same driver instance (in our case it will be 2))
          Set<String> listofallsecondbrowserrelatedwindows = driver.getWindowHandles();
          System.out.println(listofallsecondbrowserrelatedwindows);
         
// Remove all the browser handle which were openend prior to above second window (in this case, only first browser handle will be removed and second browser handle will remain)   
        listofallsecondbrowserrelatedwindows.removeAll(listofallfirstbrowserrelatedwindows);         
          System.out.println(listofallsecondbrowserrelatedwindows);         

// Assign the above second window handle to a string     
          String secondbrowser = ((String)listofallsecondbrowserrelatedwindows.toArray()[0]);
          System.out.println(secondbrowser);

// NOTE : NOW YOU HAVE TWO SEPERATE HANDLE IN TWO STRINGS (firstbrowser, secondbrowser), WHICH YOU CAN USE with drive to switch between both browsers.

// switch to secondbrowser (i.e. second window)         
          driver.switchTo().window(secondbrowser);
          driver.get("https://in.yahoo.com/");
        Thread.sleep(2000);     

// switch to firstbrowser (i.e. first window)         
          driver.switchTo().window(firstbrowser);
          driver.manage().window().maximize();
        Thread.sleep(2000);
// switch to secondbrowser (i.e. second window)         
          driver.switchTo().window(secondbrowser);
         
  }

}

Working on Multiple Frames

package abcpack;

import static org.junit.Assert.assertEquals;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MultiFrame {
    WebDriver d;
    @Test
    public void testMultiFrame() throws Exception
    {
        //Load the web page
        d.get("http://seleniumhq.github.io/selenium/docs/api/java/index.html");
        assertEquals("Overview",d.getTitle());
        List<WebElement> f=d.findElements(By.tagName("frame"));
        System.out.println("No of frames:"+f.size());
        //Switch driver focus to 1st frame
        d.switchTo().frame(0);
        d.findElement(By.linkText("com.thoughtworks.selenium")).click();
        d.switchTo().defaultContent();
        //Switch driver focus to 2nd frame
        d.switchTo().frame(1);
        d.findElement(By.linkText("Selenium")).click();
        d.switchTo().defaultContent();
        //Switch driver focus to 3rd frame
        d.switchTo().frame(2);
        assertEquals("Interface Selenium",d.findElement(By.className("title")).getText());
       
        Thread.sleep(4000);
    }
    @Before
    public void setUp()
    {
        //Launch browser
        d=new FirefoxDriver();
         d.manage().window().maximize();
        d.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
    }
    @After
    public void tearDown()
    {
        //Close browser
        d.quit();
    }


}

Remove duplicates from Array in java

package java_interview;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class Duplicate_String_Remover_Without_String
{
    static int[]  arr={1,2,3,1,4,5,3};
   
public static void main(String[] args) {
   
    //Way 1 pass
    /*TreeSet<String> set=new TreeSet<String>();
    set.add("pabbu");
    set.add("reddy");
    set.add("java_practice");
    set.add("reddy");
    set.add("aaa");
    System.out.println("printing all values from tree set: " + set);
    Iterator<String> itr=set.iterator();
        while(itr.hasNext())
        {
        System.out.println("printin tree values after iterating: " + itr.next());       
   
        }
*/
   
    //Way 2 pass   
   
        int end = arr.length;
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < end; i++) {
            set.add(arr[i]);
        }
        Iterator it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }


}

Write code for Palindrome and reverce string. e.g madam, dad




Way 1: Using For loop  :
package java_interview;

public class Polindrom_Using_ForLoop {
    static String original="abac";
  
    public static void main(String[] args) {
      
  
        String reverse="";
        int length = original.length();
        
          for ( int i = length - 1 ; i >= 0 ; i-- )
             reverse = reverse + original.charAt(i);
    
          if (original.equals(reverse))
             System.out.println(original+" is a palindrome.");
          else
             System.out.println(original+" is not a palindrome.");
    }
}


Way2 : Using String Builder:

package java_interview;

public class Polindrom_Test {
static String txt="madam";
public static void main(String[] args)
{
//Using string builder
String strbuilderTxt=new StringBuilder(txt).reverse().toString();
System.out.println("Printing string using string builder class : " + strbuilderTxt);
if(txt.equals(strbuilderTxt))
{
    System.out.println("Ploindrome :");
}
else {
    System.out.println("Not a Ploindrome :");
}
}
}
 

Selenium Grid



 Selenium-Grid allows you run your tests on different machines against different browsers in parallel.
Start hubjava -jar selenium-server-standalone-2.38.0.jar -role hub
Start nodejava -jar selenium-server-standalone-2.38.0.jar -role node  -hub http://localhost:4444/grid/register
Create RemoteWebDriver object
WebDriver driver = new RemoteWebDriver(hub-url,capabilities);

Difference between JUnit&TestNG?




Selenium code for 'google search' auto suggestions and print result?



public class Auto_Suggestions {  
   
WebDriver driver;  
   
 @BeforeTest  
 public void start(){  
   driver = new FirefoxDriver();   
 }  
    
 @Test  
  public void SearchSuggestion() {  
    
  driver.get("http://google.com");  
  driver.findElement(By.id("gbqfq")).sendKeys("v2tech");  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
    
   WebElement table = driver.findElement(By.className("gssb_m"));   
   List<WebElement> rows = table.findElements(By.tagName("tr"));   
   Iterator<WebElement> i = rows.iterator();   
   System.out.println("-----google auto suggestions are:---------");   
   while(i.hasNext()) {   
           WebElement row = i.next();   
           List<WebElement> columns = row.findElements(By.tagName("td"));   
           Iterator<WebElement> j = columns.iterator();   
           while(j.hasNext()) {   
                   WebElement column = j.next();   
                   System.out.println(column.getText());   
           }   
           System.out.println("");   
              
   System.out.println("google auto suggestions are:");   
   }   
  }   
}