Tuesday 6 December 2016

How to launch safari browser in selenium webdriver



Please follow belows steps for launching safari browser in selenium webdriver


We need to install safari driver extension in safari browser. please follow the below steps for launch safari browser.

1) Go to http://docs.seleniumhq.org/download/

2) Scroll down -> Go to the section "SafariDriver" and download "SafariDriver.safariextz"

3) Double click on "SafariDriver.safariextz" (previously downloaded)

4) Safari would open with a pop up containing "Install" button -> Click Install button

5) Now go to Preferences of Safari and you would see WebDriver (in my case WebDriver 2.48.0) is installed (Enable WebDriver checkbox is checked))

6) It's now time to instantiate SafariDriver and get the desired URL by using Java code:

WebDriver driver = new SafariDriver();
driver.get("https://www.google.com");




Error :

If we are not install SafariDriver.safariextz extension in safari browser, we will get the below error in safari browser during the automation

"Unable to establish a connection with the SafariDriver Extension"


Solution : Follow the above steps to get install "SafariDriver.safariextz" extension in safari browser.



Exception :


If we are not install SafariDriver.safariextz extension in safari browser, we will get the below exception in console during the automation

Driver instantiation Exception Remote Client is not accessible



Solution : Follow the above steps to get install "SafariDriver.safariextz" extension in safari browser.

Log4j - How to disable all log details




We can logging the step by step activity during automation. If any instance we want to disable all log details then follow the below steps


1) go to the //log/log4j.properties file

2) And set the log4j.rootLogger=OFF


log4j.rootLogger=OFF


we can set the restriction to display the log messages



1) If log4j.rootLogger= DEBUG

then it display the all level

log.debug(),log.info(), log.warn(),  log.error(), log.fatal();


2)  If log4j.rootLogger= INFO

then it will display

log.info(), log.warn(),  log.error(), log.fatal();


3)  If log4j.rootLogger= WARN

then it will display

log.warn(),  log.error(), log.fatal();


4)  If log4j.rootLogger= WARN

then it will display

log.warn(),  log.error(), log.fatal();


5)  If log4j.rootLogger= ERROR

then it will display

log.error(), log.fatal();


6)  If log4j.rootLogger= FATAL

then it will display

log.fatal();


7)  If log4j.rootLogger= OFF

then it will NOT display



http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/log4j/log4j.html#LOG4J-Basics-Logger


How to convert Java source file to Jar and working with function inside java file.




Type of JAR file

1) Executable JAR
2) Non-Executable JAR


Follow the below steps for convert JAVA source file to Non-Executable JAR file.
------------------------------------------------------------------------------

1) Create java file by using below code


public class SampleCode{



// create new Excel sheet in workbook

public static void createExcelSheet(Workbook wb, String SheetName, String ExcelPath) throws IOException
{
wb.createSheet(SheetName);
FileOutputStream output_file =new FileOutputStream(new File(ExcelPath));
wb.write(output_file);
output_file.flush();
output_file.close();

}


// verify Excel version

public static Workbook verifyExcelVersion(String FilePath) throws FileNotFoundException, IOException
{
Workbook book1=null;
String fileExtn=FilenameUtils.getExtension(FilePath);

if(fileExtn.equals("xls"))
book1=new HSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsx"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsm"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
return book1;
}




}


2) Save above source file under one package.
Example (Package) -> SampleCode.java

3) Right on  Example (Package) -> Export -> Java -> JAR file -> Click Next

4) In JAR File Specification Window

i)   verify expected Package selected or not.
ii)  select "Export Generated class files and resources".
iii) select "compress the contents of the JAR file".
iv)  provide the path in "Select the export destination"
v)   click Next.

5) In JAR Packaging Options window

i) select "Export class files with compile Errors"
ii) Select "Export class files with compile warnings"
ii) Select "Save the descriptions of this JAR in workspace"
iv) provide the path in "Description file".
v)  click Next

6) In JAR Manifest Specification window

i)   click "Generate the Manifest file".
ii)  click "seal some packages".
iii) click finish

7) Once we cick finsh two files withh get genrated in mentioned path

i) FileName.jar
ii) FileName.jardesc

8) The above JAR is ready to some other project to use existion code. This JAR is called Non Executable JAR file.




How to use and execute function with in JAR file to another package.
-------------------------------------------------------------------

1) create the project

2) Add FileName.jar file in to configure Build path.

3) Then we can use existing functions which available in FileName.jar file.



public static void main(String agrs[])
{

SampleCode obj1=new SampleCode();
Workbook book2=obj1.verifyExcelVersion(ToFilePath);
Sheet sheet2=null;


obj1.createExcelSheet(wb,"Sheet2",Download_FilePath);

}

4) By using above method we can use functions which available in FileName.jar file.

How to get Hashmap key and Hashmap value





By using below below code we can get Hashmap key and Hashmap value


Map,.




for (Map.Entry<String,String> entry : map1.entrySet()) {

System.out.println("HashMap key="+entry.getKey());
System.out.println("HashMap value="+entry.getValue());

}


How to change font color in Excel Sheet by using Apache POI




By using below code we can change the font color in Apache POI



private static void updateColor(String FilePath,int row,int col,String Sheet, String color1) throws FileNotFoundException, IOException {

Workbook book2=verifyExcelVersion(FilePath);
Sheet sheet2=book2.getSheet(Sheet);

// update Font with colors

CellStyle style=book2.createCellStyle();
Font font=book2.createFont();

if(color1.equals("RED"))
font.setColor(IndexedColors.RED.getIndex());
if(color1.equals("GREEN"))
font.setColor(IndexedColors.GREEN.getIndex());
if(color1.equals("BLUE"))
font.setColor(IndexedColors.BLUE.getIndex());

style.setFont(font);


    sheet2.getRow(row).getCell((short) col).setCellStyle(style);
   
     FileOutputStream output_file =new FileOutputStream(new File(FilePath));
     book2.write(output_file);
     output_file.flush();
     output_file.close();
     sheet2=null;
     book2=null;


}

How to display message box in java




We can display the message box during the selenium automation by using Java Swing


public static void main(String args[])
{
msgbox("The verification part is done. We can procced with update the timesheets");
}

private static void msgbox(String string) {
JOptionPane.showMessageDialog(null, string);

}

Sunday 19 June 2016

Appium Error: Failed to start an Appium session, err was: Error: Screen did not unlock

The below error occured in Appium during the execution

error: Failed to start an Appium session, err was: Error: Screen did not unlock


https://github.com/appium/appium/issues/5255


While we  checked. issue is with nexus 4(Android 4.4.2) and nexus 5(Android 5.0.1). It is working fine with nexus 7(Android 4.3)

This error occured while taking screenshot automatically and make unlock.

Appium Error: Activity used to start app doesn't exist or cannot be launched! Make sure it exists and is a launchable activity

The below error occured in appium during execution

Error: Activity used to start app doesn't exist or cannot be launched! Make sure it exists and is a launchable activity


Solution : If the we provide incorrect activity name then we are getting this error.

Android Emulator Issue: The home button, Menu button, back button, Zoom Button is not woking in Android Emulator


The home button, Menu button, back button, Zoom Button is not wotking in Android Emulator, So please use below steps for resolve this issue

-> Goto below path in machine


C:\Users\<User_ID>\.android\avd\<AVD_Name>.avd\config.ini


-> Open the config.ini file

-> change the below settings

from
hw.mainKeys=no   change to  
hw.mainKeys=yes

-> Now restart the AVD then we got home button, Menu button, back button, Zoom Button is woking in Android Emulator


hw.mainKeys=yes

Saturday 18 June 2016

Appium - Code for Automate the Calculator App in Android Mobile


Please follow below steps to Automate the mobile application in Appium


Emulator Setup for Android Mobile -> Setup




The First Appium code for Automate the calculator App



import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL; 
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.remote.CapabilityType; 
import org.openqa.selenium.remote.DesiredCapabilities; 
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest; 
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class Mobile 



WebDriver driver;

@BeforeTest 

public void setUp() throws MalformedURLException

{

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name. 
capabilities.setCapability("deviceName", "sdk"); 
// Set BROWSER_NAME desired capability. It's Android in our case here.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android"); 
// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "4.4.4"); 
// Set android platformName desired capability. It's Android in our case here. 
capabilities.setCapability("platformName", "Android");
// Set android appPackage desired capability. It is 
// com.android.calculator2 for calculator application. 
// Set your application's appPackage if you are using any other app.

capabilities.setCapability("appPackage", "com.android.calculator2"); 

// Set android appActivity desired capability. It is
// com.android.calculator2.Calculator for calculator application.
// Set your application's appPackage if you are using any other app. 

capabilities.setCapability("appActivity", "com.android.calculator2.Calculator"); 

// Created object of RemoteWebDriver will all set capabilities. 
// Set appium server address and port number in URL string.
// It will launch calculator app in android device. 

driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); 
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); 
}

@Test
public void Sum() throws IOException 


System.out.println("Appium");


driver.findElements(By.xpath("//android.widget.Button")).get(0).click();
// driver.findElement(By.name("CLR")).click(); 
// Click on number 2 button. 
driver.findElement(By.name("6")).click(); 
// Click on + button. 
driver.findElement(By.name("+")).click(); 
// Click on number 5 button. 
driver.findElement(By.name("5")).click();
// Click on = button. 
driver.findElement(By.name("=")).click(); 
// Get result from result text box. 
String result = driver.findElement(By.className("android.widget.EditText")).getText(); 
System.out.println("Number sum result is : " + result);

File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File(System.getProperty("user.dir")+"\\ScreenShots.png"));


}

@AfterTest public void End() { driver.quit(); } 

}

How to find app Launcher activity name in Appium



We have two options for find app activity name

1) By using Command Prompt
2) Manifest Info
3) Hierarchy Viewer


1) By using Command Prompt

Please find below steps to find app activity name using command prompt.


-> app APK package name. EX : com.android.calculator2

-> Launch the Android Emulator and wait till starts properly.

-> Goto command prompt and goto E:\android-sdks\platform-tools and verify the device connected properly (not offline). by using below command

E:\SDK\platform-tools>adb devices

List of devices attached
emulator-5554   device

-> Open the reuired app and keep on active in Emulator

-> GOTO and command prompt and use below commands

E:\android-sdks\platform-tools>adb logcat >log.txt

-> Now its generated log text file. Here you can search by app Package name (com.android.calculator2) then we will have log like

I/ActivityManager(  878): Displayed com.android.calculator2/.Calculator: +7s332ms


Here com.android.calculator2.Calculator is app activity name.



2) By using AndroidManifest.xml Info



http://software-testing-tutorials-automation.blogspot.in/2015/10/find-launcher-activity-and-package-name.html


-> Right click on .apk file of APK Info app(or any other .apk file for which you wants to know package and activity name).

-> Select Open with -> WinRAR archiver option from right click context menu.

-> It will open .apk file in WinRAR window and you can see AndroidManifest.xml.

-> Open AndroidManifest.xml file in notepad. Now find keyword "p a c k a g e" In notepad.

-> Package name for my APK Info app is : com.intelloware.apkinfo Find keyword "a c t i v i t y" In notepad. It will show you activity name of your app.


-> Activity name for my APK Info app is display: .MainActivity. Here you need to append package name ahead of activity name so full activity name is : com.intelloware.apkinfo.MainActivity



3) Hierarchy Viewer 


-> Launch the Android Emulator and wait till starts properly.

-> Launch the appium and start the server.

-> Open the Hierarchy viewer from below path. Android Emulator should be starts properly, its should not be closed.

C:\android-sdks\tools\hierarchyviewer.bat


-> Then goto page in emulator which activity needs to be record.

-> Then automatically we can see the package name and activity name in Hierarchy viewer

we can see in bold color

com.android.calculator2/com.android.calculator2.calculator

Here,

package Name = com.android.calculator2
Activity Name = com.android.calculator2.calculator

How to find APK Package using UI Automator Viewer


We can identify the Package name by using below two methods


1) UI Automator viewer
2) Hierarchy Viewer


1) UI Automator viewer

Please find below steps to find APK package using UI Automator viewer


-> Open the reuired app and keep on active in Emulator

-> Launch the uiautomatorviewer.bat file from below mentioned path

E:\android-sdks\tools\uiautomatorviewer.bat

-> Click "Device Screenshot ("Uiautomater Dump") in uiautomatorviewer then its taking screenshot and paste into uiautomatorviewer.

-> Now we can inspect the element.

-> Right hand side we can see the option like "package" for APK package name.




2) Hierarchy Viewer


-> Launch the Android Emulator and wait till starts properly.

-> Launch the appium and start the server.

-> Open the Hierarchy viewer from below path. Android Emulator should be starts properly, its should not be closed.

C:\android-sdks\tools\hierarchyviewer.bat


-> Then goto page in emulator which activity needs to be record.

-> Then automatically we can see the package name and activity name in Hierarchy viewer

we can see in bold color

com.android.calculator2/com.android.calculator2.calculator

Here,

package Name = com.android.calculator2
Activity Name = com.android.calculator2.calculator



How to inspect element in mobile app for appium mobile automation testing (By using Emulator)



We can inspect the element in mobile app by using uiautomatorviewer.bat file from Android SDK folder.


-> Open the required app and keep on active in Emulator

-> Launch the uiautomatorviewer.bat file from below mentioned path

E:\android-sdks\tools\uiautomatorviewer.bat

-> Click "Device Screenshot ("Uiautomater Dump") in uiautomatorviewer then its automatically taking screenshot and paste into uiautomatorviewer.

-> Now we can inspect the element from Uiautomationviewer.

UnInstall .apk file into emulator for mobile automation testing in Appium





we have two ways to Uninstall .apk file into emulator

1) By using setting in emulator
2) By using Command Prompt




1) By using setting in emulator (Like Android Phone)

-> Goto setting in emulator
-> Goto App
-> Select required app and uninstall




2) By using Command Prompt

-> Download required .pdk file

-> Launch the Android Emulator and wait till starts properly.

-> Goto command prompt and goto E:\android-sdks\platform-tools and verify the device connected properly (not offline). by using below command

E:\SDK\platform-tools>adb devices

List of devices attached
emulator-5554   device

-> Run below command for install required .apk file in command prompt.

E:\SDK\platform-tools>adb uninstall Calender.apk

Success

-> We will get "Success" message if apk uninstalled in emulator.

-> Goto emulator and verify the calender app is uninstalled or not.

Install .apk file into emulator for mobile automation testing in Appium




Please follow below steps for install .apk file into emulator


-> Download required .pdk file

-> Launch the Android Emulator and wait till starts properly.

-> Goto command prompt and goto E:\android-sdks\platform-tools and verify the device connected properly (not offline). by using below command

E:\android-sdks\platform-tools>adb devices

List of devices attached
emulator-5554   device

-> copy and paste required .apk file into below mentioned path
E:\android-sdks\platform-tools

-> Run below command for install required .apk file in command prompt.


E:\android-sdks\platform-tools>adb install Calender.apk

1910 KB/s (93651283 bytes in 431.338s)
        pkg: /data/local/tmp/Calender.apk
Success


-> We will get "Success" message if apk installed in emulator.

-> Goto emulator and verify the calender app is installed or not.

Appium Setup for Mobile Automation Testing





The below software needs to be install in our machine


1) Download ADT Plug in (Eclipse)
2) Download and Set SDK location
3) Microsoft .Net Framework
4) Appium
5) Node JS



1) ADT Plugin (in Eclipse)


Use following steps to install ADT Plugin

-> Goto Eclipse
-> Goto Help -> Install New Software
-> Here click "ADD" button
-> Then Name = ADT (Any Name)
-> URL = https://dl-ssl.google.com/android/eclipse/
-> Select all software and finish the installation

Refer this link for install ADT plugin -> http://software-testing-tutorials-automation.blogspot.in/2015/09/steps-to-install-eclipse-adt-plugin-to.html


2) Download and Set SDK Location in Eclipse

After install the ADT plugin in eclipse then we set the SDK location in Eclipse

-> once restart the Eclipse after install ADT plugin then its ask confirmation for install SDK.

-> select first option for "install SDK".

-> select first checkbox for install latest SDK

-> select second checkbox and give the path of SDK

-> click yes for send the statistics to the google and click proceed. its take some time to install SDK.



3) Microsoft .Net Framework


Download Microsoft .Net Framework by using this link -> https://www.microsoft.com/en-in/download/details.aspx?id=17851

Refer this link to download -> http://software-testing-tutorials-automation.blogspot.in/2015/09/install-other-required-software-for.html



4) Appium


Download Appium by using this link -> http://appium.io/

Refer this link to download -> http://software-testing-tutorials-automation.blogspot.in/2015/09/how-to-download-and-install-appium-in.html



5) Node JS

 Download Node JS by using this link -> https://nodejs.org/en/download/

Refer this link to download -> http://software-testing-tutorials-automation.blogspot.in/2015/09/install-other-required-software-for.html



6) Download below required jar files and configured with eclipse


gson-2.5
java-client-3.3.0



Launch Android Emulator


Pre-requiste

1) Installed SDK
2) Installed required pakages in Android SDK Manager



2) Installed required pakages in Android SDK Manager

-> Open the Android SDK Manager (Eclipse-> Window-> Android SDK Manager

-> Update Proxy settings in Android SDK Manager (Tools-> Options)

-> Refresh (Android SDK Manager-> Pakages->Reload)

-> Its list out the available pakages. Select required pakage and install

Appium - Introduction




-> Appium is mobile application software testing tools.

-> we can automate native app, Web app and Hybrid app by using Appium.

-> Its open source software automation tool which is useful to automate android and IOS platform apps.

-> Appium is cross-platform automation tool so we can write automation tests and run against IOS and Android.


Multiple Platforms Support

Appium support bellow given different platforms.

Android
IOS
FirefoxOS



Multiple Languages Support

Appium supports bellow given languages with the Selenium WebDriver API and language-specific client libraries.

Java
Objective-C
JavaScript with Node.js
PHP
Python
Ruby
C#
Clojure
Perl



Limitations Of Appium

There are few limitation in appium right now.

For Android, No Support for Android API level < 17.
Script execution is very slow on IOS platform.
Gestures support is limited.
No support for Toast messages.


Appuium supports only Android 17+ API level version only.


****************************************

What is Android SDK


-> Androd SDK is software development kit which enables to create application for android platform.

For Example, If you want to create any android software games then we need Android SDK.

-> Also its provides ability to create emulators to test new created games or any other android apps.

-> By using appium we can create and run automation tests for native apps and web apps in android device or emulators. But we need Android SDK is pre-requisite to run tests on android platform using Appium.


*************************************************


Difference between simulator and emulator


The basic difference is Emulator runs for Android OS (Samsung galaxy,htc,motorola,etc,.) but simulator runs for Mac (iOS) iPhone 3g,4,4s,iPod.


Device is Emulator
Software is simulator

Saturday 4 June 2016

How to create excel sheet using apache poi





By using below code we can create excel sheet using apache poi



code:


public static void main(String agrs[])
{

Workbook book2=verifyExcelVersion(ToFilePath);
Sheet sheet2=null;


createExcelSheet(wb,"Sheet2",Download_FilePath);

}



// create new Excel sheet in workbook

public static void createExcelSheet(Workbook wb, String SheetName, String ExcelPath) throws IOException
{
wb.createSheet(SheetName);
FileOutputStream output_file =new FileOutputStream(new File(ExcelPath));  
wb.write(output_file); 
output_file.flush();
output_file.close(); 

}


// verify Excel version

public static Workbook verifyExcelVersion(String FilePath) throws FileNotFoundException, IOException
{
Workbook book1=null;
String fileExtn=FilenameUtils.getExtension(FilePath);

if(fileExtn.equals("xls"))
book1=new HSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsx"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsm"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
return book1;
}


How to verify excel sheet present or not in apache poi



By using below code we can verify the perticular excel sheet present or not. If not available we can create by using apache POI command.



code:

public static void main(String agrs[])
{

Workbook book2=verifyExcelVersion(ToFilePath);
Sheet sheet2=null;


if(!isExcelSheetExist(wb,"Sheet2"))
createExcelSheet(wb,"Sheet2",Download_FilePath);

}


// verify Excel Sheet exist or not

public static boolean isExcelSheetExist(Workbook wb, String SheetName)
{
if(wb.getSheetIndex(SheetName)>=0)
return true;
else
return false;

}


// create new Excel sheet in workbook

public static void createExcelSheet(Workbook wb, String SheetName, String ExcelPath) throws IOException
{
wb.createSheet(SheetName);
FileOutputStream output_file =new FileOutputStream(new File(ExcelPath));  
wb.write(output_file); 
output_file.flush();
output_file.close(); 

}


// verify Excel version

public static Workbook verifyExcelVersion(String FilePath) throws FileNotFoundException, IOException
{
Workbook book1=null;
String fileExtn=FilenameUtils.getExtension(FilePath);

if(fileExtn.equals("xls"))
book1=new HSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsx"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsm"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
return book1;
}




How to create common functions for working with different format of Excel Sheet by using Apache POI



By using below verifyExcelVersion() we can create common function for handle with different Excel format by using Apache POI



code:

public static void main(String agrs[])
{

Workbook book2=verifyExcelVersion(ToFilePath);
Sheet sheet2=null;


if(!isExcelSheetExist(wb,"Sheet2"))
createExcelSheet(wb,"Sheet2",Download_FilePath);

}




// verify Excel version

public static Workbook verifyExcelVersion(String FilePath) throws FileNotFoundException, IOException
{
Workbook book1=null;
String fileExtn=FilenameUtils.getExtension(FilePath);

if(fileExtn.equals("xls"))
book1=new HSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsx"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
else if(fileExtn.equals("xlsm"))
book1=new XSSFWorkbook(new FileInputStream(FilePath));
return book1;
}

how to break out of nested loops java



break;

By using break we can come out from single loop.

But if we want to come out from all nested loop then we shoule use lables for acheiving this concept.



Example:

int points = 0;
int goal = 100;
someLabel:
while (goal <= 100) {
   for (int i = 0; i < goal; i++) {
      if (points > 50) {
         break someLabel;
      }
   points += i;
   }
}
// you are going here after break someLabel;

How to set auto detect proxy settings by using selenium in browser



Normally selenium referred the system proxy settings. If we want to use auto detect proxy setting from selenium code then we have to use different code like below



       org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
       proxy.setAutodetect(true); 
       DesiredCapabilities cap = new DesiredCapabilities();
       cap.setCapability(CapabilityType.PROXY, proxy);
       WebDriver driver5 = new FirefoxDriver(cap);
       
       driver5.manage().window().maximize();

How to Generate XSLT reports by using Ant+TestNG



We have to follow below steps to generate XSLT reports

1) ANT Installation
2) Configure XSLT and build.xml
3) Genrate XSLT report by using ANT

1) ANT Installation

-> Download Latest Version of apache-ant zip
Download latest version of apache-ant from

http://ant.apache.org/bindownload.cgi.

Extract zip folder and save into our local path.

-> Set JAVA_HOME Environment variables

* Right click on My Computer -> Properties and go to -> Advanced tab.
* Clicking on Environment variables button will open Environment variable dialog.
* Click on New button from System Variables box and add Variable Name = JAVA_HOME and Variable Value = Path of your jdk folder.
* Here my JDK folder path is 'C:\Program Files\Java\jdk1.8.0'

-> Set ANT_HOME Environment Variables

* Right click on My Computer -> Properties and go to -> Advanced tab.
* Clicking on Environment variables button will open Environment variable dialog.
* Click on New button from System Variables box and add Variable Name = ANT_HOME and Variable Value = Path of your jdk folder.
* Here my ANT folder path is 'D:\Selenium\apache-ant-1.9.7'

-> Edit Path Variable

* Right click on My Computer -> Properties and go to -> Advanced tab.
* Clicking on Environment variables button will open Environment variable dialog.
* Edit existing Path variable by selecting Path variable from System variables list.
* And click Edit button and insert  %JAVA_HOME%\bin;%ANT_HOME%\bin  at the end of Path variable value string.
* Do not forget to put semicolon (;) before %JAVA_HOME%\bin

-> Copy tools.jar from jdk/lib and paste It In jre/lib
* There will be 2 folders In your C:Program Files\Java folder.
* In my system It Is jdk1.8.0 and jre8.
* Open C:\Program Files\Java\jdk1.8.0\lib folder and copy tools.jar file.
* Open C:\Program Files\Java\jre8\lib and paste tools.jar In to It.

Now restart your system to getting system variables changes effect.

Verify ant configured properly or not
To verify that ant Is configured properly or not, follow the bellow given steps after restarting system
* Open command prompt.
* Type command "ant" and press Enter button.
* It should show you message as bellow.


C:\Users\user>ant
Buildfile: build.xml does not exist!
Build failed





2) Configure XSLT and build.xml


-> The below jar files shoule be under lib folder

* saxon-8.7
* SaxonLiaison
* testng-xslt-maven-plugin-test-0.0
* Selenium-server-standalone 2.47

-> The below files should be under project path

* build.xml  -> Link to download
* testng-results.xsl -> Link to Download

-> Configure build.xml file

Verify the Value for "project.jars" property at line no 10 of build.xml file. It should be the path of "lib" folder of project.
Verify the path of testng-results.xsl file at line no 91 of build.xml file. It should be  path of testng-results.xsl.

Note : Don't change any thing else In build.xml file.




3) Genrate XSLT report by using ANT


Once your test execution get completed and testng results generated, We can go to generate XSLT report. You need to follow bellow given steps to generate XSLT report.


-> Open command prompt.

-> Goto your project

E:\Selenium_Project\Selenium_Testing>

-> Type "ant" to check we are in correct path to generate XSLT report.


E:\Selenium_Project\Selenium_Testing>ant
Buildfile: E:\Selenium_Project\Selenium_Testing\build.xml

usage:
     [echo]
     [echo]             ant run will execute the test
     [echo]

BUILD SUCCESSFUL
Total time: 0 seconds


-> Remove Previous Build : Type Command = "ant clear"

 It should give message "BUILD SUCCESSFUL"


E:\Selenium_Project\Selenium_Testing>ant clear
Buildfile: E:\Selenium_Project\Selenium_Testing\build.xml

clear:
   [delete] Deleting directory E:\Selenium_Project\Selenium_Testing\build

BUILD SUCCESSFUL
Total time: 0 seconds


-> Compile And Generate New Build Folder : Type Command = "ant compile".

 It should give message "BUILD SUCCESSFUL"

E:\Selenium_Project\Selenium_Testing>ant compile


-> Verify Build Folder Is Generated : Now Refresh your project In eclipse.
 ant compile command will created new folder with name of  build under your project

-> Execute Test Suites : Type Command = ant run In command prompt and press enter.
It will execute your all software automation test suites which are included In testng.xml file.

 So now you can execute your software test suites from command prompt Instead of testng.xml file.

-> Generate XSLT Reports : Type Command = ant reports In command prompt and press enter.
It should give message "BUILD SUCCESSFUL"

-> open XSLT Report : Once more refresh your project In eclipse.

 ant reports command will create new folder with name = XSLT_Reports under your project


->You will find index.html file In XSLT_Reports folder.
That Is XSLT Report of your webdriver test. Open that file In any web browser.
 It Is Interactive and easy to understand that how many test cases are Pass, Fail and Skip for specific test case.



Note : If pie chart is not available in your report then you will get error message in browser like below


Error Message : SVG Pie Charts are not available. Please install a SVG viewer for your browser


So please install SVG viewer in order to see pie chart in XSLT reports.

Saturday 30 April 2016

Web Service Testing (using Client security certificate .pfx format) by using SOAP UI Tool





Please follow below steps for working with web service

Test Web Service URL = http://www.webservicex.com/currencyconvertor.asmx?WSDL
Test Client Security certificate (.pfx) = c:\test-certificate.pfx
Test Client Security certificate Password = 1234




1) create SOAP Project

- File -> New SOAP Project -> Enter Project Name -> Click ok

2) Add WSDL Link

Right Click on project -> Add Wsdl -> Enter Web Service URL -> Click ok

Ex : http://www.webservicex.com/currencyconvertor.asmx?WSDL



3) Import client Security certificate 


i) Add Certificate in Kestores

Double Click on Project -> WS-Security Configurations tab-> Keystores tab -> Click + (Add New keysore to this config) -> Select file (c:\test-certificate.pfx) -> enter password (1234) -> click ok -> The Status automatically changed to "OK" (If NOT issue in certificate).


ii) Outgoing WS-Security Configurations

- Click + (Add New Outgoing WSS Configuration) -> Enter Any name for outgoing WSS Configuration (Ex: Test_OUtgoing)-> Click "ok"

- Click + (Add new WSS Entry) -> Select Type of Entry to Add is "Signature".

- double click on "Signature" for configuration (Add below value)

Keystore = Select certificate from drop down (c:\test-certificate.pfx)
Alias = Select Alis from drop down
Password = 1234  (Test Client Security certificate Password)
Key Identifier Type = "Binary Security Token"
Signature Algorithm =
Signature canonicalization =
Digest Algorithm =
Use Single Certificate = check the checkbox


iii) incoming WS-Security Configurations

- Click + (Add New Incoming WSS Configuration) -> Enter Any name for Incoming WSS Configuration (Ex: Test_Incoming) -> Click "ok"

- Select Decrypt Keysore and Signature keystore from drop down



iv) Save all the changes



4) Add New Authorization


- Double click on "Request1" under the project
- Click "Auth" (Authentication and Security related settings) in below Request1
- Select Authorization as "Add New Authorization.."
- Select Authorization Type as "Basic"
- Select outgoing WSS = Test_OUtgoing (Which we create Outgoing WS-Security Configurations)
- Select Incoming WSS = Test_Incoming (Which we create incoming WS-Security Configurations)



5) SOAP Request

Double click on Request1 under the project and enter below mentioned code

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET/">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ConversionRate>
         <web:FromCurrency>AFA</web:FromCurrency>
         <web:ToCurrency>DZD</web:ToCurrency>
      </web:ConversionRate>
   </soapenv:Body>
</soapenv:Envelope>


And click Run (Trigger) the SOAP Request


6) SOAP Response

We are getting the below responce once we triggered the


<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <ConversionRateResponse xmlns="http://www.webserviceX.NET/">
         <ConversionRateResult>-1</ConversionRateResult>
      </ConversionRateResponse>
   </soap:Body>
</soap:Envelope>

Web Service Testing (With out using security certificate) by using SOAP UI Tool





Please follow below steps for working with web service

Test Web Service URL = http://www.webservicex.com/currencyconvertor.asmx?WSDL




1) create SOAP Project

- File -> New SOAP Project -> Enter Project Name -> Click ok

2) Add WSDL Link

Right Click on project -> Add Wsdl -> Enter Web Service URL -> Click ok

Ex : http://www.webservicex.com/currencyconvertor.asmx?WSDL

3) SOAP Request

Double click on Request1 under the project and enter below mentioned code

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.webserviceX.NET/">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ConversionRate>
         <web:FromCurrency>AFA</web:FromCurrency>
         <web:ToCurrency>DZD</web:ToCurrency>
      </web:ConversionRate>
   </soapenv:Body>
</soapenv:Envelope>


And click Run (Trigger) the SOAP Request


4) SOAP Response

We are getting the below responce once we triggered the


<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <ConversionRateResponse xmlns="http://www.webserviceX.NET/">
         <ConversionRateResult>-1</ConversionRateResult>
      </ConversionRateResponse>
   </soap:Body>
</soap:Envelope>


How to add the attribute in XML document to send the SOAP request message.



Consider below example


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
            <SOAP-ENV:Header/>
           <SOAP-ENV:Body xmlns:example="http://ws.cdyne.com/"  wsu:Id="id-123456789" >
               <example:VerifyEmail>
                   <example:email>mutantninja@gmail.com</example:email>
   <CDH/>
                   <example:LicenseKey>
<ABC>123</ABC>
   </example:LicenseKey>


               </example:VerifyEmail>
           </SOAP-ENV:Body>
     
</SOAP-ENV:Envelope>








 MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
 SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();

envelope.addNamespaceDeclaration("example", "http://ws.cdyne.com/");

SOAPBody soapBody = envelope.getBody();

soapBody.addNamespaceDeclaration("example", "http://ws.cdyne.com/");
//  soapBody.addAttribute(envelope.createName("wsu:Id"), "id-123456789");
   
QName attributeName = new QName("wsu:Id");
soapBody.addAttribute(attributeName, "id-123456789");
     


SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example").addTextNode("mutantninja@gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("CDH");
SOAPElement soapBodyElem3 = soapBodyElem.addChildElement("LicenseKey", "example")
SOAPElement soapBodyElem3 = soapBodyElem3.addChildElement("ABC").addTextNode("123");



MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");
soapMessage.saveChanges();




by using above code we can add the attribute value.

How to construct the XML document by using java code to send the SOAP request




Consider below Web Service URL and XML document.


Web Service URL = http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
            <SOAP-ENV:Header/>
           <SOAP-ENV:Body>
               <example:VerifyEmail>
                   <example:email>mutantninja@gmail.com</example:email>
                   <example:LicenseKey>123</example:LicenseKey>
               </example:VerifyEmail>
           </SOAP-ENV:Body>
     
</SOAP-ENV:Envelope>



Code for construct the XML document by using java code to send the SOAP request


 MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
 SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();

envelope.addNamespaceDeclaration("example", "http://ws.cdyne.com/");

SOAPBody soapBody = envelope.getBody();


SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example").addTextNode("mutantninja@gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example").addTextNode("123");


MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");
soapMessage.saveChanges();



By using above code we can construct the XML document by using java code to send the SOAP request message.


How to send the SOAP request message (Construct the XML document by using jave) to get the SOAP response message




We need to follow the below information for send the SOAP request and get the SOAP response by using below web service URL


Web Service URL = http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx



<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
            <SOAP-ENV:Header/>
           <SOAP-ENV:Body>
               <example:VerifyEmail>
                   <example:email>mutantninja@gmail.com</example:email>
                   <example:LicenseKey>123</example:LicenseKey>
               </example:VerifyEmail>
           </SOAP-ENV:Body>
     
</SOAP-ENV:Envelope>

http://stackoverflow.com/questions/19291283/soap-request-to-webservice-with-java


Code:



import javax.xml.soap.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class SOAPClientSAAJ {

    /**
     * Starting point for the SAAJ - SOAP Client Testing
     */
    public static void main(String args[]) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

            // Process the SOAP Response
            printSOAPResponse(soapResponse);

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("Error occurred while sending SOAP Request to Server");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://ws.cdyne.com/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("example", serverURI);


        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
        soapBodyElem1.addTextNode("mutantninja@gmail.com");
        SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
        soapBodyElem2.addTextNode("123");

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.print("Request SOAP Message = ");
        soapMessage.writeTo(System.out);
        System.out.println();

        return soapMessage;
    }

    /**
     * Method used to print the SOAP Response
     */
    private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.print("\nResponse SOAP Message = ");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
    }

}



XPATH Functions




1) Node Set Function
2) String Function
3) Boolean Function
4) Number Function




1) Node Set Function

-> last()

Identify the last item of current node set.

Ex : https://www.google.co.in

//div[@id='sfdiv']//input[last()]  -> its identify last input tag



-> position()

Identify the item as per the postion. Position value start from 14.

Ex : https://www.google.co.in

//div[@id='sfdiv']//input[position()=1]  -> its identify first input tag



-> count()

Its count the number of element from context node.


Ex : https://www.google.co.in

count(//div[@id='sfdiv']//input)  -> o/p=3, Return total number of input element.



-> local-name()


Instead of element tag(//div)) we can use local-name() (local-name()='div')

Ex : https://www.google.co.in

local-name(//div[@id='sfdiv']//input)

//*[local-name()='div' and starts-with(@id,'sfdiv')]//input



-> id()

Its returns elements which ID specified in code


Ex : https://www.google.co.in

id("sfdiv")/div//input  -> o/p=3, Identify all 3 input tag.


The xpath id("sfdiv")/div//input  and //div[@id='sfdiv']//input both are same.


**********************************************************************



2) String Functions


-> String()

we can identify the object by using text. Both Text() and String() are same.


Ex : https://www.google.co.in

//div[@id='gbw']//a[String()='Gmail']

//div[@id='gbw']//a[text()='Gmail']

Both are same.


o/p identify the object which having the GMAIL text.



-> Concat()

Its Used to concatenate the two string


Ex : https://www.google.co.in


concat(//div[@id='gbw']//a[text()],' ',//div[@id='gbw']//a[text()])

O/p String: Gmail Gmail

concat(//div[@id='gbw']//a[text()],' ',//div[@id='gbw']//div[2]//a[text()])


O/p String: Gmail Images




-> starts-with()


Its identify the object by using text which starts given string.


Ex : https://www.google.co.in

//*[local-name()='div' and starts-with(@id,'sfdiv')]//input


o/p identify all three objects.



-> Contains()

Its identify the object which contains the text

Ex: https://www.google.co.in


//div[contains(id,'sfdiv']//input

o/p identify all three objects.



-> substring-before()

Its retrives the substring of first argument

Ex : https://www.google.co.in

substring-before(//div[@id='gbw']//a[text()],'a')

o/p  String: il


we can use this xpath like below for identify the object

//div[@id='gbw']//a[contains(.,substring-before(//div[@id='gbw']//a[text()],'a'))]





-> substring-after()

Its retrives the substring of first argument

substring-after(//div[@id='gbw']//a[text()],'a')


O/P     String: il


we can use this xpath like below for identify the object

//div[@id='gbw']//a[contains(.,substring-after(//div[@id='gbw']//a[text()],'a'))]



*******************************************************************8


3) Boolean Function


-> Boolean boolean(object)

Converts the argument to a Boolean value.

Example - boolean(/journal/article/author/last[.='Jones'])



-> Boolean not(boolean)

Negates the boolean value.

Example - not(/journal/article/author/last[.='Jones'])


***************************************************


4) Number Function


Will update shortly




https://docs.oracle.com/cd/E35413_01/doc.722/e35419/dev_xpath_functions.htm#autoId19

Behaviour Driven Development framework - Cucumber


Cucumber

Cucumber is tool based on Behaviour Driven Development framework which is used with selenium for perform acceptance testing.


It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.


@Test
public void should_do_something() {
    // given
    Something something = getSomething();

    // when
    something.doSomething();
    // then
    assertSomething();

    // when
    something.doSomethingElse();
    // then
    assertSomethingElse();
}



Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code.

Saturday 23 January 2016

Getting Error Message : java.util.regex.PatternSyntaxException: Unclosed character class near index 0

While try to split the value by using "[" OR "]" then we are getting the above issue.


Ex : String str="Selenium []"
    str.split("[")

we are getting the below exception.


Exception :

java.util.regex.PatternSyntaxException: Unclosed character class near index 0


Solution

The Special character "["  and "]" used in Regular Experssions, so these characters are not standared characters.

So we should add excape character for use this special character ("\[" and "\]"). But the escape character "\" is not allowed for "["  and "]".

So we should use string as "\\[" or "\\]"


Exact code will be

Ex : String str="Selenium []"
    str.split("\\[")


http://stackoverflow.com/questions/21816788/unclosed-character-class-error

Getting Error Message : Access restriction: The type Provider is not accessible due to restriction on required library C:\Program Files\Java\jre8\lib\jsse.jar




Solution


Go to the Build Path settings in the project properties.
Remove the JRE System Library
Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.


Reason :


This works because you have multiple classes in different jar files. Removing and re-adding the JRE lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.

Getting Error Message : org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms.


Reason :

While launching Mozilla browser getting the exception


Solution:

There are two possibility for above exception

1) Mozilla browser compatibility issue

2) We may configure many version of selenium jar files in build path. So remove all jar files from configure build path and update the latest jar files.

Getting Error Message : java.lang.IllegalStateException: Cannot get a text value from a numeric formula cell



Reason :
If we read string value from Formula cell then we are getting this exception.


Solution:

Use string value in cell.

Getting Error Message : java.lang.IllegalStateException: Cannot get a text value from a numeric cell



Reason:

If we read string value from integer cell then we are getting this exception.






Solution :



Use String data in Excel

Or

Add (') in front of integer then its considered as string while reading the data from cell.



How to Enter User id and Password in Authentication window using Robot Class in selenium



We can use Robot class or AutoIT tool for enter user id and password in Authetication window using selenium


Using Robot Class
----------------


fd.get("https://www.google.co.in");
driver.findElement(By.name("btnK")).click()
       
        Thread.sleep(5000);
        Robot rb = new Robot();

        //Enter user name by ctrl-v
        StringSelection username = new StringSelection("username");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);           
        rb.keyPress(KeyEvent.VK_CONTROL);
        rb.keyPress(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_CONTROL);

        //tab to password entry field
        rb.keyPress(KeyEvent.VK_TAB);
        rb.keyRelease(KeyEvent.VK_TAB);
        Thread.sleep(2000);

        //Enter password by ctrl-v
        StringSelection pwd = new StringSelection("password");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
        rb.keyPress(KeyEvent.VK_CONTROL);
        rb.keyPress(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_CONTROL);

        //press enter
        rb.keyPress(KeyEvent.VK_ENTER);
        rb.keyRelease(KeyEvent.VK_ENTER);

        //wait
        Thread.sleep(5000);
       

How to enter the value to text box and select from suggestion drop down box


Consider the below example


Ex: https://www.google.co.in


While try to enter the any string in  google text box for searching, we are getting the suggestion drop down box. Here we need to select the value from drop down box and click search button.

use below lines of code

driver.findElement(By.id("gs_htif0)).sendKeys("Selenium Automation"+"\n");



Here, sendKeys("Selenium Automation"+"\n")

we should use "\n" for handle this issue. Its used for send the ENTER keys for click the button.

How to Write data into .xlsx excel file format file by using Apache POI file



public void WriteExcel(String FilePath,String SheetName,int row,int col,String data) throws IOException,FileNotFoundException
    { 
       
            FileInputStream fsIP= new FileInputStream(new File(FilePath)); //Read the spreadsheet that needs to be updated
            XSSFWorkbook wb = new XSSFWorkbook(fsIP); //Access the workbook
            XSSFSheet worksheet = wb.getSheet(SheetName); //Access the worksheet, so that we can update / modify it.
//            int rowcount=worksheet.getLastRowNum();//return row count
                    
//            HSSFRow row1 = worksheet.createRow(row);
            XSSFRow row1 = worksheet.getRow(row);
            XSSFCell cell = row1.createCell((short) col); //Create a new cell in current row
            cell.setCellValue(data);  //Set value to new value
            fsIP.close(); //Close the InputStream
       
            FileOutputStream output_file =new FileOutputStream(new File(FilePath));  //Open FileOutputStream to write updates
            wb.write(output_file); //write changes
            output_file.close();  //close the stream  
    }

Difference between toString() and getStringCellValue in Apachi POI




1) toString()

Its returns the string object.

If excel have the below data type variable then it returns the below corresponding values


-> IF String - Return String
-> IF Integer - Return Integer
-> If Date - Return Date
-> If Formula - Return formula (Not return value after formula get executed)



2) getStringCellValue()

Its return the string value if the cells contains only string, Other wise its returns exception.


If excel have the below data type variable then it returns the below corresponding values


-> IF String - Return String
-> IF Integer - Return IllegalStateException (Use getNumericCellValue )
-> If Date - Return IllegalStateException (Use getDateCellValue())
-> If Formula - Return IllegalStateException (Use getCellFormula and getCachedFormulaResultType)

How to Reading Formula string from excel sheet using Apache POI

How to read String,Integer,Formula Value from excel sheet(.xlsx) using Apache POI




The Apache stores two value for formula cells.

1) Retrive the Formula value (Only Formula, Not String)   - getCellFormula()
2) Retrive the string after formula got executed (Only string, NOT formula) - getCachedFormulaResultType()


So Normally we are using getCachedFormulaResultType() for retrive the strings from excel after formula get execute.


public String findValueOfTestDataFromExcel(String FilePath,String SheetName,int row,String Text) throws IOException

    {
        String str1="";
        String str2 = "";
        Double val;
        Date date1;
        FileInputStream file2=new FileInputStream(FilePath);
        XSSFWorkbook book2 = new XSSFWorkbook(file2);
        XSSFSheet sheet2 = book2.getSheet(SheetName);
       
        int col=sheet2.getRow(row).getLastCellNum();
        for(int i=0;i<=col;i++)
        {
            str1=sheet2.getRow(row).getCell(i).toString();
            if(str1.contains(Text))
            {
               
                    switch(sheet2.getRow(row).getCell(i).getCellType())
                    {
                    case Cell.CELL_TYPE_STRING:
                        str2=sheet2.getRow(row).getCell(i).getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        val=sheet2.getRow(row).getCell(i).getNumericCellValue();
                        str2=String.valueOf(Math.round(val));
                        break;
                    case Cell.CELL_TYPE_FORMULA:
//                        str2=sheet2.getRow(row).getCell(i).getCellFormula();   //Get formula
                        switch(sheet2.getRow(row).getCell(i).getCachedFormulaResultType())
                        {
                        case Cell.CELL_TYPE_STRING:
                            str2=sheet2.getRow(row).getCell(i).getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            date1=sheet2.getRow(row).getCell(i).getDateCellValue();
                            SimpleDateFormat sdf2=new SimpleDateFormat("MM'/'dd'/'yyy");
                            str2=sdf2.format(date1);
                            break;
                        }
                        break;
                   
                    }
                   
                break;           
           
            }
               
        }
        return str2;
    }
   

How to print the all value from drop down box in selenium




By using ID:

List<WebElement> allText=new Select(driver1.findElement(By.id(getId("ID1")))).getOptions();
int i=0;
for(webElement ele:allText)
{
System.out.println(ele.get(i).getText());
i++;
}



By using xpath :


List<WebElement> allText = driver.findElements(By.xpath("//*[@id="vehicleTypeName"]/option"));
int i=0;
for(webElement ele:allText)
{
System.out.println(ele.get(i).getText());
i++;
}

How to get column number from excel sheet using apache poi

We can get column number by using below different options






Option1:
int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
or


Option2 :
int noOfColumns = sh.getRow(0).getLastCellNum();


There is some difference between above two options

Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Getting Error Message : org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]


Reason :

 If we are using xls format excel file for reading/writing by using XSSF apachi poi then we will get this issue

Solution :

XSSF used only for XLSX excel file format only.
HSSF used only for XLS excel file format only










So we will use xls format excel file for reading/writing by using HSSF apachi poi for avoiding this issue.

XML Notes


XML = Extensive Markup Language

Consider below example


<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>


 <table>
    <td>Apples</td>
    <td>Bananas</td>
   <table>

 <h:table xmlns:h="http://www.w3.org/TR/html4/">
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:table>

</bookstore>



Here,

1) Element = All the item with in <> is called Element

2) Attribute = Element may have the Attribute. Its contain data related to specifi element. Ex: "Category" is Attribut.

3) Attribute Value = Attribute have the value. Here, "children" is value of "Category" attribute. Here Attribute value should be with in double quotes.

4) NameSpace =
Its used to avoid Element Name conflicts.
So we add any prefix for differentiate the Same element name that is called Namespace.
The Namespace can be defined by an "xmlns" attribute in the start tag of an element.
The namespace declaration has the following syntax. xmlns:prefix="URI".
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.


Ex: Here xmlns:h="http://www.w3.org/TR/html4/" is namespace declaration and h is prefix of the element for diffrentiate the same element name.
Here the <table> element have duplicated. So we are using namespace and add the prefix for differntiate and declare for different meaning.