Sunday, June 16, 2013

Selenium : Java Cheat Sheet


Eclipse –Java
    (http://c4learn.com/javaprogramming/)    
http://www.tutorialspoint.com/java/ 

1.    Run - Ctrl+F11
2.    Comment and Uncomment - Ctrl+/

Installation
A.
1.    Install FireFox
2.    FireBug (Firefox Addin)-There should be a bug button in Firefox next to search bar
3.    FirePath(FireFox Addin)-There should be FirePath button inside FireBug workspace
4.    Selenium Ide (Addin for FireFox)- Ide should – Open FireFox>Tools>Selenium Ide

B.    Download and Extract –Eclipse-Helios

C. Open Eclipse>Create WorkSpace>Create Project>Create Class File

Note : ”JRE.Systemlib” – Contains essential Java Files

E.     Adding Selenium Libraries
1.    Goto Download in SeleniumHq.org
2.    Under “Selenium Client & Web Driver Language Bindings” ,click on Java Download
3.    Extract the zip in any folder
4.    To load libraries into eclipse : -
In eclipse Tool Bar>Properties>Java build Path>Libraries
or
     Project Explorer>Rt Ck on Project>Properties>Java Build Path>Libraries>Add External Jars>Select all Selenium Files in the folder in one shot.

F:    Opening Variable View(used in Debug):
Open Eclipse, while in Program editor>Tool Bar>Navigation>Quick Access>Type “Variable”>Click on Variable-Debug

1.    Message output :
    System.out.print("hello");
    JOptionPane.showMessageDialog(null,"msgbox here");        
       
2.    Input :
    JOptionPane.showInputDialog(n"enter something");
   
3.    Concatenation :  "+"

4. End line : "\n"                           
- Ex : System.Out.Print("hi\n");

5.    Equality and Inequality :
"==","!="       
-Ex While(a==b)

6.    Comment : "//" or "/*...........*/ or ctrl+/
7.    Debug :    
1)Double c/k on the line, there will be dot placed corresponding to the line.
2)tool bar >Debug> f6 (Step into) ,f7 (Step over)


8.    Add Variable View view :
         Window>Navigation>Quick Access >Type Variable in window >Select Variable View


9.    IF Statements :
        if(a>b){
            System.out.print(a +"is greater");
        }else if (b>a){
            System.out.print(b +"is greater");
        }else {
            System.out.print("both are same");
        }
       

10.    While Loop :
        while (a!=0){
            System.out.print(a+"\n");
            a-=1;
        }

11.    Array and For Loops
        int aArr[]=new int[3];
        aArr[0]=0;
        aArr[1]=1;
        aArr[2]=2;
       
        for (int i=0 ;i<aArr.length;i++)
        {
            System.out.println(aArr[i]);
        }
Or
For(int i:a_Arr){  //”I” should be same type as a_Arr
}

Ex 2:     String[] aArr=oData.toString().split("\\|");
//When array size is not known

12.Continue - continue;

     
13.Break:break;

12.    2D Array and conversions  (Integer to String) and Size of Arrays
        String Res="";
        int aArr[][]=new int[3][2];
        aArr[0][0]=0;
        aArr[0][1]=1;
       
        aArr[1][0]=2;
        aArr[1][1]=3;
       
        aArr[2][0]=4;
        aArr[2][1]=5;
       
        int row=aArr.length;
        int col=aArr[0].length;
       
        for (int i=0 ;i<row;i++)  {
            for (int j=0 ;j<col;j++) {       
                Res=Res+Integer.toString(aArr[i][j]);
            }
            Res=Res+"\n";
        }
        System.out.print(Res);

       
13.    ArrayList can store any kind of Data without size declaring

                ArrayList a=new ArrayList();
a.add(1);
a.add(“hi”);
                System.out.print(aArr.size());   
 14.  Class = objects , properties ,methods
1.    Object is instance of the class
2.    Property = Ex : Editbox -> width=10px , height=5px
3.    Method = Ex: EditBox().Type “Some Data”
   
Ex1
class circle
{
         int radius;
         circle (int len){  //Constructor assigning values to instance variables
            this.radius = len;
          }
    }

    class circle_demo{
          public static void main(String args[]) {
circle c=new circle(1);
                System.out.println("radius is : " + c.radius);
          }
    }

Ex 2:Setter and Getter
    class circle
{
          Private int radius;

          void set_radius(int len){ //setter or accessor
            this.radius = len;
          }
          int  get_Length(){ // Getter or mutator
            Return radius;
          }
    }

    class circle_demo{
          public static void main(String args[]) {
circle c=new circle();
c.set_radius(1);
                System.out.println("radius is : " + c.get_radius);
          }
    }

15.    Functions 

    public static void main(String[] args)  {       
        JOptionPane.showMessageDialog(null, add_func(1,2));             
    }
   
    public static int add_func(int a,int b) {
        return (a+b);
    }
   

16. Static Functions :    
1.    Main Function is always static
2.    Static Function can only access static variables and communicate only with other static functions .
3.    Non Static are used only by Objects .
4.     Object can access both static and non static variables but preferred that objects use non static variables.
Long Story Short :
Non Static Functions -> Can only be accessed through Objects 
                                      Can make use of constructors


 Static Functions ->  Can be accessed without creation of Objects 
                                Cannot use constructors
                                 Can only use variables declared as static

Ex 2:
Class A
{
static int a=10;
int b=30;

Psvm[String[] args]{
A.m1();        //Access static methods directly without creating instance
A a=new A();              //Nonstatic needs instance
a.m1();                         //instance – access both nonstatic and static methods
a.m2();
sop(A.a);     //Static variable can be accessed directly
}

static void m1()  {               //static method can only access static variables
      Sop(a);
      SOP(b);                  //Error- cannot access non static fields !!
}
void m2{Sop(a+b); } //Non Static method can access both variables

}

17.    This

Example:

 class Car{
    String Car_Name;   
    public void method_name_car(String Car_Name){
        this.Car_Name=Car_Name;
        System.out.println("Car name="+this.Car_Name);       
    }
}

Ex 2:
class Sample
{
    public static void main(String[] args)
    {
        cClass oM1=new cClass();
        oM1.mMethod(3, 4);
        System.out.print(oM1.a+" "+oM1.b);       
    }
}

class cClass
{
    static int a;
    int b;
   
    public Object mMethod(int a ,int b)
    {
   
        this.a=a;
        this.b=b;
        return this;
       
    }
}

18.    Constructor and Constructor Overloading(same name but accepting different arguements)
class Rectangle
 {
      int length;
      int breadth;

      Rectangle(){
          length  = 20;
          breadth = 10;
      }
Rectangle(int length, int breadth) {
      this.length  = length;
      this.breadth = breadth;
  }
}
class RectangleDemo
{
      public static void main(String args[]){
          Rectangle r1 = new Rectangle();
          System.out.println("Length of Rectangle : " + r1.length);
          System.out.println("Breadth of Rectangle : " + r1.breadth);
  }
}


19. Method Overloading 

a)       Same name accepting different arguments or none 
b)   return type has to be different


class Rectangle
 {
        void area(int length, int width) {
        }

        void area(double length, double width) {
        }
}

class RectangleDemo {
    public static void main(String args[]) {
        Rectangle r1 = new Rectangle();
        r1.area(10, 20);
        r1.area(10.50, 20.50);
    }
}



20 .    Passing Object as Parameter :

class Rectangle
{
    int length;
    int width;

    Rectangle(int l, int b){
        length = l;
        width = b;
        }

    void area(Rectangle r1) {
        int areaOfRectangle = r1.length * r1.width;
        System.out.println("Area of Rectangle : "+ areaOfRectangle);
        }
}

class RectangleDemo {
    public static void main(String args[]) {
        Rectangle r1 = new Rectangle(10, 20);
        r1.area(r1);
    }
}

Output of the program :
Area of Rectangle : 200

Different Ways of Passing Object as Parameter :

Way 1 : By directly passing Object Name
class RectangleDemo{
    public static void main(String args[]) {
                Rectangle r1 = new Rectangle(10, 20);
                r1.area(r1);
        }   
}

void area(Rectangle r1)
{
        int areaOfRectangle = r1.length * r1.width;
        System.out.println("Area of Rectangle : "+ areaOfRectangle);
          }
Way 2 : By passing Instance Variables one by one

class Rectangle
 {
    int length;
    int width;

    void area(int length, int width)
{
            int areaOfRectangle = length * width;
        System.out.println("Area of Rectangle : "+ areaOfRectangle);
        }
}

class RectangleDemo
{
    public static void main(String args[])
 {
        Rectangle r1 = new Rectangle();
        Rectangle r2 = new Rectangle();

        r1.length = 20;
    r1.width = 10;
        r2.area(r1.length, r1.width);
    }
}


21.    Returning the Object From Method

      Rectangle getRectangleObject(){
        Rectangle rect = new Rectangle(10,20);
        return rect;
      }
}

22. Exception Handling    
try {
       result = number1 / number2;
       System.out.println("Result of Division : " + ans);
}catch(Exception e)
{
      System.out.println("Divide by Zero Error");
}

In the above code we can catch all types of exception because Exception is superclass of all the exceptions.
       
Ex 1:   
catch (IOException|SQLException ex) {
}   

Ex 2:
catch (ArithmeticException e) {
         System.out.println("Err: Divided by Zero");
    }catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Err: Array Out of Bound");
    }
Ex 3 :
Try{
            int i = 10/10;
} catch(Exception ex){
            System.out.println("The error occured="+ex.getMessage());
} finally {
                System.out.println("always executes not matter what !!");
                }
           }

23.Exit.
System.exit(0);

24. Throw Exception
class StudentExcepeption throws ArithmeticException // Telling Implementing class to handle this exception
{
       static void validateMarks(int age)
{
             if(marks < 75)
          throw new ArithmeticException("Reappear for exam");
             else
          System.out.println("Student is having Distinction");
       }
  

Selenium : Create Excel ,Read and Write Excel into a Array

Selenium : Create Excel ,Read and Write Excel into a Array


Link to download JAR files for Apache POI : http://poi.apache.org/download.html#POI-3.9 and http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.zip (might change according to the new update ).

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;


public class Excel_Operations
{

public static void main(String[] args)
{
System.out.print(Excel_Operations.create_Excel("C:\\Created_with_selenium.xls","D1"));
System.out.print(Excel_Operations.read_excel("C:\\Created_with_selenium.xls","D1"));
String sData[][]=new String[1][1];
sData[0][0]="00";
//sData[0][1]=1;
//sData[1][0]=2;
//sData[1][1]=3;
System.out.print(Excel_Operations.write_excel("C:\\Created_with_selenium.xls", "D1", sData));
}
//-------------------------------------------------------------------------------------
public static boolean create_Excel(String sPath,String sSheet_name)
{

Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
Sheet sheet1 = wb.createSheet(sSheet_name);
try{
FileOutputStream fileOut = new FileOutputStream(sPath);
wb.write(fileOut);
fileOut.close();
return true;
}catch(Exception E)
{
System.out.print("could not create an excel file");
return false;
}

}
//---------------------------------------------------------------------------

public static String read_excel(String sPath,String sSheet_name)
{
String sData="";
try
{
InputStream oFile = new FileInputStream(sPath);
Workbook wb = WorkbookFactory.create(oFile);
Sheet sheet = wb.getSheet(sSheet_name);//.getSheet("Sheet1");

for (Row row : sheet) //Row Count=sheet.getLastRowNum();
{
for (Cell cell : row) //Column Count= row.getLastCellNum();
{
switch (cell.getCellType())//1- string
{
case 0://cell.CELL_TYPE_NUMERIC:
sData=sData+cell.getNumericCellValue();
break;
case 1://cell.CELL_TYPE_STRING:
sData=sData+cell.getStringCellValue();
break;
}
sData=sData+"|";
}
sData=sData+"\n";
}
}catch(Exception e)
{
System.out.print("File not found");
}
return sData;
}
//-------------------------------------------------------------------------------
public static boolean write_excel(String sPath,String sSheet_name,String oData[][])
{
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(sSheet_name);
int iRows=oData.length;
int iCols=oData[0].length;
for (int iR_count=0;iR_count<=iRows-1;iR_count++ )
{
Row row = sheet.createRow(iR_count);
for (int iC_count=0;iC_count<=iCols-1;iC_count++)
{
row.createCell(iC_count).setCellValue(oData[iR_count][iC_count]);
}
}

try{
FileOutputStream fileOut = new FileOutputStream(sPath);
wb.write(fileOut);
fileOut.close();
}catch (Exception e)
{
System.out.print("file not created ");
return false;
}
return true;
}

}

Selenium : Excel operations

Selenium : Excel operations 

Please visit http://poi.apache.org/spreadsheet/quick-guide.html#NewWorkbook  for more details 

Link to download JAR files for Apache POI : http://poi.apache.org/download.html#POI-3.9 and http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.zip (might change according to the new update ).

//New Workbook
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.close();
//New Sheet
Workbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");

// Note that sheet name is Excel must not exceed 31 characters
// and must not contain any of the any of the following characters:
// 0x0000
// 0x0003
// colon (:)
// backslash (\)
// asterisk (*)
// question mark (?)
// forward slash (/)
// opening square bracket ([)
// closing square bracket (])

// You can use org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)}
// for a safe way to create valid names, this utility replaces invalid characters with a space (' ')
String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); // returns " O'Brien's sales "
Sheet sheet3 = wb.createSheet(safeName);

FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

//Working with different types of cells
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow((short)2);
row.createCell(0).setCellValue(1.1);
row.createCell(1).setCellValue(new Date());
row.createCell(2).setCellValue(Calendar.getInstance());
row.createCell(3).setCellValue("a string");
row.createCell(4).setCellValue(true);
row.createCell(5).setCellType(Cell.CELL_TYPE_ERROR);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
//Iterate over rows and cells
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
// Do something here
}
}
//Getting the cell contents
To get the contents of a cell, you first need to know what kind of cell it is
(asking a string cell for its numeric contents will get you a
NumberFormatException for example). So, you will want to switch on the cells
type, and then call the appropriate getter for that cell.
In the code below, we loop over every cell in one sheet, print out the cells
reference (eg A3), and then the cells contents.

// import org.apache.poi.ss.usermodel.*;

Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(" - ");

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
System.out.println(cell.getCellFormula());
break;
default:
System.out.println();
}
}
}
//Reading and Rewriting Workbooks
InputStream inp = new FileInputStream("workbook.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");

Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();