Not able to run java code from Eclipse to Jmeter using Groovy - groovy

The code below prints the content from the excel file (tried in eclipse) but I am not able to run it in Jmeter 3.1 using Groovy.
I throws error:
Problem in JSR223 script JSR223 Sampler, message:
javax.script.ScriptException:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed
This is my code:
public static void main (String args[]) throws IOException
{
GetExcelTableInto2DArrayListString("C:\\Users\\val1\\Desktop\\Book1.xlsx", true);
}
public static void GetExcelTableInto2DArrayListString(String excelFile, boolean debug) throws IOException{
ArrayList<String> OUT = new ArrayList<String>();
File myFile = new File(excelFile);
FileInputStream fis = null;
fis = new FileInputStream(myFile);
String columnWanted = "PhysicalIDs";
Integer columnNo = null;
XSSFWorkbook myWorkBook = null;
myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = mySheet.getRow(0); //rowIterator.next();
for(Cell cell:firstRow){
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
System.out.println(columnNo);
DataFormatter formatter = new DataFormatter(Locale.US);
if (columnNo != null){
for (Row row : mySheet) {
Cell c = row.getCell(columnNo);
System.out.println(formatter.formatCellValue(c));
if (c == null) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + myFile.toString());
}
}

I strongly doubt that your code works in eclipse (whatever it is) and anywhere else because this line:
public static void main (String args[])
is not syntactically correct neither in Java nor in Groovy.
The "good" declaration of the entry point (although it's not required for Groovy scripts) would be:
public static void main(String[] args)
Full code just in case:
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.DataFormatter
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
public static void main(String[] args) throws IOException {
GetExcelTableInto2DArrayListString("C:\\Users\\val1\\Desktop\\Book1.xlsx", true);
}
public static void GetExcelTableInto2DArrayListString(String excelFile, boolean debug) throws IOException {
ArrayList<String> OUT = new ArrayList<String>();
File myFile = new File(excelFile);
FileInputStream fis = null;
fis = new FileInputStream(myFile);
String columnWanted = "PhysicalIDs";
Integer columnNo = null;
XSSFWorkbook myWorkBook = null;
myWorkBook = new XSSFWorkbook(fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = mySheet.getRow(0); //rowIterator.next();
for (Cell cell : firstRow) {
if (cell.getStringCellValue().equals(columnWanted)) {
columnNo = cell.getColumnIndex();
}
}
System.out.println(columnNo);
DataFormatter formatter = new DataFormatter(Locale.US);
if (columnNo != null) {
for (Row row : mySheet) {
Cell c = row.getCell(columnNo);
System.out.println(formatter.formatCellValue(c));
if (c == null) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
} else {
System.out.println("could not find column " + columnWanted + " in first row of " + myFile.toString());
}
}
More information:
Lesson: A Closer Look at the "Hello World!" Application
Busy Developers' Guide to HSSF and XSSF Features
Apache Groovy - Why and How You Should Use It

Related

Return particular sheet from Workbook in byte[]

I have this excel workbook stored in my resources folder. Considering this excel is of 9 pages i want to extract a particular page and return it into from of byte[].
I created this controller
#GetMapping(value = "/getSinglePage/{pageNumber}")
private ResponseEntity<byte[]> getExcelByPageNumber(#PathVariable Integer pageNumber) throws IOException {
return new ResponseEntity<>(service.getExcelByPageNumber(pageNumber), HttpStatus.OK);
}
The service code contains--
public byte[] getExcelByPageNumber(Integer pageNumber) throws IOException {
Workbook workbook = null;
byte[] byteArray = null;
// here file.xls is my excel sheet that contains 9 sheet for example
workbook = WorkbookFactory.create(loader.getResource("classpath:file.xls").getInputStream());
//gets the sheet from given page number
Sheet sheet = workbook.getSheetAt(pageNumber);
// now i want to return this sheet in the form of byte[]
return byteArray;
}
How should I return it into form of byte[]?
By doing some POC I get to know a single worksheet could not exist without having its own workbook. And Workbook has restricted libraries to work on. So apparently I could not find any direct solution to copy or append the sheet.
What i did is I removed the sheets which are not needed that is keeping only sheet in the workbook and then writing it using ByteArrayOutputStream.
public byte[] getExcelByPageNumber(Integer pageNumber) throws IOException {
// TODO Auto-generated method stub
Workbook workbook = new XSSFWorkbook();
workbook = WorkbookFactory.create(loader.getResource("classpath:file.xls").getInputStream());
Sheet tmpSheet = workbook.getSheetAt(pageNumber - 1);
for (int i = workbook.getNumberOfSheets() - 1; i >= 0; i--) {
String sheetName = workbook.getSheetName(i).trim();
if (!tmpSheet.getSheetName().equals(sheetName)) {
workbook.removeSheetAt(i);
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
} finally {
bos.close();
}
byte[] bytes = bos.toByteArray();
return bytes;
}

testNG multiple dataproviders passing data to one class having multiple test methods

EDIT1: I have an ExcelUtility.java class to get cell data from it and pass it on to the tests methods in my test class.
I am reading from 1 excel file.
The excel file has 3 worksheets.
Every worksheet has 1 unique working table inside.
I have 1 Test class.
The test class has 3 test methods.
The test class contains 3 dataProviders.
All dataProviders differ in the worksheet name and working table name.
The tests in the test class are written in the following manner:
#Test(priority = 0, dataProvider = "dp1")
public void test01(String...strings){
}
#Test(priority = 1, dataProvider = "dp2")
public void test02(String...strings){
}
#Test(priority = 2, dataProvider = "dp3")
public void test03(String...strings){
}
I have the following java class to read from XLSX file using apache poi jars:
public class ExcelUtility {
private static XSSFWorkbook ExcelWBook;
private static XSSFSheet ExcelWSheet;
/*
* Set the File path, open Excel file
* #params - Excel Path and Sheet Name
*/
public static void setExcelFile(String path, String sheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(path);
// Access the excel data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {
throw (e);
}
}
public static String[][] getTestData(String tableName) {
String[][] testData = null;
try {
// Handle numbers and strings
DataFormatter formatter = new DataFormatter();
XSSFCell[] boundaryCells = findCells(tableName);
XSSFCell startCell = boundaryCells[0];
XSSFCell endCell = boundaryCells[1];
int startRow = startCell.getRowIndex() + 1;
int endRow = endCell.getRowIndex() - 1;
int startCol = startCell.getColumnIndex() + 1;
int endCol = endCell.getColumnIndex() - 1;
testData = new String[endRow - startRow + 1][endCol - startCol + 1];
for (int i=startRow; i<endRow+1; i++) {
for (int j=startCol; j<endCol+1; j++) {
// testData[i-startRow][j-startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
public static XSSFCell[] findCells(String tableName) {
DataFormatter formatter = new DataFormatter();
String pos = "begin";
XSSFCell[] cells = new XSSFCell[2];
for (Row row : ExcelWSheet) {
for (Cell cell : row) {
// if (tableName.equals(cell.getStringCellValue())) {
if (tableName.equals(formatter.formatCellValue(cell))) {
if (pos.equalsIgnoreCase("begin")) {
cells[0] = (XSSFCell) cell;
pos = "end";
} else {
cells[1] = (XSSFCell) cell;
}
}
}
}
return cells;
}
}
In order to read from the excel file I have organized the test methods in the following manner:
#DataProvider(name = "dp1")
public Object[][] dp1() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page1");
testData = ExcelUtility.getTestData("P1");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#DataProvider(name = "dp2")
public Object[][] dp2() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page2");
testData = ExcelUtility.getTestData("P2");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#DataProvider(name = "dp3")
public Object[][] dp3() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page3");
testData = ExcelUtility.getTestData("P3");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#Test(priority = 0, dataProvider = "dp1")
public void test01(String...strings){
//read data from excel and pass the value to the strings added as arguments in the method above
}
#Test(priority = 1, dataProvider = "dp2")
public void test02(String...strings){
}
#Test(priority = 2, dataProvider = "dp3")
public void test03(String...strings){
}
What I would like to do is the following:
Read first row data from sheet1, pass it to test1, continue to test2
Read first row data from sheet2, pass it to test2, continue to test3
Read first row data from sheet3, pass it to test3, continue to test1
Read second row data from sheet 1, pass it to test1, continue to test2
And so on, depending of number of rows in the excel sheets.
What happens is:
The first test is executed, reads worksheet 1, row 1.
The first test is executed, reads worksheet 1, row 2.
The second test is executed, reads worksheet 2, row 1.
The second test is executed, reads worksheet 2, row 2.
All tests fail because they are dependable from each other, that is why I set execution priority.
Should I change something in the Test class, or something in the ExcelUtility.java class should be changed?
Thank you in advance!
See files related to the commit
It creates testng.xml based on xlsx with test data.

File not found exception: Apache poi - dataProvider

---Data provider class---
public class TestData {
#DataProvider(name = "data")
public static Object[][] getTableArray() throws Exception {
File src = new File("‪D:/Data/Data.xlsx");
FileInputStream fis = new FileInputStream(src);//getting error for this line
Workbook wb = new XSSFWorkbook(fis);
Sheet sh = wb.getSheet("Credentials");
int rowcount = sh.getLastRowNum();
String[][] cred = getCellData(sh,rowcount);
System.out.println(cred[0][0]);
return cred;
}
public static String[][] getCellData(Sheet sh, int rowcount){
int ri=0,ci=0;
Cell cell=null;
String data[][]=null;
int colcount = 2;
for( ri=0;ri<=rowcount;ri++){
for (ci=0;ci<colcount;ci++){
cell = sh.getRow(ri).getCell(ci);
data[ri][ci]=cell.getStringCellValue();
}
System.out.println(cell);
}
return data;
}
--Accessing Class----
public class Data {
#Test(dataProvider="data", dataProviderClass = TestData.class )
public void read(String username, String password) {
System.out.println(username);
System.out.println(password);
}
}
This is my code i am getting error on the line where i have added the comment. Error is : java.io.FileNotFoundException: ?D:\Data\Data.xlsx (The filename, directory name, or volume label syntax is incorrect)

Selenium excel read and write to find row number

In my program I want to find the row number in the excel sheet matching the string I have passed as argument . It works fine for first and second row but problem is with the next rows. My code to find row number is as below :
public int findrownum(String sName, String value, int cNum) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
boolean check = true;
int i=0;
while (check){
XSSFRow rowH = ws.getRow(i);
XSSFCell cell = rowH.getCell(cNum);
String cellvalue = cellToString(cell);
if (cellvalue.equals(value)){
check = false;
}
else {
i = i+1;
}
}
return i;
}
}
I want to read third row that is the string with name registration from the excel
Sl No test case name result timestamp
1 login Pass 03/03/2014 12:11:43 PM
2 Registration
Please let me know what changes needs to be done in the code .
Thanks
I used the similar logic as mentioned by #eric in JUNIT now i am able to find the row number .But now its giving error while i try to read the data using this row number . My code to read data is as below . Please let me know what changes needs to be done public String dataread(String sName, int rNum, String cName) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
XSSFRow rowH = ws.getRow(rNum-1);
int totalRows = ws.getLastRowNum();
int i =0;
for(i=0;i<=totalRows;i++)
{
XSSFCell cell = rowH.getCell(i);
String value = cellToString(cell);
if (value.equals(cName)){
System.out.println(i);
break;
}
}
XSSFRow row = ws.getRow(rNum);
XSSFCell cell = row.getCell(i);
String value = cellToString(cell) return value;
}
In general From this Documentation you can use the getHeight() to get in which your cursor instead of writing up your own loop. Obviously this would reduce the execution time as well. Also the code which you have written could have caused the exception,as there is no more physical rows.
ws.getRow(i); can cause a fatal error if i>height of the last row
Hope the following code helps. The assumption is the data in the cell is string data. Also this is with apache poi api.
public static String getcellValue(int testRowNo, int colNo)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
cellValue = workSheet.getRow(testRowNo).getCell(colNo).getStringCellValue();
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return cellValue;
}
public static int getrowNumber(String sheetName, String cellData)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
int testRowNo = 0;
for(int rowNo =1; rowNo<=totalRows; rowNo++)
{
row = workSheet.getRow(rowNo);
testRowNo = testRowNo +1;
if(row.getCell(0).getStringCellValue().equalsIgnoreCase(cellData))
{
break;
}
}
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return testRowNo;
}

Can't copy a Worksheet that contains a Chart using EPPLUS

I'm trying to copy a worksheet that contains a chart, but when I try to do it, my code fires a "package relationship with specified id does not exist for the source part" exception, what are possible reasons for this? *If I remove the chart from the template, everything works fine.
Here's my code:
public void GenerateFromTemplate(DirectoryInfo outputPath, FileInfo templateFile,
string newFileName, List<Dictionary<string, string>> cellDataList)
{
try
{
using (ExcelPackage p = new ExcelPackage(templateFile, true))
{
bool first = true;
foreach (Dictionary<string, string> cellData in cellDataList) {
Logger.LogInfo("Adding new Sheet...");
ExcelWorksheet currentWorkSheet;
if (first)
{
currentWorkSheet = p.Workbook.Worksheets[1];
first = false;
}
else {
currentWorkSheet = p.Workbook.Worksheets.Copy("Ticker", "Ticker" + p.Workbook.Worksheets.Count);
}
foreach (KeyValuePair<string, string> cell in cellData)
{
Logger.LogInfo(cell.Key + "cell value set to" + cell.Value);
currentWorkSheet.Cells[cell.Key].Value = cell.Value;
}
}
Byte[] bin = p.GetAsByteArray();
string file = outputPath + newFileName;
Logger.LogInfo("Writing Excel File to " + file);
File.WriteAllBytes(file, bin);
Logger.LogInfo("Writing Done");
}
}
catch (Exception ex)
{
Logger.LogError(ex);
}
}
Regards!

Resources