How to call an method which resides in different project? - java

I have Two separate projects in eclipse work space is same but different two projects.
Suppose two project A & B, i have call an class suppose Test.java having main method and one simple display method from project b and i need to call from project B.In main method i am calling display method of Test.java class.
And suppose i have another class Execute.java in project A so i need call class from Project B in to Project A in Execute.java class, how do i do that?
Any suggestion will be appreciated
File : TestNGCreator.java
package testDrivers;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import projlib.Globals;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestNGCreator
{
public void runTestNGTest() throws IOException
{
//Create an instance on TestNG
TestNG myTestNG = new TestNG();
//Create an instance of XML Suite and assign a name for it.
XmlSuite mySuite = new XmlSuite();
mySuite.setName(Globals.SUITE_NAME);
//Create a list of XmlTests and add the Xmltest you created earlier to it.
List<XmlTest> myTests = new ArrayList<XmlTest>();
XSSFSheet excelWSheet = null;
XSSFWorkbook excelWBook = null;
XSSFCell cell = null;
XSSFRow row = null;
Double dblCellVal;
String strCellVal = null;
Boolean blnCellVal;
FileInputStream excelFile = new FileInputStream(Globals.CONFIG_FILE_DIR);
excelWBook = new XSSFWorkbook(excelFile);
//excelWSheet = excelWBook.getSheet(Globals.CONFIG_SHEET_NAME);
Iterator <Row> rowIterator = excelWSheet.iterator();
//Iterator <Cell> cellIterator = row.cellIterator();
String testName = null;
int colCount;
if (rowIterator.hasNext())
{
row = (XSSFRow) rowIterator.next();
colCount = row.getPhysicalNumberOfCells();
}
while (rowIterator.hasNext())
{
row = (XSSFRow) rowIterator.next();
Iterator <Cell> cellIterator = row.cellIterator();
int curCell = 0;
while (cellIterator.hasNext())
{
cell = (XSSFCell) cellIterator.next();
curCell++;
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
dblCellVal = cell.getNumericCellValue();
strCellVal = dblCellVal.toString();
break;
case Cell.CELL_TYPE_STRING:
strCellVal = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
blnCellVal = cell.getBooleanCellValue();
strCellVal = blnCellVal.toString();
break;
}
//If it is first cell then store the Test Name
if (cell.getColumnIndex()== 0)
{
testName = strCellVal;
}
if (curCell == 5) {
if (strCellVal.equals("1.0")) {
//Adding to suite
//Create an instance of XmlTest and assign a name for it.
XmlTest myTest = new XmlTest(mySuite);
myTest.setName(testName);
//Add any parameters that you want to set to the Test.
Map<String, String> testngParams = new HashMap<String,String> ();
testngParams.put("testId", testName);
myTest.setParameters(testngParams);
//Create a list which can contain the classes that you want to run.
List<XmlClass> myClasses = new ArrayList<XmlClass> ();
myClasses.add(new XmlClass("TestDriver"));
//Assign that to the XmlTest Object created earlier.
myTest.setXmlClasses(myClasses);
//Adding the test to test list created earlier
myTests.add(myTest);
break;
}
}
}
}
excelWBook.close();
//add the list of tests to your Suite.
mySuite.setTests(myTests);
//Add the suite to the list of suites.
List<XmlSuite> mySuites = new ArrayList<XmlSuite>();
mySuites.add(mySuite);
//Set the list of Suites to the testNG object you created earlier.
myTestNG.setXmlSuites(mySuites);
File file = new File(Globals.TESTNG_FILE_NAME);
System.out.println("File is: " + file);
FileWriter writer = new FileWriter(file);
writer.write(mySuite.toXml());
writer.close();
//invoke run() - this will run your class.
//myTestNG.run();
}
public static void main(String args[]) throws IOException
{
TestNGCreator testDriver = new TestNGCreator();
testDriver.runTestNGTest();
}
}
So i need to call main method.

You can do it by following below steps.
Build the first project and create jar
Right click on second project ->Build Path->Configure Build Path->Libraries->Add External Jars
Use the class from first project
Or
If you want to send/receive data from any web service, Please expose your method as REST API such a way that your web service will accept it.
You can use Apache HttpComponents to expose your method to web service, Please find the below sample code.
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config)
.disableContentCompression().setSSLSocketFactory(sslsf).build();
HttpPost postRequest = new HttpPost(url);
client.execute(postRequest);

If you are not using Maven or Gradle you can perform the following steps in order to include the project:
Properties -> Build Path -> Projects -> Add , add the project you want.

Related

Poi api XSSFWorkbook sheet cast EXCEPTION

package apsel5;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class A {
public static void main(String[] args) throws Exception{
FileInputStream f = new FileInputStream("D:\\LeadSuite.xlsx");
XSSFWorkbook wbks = new XSSFWorkbook(f);
Sheet s = (Sheet) wbks.getSheet("TestSteps");
Iterator itr = s.iterator();
while(itr.hasNext()){
Row rowitr = (Row)itr.next();
Iterator cellitr = rowitr.cellIterator();
while(cellitr.hasNext()){
Cell cell1= (Cell)cellitr.next();
switch(cell1.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell1.getBooleanCellValue());
break;
}
}
}
}
}
I get an exception after running the above code:
Exception in thread "main" java.lang.ClassCastException:
org.apache.poi.xssf.usermodel.XSSFSheet cannot be cast to
org.apache.poi.sl.usermodel.Sheet
You imported the wrong version of Sheet. Simply turn
import org.apache.poi.sl.usermodel.Sheet;
into
import org.apache.poi.ss.usermodel.Sheet;
that represents the Excel worksheet, and your code should work. No cast should be needed for Sheet, Row and Cell.
If you look at the XSSFSheet class definition, you can see that it implements org.apache.poi.ss.usermodel.Sheet. On the other hand, the org.apache.poi.sl.usermodel.Sheet interface is related with PowerPoint; in fact, according to the Javadoc, it's the
Common parent interface for Slides, Notes and Masters
So .ss. = Excel (XSSF), and .sl. = PowerPoint (XSLF). The fact that these two interfaces have the same name may actually be misleading.

Apache poi XLSX to XLS

I'm working with apache poi, i read some xlsx file, process it and then export them in xlsx format as well. But now i have the requirement of the export format to be XLS (this is to support old devices). Is there an easy way of convert the code-generated xlsx file to xls?
The all process is made with XSSF implementation.
Thanks in advance.
I agree with centic answer, but I want to add a few lines of code.
You said that you are using XSSF implementation.
So, for the workbook that you are saving do the following changes:
change XSSFWorkbook x = new XSSFWorkbook();
to Workbook x = new HSSFWorkbook();
where Workbook is import from org.apache.poi.ss.usermodel.Workbook;
Similarly
Change XSSFRow instantiation from
XSSFRow r = newXSSF();
to Row r = new HSSFRow();
and import the Row from org.apache.poi.ss.usermodel.Row;
Like the same way, change Cell instantiation to ss.usermodel package.
And finally save your HSSF workbook with .xls extension.
You will need to switch to the "ss" implementation which allows to transparently work with both HSSF (=XLS) and XSSF (=XSLX), see http://poi.apache.org/spreadsheet/converting.html for some details of the original HSSF -> SS switch which should also shed some light on supporting it for the other way around.
Then only the two constructors for HSSFWorkbook/XSSFWorkbook are needed to decide which of the two formats you want to produce.
I have faced same scenario and implemented below code for Coverting XLSX to XLS using Java
Below code will read it from directory and process using apache camel (polling file from path) and apace poi
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Optional;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class ExcelFileProcessor implements Processor {
final Logger logger = LoggerFactory.getLogger(getClass());
#Value("${test.dir.in}")
private String inDir;
#Override
public void process(Exchange exchange) throws Exception {
logger.info("Entry-ExcelFileProcessor- Process method");
long start = System.currentTimeMillis();
String fileNameWithExtn=(String) exchange.getIn().getHeader("camelFileName");
Long originalFileSize = (Long) exchange.getIn().getHeader("CamelFileLength");
String fileNameWithOutExtn = fileNameWithOutExtn(fileNameWithExtn);
logger.info("fileNameWithExtn:{}" ,fileNameWithExtn);
logger.info("fileNameWithOutExtn:{}" ,fileNameWithOutExtn);
logger.info("originalFileSize:{}" ,originalFileSize);
try(InputStream in = exchange.getIn().getBody(InputStream.class);
XSSFWorkbook wbIn = new XSSFWorkbook(in);
Workbook wbOut = new HSSFWorkbook();) {
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(0);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK: break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
cellOut.setCellComment(cellIn.getCellComment());
}
}
}
File outF = new File(inDir+fileNameWithOutExtn+".xls");
try(OutputStream out = new BufferedOutputStream(new FileOutputStream(outF));){
wbOut.write(out);
}
}catch (Exception e) {
logger.info("Error during Excel file process:{}",e.getMessage());
}
long end = System.currentTimeMillis();
logger.info("Total time processed for file in - {} ms", (end - start));
logger.info("Exit-FileProcessor- Process method");
}
public String fileNameWithOutExtn(String fileName) {
return Optional.of(fileName.lastIndexOf('.')).filter(i-> i >= 0)
.map(i-> fileName.substring(0, i)).orElse(fileName);
}
}
If you are not using camel and want to get inputstream from file use below snippet
String inpFn = "input.xlsx";
String outFn = "output.xls";
InputStream in = new BufferedInputStream(new FileInputStream(inpFn));
try {
Workbook wbIn = new XSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new HSSFWorkbook();
//continue with above code

Selenium Webdrier using Java: Exception while reading from Excel

I am using SeleniumWebDriver using Java to automation one of the portal applications. As part of this, I want to read username and password from Excel and written below code. But seeing Exception in thread "main" java.lang.NoClassDefFoundError: org/openxmlformats/schemas/drawingml/x2006/main/ThemeDocument Below is the code
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.Random;
public class BankingFaceLift {
static WebDriver driver = null;
public static void main(String[]args){
driver = new FirefoxDriver();
driver.get("https://obsit.enbduat.com/obweb/common/login.jsf?faces-redirect=true");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try
{
File file = new File("TestData.xlsx");
FileInputStream iFile = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(iFile);
XSSFSheet sheet = wb.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum();
System.out.println("the no of rows are : " + rowCount);
for (int row=1; row<=rowCount; row++)
{
String Username = sheet.getRow(row).getCell(0).getStringCellValue();
String Password = sheet.getRow(row).getCell(1).getStringCellValue();
driver.findElement(By.id("username")).sendKeys(Username);
driver.findElement(By.id("j_idt49")).sendKeys(Password);
driver.findElement(By.id("submit")).click();
I have imported poi-xxx.jar and poi-ooxml.jar1.
Kindly advice Thanks!
You need to import poi-ooxml-schemas jar as well. You can download the jar from here

Error: Could not find or load main class excel2JSON.excel

package excel2JSON;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.json.JSONArray;
import org.json.JSONObject;
public class excel {
public static void main(String[] args)
{
String str = ExcelToJSON(new File ("C:\\workbook.xlsx"));
System.out.println("JSON = " + str);
}
private static String ExcelToJSON(File file_open)
{
JSONObject json = null;
try {
FileInputStream input = new FileInputStream(file_open);
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = workbook.getSheetAt(0);
json = new JSONObject();
JSONArray rows = new JSONArray();
for (Iterator<Row> rows_it = sheet.rowIterator(); rows_it.hasNext();) {
Row row = rows_it.next();
JSONObject jason_row = new JSONObject();
JSONArray cells = new JSONArray();
for (Iterator<Cell> cells_it = row.cellIterator(); cells_it.hasNext();) {
Cell cell = cells_it.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
double numeric=cell.getNumericCellValue();
cells.put(String.valueOf(numeric));
break;
case Cell.CELL_TYPE_STRING:
cells.put(cell.getStringCellValue());
break;
}
}
jason_row.put("cell", cells);
rows.put(jason_row);
}
// Create the JSON.
json.put("rows", rows);
} catch (Exception e) {
e.printStackTrace();
}
// Get the JSON text.
return json.toString();
}
}
getting this error:
Error: Could not find or load main class excel2JSON.excel
I don't know why i am getting this error. I am new to Java and i need help to fix this issue. I am trying to convert Excel file to JSON document. This is the code i wrote for that but i am getting issue when i run the program in Eclipse.
The most common cause of this error in eclipse is when you have moved the class around, Eclipse will be trying to use an outdated run configuration which will not work.
Click the down arrow next to the green play button in Eclipse, select Run Configurations.
Delete the references to this class, then close that window, select the excel class. Click the down arrow next to the play button again and select run as Java Application.

Argument type mismatch in JUnit

I'm fairly new to Selenium webdriver and Java, previously I used Selenium IDE. I'm trying to read testdata from an Excel sheet. Which is then written to Eclipse console, which works, and should be used to execute the actual test, which doesn't work. The actual test is not executed because I get an error argument type mismatch. The code looks like this:
package Test_Excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
#RunWith(Parameterized.class)
public class TestWithExcelData {
// Our two parameters
private final int input;
private final int resultExpected;
// Constructor
public TestWithExcelData(int input, int result) {
this.input = input;
this.resultExpected = result;
}
#Parameters
public static Iterable<Object []> data() throws BiffException, IOException
{
String FilePath = "C://Selenium//workspace//testproject//src//testdata//TestData.xls";
FileInputStream fs = new FileInputStream(FilePath);
Object[][] object = new Object[6][2];
Workbook wb = Workbook.getWorkbook(fs);
//locate the excel file in the local machine
Sheet sheet = wb.getSheet("IOResult");
int i=1; //avoid header row
while(!(sheet.getCell(0, i).getContents().equals("end"))) //read data till it reaches the cell whose text is ‘end’
{
object[i-1][0]=sheet.getCell(0, i).getContents();
object[i-1][1]=sheet.getCell(1, i).getContents();
System.out.print(sheet.getCell(0, i).getContents() + "\t");
System.out.print(sheet.getCell(1, i).getContents() + "\t");
System.out.println();
i++;
}
return Arrays.asList(object);
}
#Test
public void testSquareOff(){
Assert.assertEquals(resultExpected, MathUtils.square(input));
}
}
Is there somebody who can point me in the right direction?
Thanks in advance
The method sheet.getCell(column, row).getContents() is returning a String, but your constructor expects int.
You may modify the two lines in the data() method:
object[i-1][0] = Integer.valueOf(sheet.getCell(0, i).getContents());
object[i-1][1] = Integer.valueOf(sheet.getCell(1, i).getContents());

Categories