Tuesday, May 29, 2018

How to Scroll & Zoom to an element in selenium webdriver using java

public void scrollToElemet(WebElement element) {
executeScript("window.scrollTo(arguments[0],arguments[1])", element.getLocation().x, element.getLocation().y);

}

public void scrollToElemetAndClick(WebElement element) {
scrollToElemet(element);
element.click();

}

public void scrollIntoView(WebElement element) {
executeScript("arguments[0].scrollIntoView()", element);

}

public void scrollIntoViewAndClick(WebElement element) {
scrollIntoView(element);
element.click();

}

public void scrollDownVertically() {
executeScript("window.scrollTo(0, document.body.scrollHeight)");
}

public void scrollUpVertically() {
executeScript("window.scrollTo(0, -document.body.scrollHeight)");
}

public void scrollDownByPixel() {
executeScript("window.scrollBy(0,1500)");
}

public void scrollUpByPixel() {
executeScript("window.scrollBy(0,-1500)");
}

public void ZoomInBypercentage() {
executeScript("document.body.style.zoom='40%'");
}

public void ZoomBy100percentage() {
executeScript("document.body.style.zoom='100%'");
}

How to write custome wait method in selenium webdriver using Java

package com.guru99.utils;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;

import com.guru99.testBase.TestBase;

public class WaitUtil extends TestBase
{

public static void waitForPageToLoad(long timeOutInSeconds,WebDriver driver) {

ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {

public Boolean apply(WebDriver driver) {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
try {
// System.out.println("Waiting for page to load...");
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(expectation);

} catch (Throwable error) {
System.out.println(
"Timeout waiting for Page Load Request to complete after " + timeOutInSeconds + " seconds");
Assert.assertFalse(true, "Timeout waiting for Page Load Request to complete.");

}
}

}

How to Read Xml file using java - 2nd Method

package com.guru99.readers;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class DomParserDemo {

   public static void main(String[] args) {

      try {
         File inputFile = new File("input.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("student");
         System.out.println("----------------------------");
       
         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());
           
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               System.out.println("Student roll no : "
                  + eElement.getAttribute("rollno"));
               System.out.println("First Name : "
                  + eElement
                  .getElementsByTagName("firstname")
                  .item(0)
                  .getTextContent());
               System.out.println("Last Name : "
                  + eElement
                  .getElementsByTagName("lastname")
                  .item(0)
                  .getTextContent());
               System.out.println("Nick Name : "
                  + eElement
                  .getElementsByTagName("nickname")
                  .item(0)
                  .getTextContent());
               System.out.println("Marks : "
                  + eElement
                  .getElementsByTagName("marks")
                  .item(0)
                  .getTextContent());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

How to Read CSV file using Java

package com.guru99.readers;

import java.io.File;
import java.util.Scanner;

public class CSVReader {

public static void main(String[] args) {
String fileName ="data.csv";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
System.out.println("Salary");
while(inputStream.hasNext()){
String data = inputStream.next();
String[] values = data.split(",");

System.out.println(values[2]);
//System.out.println(data );
}
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}

}

}

How to Write to JSon file using Java

package com.guru99.readers;
import java.io.FileWriter;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class WriteToJson
{
    @SuppressWarnings("unchecked")
    public static void main( String[] args )
    {
        //First Employee
        JSONObject employeeDetails = new JSONObject();
        employeeDetails.put("firstName", "Ramesh");
        employeeDetails.put("lastName", "Kudikala");
        employeeDetails.put("website", "howtodoinjava.com");
       
        JSONObject employeeObject = new JSONObject();
        employeeObject.put("employee", employeeDetails);
       
        //Second Employee
        JSONObject employeeDetails2 = new JSONObject();
        employeeDetails2.put("firstName", "Raghu");
        employeeDetails2.put("lastName", "Kunchey");
        employeeDetails2.put("website", "example.com");
       
        JSONObject employeeObject2 = new JSONObject();
        employeeObject2.put("employee", employeeDetails2);
       
        //Add employees to list
        JSONArray employeeList = new JSONArray();
        employeeList.add(employeeObject);
        employeeList.add(employeeObject2);
       
        //Write JSON file
        try (FileWriter file = new FileWriter("pathof\\jsonData.json")) {

            file.write(employeeList.toJSONString());
            file.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


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

[{"employee":{"firstName":"Lokesh","lastName":"Gupta","website":"howtodoinjava.com"}},{"employee":{"firstName":"Brian","lastName":"Schultz","website":"example.com"}}]

How to Read Json file using Java

package com.guru99.readers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonReader
{
   @SuppressWarnings("unchecked")
   public static void main(String[] args)
   {
       //JSON parser object to parse read file
       JSONParser jsonParser = new JSONParser();
       
       try {
       FileReader reader = new FileReader("pathof\\jsonData.json");
     
           //Read JSON file
           Object obj = jsonParser.parse(reader);

           JSONArray employeeList = (JSONArray) obj;
           System.out.println(employeeList);
           
           //Iterate over employee array
           employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );

       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ParseException e) {
           e.printStackTrace();
       }
   }

   private static void parseEmployeeObject(JSONObject employee)
   {
       //Get employee object within list
       JSONObject employeeObject = (JSONObject) employee.get("employee");
       
       //Get employee first name
       String firstName = (String) employeeObject.get("firstName"); 
       System.out.println(firstName);
       
       //Get employee last name
       String lastName = (String) employeeObject.get("lastName");
       System.out.println(lastName);
       
       //Get employee website name
       String website = (String) employeeObject.get("website"); 
       System.out.println(website);
   }
}

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...