Automation Using Selenium Webdriver

Sunday 18 December 2016

Encapsulation in java with example program


What is meant by encapsulation in java? 
  • Binding the data with its related functionalities known as encapsulation
  • Here data means variables and functionalities means methods.
  • So keeping the variable and related methods in one place.
  • That place is "class". class is the base for encapsulation.
  • Lets see example program on encapsulation, how the variables and methods defined in a class


What is encapsulation in object oriented programming?
Basic java example program on data encapsulation:
  1. package com.java;
  2.  
  3. public class EncapsulationDemo {
  4.  
  5.   String name;
  6.   int rno;
  7.   String address;
  8.  
  9. public String getName() {
  10.        return name;
  11.  }
  12.  
  13. public void setName(String name) {
  14.         this.name = name;

  15. public int getRno() {
  16.        return rno;
  17. }
  18.  
  19. public void setRno(int rno) {
  20.      this.rno = rno;
  21. }
  22.  
  23. public String getAddress() {
  24.         return address;
  25. }
  26.  
  27.  public void setAddress(String address) {
  28.     this.address = address;
  29. }
  30.  
  31. public void showInfo(){
  32.  
  33.       System.out.println("Name: "+getName());
  34.       System.out.println("R.No: "+getRno());
  35.       System.out.println("Name: "+getAddress());
  36.  
  37.     }
  38. }

Class:
The above example program shows how the variables and methods will be there in a class.
So class is the base for encapsulation
class is user defined data type in java means by using class we can structure our own programs.
Lest see a example program on class.

  1. package com.java;
  2.  
  3. public class ClassDemo {
  4.  
  5.     //variables of a class
  6.    String empName;
  7.    int empId;
  8.    String Designation;
  9.  
  10.  //getter and setter methods for variables 
  11.  //by using these methods we can set the value to the variable and gat the value from the
  12.  //variables
  13.  
  14.  public String getEmpName() {
  15.         return empName;
  16. }
  17.  
  18.  public void setEmpName(String empName) {
  19.       this.empName = empName;
  20. }
  21.  
  22. public int getEmpId() {
  23.        return empId;
  24. }
  25.  
  26. public void setEmpId(int empId) {
  27.         this.empId = empId;
  28. }

  29. public String getDesignation() {
  30.         return Designation;
  31. }
  32.  
  33.  public void setDesignation(String designation) {
  34.         Designation = designation;
  35. }

  36. }

Object:
Instance of class is known as object.
Instance means dynamic memory allocation. So dynamic memory allocation to class is called object.
By using "new" keyword the object will be created dynamically.
Class is a template. By using object we will get memory for all variables so that we can use them.
We can create number of objects for one class based on our requirements.

Below an example program on class and object.


  1. package com.java; 
  2.  
  3. public class User {
  4.  
  5.    String Name;
  6.     int Id;
  7.     String address;
  8.  
  9.  public String getName() {
  10.      return Name;
  11. }
  12.  
  13. public void setName(String name) {
  14.         Name = name;
  15. }
  16.  
  17. public int getId() {
  18.       return Id;
  19. }
  20.  
  21. public void setId(int id) {
  22.        Id = id;
  23. }
  24.  
  25. public String getAddress() {
  26.         return address;
  27. }
  28.  
  29. public void setAddress(String address) {
  30.         this.address = address;
  31. }
  32.  
  33. public static void main(String [] args){
  34.  
  35.        User obj= new User();
  36.  
  37.         obj.setName("sai");
  38.         obj.setId(1);
  39.         obj.setAddress("xyz");
  40.  
  41.         System.out.println(obj.getName());
  42.         System.out.println(obj.getId());
  43.         System.out.println(obj.getAddress());
  44.  
  45.     }
  46. }

Output:

  1. sai
  2. 1
  3. xyz

Wednesday 14 December 2016

Java – Remove Duplicate Number from Array

package JavaPrograms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveduplicateArray {
//
//  Remove duplicate entries from an array of long integers
//
//
public static void main(String[] args)
{
//
// A long integer array with some duplicated values
//
long [] longArray = { 11,0, 11, 22, 44, 55, 66, 77, 88, 0, 99, 77, 66, 42, 55, 66, 99, 11};
System.out.println("Original array size = " + longArray.length);
System.out.println("Original array            : " +
Arrays.toString(longArray));
//
// Want to let Java convert the array to a Set, since
// the Set object won't have duplicate entries.
//
// But first...
//
// Since the Set constructor needs a List (not an array),
// "convert" the array to a List.
//
List<Long> longList = new ArrayList<Long>();
for (int i = 0; i < longArray.length; i++)
{
longList.add(longArray[i]);
}
// Now, instantiate a Set with its constructor that has a List argument
Set <Long> longSet = new HashSet<Long>(longList);
//
// Create an array of Long objects and use Set.toArray()
// to "convert" the Set to the array.
Long[] resultNoDups = new Long[longSet.size()];
longSet.toArray(resultNoDups);
// Finally, if we want an array of long ints rather
// than an array of Long objects, create the array
// and copy the values
long [] finalArray = new long[resultNoDups.length];
for (int i = 0; i < resultNoDups.length; i++) {
finalArray[i] = resultNoDups[i];
}
// Taa-daa
System.out.println("After removing duplicates : " +
Arrays.toString(finalArray));
System.out.println("Result array size = " + finalArray.length);
System.out.println();
               }
}

Monday 12 December 2016

Reading Font Properties In Selenium WebDriver Using .getCssValue() Method



Sometimes you need to read font properties like font size, font color, font family, font background color etc.. during WebDriver test case execution. Selenium WebDriver Is very wast API and It has many built In methods to perform very small small operations on web page.Reading font property manually Is very simple task using firebug as shown In bellow given Image




If you wants to read above shown font property In selenium webdriver then you can do It using .getCssValue() Method. You can provide property name (Example : font-family, font-size, font-weight, etc.) with .getCssValue() method to read Its value.

Bellow given example will read values of font-size, color, font-family and text-align properties of "Example Login Page" text.

package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class fontTest { 
WebDriver driver = null;

    @BeforeTest
    public void setup() throws Exception {  
  driver = new FirefoxDriver();
         driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
         driver.get("http://any login page");
    }

 @Test
 public void readFontProperty(){
  //Locate text string element to read It's font properties.
  WebElement text = driver.findElement(By.xpath("//h1[contains(.,'Example Login Page')]"));
  
  //Read font-size property and print It In console.
  String fontSize = text.getCssValue("font-size");
  System.out.println("Font Size -> "+fontSize);
  
  //Read color property and print It In console.
  String fontColor = text.getCssValue("color");
  System.out.println("Font Color -> "+fontColor);
  
  //Read font-family property and print It In console.
  String fontFamily = text.getCssValue("font-family");
  System.out.println("Font Family -> "+fontFamily);
  
  //Read text-align property and print It In console.
  String fonttxtAlign = text.getCssValue("text-align");
  System.out.println("Font Text Alignment -> "+fonttxtAlign);
 }
}

Output of above example Is as bellow.
Font Size -> 26.4px
Font Color -> rgba(102, 102, 102, 1)
Font Family -> "Trebuchet MS",Trebuchet,Verdana,sans-serif
Font Text Alignment -> left


Open a link in a New tab

We use actions objects to open any hyperlink in a new tab. e.g.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;

public class NewTab {
    public static void main(String[] args) {
       WebDriver driver = new FirefoxDriver();
        driver.get("http://www.flipcart.com/");
        driver.manage().window().maximize();
        Actions act = new Actions(driver);
        WebElement link = driver.findElement(By.linkText("Flipkart First"));
        act.moveToElement(link).contextClick().sendKeys("F").perform();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
         driver.close();
   
    }
}

Sunday 11 December 2016

Final ,finally and finalize()?

Final:

  • Any variable declare along with final modifier then those variables treated as final variable.
  •  if we declare final variables along with static will became constants.
  • public final String name = "foo"; //never change this value
  • If you declare method as final that method also known as final methods.Final methods are not overridden.means we can't overridden that method in anyway.
  • public final void add(){
     }
     public class A{
     void add(){
     //Can't override
     }

     }
  • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extens that calss in anyway.
  • public final class indhu{
     }
     public class classNotAllowed extends indhu {...} //not allowed

Finally:

  • Finally blocks are followed by try or catch.finally blocks are complasary executable blocks.But finally is useful for more than just exception handling.
  •  it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
     continue, or break,Closing streams, network connection, database connection. Putting cleanup  code in a finally block is always a good practice even when no exceptions are anticipated
  •  where finally doesn't execute e.g. returning value from finally block, calling System.exit from try block etc
  • finally block always execute, except in case of JVM dies i.e. calling System.exit() . 

     lock.lock();
    try {
      //do stuff
    } catch (SomeException se) {
      //handle se
    } finally {
      lock.unlock(); //always executed, even if Exception or Error or se
      //here close the database connection and any return statements like that we have to write
    }

Finalize():

  • finalize() is a method which is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of object.Any unreferncebefore destorying if that object having any connections with databse or anything..It will remove  the connections and it will call finalize() of object.It will destroy the object.
  • If you want to Explicitly call this garbage collector you can use System.gc() or Runtime.gc() objects are there from a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. unallocate memory)
      super.finalize();
    }

Thursday 8 December 2016

Difference between enumeration and iterator and listiterator

Enumeration:

  • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
  • Enumeration uses elements() method.
  • Enumeration can traverse in forward direction only.
  • Enumeration having methods like hasMoreElement(),nextElement().

Program:

package com.ieofjavaforus;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector vector=new Vector();
vector.add("indhu");
vector.add("sindhu");
vector.add("swathi");
vector.add("swathi");
vector.add(null);
vector.add(null);
Enumeration en = vector.elements();  
    while(en.hasMoreElements()){  
         System.out.println(en.nextElement());  
    }  
}
}

Output:

indhu
sindhu
swathi
swathi
null
null

Iterator:

  • Iterator is implemented on all Java collection classes.
  • Iterator uses iterator() method.
  • Iterator can traverse in forward direction only.
  • Iterator having methods like hasNext(), next(), remove().

Program:

package com.ifjavaforus;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class IteratorDemo{
public static void main(String[] args) {
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}

}
Output:

swathi
sindhu
indhu

ListIterator:

  • ListIterator is implemented only for List type classes
  • ListIterator uses listIterator() method.
  • ListIterator can traverse in forward and backward directions.
  • ListIterator having methods like 
  • hasNext()
  • next()
  • previous()
  • hasPrevious()
  • remove()
  • nextIndex()
  • previousIndex().

Program:

package com.iofjavaforus;
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo{
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList.add("indhu");
arrayList.add("sindhu");
arrayList.add("saidesh");
arrayList.add(null);
arrayList.add(null);
ListIterator it=arrayList.listIterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

}

Output:
indhu
sindhu
saidesh
null
null