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();  
   }  
 }