org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save - file-io

I'm facing org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save:an error occurs while saving the package : The part /docProps/app.xml fail to be saved in the stream with marshaller <br/> org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller#7c81475b
Exception when try to write the each test scenario result(PASS or FAIL) into Excel sheet(.xlsx) after the each test scenario execution completion. I write the following two different modules for this purpose.
Please tell me where is the problem and how to resolve it..
//Method for writing results into Report
public void putResultstoReport(String values[])
{
int j=NoofTimesExecuted;
NoofTimesExecuted++;
XSSFRow row = sheet.createRow(j);
for(int i=0;i<values.length;i++)
{
XSSFCell cell = row.createCell(i);
cell.setCellValue(values[i]);
}
try {
System.out.println("Times:"+NoofTimesExecuted);
wb.write(fileOut);
}
//fileOut.flush();
//fileOut.close();
}
catch(Exception e) {
System.out.println("Exception at closing opened Report :"+e);
}
//Method for Creating the Excelt Report
public void createReport()
{
String FileLocation = getProperty("WorkSpace")+"//SCH_Registration//OutPut//TestResults.xlsx";
try {
fileOut = new FileOutputStream(FileLocation);
String sheetName = "TestResults"; //name of sheet
wb = new XSSFWorkbook();
sheet = wb.createSheet(sheetName);
fileOut.flush();
fileOut.close();
}
catch(Exception e)
{
System.out.println("Exception at Create Report file:"+e);
}
}

I had this problem today and fixed it already.
The problem is in putResultstoReport()
You can't wb.write(fileOut); in your cycle.
resolution:
first call putResultstoReport(); then wb.write(fileOut);

I also had this error.
I found my mistake was caused because I was opening the same file / workbook multiple times.
So I would recommend to make sure you are opening just once before attempting to close as well.

This can happen if a timeout occurs. I have code that works for a small dataset and throws this error with huge dataset.

I had the same issue.
When I shortened the output excel filename, it stopped.

I had similar Issue.
Finally I got the reason and that was version for the below jar file was getting overrided.
org.apache.xmlgraphics:batik-dom
Hence, I added below dependency and now it is working fine.
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-dom</artifactId>
<version>1.8</version>
</dependency>
This jar contains dependency for xalan.
To generate the report xalan is required.

I had the same problem user refreshing page and sending the request again before the previous request is completed.
when creating the name use millisecond in name to avoid name conflict with these updates in code of name creation resolved the above issue.
String sheetName="projectName"+System.currentTimeMillis() + ".xlsx"
FileOutputStream fileOut = new FileOutputStream(sheetName);
workbook.write(fileOut);
fileOut.close();

Related

Google Drive Api Error 403 cannotAddParent with service account

Using a service account, Google Drive API and Google SpreadSheet API, I create a spreadsheet that i then move to a specific folder, using the following code :
public async Task<File> SaveNewSpreadsheet(Spreadsheet spreadsheet, File folder)
{
try
{
Spreadsheet savedSpreadsheet = await _sheetService.Spreadsheets.Create(spreadsheet).ExecuteAsync();
string spreadsheetId = GetSpreadsheetId(savedSpreadsheet);
File spreadsheetFile = await GetFileById(spreadsheetId);
File spreadsheetFileMoved = await MoveFileToFolder(spreadsheetFile, folder);
return spreadsheetFileMoved;
}
catch (Exception e)
{
_logger.LogError(e, $"An error has occured during new spreadsheet save to Google drive API");
throw;
}
}
public async Task<File> MoveFileToFolder(File file, File folder)
{
try
{
var updateRequest = _driveService.Files.Update(new File(), file.Id);
updateRequest.AddParents = folder.Id;
if (file.Parents != null)
{
string previousParents = String.Join(",", file.Parents);
updateRequest.RemoveParents = previousParents;
}
file = await updateRequest.ExecuteAsync();
return file;
}
catch (Exception e)
{
_logger.LogError(e, $"An error has occured during file moving to folder.");
throw;
}
}
This used to work fine for a year or so, but since today, the MoveFileToFolder request throw the following exception:
Google.GoogleApiException: Google.Apis.Requests.RequestError
Increasing the number of parents is not allowed [403]
Errors [
Message[Increasing the number of parents is not allowed] Location[ - ] Reason[cannotAddParent] Domain[global]
]
The weird thing is that if I create a new service account and use it instead of the previous one, it works fine again.
I've looked for info on this "cannotAddParent" error but I couldn't find anything.
Any ideas on why this error is thrown ?
I have the same problem and filed in issue in the Google Issue Tracker. This is intended behavior, unfortunately. You are no longer able to place a file in multiple parents as in your example. See the linked documentation for migration.
Beginning Sept. 30, 2020, you will no longer be able to place a file in multiple parent folders; every file must have exactly one parent folder location. Instead, you can use a combination of status checks and a new shortcut implementation to accomplish file-related operations.
https://developers.google.com/drive/api/v2/multi-parenting

Changing screen shot name that is saved in /img folder on QAF framework

I have a requirement where I need to add the time stamp for the screenshot image that is saved in /img folder. When I see AssertionService.java(https://github.com/qmetry/qaf/blob/master/src/com/qmetry/qaf/automation/ui/selenium/AssertionService.java), I See it is adding some random string at the end.
How to remove this random string added and add time stamp? Thanks for the help in advance!
private String captureScreenShot() {
String filename = StringUtil.createRandomString(getTestCaseName()) + ".png";
try {
selenium.captureEntirePageScreenshot(getScreenShotDir() + filename, "");
} catch (Exception e) {
try {
selenium.windowFocus();
} catch (Throwable t) {
logger.error(t);
}
selenium.captureScreenshot(getScreenShotDir() + filename);
}
lastCapturedScreenShot = filename;
logger.info("Captured screen shot: " + lastCapturedScreenShot);
return filename;
}
Are you using selenium 1 or 2 api? Selenium 2 uses following code https://github.com/qmetry/qaf/blob/d58b1d1ca01b2df1a916bcd6d555df4f51a13b12/src/com/qmetry/qaf/automation/core/QAFTestBase.java#L351. Regardless of API, you can't change naming strategy for automatic screenshots. As alternate you may disable auto capturing of screenshot, capture as and when needed and set calling setLastCapturedScreenShot

JavaFX - set programmatically the destination path to print directly a node to pdf file

I want to print a node to a pdf file using "Microsoft Print to PDF" printer. Supposing that the Printer object is already extracted I have the next function which is working perfectly.
public static void printToPDF(Printer printer, Node node) {
PrinterJob job = PrinterJob.createPrinterJob(printer);
if (job != null) {
job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
PageLayout pageLayout = job.getPrinter().createPageLayout(Paper.A4, PageOrientation.PORTRAIT,
Printer.MarginType.HARDWARE_MINIMUM);
boolean printed = job.printPage(pageLayout, node);
if (printed) {
job.endJob();
} else {
System.out.println("Printing failed.");
}
} else {
System.out.println("Could not create a printer job.");
}
}
The only issue that I have here, is that a dialog box is popping up and asking for a destination path to save the pdf. I was struggling to find a solution to set the path programmatically, but with no success. Any suggestions? Thank you in advance.
After some more research I came with an ugly hack. I accessed jobImpl private field from PrinterJob, and I took attributes out of it. Therefore I inserted the destination attribute, and apparently it is working as requested. I know it is not nice, but ... is kind of workable. If you have any nicer suggestion, please do not hesitate to post them.
try {
java.lang.reflect.Field field = job.getClass().getDeclaredField("jobImpl");
field.setAccessible(true);
PrinterJobImpl jobImpl = (PrinterJobImpl) field.get(job);
field.setAccessible(false);
field = jobImpl.getClass().getDeclaredField("printReqAttrSet");
field.setAccessible(true);
PrintRequestAttributeSet printReqAttrSet = (PrintRequestAttributeSet) field.get(jobImpl);
field.setAccessible(false);
printReqAttrSet.add(new Destination(new java.net.URI("file:/C:/deleteMe/wtv.pdf")));
} catch (Exception e) {
System.err.println(e);
}

Jreport JasperRunManager.runReportToPdfStream null pointer exception

i'm trying to get a PDF report using Jasper in my Java web application but i'm facing to an null pointer exception and i'm not able to find which is the error.
here below my code :
private void caricaReport() {
try{
InputStream is = getClass().getResourceAsStream("reports/miooperearte.jasper");
File OutDir = new File(outputDir);
File outDir = new File(outputDir);
outDir.mkdirs();
OutputStream os = new FileOutputStream(new File(outDir, "testReportNadia.pdf"));
HashMap parameterMap = new HashMap();
parameterMap.put("immagini_base_dir", "/Applications/MAMP/htdocs/Dboperearte/app/webroot/images/");
Collection data = leggiOpere();
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(data,false);
JasperRunManager.runReportToPdfStream(is, os, parameterMap, dataSource);
}
catch (Exception e) {
e.printStackTrace();
}
}
variables "is", "os", "parameterMap" and "dataSource" are all filled, exception doesn't show which is the null problem only say null pointer exception...
any idea which can help me to solve or find the problem ?
Thanks
I would guess that the parameterMap doesn't contain an entry for something that the JasperRunManager is expecting - make sure you aren't missing any values from there.

YUI-Compressor: result file is empty

I am using the YUI Compressor library to minify CSS and JavaScript files. I directly use the classes CssCompressor and JavaScriptCompressor.
Unfortunatly some of the resulting files are empty without any warnings or exceptions.
I already tried it with the versions:
yuicompressor-2.4.2.jar
yuicompressor-2.4.6.jar
yuicompressor-2.4.7pre.jar
My used code is:
public static void compress(File file) {
try {
long start = System.currentTimeMillis();
File targetFile = new File("results", file.getName() + ".min");
Writer writer = new FileWriter(targetFile);
if (file.getName().endsWith(".css")) {
CssCompressor cssCompressor = new CssCompressor(new FileReader(file));
cssCompressor.compress(writer, -1);
} else if (file.getName().endsWith(".js")) {
JavaScriptCompressor jsCompressor = new JavaScriptCompressor(new FileReader(file), new MyErrorReporter());
jsCompressor.compress(writer, -1, true, false, false, true);
}
long end = System.currentTimeMillis();
System.out.println("\t compressed " + file.getName() + " within " + (end - start) + " milliseconds");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Files which do not work (are empty afterwards) are e.g.
http://code.google.com/p/open-cooliris/source/browse/trunk/fancy/jquery.fancybox.css?r=2
http://nodejs.org/sh_main.js
I know there are some bugs within the YUICompressor using media but could this be in relation with the empty results?
I had the same problem.
In my case it stemmed from that my javascript code was not ECMA valid (we use a variable named double which is not allowed according to the ECMA rules).
I did not have the courage to check if your js is valid but trying to compress different parts of your js file can easily lead you to the problem if it exists.
Well, after a while of debugging I figured out a solution.
The problem was not the YUI Compressor it self but it was the FileWriter given to the method.
Flushing an closing the FileWriter should solve the problem with empty result files
since I only need the minified String for further processing I now use a StringWriter with closing and flushing