How to write a completed Jmeter Test Plan for load testing using Jmeter API in Java

 Jmeter is excellent tool used to do load testing on the application. Jmeter has graphical(GUI) and Non graphical(Non GUI) options. Non graphical option use Jmeter API to write a complete test plan for loading testing in java.
Pre-prerequisites:
1. JMeter install somewhere.
2. Add JMeter jars from /lib and especially /lib/ext folders in your project or module class path.

Load the jmeter properties:
 //Set jmeter home for the jmeter utils to load  
 String jmeterHomelocation = "F:\\apache-jmeter-2.13\\";  
 String jmeterPropertieslocation = jmeterHomelocation + "bin\\jmeter.properties";  
   
 //JMeter Engine  
 StandardJMeterEngine jmeter = new StandardJMeterEngine();  
   
 //JMeter initialization (properties, log levels, locale, etc)  
 JMeterUtils.setJMeterHome(new File(jmeterHomelocation).getPath());  
 JMeterUtils.loadJMeterProperties(new File(jmeterPropertieslocation).getPath());  
 // see extra log messages of i.e. DEBUG level  
 JMeterUtils.initLogging();  
 JMeterUtils.initLocale();  

Create "Test Plan" Object and JOrphan HashTree:
 // JMeter Test Plan, basically JOrphan HashTree  
 HashTree testPlanTree = new HashTree();  
             
 // Test Plan  
 TestPlan testPlan = new TestPlan("Java code Test Plan");  
 testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());  
 testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());  
 testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());  

Graphical: Thread Group
Right-click on the Test Plan > Add > Threads (Users) > Thread Group
Type below values in corresponding field
Number of Threads (users)   : 1
Ramp-Up Period (in seconds) : 1
Loop Count  : 1
Non Graphical: Thread Group
 // Thread Group  
 ThreadGroup threadGroup = new ThreadGroup();  
 threadGroup.setName("Test Thread Group");  
 threadGroup.setNumThreads(1);  
 threadGroup.setRampUp(1);  
 threadGroup.setSamplerController(loopCtrl);  
 threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());  
 threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());  

Graphical: Sampler
Right-click on the Thread Group > Add > Sampler > HTTP request
Write below values in corresponding field
Server Name or IP : hiromia.blogspot.com
Port NUmber       : 80
Path              : /

Non Graphical: Sampler
 HTTPSampler examplecomSampler = new HTTPSampler();  
 examplecomSampler.setDomain("www.google.com");  
 examplecomSampler.setPort(80);  
 examplecomSampler.setPath("/");  
 examplecomSampler.setMethod("GET");  
 examplecomSampler.setName("google");  
 examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSampler.class.getName());  
 examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());  
Loop Controller:
 // Loop Controller  
  LoopController loopCtrl = new LoopController();  
  loopCtrl.setLoops(10);  
  loopCtrl.setFirst(true);  
  loopCtrl.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());  
  loopCtrl.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());  
  loopCtrl.initialize();  

Graphical: Summary Report
Right-click on the Thread Group > Add > Listener > Summary Report

Non Graphical: Summary Report
 Summariser summer = null;  
  String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");  
  if (summariserName.length() > 0) {  
    summer = new Summariser(summariserName);  
  }  
   
 // Store execution results into a .jtl file, we can save file as csv also  
  String reportFile = "report\\report.jtl";  
  String csvFile = "report\\report.csv";  
  ResultCollector logger = new ResultCollector(summer);  
  logger.setFilename(reportFile);  
  ResultCollector csvlogger = new ResultCollector(summer);  
  csvlogger.setFilename(csvFile);  
  testPlanTree.add(testPlanTree.getArray()[0], logger);  
  testPlanTree.add(testPlanTree.getArray()[0], csvlogger);  
   

Run Test Plan:
 // Run Test Plan  
 jmeter.configure(testPlanTree);  
 jmeter.run()  

Completed Jmeter Test Plan java source code:
 import java.io.File;  
 import java.io.FileOutputStream;  
 import org.apache.jmeter.config.Arguments;  
 import org.apache.jmeter.config.gui.ArgumentsPanel;  
 import org.apache.jmeter.control.LoopController;  
 import org.apache.jmeter.control.gui.LoopControlPanel;  
 import org.apache.jmeter.control.gui.TestPlanGui;  
 import org.apache.jmeter.engine.StandardJMeterEngine;  
 import org.apache.jmeter.protocol.http.control.gui.HttpTestSampleGui;  
 import org.apache.jmeter.protocol.http.sampler.HTTPSampler;  
 import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;  
 import org.apache.jmeter.reporters.ResultCollector;  
 import org.apache.jmeter.reporters.Summariser;  
 import org.apache.jmeter.save.SaveService;  
 import org.apache.jmeter.testelement.TestElement;  
 import org.apache.jmeter.testelement.TestPlan;  
 import org.apache.jmeter.threads.ThreadGroup;  
 import org.apache.jmeter.threads.gui.ThreadGroupGui;  
 import org.apache.jmeter.util.JMeterUtils;  
 import org.apache.jorphan.collections.HashTree;  
   
   
 public class CompleteNongraphicaljplan {  
   public static void main(String[] argv) throws Exception {  
   
     //Set jmeter home for the jmeter utils to load  
     String jmeterHomelocation = "F:\\apache-jmeter-2.13\\";  
     String jmeterPropertieslocation = jmeterHomelocation + "bin\\jmeter.properties";  
   
   
     //JMeter Engine  
     StandardJMeterEngine jmeter = new StandardJMeterEngine();  
   
     //JMeter initialization (properties, log levels, locale, etc)  
     JMeterUtils.setJMeterHome(new File(jmeterHomelocation).getPath());  
     JMeterUtils.loadJMeterProperties(new File(jmeterPropertieslocation).getPath());  
     // see extra log messages of i.e. DEBUG level  
     JMeterUtils.initLogging();  
     JMeterUtils.initLocale();  
   
     // JMeter Test Plan, basically JOrphan HashTree  
     HashTree testPlanTree = new HashTree();  
   
     // First HTTP Sampler - open google.com  
     HTTPSampler examplecomSampler = new HTTPSampler();  
     examplecomSampler.setDomain("www.google.com");  
     examplecomSampler.setPort(80);  
     examplecomSampler.setPath("/");  
     examplecomSampler.setMethod("GET");  
     examplecomSampler.setName("google");  
     examplecomSampler.setProperty(TestElement.TEST_CLASS, HTTPSampler.class.getName());  
     examplecomSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());  
   
   
     // Loop Controller  
     LoopController loopCtrl = new LoopController();  
     loopCtrl.setLoops(10);  
     loopCtrl.setFirst(true);  
     loopCtrl.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());  
     loopCtrl.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());  
     loopCtrl.initialize();  
   
     // Thread Group  
     ThreadGroup threadGroup = new ThreadGroup();  
     threadGroup.setName("Test Thread Group");  
     threadGroup.setNumThreads(1);  
     threadGroup.setRampUp(1);  
     threadGroup.setSamplerController(loopCtrl);  
     threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());  
     threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());  
   
     // Test Plan  
     TestPlan testPlan = new TestPlan("Java code Test Plan");  
     testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());  
     testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());  
     testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());  
   
     // Construct Test Plan from previously initialized elements  
     testPlanTree.add(testPlan);  
     HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);  
     threadGroupHashTree.add(examplecomSampler);  
       
   
     // save generated test plan to JMeter's .jmx file format  
     SaveService.saveTree(testPlanTree, new FileOutputStream("report\\jmeter_api_sample.jmx"));  
   
     //add Summarizer output to get test progress in stdout like:  
     // summary =   2 in  1.3s =  1.5/s Avg:  631 Min:  290 Max:  973 Err:   0 (0.00%)  
     Summariser summer = null;  
     String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");  
     if (summariserName.length() > 0) {  
       summer = new Summariser(summariserName);  
     }  
   
   
     // Store execution results into a .jtl file, we can save file as csv also  
     String reportFile = "summaryreport.jtl";  
     String csvFile = "summaryreport.csv";  
     ResultCollector logger = new ResultCollector(summer);  
     logger.setFilename(reportFile);  
     ResultCollector csvlogger = new ResultCollector(summer);  
     csvlogger.setFilename(csvFile);  
     testPlanTree.add(testPlanTree.getArray()[0], logger);  
     testPlanTree.add(testPlanTree.getArray()[0], csvlogger);  
       
           // Run Test Plan  
     jmeter.configure(testPlanTree);  
     jmeter.run();  
   
   
     System.exit(0);  
   
   
   }  
 }  
   

Output:

How to run Jmeter load testing script using java.

JMeter API has an option to run JMeter script which made by Jmeter GUI using java. StandardJMeterEngine is the 'heart' of JMeter. If you must execute a JMeter test from Java code, this is the best option. The absolute minimal code to read the existing .jmx file.
Pre-prerequisites:
1. JMeter install somewhere.
2. Add JMeter jars from /lib and especially /lib/ext folders in your project or module class path.

Build Jmeter load testing script using below steps:
1. Start Jmeter
Click on Jmeter_Home/bin/ApacheJMeter.jar or jmeter.sh to open Jmeter window

2. Add 'Thread Group' under 'Test Plan'
Right-click on the Test Plan > Add > Threads (Users) > Thread Group
Type below values in corresponding field
Number of Threads (users)   : 1
Ramp-Up Period (in seconds) : 1
Loop Count                  : 1

3. Add a Sampler under 'Thread Group'
Right-click on the Thread Group > Add > Sampler > HTTP request
Write below values in corresponding field
Server Name or IP : hiromia.blogspot.com
Port NUmber       : 80
Path              : /

4. Add Listener under 'Thread Group'
Right-click on the Thread Group > Add > Listener > View Results Tree

5. Finally Save Test plan with desired name

Demo Java Code:
 import org.apache.jmeter.engine.StandardJMeterEngine;  
 import org.apache.jmeter.reporters.ResultCollector;  
 import org.apache.jmeter.reporters.Summariser;  
 import org.apache.jmeter.save.SaveService;  
 import org.apache.jmeter.util.JMeterUtils;  
 import org.apache.jorphan.collections.HashTree;  
   
 import java.io.File;  
 import java.io.FileInputStream;  
   
 public class ProgramJmeterJMX {  
   
   public static void main(String[] argv) throws Exception {  
   
     //Set jmeter home for the jmeter utils to load  
     String jmeterHomelocation = "F:\\apache-jmeter-2.13\\";  
     String jmeterPropertieslocation = jmeterHomelocation + "bin\\jmeter.properties";  
   
     // JMeter Engine  
     StandardJMeterEngine jmeter = new StandardJMeterEngine();  
   
   
     // Initialize Properties, logging, locale, etc.  
     JMeterUtils.loadJMeterProperties(new File(jmeterPropertieslocation).getPath());  
     JMeterUtils.setJMeterHome(new File(jmeterHomelocation).getPath());  
     // you can comment this line out to see extra log messages of i.e. DEBUG level  
     JMeterUtils.initLogging();  
     JMeterUtils.initLocale();  
   
     // Initialize JMeter SaveService  
     SaveService.loadProperties();  
   
     // Load existing .jmx Test Plan  
     FileInputStream in = new FileInputStream(new File(jmeterHomelocation + "bin\\webloadtesting.jmx"));  
     HashTree testPlanTree = SaveService.loadTree(in);  
     in.close();  
             
     Summariser summer = null;  
     String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");  
   
     if (summariserName.length() > 0) {  
       summer = new Summariser(summariserName);  
     }  
   
     ResultCollector logger = new ResultCollector(summer);  
     testPlanTree.add(testPlanTree.getArray()[0], logger);  
   
     // Run JMeter Test  
     jmeter.configure(testPlanTree);  
     jmeter.run();  
   }  
 }     
   

Out put:

How to encode or encrypt password and other personal information in Selenium Webdriver using Java

Daily we sign in many popular websites like Facebook, Gmail, LinkedIn etc. with login credential. We need to send password as plain text to sign in those popular websites if want to write automation login script in selenium webdriver. One of the most common practice to send encrypted passwords and other personal information instead of plain text for the automation login script.

Base64: Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.
 byte[] encodedBytes = Base64.encodeBase64("TextforEncoding".getBytes());  
 System.out.println("encodedBytes " + new String(encodedBytes));  
 byte[] decodedBytes = Base64.decodeBase64(encodedBytes);  
 System.out.println("decodedBytes " + new String(decodedBytes));  
Prerequisite
1. Create a 'data.properties' file your project home directory
2. Download Base64 jar file and add jar file in project as external jar.

Demo Source code:
 import org.apache.commons.codec.binary.Base64;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.Properties;  
 import java.util.concurrent.TimeUnit;    
   
 public class Encryptionpassword {  
   private static By email = By.id("email");  
   private static By password = By.id("pass");  
   private static By loginbutton = By.id("u_0_m");  
   
   public static void main(String[] arg) throws IOException {  
   
     // Create FileInputStream Object  
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object  
     Properties prop = new Properties();  
     //load properties file  
     prop.load(fileInput);  
   
     // create Firebox object  
     WebDriver driver = new FirefoxDriver();  
     //Go to URL  
     driver.get("http://www.facebook.com");  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
   
     driver.findElement(email).clear();  
     driver.findElement(email).sendKeys(prop.getProperty("username"));  
   
     driver.findElement(password).clear();  
     driver.findElement(password).sendKeys(new String(Base64.encodeBase64(prop.getProperty("password").getBytes())));  
   
     driver.findElement(loginbutton).click();  
   
     //Print Encrypted Password  
     System.out.println("Encrypted Password =: " + new String(Base64.encodeBase64(prop.getProperty("password").getBytes())));  
     //Print Decrypted Password  
     System.out.println("Decrypted Password =: " + new String(Base64.decodeBase64(Base64.encodeBase64(prop.getProperty("password").getBytes()))));  
   
     //close firefox browser  
     driver.close();  
   }  
 }  
   

Output:

How to get extract numbers or digits or numeric values and numbers array from a string in Java


 import com.google.common.base.CharMatcher;  
 import java.util.Arrays;  
   
 public class Getnumbers {  
   
   // Get extract numbers from String  
   public static String getAllNumberfromString(String input) {  
     final StringBuilder sb = new StringBuilder();  
     for (int i = 0; i < input.length(); i++) {  
       final char c = input.charAt(i);  
       if (c > 47 && c < 58) {  
         sb.append(c);  
       }  
     }  
     return sb.toString();  
   }  
   
   // Get only Numbers from String  
   public static String getExtractDigits(String src) {  
     StringBuilder builder = new StringBuilder();  
     for (int i = 0; i < src.length(); i++) {  
       char c = src.charAt(i);  
       if (Character.isDigit(c)) {  
         builder.append(c);  
       }  
     }  
     return builder.toString();  
   }  
   
   public static void main(String[] arg) {     
   
     String input = "Total 128 jobs Found 25";  
     String str = "abc d 1234567890pqr 54897";  
   
     // Get only Numbers from Alphanumeric String using methods  
     System.out.println(getAllNumberfromString(input));  
     System.out.println(getAllNumberfromString(input));  
     System.out.println(getExtractDigits(str));  
     System.out.println(getExtractDigits(str));  
   
     // Get extract numbers from String using Regular Expressions  
     System.out.println(input.replaceAll("[^0-9]", ""));  
     System.out.println(str.replaceAll("\\D+", ""));  
   
     // Get extract numbers from String using building method  
     System.out.println(CharMatcher.DIGIT.retainFrom(input));  
   
     // Get extract numbers separately from String using Regular Expressions  
     System.out.println(input.replaceAll("[^-?0-9]+", " "));  
   
     // Get numbers array from String using Regular Expressions  
     System.out.println(Arrays.asList(str.replaceAll("[^-?0-9]+", " ").trim().split(" ")));  
   }  
 }  
   
Output:

How to operate new single window or multiple windows in selenium webdriver using java

Some Web application allows to login to their system using Gmail, Facebook, Twitter etc account. When click on Gmail, Facebook, Twitter, its icon button, new window open with a login page. Selenium webdriver provide opportunity to handle new opened window and back to original window after completing an operation on new window. In this tutorial I will show how to operate new window.


Switch between new opened windows and original window as below:
 
// Store the current window on String variable  
 String parentwindow = driver.getWindowHandle();  

 // Do the click operation that opens new window  
 // Switch to window that's your newly opened window  

 for(String winHandle : driver.getWindowHandles()){  
   driver.switchTo().window(winHandle);  
 }  

 // code to do something on new window  

 // Close the new window, if that window no more required  
 driver.close();  

 // Switch back to original browser (parent window)  
 driver.switchTo().window(parentwindow);  

 // Continue with original browser (parent window)  

Java demo source code:
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Operatenewwindow {  
   public static void main(String[] arg) {  
     WebDriver driver = new FirefoxDriver();  
     driver.manage().window().maximize();  
     driver.get("http://localhost:8080/idea/a/community/login");  

     // Store the current window on String variable  
     String parentwindow = driver.getWindowHandle();  
 // Do the click operation that opens new window  
     driver.findElement(By.className("icon-facebook")).click(); 
 
 // Switch to window that's your newly opened window  
     for (String winHandle : driver.getWindowHandles()) {  
       driver.switchTo().window(winHandle);  
     }  

 // code to do something on new window  
     driver.findElement(By.id("email")).sendKeys("hiro@gmail.com");  
     driver.findElement(By.id("pass")).sendKeys("123456789");  
     driver.findElement(By.id("loginbutton")).click();  

 // Close the new window, if that window no more required  
     driver.close();  

 // Switch back to original browser (parent window)  
     driver.switchTo().window(parentwindow); 

 
 // Continue with original browser (parent window)  
     driver.close();  
   }  
 }  

How to read JSONObject and JSONArrays from file and parse JSONObject and JSONArrays in java.

Download JSON jar and add desired project
JSON Input
 {  
  "name": "Hiro Mia",  
  "age": 30,  
  "address": {  
   "presentaddress": {  
    "streetAddress": "H#137 Sector#6, Uttara",  
    "city": "Dhaka",  
    "Country": "Bangladesh"  
   },  
   "permanentaddress": {  
    "streetAddress": "H#110 Road#10, Upshohor",  
    "city": "Sylhet",  
    "Country": "Bangladesh"  
   },  
   "officetaddress": {  
    "streetAddress": "H#11 Sector#13, Uttara",  
    "city": "Dhaka",  
    "Country": "Bangladesh"  
   }  
  },  
  "phoneNumber": [  
   {  
    "type": "home",  
    "number": "812-333-1111"  
   },  
   {  
    "type": "fax",  
    "number": "746-444-2222"  
   }  
  ],  
  "qualification": {  
   "Type": "B.Sc",  
   "institution": "SUST",  
   "Grade": "B+"  
  }  
 }  
Java Program
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import java.io.BufferedReader;  
 import java.io.FileReader;  
 import java.io.IOException;  
 public class Parsejson {  
   public static void main(String[] agr) {  
     String jsondata = "";  
     BufferedReader br = null;  
     String str;  
     try {  
       br = new BufferedReader(new FileReader("JSON Example.txt"));  
       while ((str = br.readLine()) != null) {  
         jsondata += str;  
       }  
     } catch (IOException e) {  
       e.printStackTrace();  
     } finally {  
       try {  
         if (br != null)  
           br.close();  
       } catch (IOException ex) {  
         ex.printStackTrace();  
       }  
     }  
     System.out.println("JSON Output     : "+jsondata);
  
     try {  

       JSONObject obj = new JSONObject(jsondata);  
       System.out.println("Name        : " + obj.get("name"));

  
       JSONObject address = (JSONObject) (obj.get("address"));  
       System.out.println("Address       : " + address.toString());
  

       JSONObject permanentaddress = (JSONObject) (address.get("permanentaddress"));  
       System.out.println("Permanent address  : " + permanentaddress.toString());  
       System.out.println("Street Address   : " + permanentaddress.get("streetAddress"));  


       JSONArray phoneNumber = (JSONArray) obj.get("phoneNumber");  
       System.out.println("Phone Number    : " + phoneNumber.toString());  
       System.out.println("Phone Number one  : " + phoneNumber.get(0).toString());

  
       System.out.println("Size of JSON Array : " + phoneNumber.length());  
       for (int i = 0; i < phoneNumber.length(); i++) {  
         System.out.println("Phone Number    : " + i + "  " + phoneNumber.get(i).toString());  
         JSONObject phoneNumber2 = (JSONObject) (phoneNumber.get(i));  
         System.out.println("Number       : " + i + "  " + phoneNumber2.get("number"));  
       }  


       JSONObject qualification = (JSONObject) (obj.get("qualification"));  
       System.out.println("Qualification    : " + qualification.toString());  
       System.out.println("Institution     : " + qualification.get("institution"));  


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

Output




 JSON Output        : { "name": "Hiro Mia", "age": 30, "address": {  "presentaddress": {   "streetAddress": "H#137 Sector#6, Uttara",   "city": "Dhaka",   "Country": "Bangladesh"  },  "permanentaddress": {   "streetAddress": "H#110 Road#10, Upshohor",   "city": "Sylhet",   "Country": "Bangladesh"  },  "officetaddress": {   "streetAddress": "H#11 Sector#13, Uttara",   "city": "Dhaka",   "Country": "Bangladesh"  } }, "phoneNumber": [  {   "type": "home",   "number": "812-333-1111"  },  {   "type": "fax",   "number": "746-444-2222"  } ], "qualification": {  "Type": "B.Sc",  "institution": "SUST",  "Grade": "B+" }} 
 
 Name               : Hiro Mia  
 Address            : {"permanentaddress":{"streetAddress":"H#110 Road#10, Upshohor","city":"Sylhet","Country":"Bangladesh"},"officetaddress":{"streetAddress":"H#11 Sector#13, Uttara","city":"Dhaka","Country":"Bangladesh"},"presentaddress":{"streetAddress":"H#137 Sector#6, Uttara","city":"Dhaka","Country":"Bangladesh"}}  

 Permanent address  : {"streetAddress":"H#110 Road#10, Upshohor","city":"Sylhet","Country":"Bangladesh"}  
 Street Address     : H#110 Road#10, Upshohor  
 Phone Number       : [{"number":"812-333-1111","type":"home"},{"number":"746-444-2222","type":"fax"}]  
 Phone Number one   : {"number":"812-333-1111","type":"home"}  
 Size of JSON Array : 2  
 Phone Number       : 0  {"number":"812-333-1111","type":"home"}  
 Number             : 0  812-333-1111  
 Phone Number       : 1  {"number":"746-444-2222","type":"fax"}  
 Number             : 1  746-444-2222  
 Qualification      : {"institution":"SUST","Type":"B.Sc","Grade":"B+"}  
 Institution        : SUST  

How to handle WebDriverException: Element is not clickable at point using java

Some case the element position is not fixed and we want to do some action like click button on that particular element then result an error as 'Exception in thread "main" org.openqa.selenium.WebDriverException: Element is not clickable at point (xx, yy). Other element would receive the click:'. This happens when the element is loaded into the DOM, but the position is not fixed on the UI. There can be some other divs or images or ads that are not loaded completely.

The different workable solutions provided below.
 1. Maximize browser window
 driver.manage().window().maximize();

 2. The page is getting refreshed before clicking on element.

 3. Scroll to element using Keys
driver.findElement(By.id("ID of the element")).sendKeys(Keys.PAGE_DOWN); 
 or
driver.findElement(By.id("ID of the element")).sendKeys(Keys.PAGE_UP);

4. Click on element using  Actions Class
WebElement element = driver.findElement(By.id("login-button"));
Actions action = new Actions(driver);
action.moveToElement(element).click().perform();


5. Page scroll up or down using JavaScriptExecutor
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); // if the element is on top.
jse.executeScript("scroll(0, 250)"); // if the element is on bottom. 


6. Page move particular X or Y position using JavaScriptExecutor if element is not visible
 WebElement element = driver.findElement(By.id("login-button"));
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,"element.getLocation().x+")");
element.click();

or
WebElement element = driver.findElement(By.id("login-button"));
JavascriptExecutor jse =(JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,"element.getLocation().y+")");
element.click();

or
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView()", driver.findElement(By.id("login-button"));


7.Element is not present at the time of execution. Use WebDriverWait to until the element is present.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ID of the element")));

How can handle unexpected alert exception in Selenium Webdriver using java

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.NoAlertPresentException;  
 import org.openqa.selenium.UnhandledAlertException;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Unexpectedalert {  
   public static void main(String[] args) {  
     WebDriver driver;  
     // creat firefox driver object    
     driver = new FirefoxDriver();  
     //Maximize browser window    
     driver.manage().window().maximize();  
     //Go to URL    
     driver.get("http://localhost:80/ideascalechallenge");  
     //Set timeout   
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 

 
 // handle Alert Exception  
     try {  
 // trigger unexpected alter event  
       driver.get("http://localhost:80/ideascalechallenge/a/idea?templateId=0");  
     } catch (UnhandledAlertException f) {  
       try {  
         Alert alert = driver.switchTo().alert();  
         String alertText = alert.getText();  
         System.out.println("Alert data: " + alertText);  
         alert.accept();  
         //or  depend event
         // alert.dismiss();  
       } catch (NoAlertPresentException e) {  
         e.printStackTrace();  
       }  
     }
  
   }  
 }  

How to send REST api get and post request to server and get response from server in java

REST API Get request
 import java.io.*;  
 import java.net.HttpURLConnection;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 public class Restapigetrequest {  
   public void requestresponse() {  
     String output = "";  
     String requesturl="http://httpbin.org/get";  
     try {  
       // sent get request to sever  
       URL url = new URL(requesturl);  
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
 /*  
      // Add header if need  
       conn.setRequestMethod("GET");  
       conn.setRequestProperty("Content-Type", "application/json");  
       conn.setRequestProperty("token", "da6e387d-8abc-4f88-bf21-ad37deff042e");  
  */  
       // get response from server and print response  
       if (conn.getResponseCode() != 200) {  
         System.out.println(requesturl + " -> Fail " + conn.getResponseCode());  
       } else {  
         BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));  
         while ((output = br.readLine()) != null) {  
           System.out.println(output);  
         }  
         conn.disconnect();  
       }  
     } catch (MalformedURLException e) {  
       e.printStackTrace();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
   }  
   public static void main(String[] a) throws IOException {  
     Restapigetrequest at = new Restapigetrequest();  
     at.requestresponse();  
   }  
 }  
Output:
REST API POST request
 import java.io.BufferedReader;  
 import java.io.InputStreamReader;  
 import org.apache.http.HttpResponse;  
 import org.apache.http.client.HttpClient;  
 import org.apache.http.client.methods.HttpPost;  
 import org.apache.http.entity.StringEntity;  
 import org.apache.http.impl.client.DefaultHttpClient;  
 import org.json.simple.JSONArray;  
 import org.json.simple.JSONObject;  
 public class Restapipostrequest {  
   // Generate json string  
   public static String jsonString() {  
  /*  
   {  
   "text": "Generally, these two terms,  
   "title": "test-450",  
   "Id":4869  
  }  
  */  
     JSONObject obj1 = new JSONObject();  
     obj1.put("text", "Generally, these two terms");  
     obj1.put("title", "Idea created by script");  
     obj1.put("Id", 82);  
     System.out.println(obj1.toJSONString());  
     return obj1.toJSONString();  
   }  
   public static void find_contact() {  
     HttpClient httpClient = new DefaultHttpClient();  
     String postcall ="http://httpbin.org/post";  
     try {  
       //you will need api key here!!  
       HttpPost request = new HttpPost(postcall);  
 /*  
                // Add header if need  
       request.addHeader("Content-Type", "application/json");  
       request.addHeader("api_token", "68c93d98-4ce2-4d5b-8a8c-cad25e0ab113");  
       // Add json input if need  
       StringEntity params = new StringEntity(jsonString());  
       request.setEntity(params);  
 */  
       HttpResponse response = httpClient.execute(request);  
       BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
       String result = "";  
       String line;  
       while ((line = rd.readLine()) != null) {  
         result += line;  
       }  
       System.out.println(result);  
       rd.close();  
       System.out.println("status:" + response.getStatusLine());  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
   }  
   public static void main(String args[]) {  
     find_contact();  
   }  
 }  

How to configure and run Selenium Grid

Selenium Grid : Selenium Grid is a component of Selenium that distributes multiple tests across different browsers, operating systems, and machines so that we can execute scripts in parallel. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid.

Selenium Grid has a Hub and a Node.
Hub :The hub is the central point  where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once.
NodeNodes are the Selenium instances that are linked to the Hub which execute the tests. There can be one or more nodes in a grid which can be launched on multiple machines with different platforms and browsers.

Prerequisite Software:

1. Download Eclipse
2. Download Selenium Standalone Server jar

3. The Internet Explorer Driver Server

4. Google Chrome driver for selenium webdriver

5. Opera driver for selenium webdriver


Installing TestNG for Eclipse:

Step 1 : Launch Eclipse and select Main Menu 'Help' --> 'Install New Software' .

Step 2 : Enter the URL as 'http://beust.com/eclipse' and click 'Add' .

Step 3 :  Enter the name as 'TestNG' on dialog box 'Add Repository' dialog box. and click 'OK'

Step 4 : Click 'Select All'

Step 5 : Click 'Next' to continue.

Step 6 :  Click 'Next'.

Step 7 : "Accept the License Agreement" and click 'Finish'.

Step 8 : Security Warning pops up as the validity of the software cannot be established. Click 'Ok'

Step 9 : The Installer prompts to restart Eclipse for the changes to take effect. Click 'Yes'.

Configuring the Hub:

Step 1 :  Port# 4444 must be free. The following below commandon Window command window to start the Hub by launching the Selenium Server. Now we will use the port '4444' to start the hub. 
java -jar selenium-server-standalone-2.53.0.jar -port 4444 -role hub -nodeTimeout 1000
Example: java -jar F:\Grid\selenium-server-standalone-2.53.0.jar -port 4444 -role hub -nodeTimeout 1000
Step 2 : Open desired browser and navigate to the URL http://localhost:4444 from the Hub
Step 3 : Click on 'console' link  --> click 'view config'. The config of the hub would be displayed as follows. As of now, we haven't got any nodes, hence we will not be able to see the details.

Configuring the Nodes: 

Step 1 : Start Firefox Node using the following below command.
java -jar 'the location of selenium server standalone jar' -role node -hub http://PC_IP:4444/grid/register -browser browserName=firefox -port port_number
Example:
java -jar F:\Grid\selenium-server-standalone-2.53.0.jar -role node -hub http://192.168.111.141:4444/grid/register -browser browserName=firefox -port 5555
 Step 2 : Launch Internet Explorer Node using the following below on command.
java -Dwebdriver.ie.driver='the location of IE driver' -jar 'the location of selenium server standalone jar' -role webdriver -hub http://PC_IP:4444/grid/register -browser browserName=ie,platform=WINDOWS -port port_number
Example: 
java -Dwebdriver.ie.driver=F:\Grid\IEDriverServer.exe -jar F:\Grid\selenium-server-standalone-2.53.0.jar -role webdriver -hub http://192.168.111.141:4444/grid/register -browser browserName=ie,platform=WINDOWS -port 5556 
 Step 3 : Launch Chrome Node using the following below on command.
java -Dwebdriver.chrome.driver='the location of chrome driver' -jar 'the location of selenium server standalone jar' -role webdriver -hub  http://PC_IP:4444/grid/register -browser browserName=chrome,platform=WINDOWS -port port_number
Example: 
java -Dwebdriver.chrome.driver=F:\Grid\chromedriver.exe -jar F:\Grid\selenium-server-standalone-2.53.0.jar -role webdriver -hub  http://192.168.111.141:4444/grid/register -browser browserName=chrome,platform=WINDOWS -port 5557 
Step 4 : After running the command, come back to the Hub. Navigate to the URL - http://pc_ip:4444 then Click on 'console' link ,  the Hub would now display Firefox, IE and chrome node attached to it.

 

The installation procedure of Jenkins on on Windows, Mac OS X, Ubuntu

Software requirement
Create an Environment Variable JAVA_HOME
  •     Windows
  •     Ubuntu
  •     Mac OS X --> Skip this step. No need to do anything.

Download and Install Apache Tomcat Server on Windows, Mac OS X, Ubuntu
Windows
  1. Goto http://tomcat.apache.org --> Downloads --> Tomcat 8.0 --> "8.0.{xx}" (where {xx} is the latest upgrade number) --> Binary Distributions --> Core --> "ZIP" package (e.g., "apache-tomcat-8.0.{xx}.zip", about 8 MB).
  2. Create your project directory, say "d:\myProject" or "c:\myProject". UNZIP the downloaded file into your project directory. Tomcat will be unzipped into directory "d:\myProject\apache-tomcat-8.0.{xx}".
  3. For ease of use, we shall shorten and rename this directory to "d:\myProject\tomcat".  

Mac OS X
  • Goto http://tomcat.apache.org --> Download --> Tomcat 8.0 --> "8.0.{xx}" (where {xx} denotes the latest upgrade number) --> Binary distribution --> Core --> "tar.gz" package (e.g., "apache-tomcat-8.0.{xx}.tar.gz", about 8 MB)
  • To install Tomcat:
  1. Goto "~/Downloads", double-click the downloaded tarball (e.g., "apache-tomcat-8.0.{xx}.tar.gz") to expand it into a folder (e.g., "apache-tomcat-8.0.{xx}")
  2. Move the extracted folder (e.g., "apache-tomcat-8.0.{xx}") to "/Applications".
  3. For ease of use, we shall shorten and rename this folder to "tomcat".
 Configure Tomcat Server
  • Open  tomcate-users.xml  file under "Tomcat_Home\conf\"
  • Enable the Tomcat's manager by adding the highlighted lines, inside the <tomcat-users> elements:
<tomcat-users>
  <role rolename="manager-gui"/>
  <user username="manager" password="xxxx" roles="manager-gui"/>
</tomcat-users>

Copy the jenkins.war to the Tomcat directory.:
Windows
copy jenkins.war and paste to D:\myProject\tomcat\
Ubuntu
sudo cp jenkins.war /var/lib/tomcat/webapps/
Mac OS X
sudo cp jenkins.war /Applications/tomcat/webapps/    

Start and Shutdown Tomcat Server:
Windows
1. Navigate to bin folder under tomcat directory by window Command Prompt
   Write below command to run tomcat server
       startup
   Type below command to stop tomcat server
     shutdown 
Ubuntu and Mac OS X
1. Goto to bin folder under tomcat directory using Terminal
     Write below command to run tomcat server
        sudo ./startup.sh
     Type below command to stop tomcat server
        sudo ./shutdown.sh

After starting tomcat server, Open browser and enter url like http://localhost:8080/jenkins_war_filename/ on browser address bar
Example: http://localhost:8080/jenkins/






The installation procedure of WebGoat on on Windows, Mac OS X, Ubuntu

Software requirement
Create an Environment Variable JAVA_HOME
  •     Windows
  •     Ubuntu
  •     Mac OS X --> Skip this step. No need to do anything.

Download and Install Apache Tomcat Server on Windows, Mac OS X, Ubuntu
Windows
  1. Goto http://tomcat.apache.org --> Downloads --> Tomcat 8.0 --> "8.0.{xx}" (where {xx} is the latest upgrade number) --> Binary Distributions --> Core --> "ZIP" package (e.g., "apache-tomcat-8.0.{xx}.zip", about 8 MB).
  2. Create your project directory, say "d:\myProject" or "c:\myProject". UNZIP the downloaded file into your project directory. Tomcat will be unzipped into directory "d:\myProject\apache-tomcat-8.0.{xx}".
  3. For ease of use, we shall shorten and rename this directory to "d:\myProject\tomcat".  

Mac OS X
  • Goto http://tomcat.apache.org --> Download --> Tomcat 8.0 --> "8.0.{xx}" (where {xx} denotes the latest upgrade number) --> Binary distribution --> Core --> "tar.gz" package (e.g., "apache-tomcat-8.0.{xx}.tar.gz", about 8 MB)
  • To install Tomcat:
  1. Goto "~/Downloads", double-click the downloaded tarball (e.g., "apache-tomcat-8.0.{xx}.tar.gz") to expand it into a folder (e.g., "apache-tomcat-8.0.{xx}")
  2. Move the extracted folder (e.g., "apache-tomcat-8.0.{xx}") to "/Applications".
  3. For ease of use, we shall shorten and rename this folder to "tomcat".
 Configure Tomcat Server
  • Open  tomcate-users.xml  file under "Tomcat_Home\conf\"
  • Enable the Tomcat's manager by adding the highlighted lines, inside the <tomcat-users> elements:
<tomcat-users>
  <role rolename="manager-gui"/>
  <user username="manager" password="xxxx" roles="manager-gui"/>
</tomcat-users>

Copy the WebGoat.war to the Tomcat directory.:
Windows
copy webgoat-container-7.0.1.war and paste to D:\myProject\tomcat\
Ubuntu
sudo cp webgoat-container-7.0.1.war /var/lib/tomcat/webapps/
Mac OS X
sudo cp webgoat-container-7.0.1.war /Applications/tomcat/webapps/    

Start and Shutdown Tomcat Server:
Windows
1. Navigate to bin folder under tomcat directory by window Command Prompt
   Write below command to run tomcat server
       startup
   Type below command to stop tomcat server
     shutdown 
Ubuntu and Mac OS X
1. Goto to bin folder under tomcat directory using Terminal
     Write below command to run tomcat server
        sudo ./startup.sh
     Type below command to stop tomcat server
        sudo ./shutdown.sh

After starting tomcat server, Open browser and enter url like http://localhost:8080/webgoat_war_filename/ on browser address bar
Example: http://localhost:8080/webgoat-container-7.0.1/
 Log in as admin with Username is 'webgoat' and Password is 'webgoat'




How to send Selenium Webdriver testing summary report in a Simple or an HTML or Attachment E-mail using java.

We use Selenium Webdiver automation tool for Web functional and regression testing. We run many test cases using that tool. Sometime We need to send summary testing report which reports include how many test cases are successfully passed or failed. In this tutorial I will show how to send Selenium Webdriver testing summary report in a Simple or an HTML or Attachment E-mail.


Download mail.jar and add desired project
Send a Simple E-mail
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 import javax.mail.*;  
 import javax.mail.internet.*;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Sendsimpleemail {  
   static Properties prop = null;  
   static String urls = "";  
   public static void main(String[] args) throws IOException {  
     List<WebElement> urllist = new ArrayList();  
     // Initialize driver     
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window      
     driver.manage().window().maximize();  
     //Go to URL     
     driver.get("https://www.yahoo.com/");  
     //Set timeout     
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     urllist = driver.findElements(By.tagName("a"));  
     try {  
       for (WebElement url : urllist) {  
         if ((url.getAttribute("href").trim().length() > 4) && (url.getAttribute("href").trim().contains("yahoo.com")) && !(url.getAttribute("href").trim().contains("javascript:void(0)"))) {  
           urls = urls + url.getAttribute("href").trim() + "\n";  
         }  
       }  
     } catch (NullPointerException e) {  
 //      e.printStackTrace();  
     }  
     System.out.println(urls);  
     //close firefox browser   
     driver.close();  
     // Recipient's email ID needs to be mentioned.  
     String to = "hiromia006@gmail.com";  
     // Assuming you are sending email from localhost  
     String host = "localhost";  
     // Create FileInputStream Object   
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object      
     prop = new Properties();  
     //load properties file   
     prop.load(fileInput);  
     // Get system properties  
     Properties properties = System.getProperties();  
     // Setup mail server  
     properties.setProperty("mail.smtp.host", host);  
     properties.put("mail.smtp.starttls.enable", "true");  
     properties.put("mail.smtp.host", "smtp.gmail.com");  
     properties.put("mail.smtp.user", prop.getProperty("From_email")); // User name  
     properties.put("mail.smtp.password", prop.getProperty("From_email_password")); // password  
     properties.put("mail.smtp.port", "587");  
     properties.put("mail.smtp.auth", "true");  
     Authenticator authenticator = new Authenticator() {  
       public PasswordAuthentication getPasswordAuthentication() {  
         return new PasswordAuthentication(prop.getProperty("From_email"), prop.getProperty("From_email_password"));//userid and password for "from" email address   
       }  
     };  
     // Get the default Session object.  
     Session session = Session.getDefaultInstance(properties, authenticator);  
     try {  
       // Create a default MimeMessage object.  
       MimeMessage message = new MimeMessage(session);  
       // Set From: header field of the header.  
       message.setFrom(new InternetAddress(prop.getProperty("From_email")));  
       // Set To: header field of the header.  
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
       // Set Subject: header field  
       message.setSubject("Yahoo Home page internet links");  
       // Now set the actual message  
       message.setText(urls);  
       // Send message  
       Transport.send(message);  
       System.out.println("Sent message successfully....");  
     } catch (MessagingException mex) {  
       mex.printStackTrace();  
     }  
   }  
 }  

Send an HTML E-mail
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 import javax.mail.*;  
 import javax.mail.internet.*;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Sendanhtmlemail {  
   static Properties prop = null;  
   static String urltexts = "";  
   public static void main(String[] args) throws IOException {  
     List<WebElement> urllist = new ArrayList();  
     // Initialize driver  
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Go to URL  
     driver.get("https://www.google.com/");  
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     urllist = driver.findElements(By.tagName("a"));  
     try {  
       for (WebElement url : urllist) {  
         if ((url.getText().trim().length() > 1) && !(url.getText().trim().contains("null"))) {  
           urltexts = urltexts + "<h1>"+url.getText().trim() + "<h1>\n";  
         }  
       }  
     } catch (NullPointerException e) {  
       //   e.printStackTrace();  
     }  
     System.out.println(urltexts);  
     //close firefox browser  
     driver.close();  
     // Recipient's email ID needs to be mentioned.  
     String to = "hiromia006@gmail.com";  
     // Assuming you are sending email from localhost  
     String host = "localhost";  
     // Create FileInputStream Object  
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object  
     prop = new Properties();  
     //load properties file  
     prop.load(fileInput);  
     // Get system properties  
     Properties properties = System.getProperties();  
     // Setup mail server  
     properties.setProperty("mail.smtp.host", host);  
     properties.put("mail.smtp.starttls.enable", "true");  
     properties.put("mail.smtp.host", "smtp.gmail.com");  
     properties.put("mail.smtp.user", prop.getProperty("From_email")); // User name  
     properties.put("mail.smtp.password", prop.getProperty("From_email_password")); // password  
     properties.put("mail.smtp.port", "587");  
     properties.put("mail.smtp.auth", "true");  
     Authenticator authenticator = new Authenticator() {  
       public PasswordAuthentication getPasswordAuthentication() {  
         return new PasswordAuthentication(prop.getProperty("From_email"), prop.getProperty("From_email_password"));//userid and password for "from" email address  
       }  
     };  
     // Get the default Session object.  
     Session session = Session.getDefaultInstance(properties, authenticator);  
     try {  
       // Create a default MimeMessage object.  
       MimeMessage message = new MimeMessage(session);  
       // Set From: header field of the header.  
       message.setFrom(new InternetAddress(prop.getProperty("From_email")));  
       // Set To: header field of the header.  
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
       // Set Subject: header field  
       message.setSubject("Google Home page internet links text");  
       // Send the actual HTML message, as big as you like  
       message.setContent(urltexts, "text/html" );  
       // Send message  
       Transport.send(message);  
       System.out.println("Sent message successfully....");  
     } catch (MessagingException mex) {  
       mex.printStackTrace();  
     }  
   }  
 }  

Send Attachment in E-mail
 import java.io.*;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 import javax.mail.*;  
 import javax.mail.internet.*;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import javax.activation.*;  
 public class SendAttachmentemail {  
   static Properties prop = null;  
   static String urls = "";  
   static File file;  
   public static void main(String[] args) throws IOException {  
     List<WebElement> urllist = new ArrayList();  
     // Initialize driver  
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Go to URL  
     driver.get("https://www.yahoo.com/");  
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     urllist = driver.findElements(By.tagName("a"));  
     try {  
       for (WebElement url : urllist) {  
         if ((url.getAttribute("href").trim().length() > 4) && (url.getAttribute("href").trim().contains("yahoo.com")) && !(url.getAttribute("href").trim().contains("javascript:void(0)"))) {  
           urls = urls + url.getAttribute("href").trim() + "\n";  
         }  
       }  
     } catch (NullPointerException e) {  
       //   e.printStackTrace();  
     }  
     try {  
       file = new File("Internetlinks.txt");  
       // if file doesnt exists, then create it  
       if (!file.exists()) {  
         file.createNewFile();  
       }  
       // Write text on txt file.  
       FileWriter fw = new FileWriter(file, true);  
       BufferedWriter bw = new BufferedWriter(fw);  
       bw.write(urls);  
       bw.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     System.out.println(urls);  
     //close firefox browser  
     driver.close();  
     // Recipient's email ID needs to be mentioned.  
     String to = "hiromia006@gmail.com";  
     // Assuming you are sending email from localhost  
     String host = "localhost";  
     // Create FileInputStream Object  
     FileInputStream fileInput = new FileInputStream(new File("data.properties"));  
     // Create Properties object  
     prop = new Properties();  
     //load properties file  
     prop.load(fileInput);  
     // Get system properties  
     Properties properties = System.getProperties();  
     // Setup mail server  
     properties.setProperty("mail.smtp.host", host);  
     properties.put("mail.smtp.starttls.enable", "true");  
     properties.put("mail.smtp.host", "smtp.gmail.com");  
     properties.put("mail.smtp.user", prop.getProperty("From_email")); // User name  
     properties.put("mail.smtp.password", prop.getProperty("From_email_password")); // password  
     properties.put("mail.smtp.port", "587");  
     properties.put("mail.smtp.auth", "true");  
     Authenticator authenticator = new Authenticator() {  
       public PasswordAuthentication getPasswordAuthentication() {  
         return new PasswordAuthentication(prop.getProperty("From_email"), prop.getProperty("From_email_password"));//userid and password for "from" email address  
       }  
     };  
     // Get the default Session object.  
     Session session = Session.getDefaultInstance(properties, authenticator);  
     try {  
       // Create a default MimeMessage object.  
       MimeMessage message = new MimeMessage(session);  
       // Set From: header field of the header.  
       message.setFrom(new InternetAddress(prop.getProperty("From_email")));  
       // Set To: header field of the header.  
       message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
       // Set Subject: header field  
       message.setSubject("Yahoo Home page internet links attached text field");  
       // Create the message part  
       BodyPart messageBodyPart = new MimeBodyPart();  
       // Fill the message  
       messageBodyPart.setText("have sent Yahoo home page url list by attached file");  
       // Create a multipar message  
       Multipart multipart = new MimeMultipart();  
       // Set text message part  
       multipart.addBodyPart(messageBodyPart);  
       // Part two is attachment  
       messageBodyPart = new MimeBodyPart();  
       DataSource source = new FileDataSource("Internetlinks.txt");  
       messageBodyPart.setDataHandler(new DataHandler(source));  
       messageBodyPart.setFileName("Internetlinks.txt");  
       multipart.addBodyPart(messageBodyPart);  
       // Send the complete message parts  
       message.setContent(multipart );  
       // Send message  
       Transport.send(message);  
       System.out.println("Sent message successfully....");  
     } catch (MessagingException mex) {  
       mex.printStackTrace();  
     }  
   }  
 }  

How can open and close browser tabs in selenium Webdriver on Mac using java.

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.Keys;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Openandclosetabhandler {  
   public static void main(String[] a) throws InterruptedException {  
     // Initialize driver   
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window    
     driver.manage().window().maximize();  
     //Go to URL   
     driver.get("http://www.google.com");  
     //Set timeout   
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Open new tab   
     driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");  
     //Go to URL   
     driver.get("http://www.yahoo.com/");  
     //Set new tab timeout   
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Do some operation       
     driver.findElement(By.partialLinkText("Sign in")).click();  
     Thread.sleep(2000);  
     // Switch first tab   
     driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "w");  
     driver.switchTo().defaultContent();  
     Thread.sleep(2000);  
     // Operation   
     driver.findElement(By.partialLinkText("Gmail")).click();  
     Thread.sleep(2000);  
     // Browser close    
     driver.close();  
   }  
 }