1
0
mirror of https://github.com/apache/poi.git synced 2025-02-15 06:24:58 +00:00

Replace manual close with try-with-resources

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1871590 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2019-12-15 14:53:11 +00:00
parent 2748844549
commit 1a5cec89d8
53 changed files with 322 additions and 608 deletions
src
examples/src/org/apache/poi
hsmf/examples
hssf/usermodel/examples
java/org/apache/poi
ooxml
scratchpad
testcases/org/apache/poi

@ -63,62 +63,56 @@ public class Msg2txt {
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);
}
}
}
}
/**
@ -137,15 +131,9 @@ public class Msg2txt {
}
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());
}
}
/**

@ -173,23 +173,12 @@ public class OfficeDrawing {
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;
}

@ -55,10 +55,8 @@ public class FormulaViewer
* @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) {
@ -70,11 +68,7 @@ public class FormulaViewer
}
}
}
} finally {
is.close();
}
} finally {
fs.close();
}
}

@ -76,11 +76,8 @@ public class HSSFEventFactory {
name = WORKBOOK_DIR_ENTRY_NAMES[0];
}
InputStream in = dir.createDocumentInputStream(name);
try {
try (InputStream in = dir.createDocumentInputStream(name)) {
processEvents(req, in);
} finally {
in.close();
}
}
@ -111,12 +108,9 @@ public class HSSFEventFactory {
*/
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);
}
}
/**

@ -186,11 +186,8 @@ public class StandardEncryptor extends Encryptor implements Cloneable {
// 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);

@ -200,11 +200,8 @@ public class CellElapsedFormatter extends CellFormatter {
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();
}
}

@ -63,11 +63,8 @@ public class CellGeneralFormatter extends CellFormatter {
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

@ -456,11 +456,8 @@ public class CellNumberFormatter extends CellFormatter {
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) {
@ -734,11 +731,8 @@ public class CellNumberFormatter extends CellFormatter {
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);
}

@ -66,11 +66,8 @@ public class FontMetricsDumper {
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();
}
}
}

@ -36,11 +36,8 @@ public class HexRead {
*/
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);
}
}

@ -252,15 +252,12 @@ public class AgileEncryptor extends Encryptor implements Cloneable {
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();

@ -46,17 +46,11 @@ public class XSLFMetroShape {
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);
}
}
}

@ -1459,20 +1459,10 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
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);

@ -112,17 +112,11 @@ public class XWPFEndnotes extends XWPFAbstractFootnotesEndnotes {
@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()) {

@ -90,9 +90,7 @@ public class XWPFFooter extends XWPFHeaderFooter {
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
@ -119,10 +117,6 @@ public class XWPFFooter extends XWPFHeaderFooter {
cursor.dispose();
} catch (Exception e) {
throw new POIXMLException(e);
} finally {
if (is != null) {
is.close();
}
}
}

@ -112,17 +112,11 @@ public class XWPFFootnotes extends XWPFAbstractFootnotesEndnotes {
@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()) {

@ -93,9 +93,7 @@ public class XWPFHeader extends XWPFHeaderFooter {
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
@ -122,10 +120,6 @@ public class XWPFHeader extends XWPFHeaderFooter {
cursor.dispose();
} catch (XmlException e) {
throw new POIXMLException(e);
} finally {
if (is != null) {
is.close();
}
}
}

@ -250,18 +250,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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);
@ -314,7 +306,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
/**
* Adds a new paragraph at the end of the header or footer
*
*
* @return new {@link XWPFParagraph} object
*/
public XWPFParagraph createParagraph() {
@ -323,10 +315,10 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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
@ -337,7 +329,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
bodyElements.add(table);
return table;
}
/**
* Removes a specific paragraph from this header / footer
*
@ -353,11 +345,11 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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)) {
@ -369,7 +361,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
bodyElements.remove(table);
}
}
/**
* Clears all paragraphs and tables from this header / footer
*/
@ -381,7 +373,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
tables.clear();
bodyElements.clear();
}
/**
* add a new paragraph at position of the cursor
*
@ -590,14 +582,14 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
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) {
@ -609,6 +601,6 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
}
}
super.prepareForCommit();
}
}

@ -80,15 +80,12 @@ public class XWPFStyles extends POIXMLDocumentPart {
@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();
}
}

@ -225,16 +225,13 @@ public final class TestPOIXMLDocument {
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();
}
}
@ -243,10 +240,9 @@ public final class TestPOIXMLDocument {
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));
@ -254,20 +250,18 @@ public final class TestPOIXMLDocument {
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();
}
}
@ -315,12 +309,9 @@ public final class TestPOIXMLDocument {
@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();
}
}

@ -55,13 +55,10 @@ public class TestDrawPictureShape {
/** 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();
}
}

@ -102,43 +102,42 @@ public class TestFormulaParser {
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
@ -149,17 +148,14 @@ public class TestFormulaParser {
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("+");
@ -167,8 +163,6 @@ public class TestFormulaParser {
parseExpectedException("IF()");
parseExpectedException("IF("); //no closing paren
parseExpectedException("myFunc(", workbook); //no closing paren
} finally {
wb.close();
}
}

@ -65,9 +65,8 @@ public class TestStructuredReferences {
@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");
@ -75,21 +74,21 @@ public class TestStructuredReferences {
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(
@ -102,11 +101,9 @@ public class TestStructuredReferences {
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();
}
}

@ -184,16 +184,13 @@ public class TestXSSFEventBasedExcelExtractor {
*/
@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");
}
}
/**
@ -206,21 +203,14 @@ public class TestXSSFEventBasedExcelExtractor {
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();
}
}
@ -242,25 +232,18 @@ public class TestXSSFEventBasedExcelExtractor {
"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();
}
}
@ -307,48 +290,35 @@ public class TestXSSFEventBasedExcelExtractor {
"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();
}
}

@ -217,29 +217,23 @@ public class TestXSSFExcelExtractor extends TestCase {
* 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");
}
}
}

@ -37,26 +37,23 @@ public class TestSXSSFDataValidation extends BaseTestDataValidation {
@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();
}
}
}

@ -111,20 +111,17 @@ public final class TestSXSSFSheet extends BaseTestXSheet {
@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();
}
}

@ -61,14 +61,10 @@ public final class TestSheetDataWriter {
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);
}
@ -80,14 +76,10 @@ public final class TestSheetDataWriter {
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("&#xd;&#xa;", text);
}
assertEquals("&#xd;&#xa;", text);
} finally {
IOUtils.closeQuietly(writer);
}

@ -196,8 +196,7 @@ public final class TestXSSFComment extends BaseTestCellComment {
@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);
@ -241,35 +240,32 @@ public final class TestXSSFComment extends BaseTestCellComment {
+ ", 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);
@ -294,7 +290,7 @@ public final class TestXSSFComment extends BaseTestCellComment {
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());
*/
@ -302,14 +298,9 @@ public final class TestXSSFComment extends BaseTestCellComment {
// 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();
}
}

@ -175,12 +175,9 @@ public class TestXSSFDrawing {
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();
}

@ -33,23 +33,22 @@ public class TestXSSFSheetMergeRegions {
@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;
}
@ -57,8 +56,6 @@ public class TestXSSFSheetMergeRegions {
// 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();
}
}

@ -27,28 +27,27 @@ import org.junit.Test;
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());
@ -59,7 +58,7 @@ public class TestXSSFTextParagraph {
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());
@ -69,7 +68,7 @@ public class TestXSSFTextParagraph {
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);
@ -78,19 +77,19 @@ public class TestXSSFTextParagraph {
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);
@ -112,7 +111,7 @@ public class TestXSSFTextParagraph {
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);
@ -120,7 +119,7 @@ public class TestXSSFTextParagraph {
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);
@ -128,13 +127,13 @@ public class TestXSSFTextParagraph {
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);
@ -152,13 +151,13 @@ public class TestXSSFTextParagraph {
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);
@ -170,7 +169,7 @@ public class TestXSSFTextParagraph {
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);
@ -187,12 +186,10 @@ public class TestXSSFTextParagraph {
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();
}
}
}

@ -27,11 +27,10 @@ import org.junit.Test;
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();
@ -41,17 +40,17 @@ public class TestXSSFTextRun {
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);
@ -66,7 +65,7 @@ public class TestXSSFTextRun {
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);
@ -74,28 +73,28 @@ public class TestXSSFTextRun {
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());
@ -113,7 +112,7 @@ public class TestXSSFTextRun {
assertTrue(run.isSubscript());
run.setSubscript(false);
assertFalse(run.isSubscript());
assertEquals(TextCap.NONE, run.getTextCap());
assertFalse(run.isBold());
@ -133,10 +132,8 @@ public class TestXSSFTextRun {
assertTrue(run.isUnderline());
run.setUnderline(false);
assertFalse(run.isUnderline());
assertNotNull(run.toString());
} finally {
wb.close();
}
}
}

@ -112,11 +112,8 @@ public class TestXSSFVMLDrawing {
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);
@ -150,11 +147,8 @@ public class TestXSSFVMLDrawing {
@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);
@ -168,11 +162,8 @@ public class TestXSSFVMLDrawing {
@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;

@ -36,14 +36,14 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
*/
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:");
@ -53,11 +53,11 @@ public final class VSDDumper {
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() {
@ -65,7 +65,7 @@ public final class VSDDumper {
ps.println();
dumpStream(hdgf.getTrailerStream(), 0);
}
private void dumpStream(Stream stream, int indent) {
Pointer ptr = stream.getPointer();
dumpVal("Stream at", ptr.getOffset(), indent);
@ -111,7 +111,7 @@ public final class VSDDumper {
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);
@ -130,6 +130,6 @@ public final class VSDDumper {
ps.print(tabs.substring(0,indent));
ps.print(label);
ps.print('\t');
ps.println(value);
ps.println(value);
}
}

@ -52,14 +52,11 @@ public final class HMEFDumper {
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();
}
}
}

@ -93,19 +93,16 @@ public final class HMEFContentsExtractor {
}
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();
}
}
@ -156,11 +153,8 @@ public final class HMEFContentsExtractor {
// 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());
}
}
}

@ -65,30 +65,27 @@ public final class PICT extends Metafile {
}
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();
}

@ -50,7 +50,7 @@ import org.w3c.dom.Text;
/**
* Converts xls files (97-2007) to XSL FO.
*
*
* @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
*/
@Beta
@ -69,7 +69,7 @@ public class ExcelToFoConverter extends AbstractExcelConverter
/**
* Java main() interface to interact with {@link ExcelToFoConverter}
*
*
* <p>
* Usage: ExcelToHtmlConverter infile outfile
* </p>
@ -97,21 +97,18 @@ public class ExcelToFoConverter extends AbstractExcelConverter
/**
* 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();
}
}
@ -182,7 +179,7 @@ public class ExcelToFoConverter extends AbstractExcelConverter
/**
* 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
*/
@ -453,7 +450,7 @@ public class ExcelToFoConverter extends AbstractExcelConverter
/**
* 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,
@ -714,7 +711,7 @@ public class ExcelToFoConverter extends AbstractExcelConverter
/**
* 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
*/

@ -478,11 +478,8 @@ public class AbstractWordUtils
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);
}
}

@ -134,11 +134,8 @@ public final class TestVisioExtractor {
}
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();
}
}
}

@ -166,9 +166,9 @@ public final class TestCompressedRTF {
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")) {
@ -196,7 +196,7 @@ public final class TestCompressedRTF {
}
// 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);

@ -44,12 +44,9 @@ public class HSLFTestDataSamples {
}
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);
}
}
/**

@ -45,31 +45,22 @@ public final class TestEncryptedFile {
@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();
}
}
}
}

@ -67,16 +67,13 @@ public final class TestCurrentUserAtom {
@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

@ -366,12 +366,9 @@ public final class TestPictures {
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);

@ -157,13 +157,12 @@ public final class TestFormulaParser {
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];
@ -192,8 +191,7 @@ public final class TestFormulaParser {
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());
@ -210,11 +208,7 @@ public final class TestFormulaParser {
wb2.write(fos);
fos.close();
*/
} finally {
wb2.close();
}
} finally {
wb.close();
}
}
@ -779,21 +773,18 @@ public final class TestFormulaParser {
}
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();
}
}

@ -158,21 +158,15 @@ public final class TestLbsDataSubRecord extends TestCase {
"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();
}
}
}

@ -116,17 +116,11 @@ public class TestDataSource extends TestCase
}
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 {

@ -226,8 +226,7 @@ public class TestWorkbookEvaluator {
*/
@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();
@ -249,8 +248,6 @@ public class TestWorkbookEvaluator {
cv = fe.evaluate(cell);
assertEquals(CellType.ERROR, cv.getCellType());
assertEquals(ErrorEval.CIRCULAR_REF_ERROR.getErrorCode(), cv.getErrorValue());
} finally {
wb.close();
}
}

@ -44,13 +44,10 @@ public final class TestFixed {
@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();
}
}

@ -112,14 +112,11 @@ public abstract class BaseTestDataFormat {
}
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();
}
}

@ -76,30 +76,24 @@ public abstract class BaseTestPicture {
@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();
}
}