Tuesday, December 30, 2014

Selecting a date from Datepicker using Selenium WebDriver

  driver.switchTo().frame(0); 
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
 //Click on textbox so that datepicker will come 
  driver.findElement(By.id("datepicker")).click(); 
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); 
  //Click on next so that we will be in next month 
  driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click(); 
   
  /*DatePicker is a table.So navigate to each cell  
   * If a particular cell matches value 13 then select it 
   */ 
  WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div")); 
  List rows=dateWidget.findElements(By.tagName("tr")); 
  List columns=dateWidget.findElements(By.tagName("td")); 
   
  for (WebElement cell: columns){ 
   //Select 13th Date  
   if (cell.getText().equals("13")){ 
   cell.findElement(By.linkText("13")).click(); 
   break; 
   } 
  }  
 
  (OR)
 
   WebElement dateWidget;
 List rows;
 List columns;
 List list = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
 // Expected Date, Month and Year
 int expMonth;
 int expYear;
 String expDate = null;
 // Calendar Month and Year
 String calMonth = null;
 String calYear = null;
 boolean dateNotFound;

 driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on textbox of Date so that datepicker will appear
  driver.findElement(By.id("datepicker")).click();
  dateNotFound = true;
  expMonth= 3;
  expYear = 2015;
  expDate = "12";
  while(dateNotFound)
  {
 
   calMonth = driver.findElement(By.className("ui-datepicker-month")).getText();
   calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
   if(list.indexOf(calMonth)+1 == expMonth && (expYear == Integer.parseInt(calYear)))
   {
    selectDate(expDate);
    dateNotFound = false;
   }
   else if(list.indexOf(calMonth)+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
   }
   else if(list.indexOf(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span")).click();
   }
  }
  Thread.sleep(3000);
 }

 public void selectDate(String date)
 {
 dateWidget = driver.findElement(By.id("ui-datepicker-div"));
 rows=dateWidget.findElements(By.tagName("tr"));
 columns=dateWidget.findElements(By.tagName("td"));

 for (WebElement cell: columns){
  //Selects Date
  if (cell.getText().equals(date)){
   cell.findElement(By.linkText(date)).click();
   break;
  }
 }
 }

 
Datepicker

Tuesday, December 23, 2014

@DataProvider Annotation in TestNG

 
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderExample {

//This test method declares that its data should be supplied by the Data Provider
// "getdata" is the function name which is passing the data
// Number of columns should match the number of input parameters
 
@Test(dataProvider="getData")
public void setData(String username, String password)
{
System.out.println("you have provided username as::"+username);
System.out.println("you have provided password as::"+password);
}

@DataProvider
public Object[][] getData()
{
//Rows - Number of times your test has to be repeated.
//Columns - Number of parameters in test data.
Object[][] data = new Object[3][2];

// 1st row
data[0][0] ="sampleuser1";
data[0][1] = "abcdef";

// 2nd row
data[1][0] ="testuser2";
data[1][1] = "zxcvb";
// 3rd row
data[2][0] ="guestuser3";
data[2][1] = "pass123";

return data;
}
}

Tuesday, October 21, 2014

Java Code to convert Html to PDF Using wkhtmltopdf

Basic thing to do:
     Need to install all the basic stuffs for java and download wkhtmltopdf from below link
     Link : http://code.google.com/p/wkhtmltopdf/downloads/detail?name=wkhtmltopdf-0.9.9-installer.exe&
Source Code :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Java_pdf {
   public static void main(String[] args) throws IOException {
        try
        {
            String htmlFilePath = "D:/html2pdf/a.html";
            String pdfFilePath = "D:/html2pdf/test.pdf";
            ProcessBuilder pb = new ProcessBuilder("C:/Program Files/wkhtmltopdf/wkhtmltopdf.exe", htmlFilePath, pdfFilePath);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
          
            String line = inStreamReader.readLine();
          
                    while(line != null)
                    {
                        System.out.println(line);
                        line = inStreamReader.readLine();
                    }
        }
        catch(Exception e)
        {
            System.out.println("coming-->"+e.getMessage() );
        }
    }
}

Saturday, September 13, 2014

JFree Chart for Test Case Execution Status


import java.io.File;
import java.io.IOException;
import org.jfree.chart.*;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;


 public void pieChartReport()

 {

  // Creating a simple pie chart with 
DefaultPieDataset dataset = new DefaultPieDataset();

   dataset.setValue("PASSED", new Integer(60));
   dataset.setValue("FAILED", new Integer(25));
   dataset.setValue("SKIPPED", new Integer(10));
   dataset.setValue("NOTRUN", new Integer(5));


  JFreeChart piechart = ChartFactory.createPieChart("Test Cases Execution  Status", dataset, true, true, false);
PiePlot plot = (PiePlot) piechart.getPlot();

PieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator("{0} = {2}", new DecimalFormat("0"),new DecimalFormat("0.00%"));

       
        plot.setLabelGenerator(generator);
        plot.setBackgroundPaint(Color.WHITE);
        plot.setSectionPaint("PASSED", Color.GREEN);
        plot.setSectionPaint("FAILED", Color.RED);
        plot.setSectionPaint("SKIPPED", Color.BLUE);
        plot.setSectionPaint("NOTRUN", Color.YELLOW);

   try {

   ChartUtilities.saveChartAsJPEG(new File(

"D:\\simplePiechart.jpg"), 1, piechart, 640, 480);

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }
 
Note: Required JFreeChart and JCommon jars.
 

Tuesday, August 12, 2014

TestLink Integration With Selenium

package com.test;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import testlink.api.java.client.TestLinkAPIClient;
import testlink.api.java.client.TestLinkAPIException;
import testlink.api.java.client.TestLinkAPIResults;

public class AutomatedUpdateExample {

public static String DEVKEY="2f404203b306bd8dd811a7f824c194d0";
public static String URL="http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php";

public static void reportResult(String TestProject,String TestPlan,String Testcase,String Build,String Notes,String Result) throws TestLinkAPIException{
TestLinkAPIClient api=new TestLinkAPIClient(DEVKEY, URL);
api.reportTestCaseResult(TestProject, TestPlan, Testcase, Build, Notes, Result);
}

@Test
public void Test1()throws Exception
{
AutomatedUpdateExample a=new AutomatedUpdateExample();
WebDriver driver=new FirefoxDriver();
WebDriverWait wait=new WebDriverWait(driver, 600);
String testProject="Gmail";
String testPlan="SampleTestPlan";
String testCase="GmailLogin1";
String build="SampleBuild";
String notes=null;
String result=null;
try{
driver.manage().window().maximize();
driver.get("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1");
driver.findElement(By.id("Email")).sendKeys("testlink.msoftgp");
driver.findElement(By.id("Passwd")).sendKeys("*******");
driver.findElement(By.id("signIn")).click();
driver.switchTo().defaultContent();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("+Testlink")));
result= TestLinkAPIResults.TEST_PASSED;
notes="Executed successfully";
}
catch(Exception e){
result=TestLinkAPIResults.TEST_FAILED;
notes="Execution failed";
}
finally{

api.reportResult(testProject, testPlan, testCase, build, notes, result);
driver.quit();
}
}
}

Tuesday, April 15, 2014

XML File Reading, Generation and Modification in Java

Reading:
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;
import java.io.File;
public class ReadXML {
public static void main(String arg[]) {
try {
File inputfile = new File(System.getProperty("user.dir") + "\\OR.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docbuilder = dbFactory.newDocumentBuilder();
Document doc = docbuilder.parse(inputfile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodelist = doc.getElementsByTagName("Object");
System.out.println("##################################");
for (int tmp = 0; tmp < nodelist.getLength(); tmp++) {
Node nNode = nodelist.item(tmp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("object name : " + eElement.getAttribute("name"));
System.out.println(
"propertytype : " + eElement.getElementsByTagName("propertytype").item(0).getTextContent());
System.out.println("propertyvalue: "
+ eElement.getElementsByTagName("propertyvalue").item(0).getTextContent());
System.out.println("--------------------------------------");
}
}
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
}
}
 

Generation:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLFileGeneration {

public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("suite");
doc.appendChild(rootElement);
Attr attributeSuite = doc.createAttribute("name");
attributeSuite.setValue("Suite");
rootElement.setAttributeNode(attributeSuite);
attributeSuite = doc.createAttribute("parallel");
attributeSuite.setValue("none");
rootElement.setAttributeNode(attributeSuite);
// staff elements
Element test = doc.createElement("test");
rootElement.appendChild(test);
// set attribute to staff element
Attr attr = doc.createAttribute("name");
attr.setValue("Test");
test.setAttributeNode(attr);
attr = doc.createAttribute("preserve-order");
attr.setValue("true");
test.setAttributeNode(attr);
// firstname elements
Element classes = doc.createElement("classes");
test.appendChild(classes);
// lastname elements
Element class1 = doc.createElement("class");
classes.appendChild(class1);
attr = doc.createAttribute("name");
attr.setValue("com.abc.testscript.javafile");
class1.setAttributeNode(attr);
// nickname elements methods
Element methods = doc.createElement("methods");
class1.appendChild(methods);
// lastname elements
Element include = doc.createElement("include");
methods.appendChild(include);
attr = doc.createAttribute("name");
attr.setValue("MethodName");
include.setAttributeNode(attr);
Element listeners = doc.createElement("listeners");
rootElement.appendChild(listeners);
Element listener = doc.createElement("listener");
listeners.appendChild(listener);
attr = doc.createAttribute("class-name");
attr.setValue("com.abc.listener.TestListener");
listener.setAttributeNode(attr);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(System.getProperty("user.dir") + "/testNG.xml"));
// Output to console for testing
transformer.transform(source, result);
System.out.println(" XML File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}

Modification:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

public static void main(String[] args) {
String filePath = "employee.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();

// update attribute value
updateAttributeValue(doc);
// update Element value
updateElementValue(doc);
// delete element
deleteElement(doc);
// add new element
addElement(doc);

// write the updated document to file or console
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("employee_updated.xml"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("XML file updated successfully");

} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {

e1.printStackTrace();

}
}

private static void addElement(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
Element salaryElement = doc.createElement("salary");
salaryElement.appendChild(doc.createTextNode("10000"));
emp.appendChild(salaryElement);
}
}

private static void deleteElement(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
Node genderNode = emp.getElementsByTagName("gender").item(0);
emp.removeChild(genderNode);
}
}

private static void deleteNodes(Document doc) {
NodeList steps = doc.getElementsByTagName("Employee");
for (int i = 0; i < steps.getLength(); i++) {
Node node = steps.item(i);
node.getParentNode().removeChild(node);
}
}

private static void deleteChildNodes(Document doc) {
NodeList steps = doc.getElementsByTagName("Employee");
for (int i = 0; i < steps.getLength(); i++) {
Node node = steps.item(i);
NodeList nList = node.getChildNodes();
for (int j = 0; j < nList.getLength(); j++) {
Node cnode = nList.item(j);
cnode.getParentNode().removeChild(cnode);
}
}
}

private static void updateElementValue(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
Node name = emp.getElementsByTagName("name").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().toUpperCase());
}
}

private static void updateAttributeValue(Document doc) {
NodeList employees = doc.getElementsByTagName("Employee");
Element emp = null;
// loop for each employee
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element) employees.item(i);
String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
if (gender.equalsIgnoreCase("male")) {
// prefix id attribute with M
emp.setAttribute("id", "M" + emp.getAttribute("id"));
} else {
// prefix id attribute with F
emp.setAttribute("id", "F" + emp.getAttribute("id"));
}
}
}

}

Comparing 2 images in Java-Selenium

import java.awt.Image; 
import java.awt.Toolkit;  
import java.awt.image.PixelGrabber;  
import java.io.File;

public static String processImage() {
System.out.println("Executing processImage Keyword");
try {
String file1 = "D:\\Images\\images.JPEG";
String file2 = "D:\\Images\\images2.JPEG";
Image pic1= Toolkit.getDefaultToolkit().getImage(file1);
Image pic2= Toolkit.getDefaultToolkit().getImage(file2);
try {
PixelGrabber grab11 = new PixelGrabber(pic1, 0, 0, -1, -1,
false);
PixelGrabber grab21 = new PixelGrabber(pic2, 0, 0, -1, -1,
false);
int[] array1= null;
if (grab11.grabPixels()) {
int width = grab11.getWidth();
int height = grab11.getHeight();
array1= new int[width * height];
array1= (int[]) grab11.getPixels();
}
int[] array2 = null;
if (grab21.grabPixels()) {
int width = grab21.getWidth();
int height = grab21.getHeight();
array2 = new int[width * height];
array2 = (int[]) grab21.getPixels();
}
System.out.println("Pixels equal: "
+ java.util.Arrays.equals(array1, array2 ));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
return "Pass";
} catch (Throwable t) {
// report error
return "Fail - " + t.getMessage();
}
}