Getting error in reading data from excel in selenium webdriver (java) - selenium

Here is my code
public class MyClass
{
public void readExcel(String filePath,String fileName,String sheetName) throws IOException{
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// To Maximize browser screen
driver.manage().window().maximize();
//Test 5 : Excel Read
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
String fileExtensionName = fileName.substring(fileName.indexOf("."));
Workbook guru99Workbook = null;
if(fileExtensionName.equals(".xlsx")) {
guru99Workbook = new XSSFWorkbook(inputStream);
}
else if(fileExtensionName.equals(".xls")){
guru99Workbook = new HSSFWorkbook(inputStream);
}
Sheet guru99Sheet = guru99Workbook.getSheet(sheetName);
//Find number of rows in excel file
int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();
for (int i = 0; i < rowCount+1; i++) {
Row row = guru99Sheet.getRow(i);
//Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
//Print Excel data in console
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
}
}
//Main function is calling readExcel function to read data from excel file
public static void main(String...strings) throws IOException{
//Create an object of ReadGuru99ExcelFile class
MyClass objExcelFile = new MyClass();
//Prepare the path of excel file
String filePath = System.getProperty("user.dir")+"\\src\\newpackage";
//excelExportAndFileIO
//Call read file method of the class to read data
objExcelFile.readExcel(filePath,"Keywords.xlsx","ExcelGuru99Demo");
}
}
Here is the error :
Exception in thread "main" java.lang.NoSuchFieldError:
RAW_XML_FILE_HEADER at
org.apache.poi.poifs.filesystem.FileMagic.(FileMagic.java:42)
at
org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:208)
at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:98)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:324)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37) at
org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:295)
at newpackage.MyClass.readExcel(MyClass.java:139) at
newpackage.MyClass.main(MyClass.java:184)
PS : I am new to Selenium so learning this feature from :
https://www.guru99.com/all-about-excel-in-selenium-poi-jxl.html
Please help me , TIA

Hi I googled for it & found solution of my error :
I had to include one more jar.
xmlbeans-2.3.0.jar
Such error or suggestion was not giving though while creating / building code, I wonder why not..

Related

Write Status of test case with Hash Map and Selenium

I am using Hash Map to read the get excel data and use them in methods to perform If...else validations.
I am using class file for initializing the Hash Map for reading the data. it goes as shown below
public class SampleDataset {
public static HashMap<String, ArrayList<String>> main() throws IOException {
final String DatasetSheet = "src/test/resources/SampleDataSet.xlsx";
final String DatasetTab = "TestCase";
Object[][] ab = DataLoader.ReadMyExcelData(DatasetSheet, DatasetTab);
int rowcount = DataLoader.myrowCount(DatasetSheet, DatasetTab);
int colcount = DataLoader.mycolCount(DatasetSheet, DatasetTab);
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
// i = 2 to avoid column names
for (int i = 2; i < rowcount;) {
ArrayList<String> mycolvalueslist = new ArrayList<String>();
for (int j = 0; j < colcount;) {
mycolvalueslist.add(ab[i][j].toString());
j++;
}
map.put(ab[i][0].toString(), mycolvalueslist);
i++;
}
return map;
}
I am using this map in my testcase file which is as shown below
#Test //Testcase
public void testThis() throws Exception {
try {
launchMainApplication();
TestMain MainPage = new TestMain(tool, test, user, application);
HashMap<String, ArrayList<String>> win = SampleDataset.main();
SortedSet<String> keys = new TreeSet<>(win.keySet());
for (String i : keys) {
System.out.println("########### Test = " + win.get(i).get(0) + " ###########");
MainPage.step01(win.get(i).get(1));
MainPage.step02(win.get(i).get(2));
}
test.setResult("pass");
} catch (AlreadyRunException e) {
} catch (Exception e) {
verificationErrors.append(e.getMessage());
throw e;
}
}
#Override
#After
public void tearDown() throws Exception {
super.tearDown();
}
I want to write the status as PASS or FAIL for all the testcase initiated through above FOR-LOOP on to same excel by creating new column as Status for each row of test case
my excel sheet is as shown below
Cereate global List. After every test case add status result in the list.
After all test cases are finished, iterate trough te list and updete your excell file. In this way.
public static void main(String[] args) throws EncryptedDocumentException, IOException {
// Step 1: load your excel file as a Workbook
String excelFilePath = "D:\\Desktop\\testExcel.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));
// Step 2: modify your Workbook as you prefer
Iterator<Sheet> sheetIterator = workbook.sheetIterator(); // Getting an iterator for all the sheets
while (sheetIterator.hasNext()) {
Iterator<Row> rowIterator = sheetIterator.next().rowIterator(); // Getting an iterator for all the rows (of current sheet)
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Put here your internal logic to understand if the row needs some changes!
int cellsn = row.getLastCellNum();
row.getCell(cellsn).setCellValue("String that you gat from List = list.get(rownumber)")
}
}
You may need Apache POI.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.00</version>
</dependency>

How to check for broken links and save the result in excel using selenium webdriver?

I need to get all the links in a web page and store it in first column in excel sheet and check whether the link is broken are valid and update the result in second column in same excel sheet.
Here is the code I have tried,
public class login {
public WebDriver driver;
#BeforeTest
public void login1() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "driver path");
driver.get("url");
Thread.sleep(20000);
}
#Test
public void data() throws IOException {
File src = new File("excel path");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet Sheet1 = wb.getSheetAt(0);
Sheet1.createRow(0).createCell(0);
List<WebElement> links=driver.findElements(By.tagName("a"));
String url = "";
HttpURLConnection huc;
int respCode = 200;
int cell =0;
for(int i=0;i<links.size();i++) {
WebElement alinks = links.get(i);
String allinks = alinks.getAttribute("href");
System.out.println(allinks);
XSSFRow row = Sheet1.createRow(i);
XSSFCell excelCell = row.createCell(cell);
excelCell.setCellValue(allinks);
}
Iterator<WebElement> it = links.iterator();
while(it.hasNext()){
url = it.next().getAttribute("href");
System.out.println(url);
if(url == null || url.isEmpty()){
System.out.println("URL is not yet published");
continue;
}
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
for (int i=1; i <= Sheet1.getLastRowNum(); i++){
Cell resultCell= Sheet1.getRow(i).getCell(1);
if(respCode >= 400){
System.out.println(url+" is a broken link");
resultCell.setCellValue("FAIL");
}
else{
System.out.println(url+" is a valid link");
resultCell.setCellValue("PASS");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
}
With this code I can able to get all the links from the web page and store it in first column of excel sheet but when checking for broken links only the first link is checked and before checking second link it throws java.lang.NullPointerException error at this line resultCell.setCellValue("PASS"); Can any one help on this?
In the above case, the cell does not exist yet, so getCell returns null.
You must detect this and create the cell if it doesn't exist, with createCell method:
Cell resultCell= Sheet1.getRow(i).getCell(1);
if (cell == null)
{
cell = Sheet1.getRow(i).createCell(1);
}
// Then set the value.
cell.setCellValue("PASS");
Alternatively, there is an overload of getCell where you can specify a MissingCellPolicy so that a blank Cell is automatically created if it didn't already exist:
cell = sheet.getRow(i).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

Not able to write output in the excel using selenium code

public class AustriaRegro {
public String Result;
WebDriver driver;
WebDriverWait wait;
Sheet s;
WritableSheet ws;
WritableWorkbook wc;
Workbook w;
#Test
public void TestSetup() throws IOException, BiffException, RowsExceededException, WriteException{
System.setProperty("webdriver.chrome.driver","C:\\Users\\yirsh\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
FileInputStream fi = new FileInputStream("C:\\Users\\yirsh\\Desktop\\UAT WEBSHOP.xls");
w = Workbook.getWorkbook(fi);
s = w.getSheet("Regro");
FileOutputStream fo = new FileOutputStream("C:\\Users\\yirsh\\Desktop\\UATWEBSHOPResult.xls");
wc =Workbook.createWorkbook(fo);
ws = wc.createSheet("Query_data", 0);
Sheet sheets = w.getSheet("Query_data");
String inputdata[] [] = new String[s.getRows()][s.getColumns()];
for (int i=0;i<s.getRows();i++)
{
for(int k=0;k< s.getColumns();k++)
{
inputdata[i][k] = s.getCell(k,i).getContents();
Label l = new Label(k,i , inputdata[i][k]);
Label la = new Label(4,0,"Results");
ws.addCell(l);
ws.addCell(la);
}
}
for(int row=1; row <= s.getRows() ; row++){
driver.manage().deleteAllCookies();
wait = new WebDriverWait(driver,30);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://path/");
driver.manage().window().maximize();
String username = s.getCell(2,row).getContents();
System.out.println("***********************************");
System.out.println("Username: "+username);
driver.findElement(By.id("j_username_leftAside")).sendKeys(username);
String password= s.getCell(3,row).getContents();
System.out.println("Password: "+password);
driver.findElement(By.id("j_password_leftAside")).sendKeys(password);
driver.findElement(By.xpath("/html[#class=' js opacity generatedcontent pointerevents']/body[#class='page-homepage pageType-ContentPage template-pages-layout-RexelHomePageLayout pageLabel-homepage language-de ']/div[#id='page']/div[#id='content']/div[#id='content']/div[#class='content-top-inner']/div[#id='content-inner']/div[#class='mid-wrapper'][1]/div[#class='yCmsContentSlot']/div[#class='login clear']/form[#id='loginForm']/div[#class='left sign-in']/button[#class='Sign-in rx-btn mb0']")).click();
try{
if((driver.findElement(By.xpath(".//*[#id='globalMessages']/div"))).isDisplayed()){
System.out.println("Login Failed");
Result="Failed";
String Error=driver.findElement(By.xpath(".//*[#id='globalMessages']/div")).getText();
System.out.println("The Error mesaage is :"+Error);
System.out.println("***********************************************************************************************************");
}
}
catch (Exception e){
System.out.println("Login Sucessfull");
Result="Pass";
System.out.println("***********************************");
driver.findElement(By.xpath(".//*[#id='content-inner']/div[1]/div/div[2]/div[3]/div/div/ul/li[9]/a")).click();
}
Label lb = new Label(4,1,Result);
ws.addCell(lb);
}
driver.close();
}
}
I am writing a code to fetch data from an excel sheet and run selenium tests on it and write the output in a different excel file. Result Excel has been created but data is not inserted.Need to correct the code so that it can insert the results.Only saving the result in excel is pending remaining all working fine as expected.
You'll need to write to file. I believe you can do so by calling WritableWorkbook.write(). Remember to close the files afterward.
...
...
Label lb = new Label(4,1,Result);
ws.addCell(lb);
}
wc.write();
wc.close();
w.close();
driver.close();
See the documentation here. The write function can throw an IOException, so you'll have to handle that at some point - I see you're passing that exception up the stack, that's fine.

Selenium WebDriver generates StaleElementReferenceExeption on getText() on table elements

The current environment:
Selenium Server version 2.37.0
RemoteWebDriver running on Firefox
no Ajax / asynchronously loaded content
My tests are attempting to validate the content of each cell of an HTML table. Before accessing any table element an explicit wait verifies that the <tbody> element exists
ExpectedCondition<WebElement> recruitTableIsPresent = ExpectedConditions.presenceOfElementLocated(By.id("newRecruitFieldAgentWidget:newRecruitDataTable_data"));
new WebDriverWait(driver, 5).until(recruitTableIsPresent);
Once the table is verified to exist, data is pulled out by row and column
private Stats[] parseStats() {
String xpath = "//tbody[#id='regionalFieldAgentWidget:regionalDataTable_data']/tr[%d]/td[%d]";
Stats[] stats = new Stats[3];
for (int i = 0; i < stats.length; i++) {
String inProgresOrders = cellContent(xpath, i, 1);
String maxCapacity = cellContent(xpath, i, 2);
String allocationRatio = cellContent(xpath, i, 3);
Stats[i] = new Stats(inProgressORders, maxCapacity, allocationRatio);
}
return stats;
}
private String cellContent(String xpathTemplate, int row, int cell) {
String xpath = String.format(xpathTemplate, row + 1, cell + 1);
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
WebElement elementByXPath = driver.findElementByXPath(xpath);
return elementByXPath.getText();
}
I don't see any race conditions, since the table content is populated with the page, and not in an asynchronous call. Additionally, I have seen other answers that suggest invoking findElement() via the driver instance will refresh the cache. Lastly, the explicit wait before accessing the element should ensure that the <TD> tag is present.
What could be causing the getText() method return the following exception:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
It's worthwhile to note that the failure is intermittent. Some executions fail while other passes through the same code pass. The table cell causing the failure are also not consistent.
There is a solution to this using Html-Agility-Pack.
This will work only if you want to read the data from that page.
This goes likes this
//Convert the pageContent into documentNode.
void _getHtmlNode(IWebDriver driver){
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(driver.PageSource);
return htmlDocument.DocumentNode;
}
private Stats[] parseStats(){
String xpath = "//tbody[#id='regionalFieldAgentWidget:regionalDataTable_data']/tr[%d]/td[%d]";
Stats[] stats = new Stats[3];
for (int i = 0; i < stats.Length; i++) {
String inProgresOrders = cellContent(xpath, i, 1);
String maxCapacity = cellContent(xpath, i, 2);
String allocationRatio = cellContent(xpath, i, 3);
Stats[i] = new Stats(inProgressORders, maxCapacity, allocationRatio);
}
return stats;
}
private String cellContent(String xpathTemplate, int row, int cell) {
String xpath = String.format(xpathTemplate, row + 1, cell + 1);
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
var documentNode = _getHtmlNode(driver);
var elementByXPath = documentNode.SelectSingleNode(xpath);
return elementByXPath.InnerText;
}
now read any data.
Some tips for using htmlNode.
1. Similar to driver.FindElement: document.SelectSingleNode
2. Similar to driver.FindElements: document.SelectNodes
3. Similar to driver.Text: document.InnerText.
For more search regarding HtmlNode.
Turns out there was a race condition as I've already mentioned. Since jQuery is available via PrimeFaces there is a very handy solution mentioned in a few other posts. I implemented the following method to wait for any asynchronous requests to return before parsing page elements
public static void waitForPageLoad(JavascriptExecutor jsContext) {
while (getActiveConnections(jsContext) > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
private static long getActiveConnections(JavascriptExecutor jsContext) {
return (Long) jsContext.executeScript("return (window.jQuery || { active : 0 }).active");
}
Each built in driver implementation implements the JavascriptExecutor interface, so the calling code is very straightforward:
WebDriver driver = new FirefoxDriver();
waitForPageLoad((JavascriptExecutor) driver);

excel file upload using apache file upload

I am developing an testing automation tool in linux system. I dont have write permissions for tomcat directory which is located on server. I need to develop an application where we can select an excel file so that the excel content is automatically stored in already existing table.
For this pupose i have written an form to select an file which is posted to a servlet CommonsFileUploadServlet where i am storing the uploaded file and then calling ReadExcelFile class which reads the file path and create a vector for data in file which is used to sstore data in database.
My problem is that i am not able to store the uploaded file in directory. Is it necessary to have permission rights for tomcat to do this. Can i store the file on my system and pass the path to ReadExcelFile.class
Please guide me
My code is as follows:
Form in jsp
CommonsFileUploadServlet class code:
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
File file = new File("/",item.getName());
String realPath = getServletContext().getRealPath("/")+"/"+item.getName();
item.write(file);
ReadExcelFile ref= new ReadExcelFile();
String res=ref.insertReq(realPath,"1");
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
ReadExcelFile code:
public static String insertReq(String fileName,String sno) {
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName,sno);
//store the data to database
storeCellDataToDatabase(dataHolder);
}
public static Vector readExcelFile(String fileName,String Sno)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(s);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
short minColIndex = myRow.getFirstCellNum();
short maxColIndex = myRow.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
{
cellStoreVector.addElement(myCell);
}
else
{
cellStoreVector.addElement(myCell);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void storeCellDataToDatabase(Vector dataHolder)
{
Connection conn;
Statement stmt;
String query;
try
{
// get connection and declare statement
int z;
for (int i=1;i<dataHolder.size(); i++)
{
z=0;
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
String []stringCellValue=new String[10];
for (int j=0; j < cellStoreVector.size();j++,z++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
if(myCell==null)
stringCellValue[z]=" ";
else
stringCellValue[z] = myCell.toString();
}
try
{
//inserting into database
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
stmt.close();
conn.close();
System.out.println("success");
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
POI will happily open from an old InputStream, it needn't be a File one.
I'd suggest you look at the Commons FileUpload Streaming API and consider just passing the excel part straight to POI without touching the disk