Getting null at workbook - java

I am beginner in selenium webdriver, I have created a main class in these I have created an object of writable class and in these I get the "testSuitName" and then it goes to the writable class.
In writable class I have created an constructor and pass the string, in these I get the value.
After that when I try to get the workbook it displayed the null but the way I have given an path is correct according to windows OS. Also, in "testSuitePath" I get my workbook.
Below are the snapshot which I have taken at the time of debug:
I am not able to get the problem that, where I am going wrong?
Can any one please help to resolving it.
Below are constructor where this line has written:
public WritableData(String testSuitePath, String OBJECT_REPOSITORY_PATH) throws RowsExceededException, WriteException
{
// TODO Auto-generated constructor stub
try {
Workbook wbook = Workbook.getWorkbook(new File(testSuitePath));
WritableWorkbook wwbCopy= Workbook.createWorkbook(new File(testSuitePath),wbook);
System.out.println("writable workbookC-->" +wwbCopy);
WritableSheet shSheet=wwbCopy.getSheet("Login");
System.out.println("writable sheetC-->" +shSheet);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception message" + e.getMessage()); e.printStackTrace(); }
}

At that point you have paused BEFORE executing the Workbook.getWorkbook(...) method, so the value is still null.
If you step one more line you should see a value there.

Related

Can static content on spring-boot-web application be dynamic (refreshed)?

I am still searching around this subject, but I cannot find a simple solution, and I don't sure it doesn't exist.
Part 1
I have a service on my application that's generating an excel doc, by the dynamic DB data.
public static void
notiSubscribersToExcel(List<NotificationsSubscriber>
data) {
//generating the file dynamically from DB's data
String prefix = "./src/main/resources/static";
String directoryName = prefix + "/documents/";
String fileName = directoryName + "subscribers_list.xlsx";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
try (OutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Part 2
I want to access it from the browser, so when I call it will get downloaded.
I know that for the static content, all I need to do is to call to the file, from the browser like that:
http://localhost:8080/documents/myfile.xlsx
After I would be able to do it, all I need is to create link to this url from my client app.
The problem -
Currently if I call to the file as above, it will download only the file which have been there in the compiling stage, but if I am generating a new files after the app is running the content won't be available.
It seems that the content is (as it's called) "static" and cannot be changed after startup.
So my question is
is there is a way to define a folder on the app structure that will be dynamic? I just want to access the new generated file.
BTW I found this answer and others which doing configuration methods, or web services, but I don't want all this. And I have tried some of them, but the result is the same.
FYI I don't bundle my client app with the server app, I run them from different hosts
The problem is to download the file with the dynamic content from a Spring app.
This can be solved with Spring BOOT. Here is the solution as shown in this illustration - when i click Download report, my app generates a dynamic Excel report and its downloaded to the browser:
From a JS, make a get request to a Spring Controller:
function DownloadReport(e){
//Post the values to the controller
window.location="../report" ;
}
Here is the Spring Controller GET Method with /report:
#RequestMapping(value = ["/report"], method = [RequestMethod.GET])
#ResponseBody
fun report(request: HttpServletRequest, response: HttpServletResponse) {
// Call exportExcel to generate an EXCEL doc with data using jxl.Workbook
val excelData = excel.exportExcel(myList)
try {
// Download the report.
val reportName = "ExcelReport.xls"
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-disposition", "attachment; filename=$reportName")
org.apache.commons.io.IOUtils.copy(excelData, response.outputStream)
response.flushBuffer()
} catch (e: Exception) {
e.printStackTrace()
}
}
This code is implemented in Kotlin - but you can implement it as easily in Java too.

how to check if output folder is created in java?

I am coming to an issue where I am trying to check if output folder is there and if not create one in my code below. So, I tried doing that way as shown in my code but I dont know if its the proper a way of doing it? can you please advise. thanks for the help.
here is my code:
String outputFolder2 = Printer.getOutputFolder();
File outFileTwo = new File(outputFolder2);
if (!outFileTwo.exists()) {
if (!outFileTwo.mkdir()) {
System.out.println("Failed to make directory for: " + outputFolder2);
}
}
To check if the directory exists:
Files.isDirectory(Paths.get("/the/path"))
To create dir if not exists:
Files.createDirectories(Paths.get("/the/path"))
Simply use
dirPathFileObj.mkdir();
From java.io.File;
If the method detects that no such directory exists, it will automatically create one. Otherwise, it will simply do nothing in terms of File creation.
It's recommended to use the nio package for new code that interacts with files -- it's faster, and easier to code for. Here's how I would write that code, in the form of a junit test that I ran to verify it:
#Test
public void testSomething() {
Path dirPath = Paths.get("C:/I/do/not/exist");
Path filePath = dirPath.resolve("newFile.txt");
try {
assertFalse(Files.exists(dirPath));
dirPath = createDirectories(dirPath);
filePath = Files.createFile(filePath);
assertTrue(Files.exists(filePath));
} catch (IOException iox) {
iox.printStackTrace();
} finally {
try {
Files.deleteIfExists(filePath);
Files.deleteIfExists(dirPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This will create C:\I\do\not\exist\newFile.txt, then delete C:\I\do\not\exist, (leaving C:\I\do\not\). For production code, you'd want to remove the asserts and fill in those catch clauses

How to take screenshot of failed test in selenium webdriver using ReportNG

If anyone know how to take screenshot of failed test/methods in selenium webdriver using reportNG then please help.
If you provide code then its helpfull or provide some ideas to solve this problem.
Thanks in advance.
Yes, It is possible.
WebDriver firfoxDriver = new FirefoxDriver();
firfoxDriver.get("https://stackoverflow.com/");
File file = ((TakesScreenshot)firfoxDriver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(file, new File("E:\\Data\\ss.png"));
Or You can use this:
#AfterMethod(alwaysRun=true)
public void catchExceptions(ITestResult result){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
String methodName = result.getName();
if(!result.isSuccess()){
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File((String) PathConverter.convert("failure_screenshots/"+methodName+"_"+formater.format(calendar.getTime())+".png")));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Well It's depend on your framework that where the control is going after failing the method.
Suppose in your case it is going in catch exception block then copy that code in catch block.
File file = ((TakesScreenshot)firfoxDriver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File("YOUR PATH"+Filename+.JPG));
You can use Itestlistener in testng to take screenshot. testng has an in built function by which you can take screenshot when it fails.
Just create a seperate listerner class and paste this code:
public class listeners implements ITestListener{
//This "Base " is the main class where you can pass the result of test case and write the //code for screenshot
//I cam creating an object so I can access the method that I created for screenshot in this base class.
//I am also getting the result name so I can identify which test case it got failed
Base b = new Base();
public void onTestFailure(ITestResult result) {
try {
//Getting the result name by result.getName() method
b.getScreenshot( result.getName());
System.out.println("The Failed test is=="+result.getName());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I created this getScreenshot method in the base class and passing the result name
public class Base {
public WebDriver InitializeDr() throws IOException {
//Creating the method to take screenshot in the Base class
public void getScreenshot(String result) throws IOException
{
File dest=new File("D:\\Work\\KT\\Scr Shot\\"+result+"test.png");
File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, dest);
}
}
}

Damaged file handling

I would like to know if anyone has any advice on handling damaged files with Apache POI
I am trying to open a file and am receiving this message:
Exception in thread "main" org.apache.poi.hssf.record.RecordInputStream$LeftoverDataException: Initialisation of record 0x1C left 2 bytes remaining still to be read.
at org.apache.poi.hssf.record.RecordInputStream.hasNextRecord(RecordInputStream.java:156)
at org.apache.poi.hssf.record.RecordFactoryInputStream.nextRecord(RecordFactoryInputStream.java:231)
at org.apache.poi.hssf.record.RecordFactory.createRecords(RecordFactory.java:480)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:301)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:95)
at ExcelImporter.EditFileImportDialog.main(EditFileImportDialog.java:409)
Here is an SSCCE
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class EditFileImportDialog {
/* Omitted irrelevent code */
public static void main(String[] args) {
File file = new File("Z:\\Path\\To\\File_causing_the_trouble.xls");
try {
Workbook wb = WorkbookFactory.create(file); // Line 409 for ref to the exception stack trace
System.out.println(wb);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This happens with this file only, and the exception is not thrown if I open the file in excel and save it, then try to open it with POI. Any suggestion as to how I could handle this?
EDIT:
As a note, my issue may be related to this question, but upgrading POI did not fix my issue and there are dissimilarities with the described file. I have searched around for similar answers but perhaps if someone knows what's wrong with the excel file itself, I can write something to patch the file.
EDIT 2
The file creation is not in my control. Excel fixes the file itself just upon opening and re-saving it. My question though is whether anyone can think of a way to adjust/augment POI to handle this damaged file in the same way that excel is able to fix the issue.
EDIT 3
In response to several comments/answers:
My end goal would be to not use excel at all.
File is sent in.
Program runs.
Handles the error.
Processes data.
You could try using HSSFWorkbook to open .xls files.
You could use the following code to check how POI respond determining xls format.
private boolean isExcel(InputStream i) throws IOException {
return (POIFSFileSystem.hasPOIFSHeader(i) || POIXMLDocument.hasOOXMLHeader(i));
}
I would use :
InputStream input = new FileInputStream(fileName);
Instead of :
File file = new File("Z:\\Path\\To\\File_causing_the_trouble.xls");
Did you check what is wrong with the cell 0x1C in your file ?
The best option would be to create a new file and make it a point to remember that you close the file before executing the program. That would be the simplest solution.
Exception in thread main is not a coding problem. You should replace wrong cell references in Excel-Workbook!
Exception in thread "main" org.apache.poi.hssf.record.RecordInputStream$LeftoverDataException:
Initialisation of record 0x23 left 12 bytes remaining still to be read.
This Exception is thrown when i try to open an Excel-Workbook with POI HSSF, that contains a DDE Cell Reference. I have this problem with a cell reference type of 'Excel.Type.12' e.g.:
=Excel.Sheet.12|'\servername\pathname\Workbook.xlsx'!'!Sheetname!Z23S22'
Workaround: Replace the reference with a reference of type 'Sheet' e.g.:
='Drive:\pathname[Workbook.xlsx]Sheetname'!$V$23
Save your Workbook and try it again.
Try creating an XSSFWorkbook instead from a FileInputStream.
With changes your sample would look like:
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class EditFileImportDialog {
/* Omitted irrelevent code */
public static void main(String[] args) {
String file = "Z:\\Path\\To\\File_causing_the_trouble.xls";
try {
InputStream databaseFile = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(databaseFile);
System.out.println(wb);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You might have already checked, but if not, see https://bz.apache.org/bugzilla/show_bug.cgi?id=47251 if helps. It has similar problem(s) and you may find answer on how to handle it.

Saving a .jpg to byte[] android

This shouldn't be that hard, but I cannot figure this out. I need to save an image, on my end only, and build it dynamically so all my users will view these images. The tutorials on Parse.com are very helpful, but not in the case of images. I need detailed explanations or helpful links. Thanks for looking.
This is all I have so far as far as saving an image. I am properly getting the file in my Data Browser, but if I try to view it, it only shows my string "beatdown.jpg" not the actual jpg.
....
private void saveImage() {
// TODO Auto-generated method stub
InputStream header = new FileInputStream("beatdown.jpg");
byte[] head = IOUtils.toByteArray(header);
ParseFile file = new ParseFile(head);
try{
file.save();
} catch (ParseException e) {
e.printStackTrace();
}
ParseObject displayImage = new ParseObject("displayImage");
displayImage.put("header", file);
try{
displayImage.save();
} catch (ParseException e1){
e1.printStackTrace();
}
}
I understand I am trying to get the string of "beatdown.jpg" to bytes in the code above, and it is not handling it as a .jpg. But I don't know how to make it a .jpg.
EDIT: I added commons-io. But when I run the code (see the above updated code), it won't register on anything on parse.com. I am getting this in my logcat;
Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection#40cf2498 that was originally bound here
The key elements are:
File f = new File("pathToFile");
FileInputStream fis = new FileInputStream(f);
byte[] bytes = new byte[f.length()];
fis.read(bytes);
Of course there's exception handling and the like to do, but this should be enough to give you the general idea.

Categories