Automation Using Selenium Webdriver

Friday, 30 September 2016

Write Excel in Selenium Using Apache POI

Write Excel in Selenium Using Apache POI

In below example I am Writing .xlsx file

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.testng.annotations.Test;

public class ReadandWriteExcel {

 public static void main(String []args){

  try {

  // Specify the file path which you want to create or write

  File src=new File("./testdata/test.xlsx");

  // Load the file

  FileInputStream fis=new FileInputStream(src);

   // load the workbook

   XSSFWorkbook wb=new XSSFWorkbook(fis);

  // get the sheet which you want to modify or create

   XSSFSheet sh1= wb.getSheetAt(0);

 // getRow specify which row we want to read and getCell which column

 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());

// here createCell will create column

// and setCellvalue will set the value

 sh1.getRow(0).createCell(2).setCellValue("2.41.0");

 sh1.getRow(1).createCell(2).setCellValue("2.5");

 sh1.getRow(2).createCell(2).setCellValue("2.39");


// here we need to specify where you want to save file

 FileOutputStream fout=new FileOutputStream(new File("location of file/filename.xlsx"));


// finally write content

 wb.write(fout);

// close the file

 fout.close();

  } catch (Exception e) {

   System.out.println(e.getMessage());

  }

 }

}
Please comment in below section if you are facing any issue. Thanks For visiting my blog keep in touch

Thursday, 29 September 2016

Read data from Excel files in Selenium Using Apache POI

Read and Write Excel Programs


I am Reading simple .xlsx file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;


public class ReadandWriteExcel {

 public static void main(String []args){

  try {
  // Specify the path of file
  File src=new File("filepath/excelsheetname.xlsx");

   // load file
   FileInputStream fis=new FileInputStream(src);

   // Load workbook
   XSSFWorkbook wb=new XSSFWorkbook(fis);
 
   // Load sheet- Here we are loading first sheetonly
      XSSFSheet sh1= wb.getSheetAt(0);

  // getRow() specify which row we want to read.

  // and getCell() specify which column to read.
  // getStringCellValue() specify that we are reading String data.


 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());

 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());

  } catch (Exception e) {

   System.out.println(e.getMessage());

  }

 }

}

How to take screen shots of all page links in web site Automatically

How to take screen shots of all page links in web site Automatically


How to take screen shots of all page links in a web site automatically in Chrome driver using Selenium Web Driver.

Below Example Best Check it and Execute Programme   

package ScreenShot;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class LinksScreenshot 
   {
//TestCase id:1 Step1:Decp
//TestCase id:1 Step2:Launch Chrome
//TestCase id:1 Step3:Navigate to newtours.demoaut
//TestCase id:1 Step4:Capture all links
//TestCase id:1 Step5:click on the all links and take screen shots
//Test Case id:1 Step6:close the browser

public static void main(String[] arg) throws IOException

{
 System.out.println("**********excution will stat wait**************");

 System.setProperty("webdriver.chrome.driver",  "C:\\chromedriver.exe");
 WebDriver driver=new ChromeDriver();
         driver.get("http://newtours.demoaut.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
       List<WebElement> links=driver.findElements(By.tagName("a"));
        System.out.println("no of links:" +links.size());

      for(int i=0;i<links.size();i++)
      {
          if((links.get(i).isDisplayed()))
          {
          String linkname=links.get(i).getText();
                 links.get(i).click();
                
             File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("E:\\Jagan\\ScreenShot"+linkname+"png"));
   

          driver.navigate().back();
         

          links=driver.findElements(By.tagName("a"));
          
          }     
         
      }
      driver.close();
 }
        
          }       
      

      //OutPut:No of Links:16 We did get
 
 


  

Wednesday, 28 September 2016

Polymorphism in Java

Polymorphism in Java

The process of representing one form in multiple forms is known as Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
Polymorphism is not a programming concept but it is one of the principal of OOPs. For many objects oriented programming language polymorphism principle is common but whose implementations are varying from one objects oriented programming language to another object oriented programming language.

Real life example of polymorphism

Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors.real life example of polymorphism

How to achieve Polymorphism in Java ?

In java programming the Polymorphism principal is implemented with method overriding concept of java.
Polymorphism principal is divided into two sub principal they are:
  • Static or Compile time polymorphism
  • Dynamic or Runtime polymorphism
Note: Java programming does not support static polymorphism because of its limitations and java always supports dynamic polymorphism.

Let us consider the following diagram

Here original form or original method always resides in base class and multiple forms represents overridden method which resides in derived classes.
polymorphism in java
In the above diagram the sum method which is present in BC class is called original form and the sum() method which are present in DC1 and DC2 are called overridden form hence Sum() method is originally available in only one form and it is further implemented in multiple forms. Hence Sum() method is one of the polymorphism method.

Example of runtime polymorphism.

In below example we create two class Person an Employee, Employee class extends Person class feature and override walk() method. We are calling the walk() method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Here method invocation is determined by the JVM not compiler, So it is known as runtime polymorphism.

Example of Polymorphism in Java

class Person
{
void walk()
{
System.out.println("Can Run....");
}
}
class Employee extends Person
{
void walk()
{
System.out.println("Running Fast...");
}
public static void main(String arg[])
{
Person p=new Employee(); //upcasting
p.walk();
}
}

Output

Running fast...

Dynamic Binding

Dynamic binding always says create an object of base class but do not create the object of derived classes. Dynamic binding principal is always used for executing polymorphic applications.
The process of binding appropriate versions (overridden method) of derived classes which are inherited from base class with base class object is known as dynamic binding.
Advantages of dynamic binding along with polymorphism with method overriding are.
  • Less memory space
  • Less execution time
  • More performance

Static polymorphism

The process of binding the overloaded method within object at compile time is known as Static polymorphism due to static polymorphism utilization of resources (main memory space) is poor because for each and every overloaded method a memory space is created at compile time when it binds with an object. In C++ environment the above problem can be solve by using dynamic polymorphism by implementing with virtual and pure virtual function so most of the C++ developer in real worlds follows only dynamic polymorphism.

Dynamic polymorphism

In dynamic polymorphism method of the program binds with an object at runtime the advantage of dynamic polymorphism is allocating the memory space for the method (either for overloaded method or for override method) at run time.

Conclusion

The advantage of dynamic polymorphism is effective utilization of the resources, so java always use dynamic polymorphism. Java does not support static polymorphism because of its limitation.

Encapsulation

Encapsulation in Java

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation. Encapsulation is achieved in java language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In java language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method.

Advantage of Encapsulation

The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class.

Real life example of Encapsulation

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side capsule.
real life example of encapsulation

Benefits of encapsulation

  • Provides abstraction between an object and its clients.
  • Protects an object from unwanted access by clients.
  • Example: A bank application forbids (restrict) a client to change an Account's balance.

Let's see the Example of Encapsulation in java

Example

class Employee
{  
private String name;  
   
public String getName()
{  
return name;  
}  
public void setName(String name){  
this.name=name;
}  
}  

class Demo
{  
public static void main(String[] args)
{  
Employee e=new Employee();  
e.setName("Harry");  
System.out.println(e.getName());  
}  
}  

Output

Harry

Abstraction In Java

Abstraction in Java

Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is implemented automatically while writing the code in the form of class and object.

Real Life Example of Abstraction

Abstraction shows only important things to the user and hides the internal details for example when we ride a bike, we only know about how to ride bike but can not know about how it work ? and also we do not know internal functionality of bike.
real life example of abstraction
Note: Data abstraction can be used to provide security for the data from the unauthorized methods.
Note: In java language data abstraction can be achieve using class.

Example of Abstraction

class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties 
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and 
balance is required and remaining properties 
are hidden for fund transfer method */
}

How to achieve Abstraction ?

There are two ways to achieve abstraction in java
  • Abstract class (0 to 100%)
  • Interface (Achieve 100% abstraction)
Read more about Interface and Abstract class in previous section.

Difference between Encapsulation and Abstraction

Encapsulation is not provides fully security because we can access private member of the class using reflation API, but in case of Abstraction we can't access static, abstract data member of class.

Interface

Interface in Java

Interface is similar to class which is collection of public static final variables (constants) and abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.

Why we use Interface ?

  • It is used to achieve fully abstraction.
  • By using Interface, you can achieve multiple inheritance in java.
  • It can be used to achieve loose coupling.

properties of Interface

  • It is implicitly abstract. So we no need to use the abstract keyword when declaring an interface.
  • Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
  • Methods in an interface are implicitly public.
  • All the data members of interface are implicitly public static final.

How interface is similar to class ?

Whenever we compile any Interface program it generate .class file. That means the bytecode of an interface appears in a .class file.

How interface is different from class ?

  • You can not instantiate an interface.
  • It does not contain any constructors.
  • All methods in an interface are abstract.
  • Interface can not contain instance fields. Interface only contains public static final variables.
  • Interface is can not extended by a class; it is implemented by a class.
  • Interface can extend multiple interfaces. It means interface support multiple inheritance

Behavior of compiler with Interface program

Interface
In the above image when we compile any interface program, by default compiler added public static final before any variable and public abstract before any method. Because Interface is design for fulfill universal requirements and to achieve fully abstraction.

Declaring Interfaces:

The interface keyword is used to declare an interface.

Example

interface Person
{  
 datatype variablename=value;
 //Any number of final, static fields
 returntype methodname(list of parameters or no parameters)
 //Any number of abstract method declarations
}  

Explanations

In the above syntax Interface is a keyword interface name can be user defined name the default signature of variable is public static final and for method is public abstract. JVM will be added implicitly public static final before data members and public abstract before method.

Example

public static final datatype variable name=value; ----> for data member
public abstract returntype methodname(parameters)---> for method

Implementing Interfaces:

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Example

interface Person
{  
void run();
}  
class Employee implements Person
{
public void run()
{
System.out.println("Run fast");
} 
}

When we use abstract and when Interface

If we do not know about any things about implementation just we have requirement specification then we should be go for Interface
If we are talking about implementation but not completely (partially implemented) then we should be go for abstract

Rules for implementation interface

  • A class can implement more than one interface at a time.
  • A class can extend only one class, but implement many interfaces.
  • An interface can extend another interface, similarly to the way that a class can extend another class.

Relationship between class and Interface

  • Any class can extends another class
  • class to class
  • Any Interface can extends another Interface.
  • interface to interface
  • Any class can Implements another Interface
  • class to interface
  • Any Interface can not extend or Implements any class.
  • interface to class

Difference between Abstract class and Interface

Abstract classInterface
1It is collection of abstract method and concrete methods.It is collection of abstract method.
2There properties can be reused commonly in a specific application.There properties commonly usable in any application of java environment.
3It does not support multiple inheritance.It support multiple inheritance.
4Abstract class is preceded by abstract keyword.It is preceded by Interface keyword.
5Which may contain either variable or constants.Which should contains only constants.
6The default access specifier of abstract class methods are default.There default access specifier of interface method are public.
7These class properties can be reused in other class using extend keyword.These properties can be reused in any other class using implements keyword.
8Inside abstract class we can take constructor.Inside interface we can not take any constructor.
9For the abstract class there is no restriction like initialization of variable at the time of variable declaration.For the interface it should be compulsory to initialization of variable at the time of variable declaration.
10There are no any restriction for abstract class variable.For the interface variable can not declare variable as private, protected, transient, volatile.
11There are no any restriction for abstract class method modifier that means we can use any modifiers.For the interface method can not declare method as strictfp, protected, static, native, private, final, synchronized.

Example of Interface

interface Person
{  
void run();  // abstract method
}  
class A implements Person
{  
public void run()
{
System.out.println("Run fast");
}   
public static void main(String args[])
 {  
 A obj = new A();  
 obj.run();  
 }  
}  

Output

Run fast

Multiple Inheritance using interface

Example

interface Developer
{  
void disp();
}  
interface Manager
{
void show();
} 

class Employee implements Developer, Manager
{
public void disp()
{
System.out.println("Hello Good Morning");  
}
public void show()
{
System.out.println("How are you ?");  
}
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}  
} 

Output

Hello Good Morning
How are you ?

Marker or tagged interface

An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

Example

//Way of writing Serializable interface  
public interface Serializable
{  
}  

Why interface have no constructor ?

Because, constructor are used for eliminate the default values by user defined values, but in case of interface all the data members are public static final that means all are constant so no need to eliminate these values.
Other reason because constructor is like a method and it is concrete method and interface does not have concrete method it have only abstract methods that's why interface have no constructor.