file is not getting passed as an input - java

I'm getting NullPointerException upon passing a .xlsb file to a method. It seems that file is not getting selected but the file exists in that folder. Please advise
public class readxlsb {
public static void main(String[] args) throws Exception {
try {
String fileName1 ="C:\\abc\\TULDUBINV_EX_10768148_1.xlsb";
com.smartxls.WorkBook wb = new com.smartxls.WorkBook();
System.out.println(wb);
wb.readXLSB(fileName1);
System.out.println(wb);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The constructor of the API have the following methods:
public void readXLSB(String filename) throws Exception {
this.a.q(filename);
}
public void readXLSB(InputStream in) throws Exception {
this.a.d(in);
}
public void readXLSB(InputStream in, String pass) throws Exception {
this.a.a(in, pass);
}

Why not to use jxl.Workbook, it's much easier and comprehensive. I have worked with jxl and highly rely on it. Use like-Workbook workBook = Workbook.getWorkbook(new File("C:\\abc\\TULDUBINV_EX_10768148_1.xlsb"));
Sheet sheet = workBook.getSheet(0);

Related

The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (int)

import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class ExcelUtils {
private XSSFSheet ExcelWSheet;
private XSSFWorkbook ExcelWBook;
//Constructor to connect to the Excel with sheetname and Path
public Excelutils(String Path, String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
//This method is to set the rowcount of the excel.
public int excel_get_rows() throws Exception {
try {
return ExcelWSheet.getPhysicalNumberOfRows();
} catch (Exception e) {
throw (e);
}
}
//This method to get the data and get the value as number.
public double getCellDataasnumber(int RowNum, int ColNum) throws Exception {
try {
double CellData =
ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue();
System.out.println("The value of CellData " + CellData);
return CellData;
} catch (Exception e) {
return 000.00;
}
}
}
And in Main function i am calling
import Utils.ExcelUtils;
public class getInt extends OpenDriver {
#Test
public void getInt() throws Exception {
ExcelUtils TestData = new ExcelUtils("D:\\Selenium Automation\\TestData\\user.xlsx",
"User");
driver = LaunchBrowser();
driver.findElement(By.xpath("//input[#name='capacity']")).sendKeys(TestData.getCellDataasnumber(1, 3));
}
}
here i have created a excelutils and defined all my functions overthere
in main i have used excelUtils and passing value
I am getting error "The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (int)"
TestData.getCellDataasnumber(1, 3) will get number 25 from excel sheet.
tried, error not fixing
How can i fix this error
Just as the error says, you need a CharSequence as the parameter of the sendKeys method, instead of an int:
The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (int)
This means that you have to convert the int to a CharSequence. In practice, the simplest way to get a CharSequence is to create a String, so the solution is to convert the int to a String. You can achieve this in the following way:
String.valueOf(TestData.getCellDataasnumber(1, 3))

Why my fileOutputstream ignores append "true" flag?

I m trying to wrap FileinputStream and change close method of Parent in my wrapper class "Amigo". As u can see in code, i use default FileInputStream object to write some data in end of file in case of using .close() method. But, despite that i use "append" to "true" flag in the fileOutputStream field, my programm is still overwrites data in file. Why is this happens?
public class AmigoOutputStream extends FileOutputStream{
public static String fileName = "C:\\Users\\Егор\\IdeaProjects\\JavaRushTasks\\2.JavaCore\\src\\com\\javarush\\task\\task18\\task1813\\r.txt";
private FileOutputStream fileOutputStream = new FileOutputStream(fileName,true);
private static final String JAVA_RUSH = "JavaRush © All rights reserved.";
public AmigoOutputStream(FileOutputStream name) throws FileNotFoundException {
super(String.valueOf(name),true);
}
public static void main(String[] args) throws IOException {
new AmigoOutputStream(new FileOutputStream(fileName)).close();
}
#Override
public void close() throws IOException {
fileOutputStream.flush();
fileOutputStream.write(JAVA_RUSH.getBytes());
fileOutputStream.close();
}
}
The line with new FileOutputStream(fileName) inside main will wipe the file and that runs before new FileOutputStream(fileName,true) which is inside the class.
You are also creating a new file which has an unusual name - set to String.valueOf(name). You may want something like this which allows caller to specify the file and means AmigoOutputStream always sends extra bytes to some file:
public class AmigoOutputStream extends FileOutputStream{
private static final String JAVA_RUSH = "JavaRush © All rights reserved.";
public AmigoOutputStream(String name) throws FileNotFoundException {
super(name,true);
}
public static void main(String[] args) throws IOException {
try(OutputStream os = new AmigoOutputStream("r.txt")) {
}
}
#Override
public void close() throws IOException {
write(JAVA_RUSH.getBytes());
super.close();
}
}

Datadriven not working using Testng data provider

I am trying to read data from excel using apache poi with testng data provider but testng is skipping my test method.
Below is the error am getting
SKIPPED: VerifyLoanDetails
java.lang.RuntimeException: java.lang.NullPointerException
Caused by: java.lang.NullPointerException at com.seleniumhybrid.utils.ExcelUtil.getTestdata(ExcelUtil.java:62) at com.seleniumdata.zmartano.LoanDetails.getdata(LoanDetails.java:50)
Below is my class to read data from excel
public class ExcelUtil{
static Workbook book;
static Sheet sheet;
public static String Testdata_sheet = Constants.path_TestData;
public static Object [][] getTestdata(String sheetname) {
FileInputStream file = null;
try{
file = new FileInputStream(Testdata_sheet);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
}
catch(InvalidFormatException e ) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetname);
Object [][]data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for (int i=0;i<sheet.getLastRowNum();i++) {
for(int k=0;k<sheet.getRow(0).getLastCellNum();k++) {
data[i][k]= sheet.getRow(i+1).getCell(k).toString();
}
}
return data;
}
}
below is my test class to acess the data
public class LoanDetails extends Configreader{
WebDriver driver;
#BeforeTest
public void beforetest() throws Exception {
driver = Browser.GetBrowser();
}
#Test(dataProvider = "getdata")
public void VerifyLoanDetails(String username) throws Exception {
driver.findElement(By.xpath(pro.getProperty("account_xpath"))).click();
driver.findElement(By.xpath(pro.getProperty("username_id"))).sendKeys(username);
}
#DataProvider
public Object[][] getdata(){
Object data [][] = ExcelUtil.getTestdata("credentials");
return data;
}
}

what are advantage of using ResourceBundle for reading properties file?

public class Query {
private final String BUNDLE_NAME="Query";
private final ResourceBundle RB=ResourceBundle.getBundle(BUNDLE_NAME);
public Query(){
}
public String getValue(String key) throws FileNotFoundException{
return RB.getString(key);
}
}
public class Query_properties {
public static Properties pos=new Properties();
public static String sqlData(String q) throws IOException {
try{
FileInputStream fis=new FileInputStream(System.getProperty("user.dir")+"/Query.properties");
pos.load(fis);
pos.getProperty(q);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return pos.getProperty(q);
}
Here i use two kind of code which read property file but i am not sure which one fine my selenium automation

Creating a new MS Access file in Java using Jackcess

I have referred selected answer to this question: Java: Create MSAccess Database File (.mdb 0r .accdb) using Java.
I have MS Office 2010 in my machine. I am trying to create access database file (*.mdb / *.accdb). But, still the file is not getting created itself throwing following exception:
Exception in thread "main" java.io.FileNotFoundException: given file does not exist: C:\Users\473886\Desktop\employeedb1.mdb
at com.healthmarketscience.jackcess.impl.DatabaseImpl.open(DatabaseImpl.java:360)
at com.healthmarketscience.jackcess.DatabaseBuilder.open(DatabaseBuilder.java:170)
at mdb.MDBWriter.createDatabase(MDBWriter.java:93)
at mdb.MDBWriter.startDatabaseProcess(MDBWriter.java:107)
at mdb.MDBWriter.main(MDBWriter.java:120)
I have used the same code available in the answer with one modification that I have used file dialog that will ask me where I want to save the database file:
public class MDBWriter {
public static String saveFile(Frame f, String title, String defDir, String fileType) {
FileDialog fd = new FileDialog(f, title, FileDialog.SAVE);
fd.setFile(fileType);
fd.setDirectory(defDir);
fd.setLocation(50, 50);
fd.show();
return (fd.getDirectory() + "\\" + fd.getFile());
}
private static Database createDatabase(String databaseName) throws IOException {
// return Database.create(new File(databaseName));
File file = new File(databaseName);
return new DatabaseBuilder(file)
.setFileFormat(Database.FileFormat.V2010)
.open();
}
private static TableBuilder createTable(String tableName) {
return new TableBuilder(tableName);
}
public static void addColumn(Database database, TableBuilder tableName, String columnName, Types sqlType) throws SQLException, IOException {
tableName.addColumn(new ColumnBuilder(columnName).setSQLType(Types.INTEGER).toColumn()).toTable(database);
}
public static void startDatabaseProcess() throws IOException, SQLException {
String fileName = saveFile(new Frame(), "Save...", ".\\", "*.mdb");
String databaseName = "D:\\employeedb1.accdb"; // Creating an MS Access database
Database database = createDatabase(fileName);
String tableName = "Employee"; // Creating table
Table table = createTable(tableName)
.addColumn(new ColumnBuilder("Emp_Id").setSQLType(Types.INTEGER).toColumn())
.addColumn(new ColumnBuilder("Emp_Name").setSQLType(Types.VARCHAR).toColumn())
.addColumn(new ColumnBuilder("Emp_Employer").setSQLType(Types.VARCHAR).toColumn())
.toTable(database);
table.addRow(122875, "Sarath Kumar Sivan","Infosys Limited.");//Inserting values into the table
}
public static void main(String[] args) throws IOException, SQLException {
startDatabaseProcess();
}
}
Please suggest some solution.
If you want to create a new database, you need to call DatabaseBuilder.create(), not open() (which opens an existing database).
No way to create [an Access database] from [Java] code !
Nonsense. The following works on any platform with Java and Jackcess...
import com.healthmarketscience.jackcess.*;
import java.io.File;
public class bar {
public static void main(String[] args) {
try {
DatabaseBuilder.create(Database.FileFormat.V2010, new File("/home/gord/jTest.accdb"));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done!");
}
}
..and the following code works in Java on Windows without Jackcess (but requires the Access Database Engine)...
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CreateAccdb {
public static void main(String[] args) {
String databaseName = "C:\\__tmp\\employeedb1.accdb";
String tempScriptName = System.getenv("TEMP") + "\\$$CreateAccdbScript.vbs";
try {
BufferedWriter out = new BufferedWriter(new FileWriter(tempScriptName));
out.write("Set cat = CreateObject(\"ADOX.Catalog\")");
out.newLine();
out.write("cat.Create \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + databaseName + ";\"");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
String cmd = "cscript " + tempScriptName;
try {
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader rdr =
new BufferedReader(new InputStreamReader(p.getErrorStream()));
int errorLines = 0;
String line = rdr.readLine();
while (line != null) {
errorLines++;
System.out.println(line); // display error line(s), if any
line = rdr.readLine();
}
if (errorLines == 0) {
System.out.println("The operation completed successfully.");
}
} catch(Exception e) {
e.printStackTrace();
}
try {
Files.deleteIfExists(Paths.get(tempScriptName));
} catch(Exception e) {
e.printStackTrace();
}
}
}
According to the answer available here. The only solution is to copy an existing empty mdb, connect to this and create tables etc. No way to create a mdb from code !

Categories

Resources