public void processMessage() throws IOException {
String txtFileName = fileNameStem + ".txt";
String attDirName = fileNameStem + "-att";
- PrintWriter txtOut = null;
- try {
- txtOut = new PrintWriter(txtFileName);
- try {
- String displayFrom = msg.getDisplayFrom();
- txtOut.println("From: "+displayFrom);
- } catch (ChunkNotFoundException e) {
- // ignore
- }
- try {
- String displayTo = msg.getDisplayTo();
- txtOut.println("To: "+displayTo);
- } catch (ChunkNotFoundException e) {
- // ignore
- }
- try {
- String displayCC = msg.getDisplayCC();
- txtOut.println("CC: "+displayCC);
- } catch (ChunkNotFoundException e) {
- // ignore
- }
- try {
- String displayBCC = msg.getDisplayBCC();
- txtOut.println("BCC: "+displayBCC);
- } catch (ChunkNotFoundException e) {
- // ignore
- }
- try {
- String subject = msg.getSubject();
- txtOut.println("Subject: "+subject);
- } catch (ChunkNotFoundException e) {
- // ignore
- }
- try {
- String body = msg.getTextBody();
- txtOut.println(body);
- } catch (ChunkNotFoundException e) {
- System.err.println("No message body");
- }
-
- AttachmentChunks[] attachments = msg.getAttachmentFiles();
- if(attachments.length > 0) {
- File d = new File(attDirName);
- if(d.mkdir()) {
- for(AttachmentChunks attachment : attachments) {
- processAttachment(attachment, d);
- }
- } else {
- System.err.println("Can't create directory "+attDirName);
- }
- }
- } finally {
- if(txtOut != null) {
- txtOut.close();
- }
- }
+ try (PrintWriter txtOut = new PrintWriter(txtFileName)) {
+ try {
+ String displayFrom = msg.getDisplayFrom();
+ txtOut.println("From: " + displayFrom);
+ } catch (ChunkNotFoundException e) {
+ // ignore
+ }
+ try {
+ String displayTo = msg.getDisplayTo();
+ txtOut.println("To: " + displayTo);
+ } catch (ChunkNotFoundException e) {
+ // ignore
+ }
+ try {
+ String displayCC = msg.getDisplayCC();
+ txtOut.println("CC: " + displayCC);
+ } catch (ChunkNotFoundException e) {
+ // ignore
+ }
+ try {
+ String displayBCC = msg.getDisplayBCC();
+ txtOut.println("BCC: " + displayBCC);
+ } catch (ChunkNotFoundException e) {
+ // ignore
+ }
+ try {
+ String subject = msg.getSubject();
+ txtOut.println("Subject: " + subject);
+ } catch (ChunkNotFoundException e) {
+ // ignore
+ }
+ try {
+ String body = msg.getTextBody();
+ txtOut.println(body);
+ } catch (ChunkNotFoundException e) {
+ System.err.println("No message body");
+ }
+
+ AttachmentChunks[] attachments = msg.getAttachmentFiles();
+ if (attachments.length > 0) {
+ File d = new File(attDirName);
+ if (d.mkdir()) {
+ for (AttachmentChunks attachment : attachments) {
+ processAttachment(attachment, d);
+ }
+ } else {
+ System.err.println("Can't create directory " + attDirName);
+ }
+ }
+ }
}
/**
}
File f = new File(dir, fileName);
- OutputStream fileOut = null;
- try {
- fileOut = new FileOutputStream(f);
- fileOut.write(attachment.getAttachData().getValue());
- } finally {
- if(fileOut != null) {
- fileOut.close();
- }
- }
+ try (OutputStream fileOut = new FileOutputStream(f)) {
+ fileOut.write(attachment.getAttachData().getValue());
+ }
}
/**
private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException
{
int pictureIndex;
- FileInputStream fis = null;
- ByteArrayOutputStream bos = null;
- try
- {
- fis = new FileInputStream( path);
- bos = new ByteArrayOutputStream( );
+ try (FileInputStream fis = new FileInputStream(path);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
int c;
- while ( (c = fis.read()) != -1)
- bos.write( c );
- pictureIndex = wb.addPicture( bos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG );
- }
- finally
- {
- if (fis != null)
- fis.close();
- if (bos != null)
- bos.close();
+ while ((c = fis.read()) != -1)
+ bos.write(c);
+ pictureIndex = wb.addPicture(bos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG);
}
return pictureIndex;
}
* @throws IOException if the file contained errors
*/
public void run() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem(new File(file), true);
- try {
- InputStream is = BiffViewer.getPOIFSInputStream(fs);
- try {
+ try (POIFSFileSystem fs = new POIFSFileSystem(new File(file), true)) {
+ try (InputStream is = BiffViewer.getPOIFSInputStream(fs)) {
List<Record> records = RecordFactory.createRecords(is);
for (Record record : records) {
}
}
}
- } finally {
- is.close();
}
- } finally {
- fs.close();
}
}
name = WORKBOOK_DIR_ENTRY_NAMES[0];
}
- InputStream in = dir.createDocumentInputStream(name);
- try {
+ try (InputStream in = dir.createDocumentInputStream(name)) {
processEvents(req, in);
- } finally {
- in.close();
}
}
*/
public short abortableProcessWorkbookEvents(HSSFRequest req, DirectoryNode dir)
throws IOException, HSSFUserException {
- InputStream in = dir.createDocumentInputStream("Workbook");
- try {
- return abortableProcessEvents(req, in);
- } finally {
- in.close();
- }
+ try (InputStream in = dir.createDocumentInputStream("Workbook")) {
+ return abortableProcessEvents(req, in);
+ }
}
/**
// value, depending on the block size of the chosen encryption algorithm
leos.writeLong(countBytes);
- FileInputStream fis = new FileInputStream(fileOut);
- try {
+ try (FileInputStream fis = new FileInputStream(fileOut)) {
IOUtils.copy(fis, leos);
- } finally {
- fis.close();
}
if (!fileOut.delete()) {
logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut);
parts[i] = specs.get(i).valueFor(elapsed);
}
- Formatter formatter = new Formatter(toAppendTo, Locale.ROOT);
- try {
+ try (Formatter formatter = new Formatter(toAppendTo, Locale.ROOT)) {
formatter.format(printfFmt, parts);
- } finally {
- formatter.close();
}
}
stripZeros = false;
}
- Formatter formatter = new Formatter(toAppendTo, locale);
- try {
+ try (Formatter formatter = new Formatter(toAppendTo, locale)) {
formatter.format(locale, fmt, value);
- } finally {
- formatter.close();
}
if (stripZeros) {
// strip off trailing zeros
writeFraction(value, null, fractional, output, mods);
} else {
StringBuffer result = new StringBuffer();
- Formatter f = new Formatter(result, locale);
- try {
+ try (Formatter f = new Formatter(result, locale)) {
f.format(locale, printfFmt, value);
- } finally {
- f.close();
}
if (numerator == null) {
private void writeSingleInteger(String fmt, int num, StringBuffer output, List<Special> numSpecials, Set<CellNumberStringMod> mods) {
StringBuffer sb = new StringBuffer();
- Formatter formatter = new Formatter(sb, locale);
- try {
+ try (Formatter formatter = new Formatter(sb, locale)) {
formatter.format(locale, fmt, num);
- } finally {
- formatter.close();
}
writeInteger(sb, output, numSpecials, mods, false);
}
props.setProperty("font." + fontName + ".widths", widths.toString());
}
- OutputStream fileOut = new FileOutputStream("font_metrics.properties");
- try {
+ try (OutputStream fileOut = new FileOutputStream("font_metrics.properties")) {
props.store(fileOut, "Font Metrics");
- } finally {
- fileOut.close();
}
}
}
*/
public static byte[] readData( String filename ) throws IOException {
File file = new File( filename );
- InputStream stream = new FileInputStream( file );
- try {
- return readData( stream, -1 );
- } finally {
- stream.close();
+ try (InputStream stream = new FileInputStream(file)) {
+ return readData(stream, -1);
}
}
byte[] buf = new byte[1024];
LittleEndian.putLong(buf, 0, oleStreamSize);
integrityMD.update(buf, 0, LittleEndianConsts.LONG_SIZE);
-
- InputStream fis = new FileInputStream(tmpFile);
- try {
+
+ try (InputStream fis = new FileInputStream(tmpFile)) {
int readBytes;
while ((readBytes = fis.read(buf)) != -1) {
integrityMD.update(buf, 0, readBytes);
}
- } finally {
- fis.close();
}
byte[] hmacValue = integrityMD.doFinal();
public static Shape<?,?> parseShape(byte[] metroBytes)
throws InvalidFormatException, IOException, XmlException {
PackagePartName shapePN = PackagingURIHelper.createPartName("/drs/shapexml.xml");
- OPCPackage pkg = null;
- try {
- pkg = OPCPackage.open(new ByteArrayInputStream(metroBytes));
+ try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(metroBytes))) {
PackagePart shapePart = pkg.getPart(shapePN);
CTGroupShape gs = CTGroupShape.Factory.parse(shapePart.getInputStream(), DEFAULT_XML_OPTIONS);
XSLFGroupShape xgs = new XSLFGroupShape(gs, null);
- return xgs.getShapes().get(0);
- } finally {
- if (pkg != null) {
- pkg.close();
- }
+ return xgs.getShapes().get(0);
}
}
}
xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
/* write bytes to new part */
PackagePart picDataPart = xwpfPicData.getPackagePart();
- OutputStream out = null;
- try {
- out = picDataPart.getOutputStream();
+ try (OutputStream out = picDataPart.getOutputStream()) {
out.write(pictureData);
} catch (IOException e) {
throw new POIXMLException(e);
- } finally {
- try {
- if (out != null) {
- out.close();
- }
- } catch (IOException e) {
- // ignore
- }
}
registerPackagePictureData(xwpfPicData);
@Override
protected void onDocumentRead() throws IOException {
EndnotesDocument notesDoc;
- InputStream is = null;
- try {
- is = getPackagePart().getInputStream();
+ try (InputStream is = getPackagePart().getInputStream()) {
notesDoc = EndnotesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
ctEndnotes = notesDoc.getEndnotes();
} catch (XmlException e) {
throw new POIXMLException();
- } finally {
- if (is != null) {
- is.close();
- }
}
for (CTFtnEdn note : ctEndnotes.getEndnoteList()) {
protected void onDocumentRead() throws IOException {
super.onDocumentRead();
FtrDocument ftrDocument = null;
- InputStream is = null;
- try {
- is = getPackagePart().getInputStream();
+ try (InputStream is = getPackagePart().getInputStream()) {
ftrDocument = FtrDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
headerFooter = ftrDocument.getFtr();
// parse the document with cursor and add
cursor.dispose();
} catch (Exception e) {
throw new POIXMLException(e);
- } finally {
- if (is != null) {
- is.close();
- }
}
}
@Override
protected void onDocumentRead() throws IOException {
FootnotesDocument notesDoc;
- InputStream is = null;
- try {
- is = getPackagePart().getInputStream();
+ try (InputStream is = getPackagePart().getInputStream()) {
notesDoc = FootnotesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
ctFootnotes = notesDoc.getFootnotes();
} catch (XmlException e) {
throw new POIXMLException();
- } finally {
- if (is != null) {
- is.close();
- }
}
for (CTFtnEdn note : ctFootnotes.getFootnoteList()) {
protected void onDocumentRead() throws IOException {
super.onDocumentRead();
HdrDocument hdrDocument = null;
- InputStream is = null;
- try {
- is = getPackagePart().getInputStream();
+ try (InputStream is = getPackagePart().getInputStream()) {
hdrDocument = HdrDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
headerFooter = hdrDocument.getHdr();
// parse the document with cursor and add
cursor.dispose();
} catch (XmlException e) {
throw new POIXMLException(e);
- } finally {
- if (is != null) {
- is.close();
- }
}
}
xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx);
/* write bytes to new part */
PackagePart picDataPart = xwpfPicData.getPackagePart();
- OutputStream out = null;
- try {
- out = picDataPart.getOutputStream();
+ try (OutputStream out = picDataPart.getOutputStream()) {
out.write(pictureData);
} catch (IOException e) {
throw new POIXMLException(e);
- } finally {
- try {
- if (out != null) out.close();
- } catch (IOException e) {
- // ignore
- }
}
document.registerPackagePictureData(xwpfPicData);
/**
* Adds a new paragraph at the end of the header or footer
- *
+ *
* @return new {@link XWPFParagraph} object
*/
public XWPFParagraph createParagraph() {
bodyElements.add(paragraph);
return paragraph;
}
-
+
/**
* Adds a new table at the end of the header or footer
- *
+ *
* @param rows - number of rows in the table
* @param cols - number of columns in the table
* @return new {@link XWPFTable} object
bodyElements.add(table);
return table;
}
-
+
/**
* Removes a specific paragraph from this header / footer
*
bodyElements.remove(paragraph);
}
}
-
+
/**
* Removes a specific table from this header / footer
- *
- * @param table - {@link XWPFTable} object to remove
+ *
+ * @param table - {@link XWPFTable} object to remove
*/
public void removeTable(XWPFTable table) {
if (tables.contains(table)) {
bodyElements.remove(table);
}
}
-
+
/**
* Clears all paragraphs and tables from this header / footer
*/
tables.clear();
bodyElements.clear();
}
-
+
/**
* add a new paragraph at position of the cursor
*
public POIXMLDocumentPart getPart() {
return this;
}
-
+
@Override
protected void prepareForCommit() {
// must contain at least an empty paragraph
if (bodyElements.size() == 0) {
createParagraph();
}
-
+
// Cells must contain at least an empty paragraph
for (XWPFTable tbl : tables) {
for (XWPFTableRow row : tbl.tableRows) {
}
}
super.prepareForCommit();
-
+
}
}
@Override
protected void onDocumentRead() throws IOException {
StylesDocument stylesDoc;
- InputStream is = getPackagePart().getInputStream();
- try {
+ try (InputStream is = getPackagePart().getInputStream()) {
stylesDoc = StylesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS);
setStyles(stylesDoc.getStyles());
latentStyles = new XWPFLatentStyles(ctStyles.getLatentStyles(), this);
} catch (XmlException e) {
throw new POIXMLException("Unable to read styles", e);
- } finally {
- is.close();
}
}
POIDataSamples pds = POIDataSamples.getDocumentInstance();
@SuppressWarnings("resource")
OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"));
- OPCParser doc = new OPCParser(pkg);
- try {
+ try (OPCParser doc = new OPCParser(pkg)) {
doc.parse(new TestFactory());
-
- for(POIXMLDocumentPart rel : doc.getRelations()){
+
+ for (POIXMLDocumentPart rel : doc.getRelations()) {
//TODO finish me
assertNotNull(rel);
}
- } finally {
- doc.close();
}
}
POIDataSamples pds = POIDataSamples.getDocumentInstance();
@SuppressWarnings("resource")
OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"));
- OPCParser doc = new OPCParser(pkg);
- try {
+ try (OPCParser doc = new OPCParser(pkg)) {
doc.parse(new TestFactory());
-
+
// Non-indexed parts: Word is taken, Excel is not
assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 0));
assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, -1));
assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 0));
assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, -1));
assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 99));
-
+
// Indexed parts:
// Has 2 headers
assertEquals(0, doc.getNextPartNumber(XWPFRelation.HEADER, 0));
assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, -1));
assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, 1));
assertEquals(8, doc.getNextPartNumber(XWPFRelation.HEADER, 8));
-
+
// Has no Excel Sheets
assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 0));
assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, -1));
assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 1));
- } finally {
- doc.close();
}
}
@Test(expected=POIXMLException.class)
public void testInvalidCoreRel() throws IOException {
POIDataSamples pds = POIDataSamples.getDiagramInstance();
- OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"));
-
- try {
+
+ try (OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx"))) {
new POIXMLDocumentPart(open, "somethingillegal");
- } finally {
- open.close();
}
}
/** a generic way to open a sample slideshow document **/
public static SlideShow<?,?> openSampleDocument(String sampleName) throws IOException {
- InputStream is = ssSamples.openResourceAsStream(sampleName);
- try {
+ try (InputStream is = ssSamples.openResourceAsStream(sampleName)) {
return SlideShowFactory.create(is);
} catch (Exception e) {
throw new RuntimeException(e);
- } finally {
- is.close();
}
}
public void testMacroFunction() throws Exception {
// testNames.xlsm contains a VB function called 'myFunc'
final String testFile = "testNames.xlsm";
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFile);
- try {
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFile)) {
XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb);
-
+
//Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands would go here...), FunctionPtg(myFunc)]
Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", workbook, FormulaType.CELL, -1);
assertEquals(3, ptg.length);
-
+
// the name gets encoded as the first operand on the stack
NameXPxg tname = (NameXPxg) ptg[0];
assertEquals("myFunc", tname.toFormulaString());
-
+
// the function's arguments are pushed onto the stack from left-to-right as OperandPtgs
StringPtg arg = (StringPtg) ptg[1];
assertEquals("arg", arg.getValue());
-
+
// The external FunctionPtg is the last Ptg added to the stack
// During formula evaluation, this Ptg pops off the the appropriate number of
- // arguments (getNumberOfOperands()) and pushes the result on the stack
+ // arguments (getNumberOfOperands()) and pushes the result on the stack
AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2];
assertTrue(tfunc.isExternalFunction());
-
+
// confirm formula parsing is case-insensitive
FormulaParser.parse("mYfUnC(\"arg\")", workbook, FormulaType.CELL, -1);
-
+
// confirm formula parsing doesn't care about argument count or type
// this should only throw an error when evaluating the formula.
FormulaParser.parse("myFunc()", workbook, FormulaType.CELL, -1);
FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", workbook, FormulaType.CELL, -1);
-
+
// A completely unknown formula name (not saved in workbook) should still be parseable and renderable
// but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated.
FormulaParser.parse("yourFunc(\"arg\")", workbook, FormulaType.CELL, -1);
-
+
// Make sure workbook can be written and read
XSSFTestDataSamples.writeOutAndReadBack(wb).close();
-
+
// Manually check to make sure file isn't corrupted
// TODO: develop a process for occasionally manually reviewing workbooks
// to verify workbooks are not corrupted
wb.write(fos);
fos.close();
*/
- } finally {
- wb.close();
}
}
@Test
public void testParserErrors() throws Exception {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("testNames.xlsm");
- try {
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("testNames.xlsm")) {
XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb);
-
+
parseExpectedException("(");
parseExpectedException(")");
parseExpectedException("+");
parseExpectedException("IF()");
parseExpectedException("IF("); //no closing paren
parseExpectedException("myFunc(", workbook); //no closing paren
- } finally {
- wb.close();
}
}
@Test
public void testTableFormulas() throws Exception {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
- try {
-
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx")) {
+
final FormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
final XSSFSheet tableSheet = wb.getSheet("Table");
final XSSFSheet formulaSheet = wb.getSheet("Formulas");
confirm(eval, tableSheet.getRow(5).getCell(0), 49);
confirm(eval, formulaSheet.getRow(0).getCell(0), 209);
confirm(eval, formulaSheet.getRow(1).getCell(0), "one");
-
+
// test changing a table value, to see if the caches are properly cleared
// Issue 59814
-
+
// this test passes before the fix for 59814
tableSheet.getRow(1).getCell(1).setCellValue("ONEA");
confirm(eval, formulaSheet.getRow(1).getCell(0), "ONEA");
-
+
// test adding a row to a table, issue 59814
Row newRow = tableSheet.getRow(7);
if (newRow == null) newRow = tableSheet.createRow(7);
newRow.createCell(0, CellType.FORMULA).setCellFormula("\\_Prime.1[[#This Row],[@Number]]*\\_Prime.1[[#This Row],[@Number]]");
newRow.createCell(1, CellType.STRING).setCellValue("thirteen");
newRow.createCell(2, CellType.NUMERIC).setCellValue(13);
-
+
// update Table
final XSSFTable table = wb.getTable("\\_Prime.1");
final AreaReference newArea = wb.getCreationHelper().createAreaReference(
table.updateReferences();
// these fail before the fix for 59814
- confirm(eval, tableSheet.getRow(7).getCell(0), 13*13);
- confirm(eval, formulaSheet.getRow(0).getCell(0), 209 + 13*13);
+ confirm(eval, tableSheet.getRow(7).getCell(0), 13 * 13);
+ confirm(eval, formulaSheet.getRow(0).getCell(0), 209 + 13 * 13);
- } finally {
- wb.close();
}
}
*/
@Test
public void testShapes() throws Exception{
- XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("WithTextBox.xlsx");
-
- try {
- String text = ooxmlExtractor.getText();
- assertContains(text, "Line 1");
- assertContains(text, "Line 2");
- assertContains(text, "Line 3");
- } finally {
- ooxmlExtractor.close();
- }
+
+ try (XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("WithTextBox.xlsx")) {
+ String text = ooxmlExtractor.getText();
+ assertContains(text, "Line 1");
+ assertContains(text, "Line 2");
+ assertContains(text, "Line 3");
+ }
}
/**
String expectedOutput = "Sheet1\n99.99\n";
- XSSFExcelExtractor extractor = new XSSFExcelExtractor(
- XSSFTestDataSamples.openSampleWorkbook("56011.xlsx"));
- try {
+ try (XSSFExcelExtractor extractor = new XSSFExcelExtractor(
+ XSSFTestDataSamples.openSampleWorkbook("56011.xlsx"))) {
assertEquals(expectedOutput, extractor.getText().replace(",", "."));
- } finally {
- extractor.close();
}
- XSSFEventBasedExcelExtractor fixture =
- new XSSFEventBasedExcelExtractor(
- XSSFTestDataSamples.openSamplePackage("56011.xlsx"));
- try {
+ try (XSSFEventBasedExcelExtractor fixture = new XSSFEventBasedExcelExtractor(
+ XSSFTestDataSamples.openSamplePackage("56011.xlsx"))) {
assertEquals(expectedOutput, fixture.getText().replace(",", "."));
- } finally {
- fixture.close();
}
}
"Sheet1\n" +
"abc\t123\n";
- XSSFExcelExtractor extractor = new XSSFExcelExtractor(
- XSSFTestDataSamples.openSampleWorkbook("headerFooterTest.xlsx"));
- try {
+ try (XSSFExcelExtractor extractor = new XSSFExcelExtractor(
+ XSSFTestDataSamples.openSampleWorkbook("headerFooterTest.xlsx"))) {
assertEquals(expectedOutputWithHeadersAndFooters, extractor.getText());
extractor.setIncludeHeadersFooters(false);
assertEquals(expectedOutputWithoutHeadersAndFooters, extractor.getText());
- } finally {
- extractor.close();
}
- XSSFEventBasedExcelExtractor fixture =
- new XSSFEventBasedExcelExtractor(
- XSSFTestDataSamples.openSamplePackage("headerFooterTest.xlsx"));
- try {
+ try (XSSFEventBasedExcelExtractor fixture = new XSSFEventBasedExcelExtractor(
+ XSSFTestDataSamples.openSamplePackage("headerFooterTest.xlsx"))) {
assertEquals(expectedOutputWithHeadersAndFooters, fixture.getText());
fixture.setIncludeHeadersFooters(false);
assertEquals(expectedOutputWithoutHeadersAndFooters, fixture.getText());
- } finally {
- fixture.close();
}
}
"Comment by Shaun Kalley: Comment A7\tComment by Shaun Kalley: Comment B7\n" +
"Comment by Shaun Kalley: Comment A8\tComment by Shaun Kalley: Comment B8\n";
- XSSFExcelExtractor extractor = new XSSFExcelExtractor(
- XSSFTestDataSamples.openSampleWorkbook("commentTest.xlsx"));
- try {
+ try (XSSFExcelExtractor extractor = new XSSFExcelExtractor(
+ XSSFTestDataSamples.openSampleWorkbook("commentTest.xlsx"))) {
assertEquals(expectedOutputWithoutComments, extractor.getText());
extractor.setIncludeCellComments(true);
assertEquals(nonEventBasedExtractorOutputWithComments, extractor.getText());
- } finally {
- extractor.close();
}
- XSSFEventBasedExcelExtractor fixture =
- new XSSFEventBasedExcelExtractor(
- XSSFTestDataSamples.openSamplePackage("commentTest.xlsx"));
- try {
+ try (XSSFEventBasedExcelExtractor fixture = new XSSFEventBasedExcelExtractor(
+ XSSFTestDataSamples.openSamplePackage("commentTest.xlsx"))) {
assertEquals(expectedOutputWithoutComments, fixture.getText());
fixture.setIncludeCellComments(true);
assertEquals(eventBasedExtractorOutputWithComments, fixture.getText());
- } finally {
- fixture.close();
}
}
@Test
public void testFile56278_normal() throws Exception {
// first with normal Text Extractor
- POIXMLTextExtractor extractor = new XSSFExcelExtractor(
- XSSFTestDataSamples.openSampleWorkbook("56278.xlsx"));
- try {
+ try (POIXMLTextExtractor extractor = new XSSFExcelExtractor(
+ XSSFTestDataSamples.openSampleWorkbook("56278.xlsx"))) {
assertNotNull(extractor.getText());
- } finally {
- extractor.close();
}
}
@Test
public void testFile56278_event() throws Exception {
// then with event based one
- POIXMLTextExtractor extractor = getExtractor("56278.xlsx");
- try {
+ try (POIXMLTextExtractor extractor = getExtractor("56278.xlsx")) {
assertNotNull(extractor.getText());
- } finally {
- extractor.close();
}
}
* Simple test for text box text
*/
public void testTextBoxes() throws IOException {
- XSSFExcelExtractor extractor = getExtractor("WithTextBox.xlsx");
- try {
- extractor.setFormulasNotResults(true);
- String text = extractor.getText();
- assertContains(text, "Line 1");
- assertContains(text, "Line 2");
- assertContains(text, "Line 3");
- } finally {
- extractor.close();
- }
+ try (XSSFExcelExtractor extractor = getExtractor("WithTextBox.xlsx")) {
+ extractor.setFormulasNotResults(true);
+ String text = extractor.getText();
+ assertContains(text, "Line 1");
+ assertContains(text, "Line 2");
+ assertContains(text, "Line 3");
+ }
}
public void testPhoneticRuns() throws Exception {
- XSSFExcelExtractor extractor = getExtractor("51519.xlsx");
- try {
- String text = extractor.getText();
- assertContains(text, "\u8C4A\u7530");
- //this shows up only as a phonetic run and should not appear
- //in the extracted text
- assertNotContained(text, "\u30CB\u30DB\u30F3");
- } finally {
- extractor.close();
- }
+ try (XSSFExcelExtractor extractor = getExtractor("51519.xlsx")) {
+ String text = extractor.getText();
+ assertContains(text, "\u8C4A\u7530");
+ //this shows up only as a phonetic run and should not appear
+ //in the extracted text
+ assertNotContained(text, "\u30CB\u30DB\u30F3");
+ }
}
}
@Test
public void test53965() throws Exception {
- SXSSFWorkbook wb = new SXSSFWorkbook();
- try {
+ try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
Sheet sheet = wb.createSheet();
List<? extends DataValidation> lst = sheet.getDataValidations(); //<-- works
assertEquals(0, lst.size());
-
+
//create the cell that will have the validation applied
sheet.createRow(0).createCell(0);
-
+
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DataValidation validation = dataValidationHelper.createValidation(constraint, addressList);
sheet.addValidationData(validation);
-
+
// this line caused XmlValueOutOfRangeException , see Bugzilla 3965
lst = sheet.getDataValidations();
assertEquals(1, lst.size());
- } finally {
- wb.close();
}
}
}
@Test
public void overrideFlushedRows() throws IOException {
- Workbook wb = new SXSSFWorkbook(3);
- try {
+ try (Workbook wb = new SXSSFWorkbook(3)) {
Sheet sheet = wb.createSheet();
-
+
sheet.createRow(1);
sheet.createRow(2);
sheet.createRow(3);
sheet.createRow(4);
-
+
thrown.expect(Throwable.class);
thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk.");
sheet.createRow(1);
- } finally {
- wb.close();
}
}
writer.outputQuotedString(unicodeSurrogates);
writer.close();
File file = writer.getTempFile();
- FileInputStream is = new FileInputStream(file);
- String text;
- try {
- text = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8);
- } finally {
- is.close();
+ try (FileInputStream is = new FileInputStream(file)) {
+ String text = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8);
+ assertEquals(unicodeSurrogates, text);
}
- assertEquals(unicodeSurrogates, text);
} finally {
IOUtils.closeQuietly(writer);
}
writer.outputQuotedString("\r\n");
writer.close();
File file = writer.getTempFile();
- FileInputStream is = new FileInputStream(file);
- String text;
- try {
- text = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8);
- } finally {
- is.close();
+ try (FileInputStream is = new FileInputStream(file)) {
+ String text = new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8);
+ assertEquals("
", text);
}
- assertEquals("
", text);
} finally {
IOUtils.closeQuietly(writer);
}
@Test
public void testBug58175() throws IOException {
- Workbook wb = new SXSSFWorkbook();
- try {
+ try (Workbook wb = new SXSSFWorkbook()) {
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(1);
+ ", 0";
vmlShape2.getClientDataArray(0).setAnchorArray(0, position);
}
-
+
CellAddress ref = new CellAddress(ca.getRow1(), ca.getCol1());
XSSFComment shape2 = new XSSFComment(comments, comments.newComment(ref), vmlShape2);
-
+
assertEquals(shape1.getAuthor(), shape2.getAuthor());
assertEquals(shape1.getClientAnchor(), shape2.getClientAnchor());
assertEquals(shape1.getColumn(), shape2.getColumn());
assertEquals(shape1.getRow(), shape2.getRow());
assertEquals(shape1.getCTComment().toString(), shape2.getCTComment().toString());
assertEquals(shape1.getCTComment().getRef(), shape2.getCTComment().getRef());
-
+
/*CommentsTable table1 = shape1.getCommentsTable();
CommentsTable table2 = shape2.getCommentsTable();
assertEquals(table1.getCTComments().toString(), table2.getCTComments().toString());
assertEquals(table1.getNumberOfComments(), table2.getNumberOfComments());
assertEquals(table1.getRelations(), table2.getRelations());*/
-
- assertEquals("The vmlShapes should have equal content afterwards",
+
+ assertEquals("The vmlShapes should have equal content afterwards",
vmlShape1.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), vmlShape2.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"));
- } finally {
- wb.close();
}
}
@Ignore("Used for manual testing with opening the resulting Workbook in Excel")
@Test
public void testBug58175a() throws IOException {
- Workbook wb = new SXSSFWorkbook();
- try {
+ try (Workbook wb = new SXSSFWorkbook()) {
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(1);
comment.setString(str);
comment.setAuthor("Apache POI");
- /* fixed the problem as well
+ /* fixed the problem as well
* comment.setColumn(cell.getColumnIndex());
* comment.setRow(cell.getRowIndex());
*/
// Assign the comment to the cell
cell.setCellComment(comment);
- OutputStream out = new FileOutputStream("C:\\temp\\58175.xlsx");
- try {
+ try (OutputStream out = new FileOutputStream("C:\\temp\\58175.xlsx")) {
wb.write(out);
- } finally {
- out.close();
}
- } finally {
- wb.close();
}
}
XSSFDrawing drawing = sheet.createDrawingPatriarch();
assertNotNull(drawing);
}
- OPCPackage pkg = wb.getPackage();
- try {
+ try (OPCPackage pkg = wb.getPackage()) {
assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size());
checkRewrite(wb);
- } finally {
- pkg.close();
}
wb.close();
}
@Test
public void testMergeRegionsSpeed() throws IOException {
- final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57893-many-merges.xlsx");
- try {
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57893-many-merges.xlsx")) {
long millis = Long.MAX_VALUE;
- // in order to reduce the number of false positives we run it a few times before we fail,
- // sometimes it fails on machines that are busy at the moment.
- for(int i = 0;i < 5;i++) {
+ // in order to reduce the number of false positives we run it a few times before we fail,
+ // sometimes it fails on machines that are busy at the moment.
+ for (int i = 0; i < 5; i++) {
millis = runTest(wb);
- if(millis < 2000) {
+ if (millis < 2000) {
break;
}
- LOG.log(POILogger.INFO,"Retry " + i + " because run-time is too high: " + millis);
+ LOG.log(POILogger.INFO, "Retry " + i + " because run-time is too high: " + millis);
}
boolean inGump = false;
String version = System.getProperty("version.id");
- if(version != null && version.startsWith("gump-")) {
+ if (version != null && version.startsWith("gump-")) {
inGump = true;
}
// when running in Gump, the VM is very slow, so we should allow much more time
assertTrue("Should have taken <2000 ms to iterate 50k merged regions but took " + millis,
inGump ? millis < 8000 : millis < 2000);
- } finally {
- wb.close();
}
}
public class TestXSSFTextParagraph {
@Test
public void testXSSFTextParagraph() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
-
+
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
-
+
XSSFFont font = wb.createFont();
Color color = new Color(0, 255, 255);
font.setColor(new XSSFColor(color, wb.getStylesSource().getIndexedColors()));
font.setFontName("Arial");
rt.applyFont(font);
-
+
shape.setText(rt);
-
+
List<XSSFTextParagraph> paras = shape.getTextParagraphs();
assertEquals(1, paras.size());
-
+
XSSFTextParagraph text = paras.get(0);
assertEquals("Test String", text.getText());
-
+
assertFalse(text.isBullet());
assertNotNull(text.getXmlObject());
assertEquals(shape.getCTShape(), text.getParentShape());
assertEquals(2, text.getTextRuns().size());
text.addNewTextRun();
assertEquals(3, text.getTextRuns().size());
-
+
assertEquals(TextAlign.LEFT, text.getTextAlign());
text.setTextAlign(null);
assertEquals(TextAlign.LEFT, text.getTextAlign());
assertEquals(TextAlign.RIGHT, text.getTextAlign());
text.setTextAlign(null);
assertEquals(TextAlign.LEFT, text.getTextAlign());
-
+
text.setTextFontAlign(TextFontAlign.BASELINE);
assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign());
text.setTextFontAlign(TextFontAlign.BOTTOM);
assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign());
text.setTextFontAlign(null);
assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign());
-
+
assertNull(text.getBulletFont());
text.setBulletFont("Arial");
assertEquals("Arial", text.getBulletFont());
-
+
assertNull(text.getBulletCharacter());
text.setBulletCharacter(".");
assertEquals(".", text.getBulletCharacter());
-
+
assertNull(text.getBulletFontColor());
text.setBulletFontColor(color);
assertEquals(color, text.getBulletFontColor());
-
+
assertEquals(100.0, text.getBulletFontSize(), 0.01);
text.setBulletFontSize(1.0);
assertEquals(1.0, text.getBulletFontSize(), 0.01);
assertEquals(0.0, text.getIndent(), 0.01);
text.setIndent(-1.0);
assertEquals(0.0, text.getIndent(), 0.01);
-
+
assertEquals(0.0, text.getLeftMargin(), 0.01);
text.setLeftMargin(3.0);
assertEquals(3.0, text.getLeftMargin(), 0.01);
assertEquals(0.0, text.getLeftMargin(), 0.01);
text.setLeftMargin(-1.0);
assertEquals(0.0, text.getLeftMargin(), 0.01);
-
+
assertEquals(0.0, text.getRightMargin(), 0.01);
text.setRightMargin(4.5);
assertEquals(4.5, text.getRightMargin(), 0.01);
assertEquals(0.0, text.getRightMargin(), 0.01);
text.setRightMargin(-1.0);
assertEquals(0.0, text.getRightMargin(), 0.01);
-
+
assertEquals(0.0, text.getDefaultTabSize(), 0.01);
-
+
assertEquals(0.0, text.getTabStop(0), 0.01);
text.addTabStop(3.14);
assertEquals(3.14, text.getTabStop(0), 0.01);
-
+
assertEquals(100.0, text.getLineSpacing(), 0.01);
text.setLineSpacing(3.15);
assertEquals(3.15, text.getLineSpacing(), 0.01);
assertEquals(6.17, text.getSpaceAfter(), 0.01);
text.setSpaceAfter(-8.17);
assertEquals(-8.17, text.getSpaceAfter(), 0.01);
-
+
assertEquals(0, text.getLevel());
text.setLevel(1);
assertEquals(1, text.getLevel());
text.setLevel(4);
assertEquals(4, text.getLevel());
-
+
assertTrue(text.isBullet());
assertFalse(text.isBulletAutoNumber());
text.setBullet(false);
assertFalse(text.isBulletAutoNumber());
assertEquals(0, text.getBulletAutoNumberStart());
assertEquals(ListAutoNumber.ARABIC_PLAIN, text.getBulletAutoNumberScheme());
-
+
text.setBullet(false);
assertFalse(text.isBullet());
text.setBullet(ListAutoNumber.CIRCLE_NUM_DB_PLAIN);
assertEquals(10, text.getBulletAutoNumberStart());
assertEquals(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, text.getBulletAutoNumberScheme());
-
+
assertNotNull(text.toString());
-
+
new XSSFTextParagraph(text.getXmlObject(), shape.getCTShape());
- } finally {
- wb.close();
}
}
}
public class TestXSSFTextRun {
@Test
public void testXSSFTextParagraph() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- try {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
-
+
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFTextParagraph para = shape.addNewTextParagraph();
assertEquals(1, runs.size());
XSSFTextRun run = runs.get(0);
assertEquals("Line 1", run.getText());
-
+
assertNotNull(run.getParentParagraph());
assertNotNull(run.getXmlObject());
assertNotNull(run.getRPr());
-
- assertEquals(new Color(0,0,0), run.getFontColor());
-
+
+ assertEquals(new Color(0, 0, 0), run.getFontColor());
+
Color color = new Color(0, 255, 255);
run.setFontColor(color);
assertEquals(color, run.getFontColor());
-
+
assertEquals(11.0, run.getFontSize(), 0.01);
run.setFontSize(12.32);
assertEquals(12.32, run.getFontSize(), 0.01);
assertTrue(e.getMessage().contains("0.9"));
}
assertEquals(11.0, run.getFontSize(), 0.01);
-
+
assertEquals(0.0, run.getCharacterSpacing(), 0.01);
run.setCharacterSpacing(12.31);
assertEquals(12.31, run.getCharacterSpacing(), 0.01);
assertEquals(0.0, run.getCharacterSpacing(), 0.01);
run.setCharacterSpacing(0.0);
assertEquals(0.0, run.getCharacterSpacing(), 0.01);
-
+
assertEquals("Calibri", run.getFontFamily());
- run.setFontFamily("Arial", (byte)1, (byte)1, false);
+ run.setFontFamily("Arial", (byte) 1, (byte) 1, false);
assertEquals("Arial", run.getFontFamily());
- run.setFontFamily("Arial", (byte)-1, (byte)1, false);
+ run.setFontFamily("Arial", (byte) -1, (byte) 1, false);
assertEquals("Arial", run.getFontFamily());
- run.setFontFamily("Arial", (byte)1, (byte)-1, false);
+ run.setFontFamily("Arial", (byte) 1, (byte) -1, false);
assertEquals("Arial", run.getFontFamily());
- run.setFontFamily("Arial", (byte)1, (byte)1, true);
+ run.setFontFamily("Arial", (byte) 1, (byte) 1, true);
assertEquals("Arial", run.getFontFamily());
- run.setFontFamily(null, (byte)1, (byte)1, false);
+ run.setFontFamily(null, (byte) 1, (byte) 1, false);
assertEquals("Calibri", run.getFontFamily());
- run.setFontFamily(null, (byte)1, (byte)1, false);
+ run.setFontFamily(null, (byte) 1, (byte) 1, false);
assertEquals("Calibri", run.getFontFamily());
run.setFont("Arial");
assertEquals("Arial", run.getFontFamily());
-
- assertEquals((byte)0, run.getPitchAndFamily());
+
+ assertEquals((byte) 0, run.getPitchAndFamily());
run.setFont(null);
- assertEquals((byte)0, run.getPitchAndFamily());
-
+ assertEquals((byte) 0, run.getPitchAndFamily());
+
assertFalse(run.isStrikethrough());
run.setStrikethrough(true);
assertTrue(run.isStrikethrough());
assertTrue(run.isSubscript());
run.setSubscript(false);
assertFalse(run.isSubscript());
-
+
assertEquals(TextCap.NONE, run.getTextCap());
assertFalse(run.isBold());
assertTrue(run.isUnderline());
run.setUnderline(false);
assertFalse(run.isUnderline());
-
+
assertNotNull(run.toString());
- } finally {
- wb.close();
}
}
}
public void testFindCommentShape() throws IOException, XmlException {
XSSFVMLDrawing vml = new XSSFVMLDrawing();
- InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml");
- try {
+ try (InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml")) {
vml.read(stream);
- } finally {
- stream.close();
}
CTShape sh_a1 = vml.findCommentShape(0, 0);
@Test
public void testRemoveCommentShape() throws IOException, XmlException {
XSSFVMLDrawing vml = new XSSFVMLDrawing();
- InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml");
- try {
+ try (InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml")) {
vml.read(stream);
- } finally {
- stream.close();
}
CTShape sh_a1 = vml.findCommentShape(0, 0);
@Test
public void testEvilUnclosedBRFixing() throws IOException, XmlException {
XSSFVMLDrawing vml = new XSSFVMLDrawing();
- InputStream stream = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("bug-60626.vml");
- try {
+ try (InputStream stream = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("bug-60626.vml")) {
vml.read(stream);
- } finally {
- stream.close();
}
Pattern p = Pattern.compile("<br/>");
int count = 0;
*/
public final class VSDDumper {
final static String tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
-
+
private final PrintStream ps;
private final HDGFDiagram hdgf;
VSDDumper(PrintStream ps, HDGFDiagram hdgf) {
this.ps = ps;
this.hdgf = hdgf;
}
-
+
public static void main(String[] args) throws Exception {
if(args.length == 0) {
System.err.println("Use:");
try (POIFSFileSystem poifs = new POIFSFileSystem(new File(args[0]));
HDGFDiagram hdgf = new HDGFDiagram(poifs)) {
- PrintStream ps = System.out;
- ps.println("Opened " + args[0]);
- VSDDumper vd = new VSDDumper(ps, hdgf);
- vd.dumpFile();
- }
+ PrintStream ps = System.out;
+ ps.println("Opened " + args[0]);
+ VSDDumper vd = new VSDDumper(ps, hdgf);
+ vd.dumpFile();
+ }
}
public void dumpFile() {
ps.println();
dumpStream(hdgf.getTrailerStream(), 0);
}
-
+
private void dumpStream(Stream stream, int indent) {
Pointer ptr = stream.getPointer();
dumpVal("Stream at", ptr.getOffset(), indent);
dumpVal(command.getDefinition().getName(), ""+command.getValue(), indent+1);
}
}
-
+
private void dumpVal(String label, long value, int indent) {
ps.print(tabs.substring(0,indent));
ps.print(label);
ps.print(tabs.substring(0,indent));
ps.print(label);
ps.print('\t');
- ps.println(value);
+ ps.println(value);
}
}
continue;
}
- InputStream stream = new FileInputStream(arg);
- try {
- HMEFDumper dumper = new HMEFDumper(stream);
- dumper.setTruncatePropertyData(truncatePropData);
- dumper.dump();
- } finally {
- stream.close();
- }
+ try (InputStream stream = new FileInputStream(arg)) {
+ HMEFDumper dumper = new HMEFDumper(stream);
+ dumper.setTruncatePropertyData(truncatePropData);
+ dumper.dump();
+ }
}
}
}
dest = new File(name + ".txt");
}
-
- OutputStream fout = new FileOutputStream(dest);
- try {
+
+ try (OutputStream fout = new FileOutputStream(dest)) {
if (body instanceof MAPIStringAttribute) {
// Save in a predictable encoding, not raw bytes
- String text = ((MAPIStringAttribute)body).getDataString();
+ String text = ((MAPIStringAttribute) body).getDataString();
fout.write(text.getBytes(StringUtil.UTF8));
} else {
// Save the raw bytes, should be raw RTF
fout.write(body.getData());
}
- } finally {
- fout.close();
}
}
// Save it
File file = new File(dir, filename);
- OutputStream fout = new FileOutputStream(file);
- try {
- fout.write( att.getContents() );
- } finally {
- fout.close();
+ try (OutputStream fout = new FileOutputStream(file)) {
+ fout.write(att.getContents());
}
}
}
}
byte[] chunk = new byte[4096];
ByteArrayOutputStream out = new ByteArrayOutputStream(header.getWmfSize());
- InflaterInputStream inflater = new InflaterInputStream( bis );
- try {
+ try (InflaterInputStream inflater = new InflaterInputStream(bis)) {
int count;
- while ((count = inflater.read(chunk)) >=0 ) {
- out.write(chunk,0,count);
+ while ((count = inflater.read(chunk)) >= 0) {
+ out.write(chunk, 0, count);
// PICT zip-stream can be erroneous, so we clear the array to determine
// the maximum of read bytes, after the inflater crashed
- bytefill(chunk, (byte)0);
+ bytefill(chunk, (byte) 0);
}
} catch (Exception e) {
int lastLen;
- for (lastLen=chunk.length-1; lastLen>=0 && chunk[lastLen] == 0; lastLen--);
+ for (lastLen = chunk.length - 1; lastLen >= 0 && chunk[lastLen] == 0; lastLen--) ;
if (++lastLen > 0) {
if (header.getWmfSize() > out.size()) {
// sometimes the wmfsize is smaller than the amount of already successfully read bytes
// in this case we take the lastLen as-is, otherwise we truncate it to the given size
lastLen = Math.min(lastLen, header.getWmfSize() - out.size());
}
- out.write(chunk,0,lastLen);
+ out.write(chunk, 0, lastLen);
}
// End of picture marker for PICT is 0x00 0xFF
- LOG.log(POILogger.ERROR, "PICT zip-stream is invalid, read as much as possible. Uncompressed length of header: "+header.getWmfSize()+" / Read bytes: "+out.size(), e);
- } finally {
- inflater.close();
+ LOG.log(POILogger.ERROR, "PICT zip-stream is invalid, read as much as possible. Uncompressed length of header: " + header.getWmfSize() + " / Read bytes: " + out.size(), e);
}
return out.toByteArray();
}
/**
* Converts xls files (97-2007) to XSL FO.
- *
+ *
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Beta
/**
* Java main() interface to interact with {@link ExcelToFoConverter}
- *
+ *
* <p>
* Usage: ExcelToHtmlConverter infile outfile
* </p>
/**
* Converts Excel file (97-2007) into XSL FO file.
- *
+ *
* @param xlsFile
* file to process
* @return DOM representation of result XSL FO
*/
public static Document process( File xlsFile ) throws Exception
{
- final HSSFWorkbook workbook = AbstractExcelUtils.loadXls( xlsFile );
- try {
+ try (HSSFWorkbook workbook = AbstractExcelUtils.loadXls(xlsFile)) {
ExcelToFoConverter excelToHtmlConverter = new ExcelToFoConverter(
XMLHelper.newDocumentBuilder().newDocument() );
- excelToHtmlConverter.processWorkbook( workbook );
+ excelToHtmlConverter.processWorkbook(workbook);
return excelToHtmlConverter.getDocument();
- } finally {
- workbook.close();
}
}
/**
* Returns <tt>false</tt> if cell style by itself (without text, i.e.
* borders, fill, etc.) worth a mention, <tt>true</tt> otherwise
- *
+ *
* @return <tt>false</tt> if cell style by itself (without text, i.e.
* borders, fill, etc.) worth a mention, <tt>true</tt> otherwise
*/
/**
* Creates COLGROUP element with width specified for all columns. (Except
* first if <tt>{@link #isOutputRowNumbers()}==true</tt>)
- *
+ *
* @return table width in inches
*/
protected float processColumnWidths( HSSFSheet sheet, int maxSheetColumns,
/**
* Process single sheet (as specified by 0-based sheet index)
- *
+ *
* @return <tt>true</tt> if result were added to FO document, <tt>false</tt>
* otherwise
*/
public static HWPFDocumentCore loadDoc( File docFile ) throws IOException
{
- final FileInputStream istream = new FileInputStream( docFile );
- try {
- return loadDoc( istream );
- } finally {
- istream.close();
+ try (FileInputStream istream = new FileInputStream(docFile)) {
+ return loadDoc(istream);
}
}
}
private VisioTextExtractor openExtractor(String fileName) throws IOException {
- InputStream is = _dgTests.openResourceAsStream(fileName);
- try {
+ try (InputStream is = _dgTests.openResourceAsStream(fileName)) {
return new VisioTextExtractor(is);
- } finally {
- is.close();
}
}
}
msg = new HMEFMessage(is);
}
- MAPIAttribute attr = msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED);
- assertNotNull(attr);
- MAPIRtfAttribute rtfAttr = (MAPIRtfAttribute) attr;
+ MAPIAttribute attr = msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED);
+ assertNotNull(attr);
+ MAPIRtfAttribute rtfAttr = (MAPIRtfAttribute)attr;
final byte[] expected;
try (InputStream stream = _samples.openResourceAsStream("quick-contents/message.rtf")) {
}
// By String
- String expString = new String(expected, StandardCharsets.US_ASCII);
+ String expString = new String(expected, StandardCharsets.US_ASCII);
String decompStr = rtfAttr.getDataString();
assertEquals(expString.length(), decompStr.length());
assertEquals(expString, decompStr);
}
public static HSLFSlideShow getSlideShow(String fileName) throws IOException {
- InputStream is = openSampleFileStream(fileName);
- try {
- return new HSLFSlideShow(is);
- } finally {
- is.close();
- }
+ try (InputStream is = openSampleFileStream(fileName)) {
+ return new HSLFSlideShow(is);
+ }
}
/**
@Test(expected=EncryptedPowerPointFileException.class)
public void testLoadEncrypted1() throws IOException {
- InputStream is = slTests.openResourceAsStream("Password_Protected-hello.ppt");
- try {
+ try (InputStream is = slTests.openResourceAsStream("Password_Protected-hello.ppt")) {
new HSLFSlideShowImpl(is).close();
- } finally {
- is.close();
- }
+ }
}
@Test(expected=EncryptedPowerPointFileException.class)
public void testLoadEncrypted2() throws IOException {
- InputStream is = slTests.openResourceAsStream("Password_Protected-np-hello.ppt");
- try {
+ try (InputStream is = slTests.openResourceAsStream("Password_Protected-np-hello.ppt")) {
new HSLFSlideShowImpl(is).close();
- } finally {
- is.close();
- }
+ }
}
@Test(expected=EncryptedPowerPointFileException.class)
public void testLoadEncrypted3() throws IOException {
- InputStream is = slTests.openResourceAsStream("Password_Protected-56-hello.ppt");
- try {
+ try (InputStream is = slTests.openResourceAsStream("Password_Protected-56-hello.ppt")) {
new HSLFSlideShowImpl(is).close();
- } finally {
- is.close();
- }
+ }
}
}
@Test(expected = EncryptedPowerPointFileException.class)
public void readEnc() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_slTests.getFile(encFile));
-
- try {
- new CurrentUserAtom(fs.getRoot());
- assertTrue(true); // not yet failed
-
- new HSLFSlideShowImpl(fs).close();
- } finally {
- fs.close();
- }
+
+ try (POIFSFileSystem fs = new POIFSFileSystem(_slTests.getFile(encFile))) {
+ new CurrentUserAtom(fs.getRoot());
+ assertTrue(true); // not yet failed
+
+ new HSLFSlideShowImpl(fs).close();
+ }
}
@Test
expectImages(docA, 1);
HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA);
-
- OutputStream out = new FileOutputStream("/tmp/58804_1_out.doc");
- try {
+
+ try (OutputStream out = new FileOutputStream("/tmp/58804_1_out.doc")) {
docB.write(out);
- } finally {
- out.close();
}
expectImages(docB, 1);
public void testMacroFunction() throws IOException {
// testNames.xls contains a VB function called 'myFunc'
final String testFile = "testNames.xls";
- HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(testFile);
- try {
+ try (HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(testFile)) {
HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb);
//Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands go here...), FunctionPtg(myFunc)]
Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", book, FormulaType.CELL, -1);
- assertEquals(3, ptg.length);
+ assertEquals(3, ptg.length);
// the name gets encoded as the first operand on the stack
NamePtg tname = (NamePtg) ptg[0];
FormulaParser.parse("yourFunc(\"arg\")", book, FormulaType.CELL, -1);
// Verify that myFunc and yourFunc were successfully added to Workbook names
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb);
- try {
+ try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb)) {
// HSSFWorkbook/EXCEL97-specific side-effects user-defined function names must be added to Workbook's defined names in order to be saved.
assertNotNull(wb2.getName("myFunc"));
assertEqualsIgnoreCase("myFunc", wb2.getName("myFunc").getNameName());
wb2.write(fos);
fos.close();
*/
- } finally {
- wb2.close();
}
- } finally {
- wb.close();
}
}
}
assertEquals("test\"ing", sp.getValue());
- HSSFWorkbook wb = new HSSFWorkbook();
- try {
+ try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "Sheet1");
-
+
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellFormula("right(\"test\"\"ing\", 3)");
String actualCellFormula = cell.getCellFormula();
- if("RIGHT(\"test\"ing\",3)".equals(actualCellFormula)) {
+ if ("RIGHT(\"test\"ing\",3)".equals(actualCellFormula)) {
fail("Identified bug 28754b");
}
assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula);
- } finally {
- wb.close();
}
}
"00, " + //compression flag
"00"); //padding byte
- LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data));
- try {
+ try (LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data))) {
LbsDataSubRecord.LbsDropData lbs = new LbsDataSubRecord.LbsDropData(in);
-
+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- LittleEndianOutputStream out = new LittleEndianOutputStream(baos);
- try {
+ try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) {
lbs.serialize(out);
-
+
assertArrayEquals(data, baos.toByteArray());
- } finally {
- out.close();
}
- } finally {
- in.close();
}
}
}
}
private void writeDataToFile(File temp) throws IOException {
- OutputStream str = new FileOutputStream(temp);
- try {
- InputStream in = data.openResourceAsStream("Notes.ole2");
- try {
- IOUtils.copy(in, str);
- } finally {
- in.close();
- }
- } finally {
- str.close();
- }
+ try (OutputStream str = new FileOutputStream(temp)) {
+ try (InputStream in = data.openResourceAsStream("Notes.ole2")) {
+ IOUtils.copy(in, str);
+ }
+ }
}
private void checkDataSource(FileBackedDataSource ds, boolean writeable) throws IOException {
*/
@Test
public void testResultOutsideRange() throws IOException {
- Workbook wb = new HSSFWorkbook();
- try {
+ try (Workbook wb = new HSSFWorkbook()) {
Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0);
cell.setCellFormula("D2:D5"); // IF(TRUE,D2:D5,D2) or OFFSET(D2:D5,0,0) would work too
FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator();
cv = fe.evaluate(cell);
assertEquals(CellType.ERROR, cv.getCellType());
assertEquals(ErrorEval.CIRCULAR_REF_ERROR.getErrorCode(), cv.getErrorValue());
- } finally {
- wb.close();
}
}
@Before
public void setUp() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- try {
+ try (HSSFWorkbook wb = new HSSFWorkbook()) {
HSSFSheet sheet = wb.createSheet("new sheet");
cell11 = sheet.createRow(0).createCell(0);
evaluator = new HSSFFormulaEvaluator(wb);
- } finally {
- wb.close();
}
}
}
private void readbackFormat(String msg, String fmt) throws IOException {
- Workbook wb = _testDataProvider.createWorkbook();
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
DataFormat dataFormat = wb.createDataFormat();
short fmtIdx = dataFormat.getFormat(fmt);
String readbackFmt = dataFormat.getFormat(fmtIdx);
assertEquals(msg, fmt, readbackFmt);
- } finally {
- wb.close();
}
}
@Test
public void testResizeNoColumns() throws IOException {
- Workbook wb = _testDataProvider.createWorkbook();
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet();
-
+
Row row = sheet.createRow(0);
-
+
handleResize(wb, sheet, row);
- } finally {
- wb.close();
}
}
@Test
public void testResizeWithColumns() throws IOException {
- Workbook wb = _testDataProvider.createWorkbook();
- try {
+ try (Workbook wb = _testDataProvider.createWorkbook()) {
Sheet sheet = wb.createSheet();
-
+
Row row = sheet.createRow(0);
row.createCell(0);
-
+
handleResize(wb, sheet, row);
- } finally {
- wb.close();
}
}