aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorDominik Stadler <centic@apache.org>2019-12-15 14:53:11 +0000
committerDominik Stadler <centic@apache.org>2019-12-15 14:53:11 +0000
commit1a5cec89d8d36f2a7cd5643b221befd57fa515b7 (patch)
tree6a6719f33761c08a719599393ca310eafcb7834e /src
parent2748844549b50dc11e8ef19dcd506c820c1a1e19 (diff)
downloadpoi-1a5cec89d8d36f2a7cd5643b221befd57fa515b7.tar.gz
poi-1a5cec89d8d36f2a7cd5643b221befd57fa515b7.zip
Replace manual close with try-with-resources
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1871590 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src')
-rw-r--r--src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java118
-rw-r--r--src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java21
-rw-r--r--src/java/org/apache/poi/hssf/dev/FormulaViewer.java10
-rw-r--r--src/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java14
-rw-r--r--src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java5
-rw-r--r--src/java/org/apache/poi/ss/format/CellElapsedFormatter.java5
-rw-r--r--src/java/org/apache/poi/ss/format/CellGeneralFormatter.java5
-rw-r--r--src/java/org/apache/poi/ss/format/CellNumberFormatter.java10
-rw-r--r--src/java/org/apache/poi/util/FontMetricsDumper.java5
-rw-r--r--src/java/org/apache/poi/util/HexRead.java7
-rw-r--r--src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java7
-rw-r--r--src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java10
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java12
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFEndnotes.java8
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java8
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java8
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java8
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java34
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java5
-rw-r--r--src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java27
-rw-r--r--src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java5
-rw-r--r--src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java32
-rw-r--r--src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java19
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java74
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java34
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java11
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java9
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java20
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java27
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java5
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java17
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java49
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java45
-rw-r--r--src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java15
-rw-r--r--src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java20
-rw-r--r--src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java13
-rw-r--r--src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java16
-rw-r--r--src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java17
-rw-r--r--src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToFoConverter.java19
-rw-r--r--src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordUtils.java7
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java5
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java8
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java9
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java21
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java17
-rw-r--r--src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java7
-rw-r--r--src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java21
-rw-r--r--src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java14
-rw-r--r--src/testcases/org/apache/poi/poifs/nio/TestDataSource.java16
-rw-r--r--src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java5
-rw-r--r--src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java5
-rw-r--r--src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java5
-rw-r--r--src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java18
53 files changed, 323 insertions, 609 deletions
diff --git a/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java b/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java
index 6c097df106..83d4701289 100644
--- a/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java
+++ b/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java
@@ -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());
+ }
}
/**
diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java
index ce4935230c..39b388ea32 100644
--- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java
+++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java
@@ -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;
}
diff --git a/src/java/org/apache/poi/hssf/dev/FormulaViewer.java b/src/java/org/apache/poi/hssf/dev/FormulaViewer.java
index b5f0d3f5f0..90a3015166 100644
--- a/src/java/org/apache/poi/hssf/dev/FormulaViewer.java
+++ b/src/java/org/apache/poi/hssf/dev/FormulaViewer.java
@@ -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();
}
}
diff --git a/src/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java b/src/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java
index 32463a55e2..1283ae517b 100644
--- a/src/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java
+++ b/src/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java
@@ -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);
+ }
}
/**
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
index e3662b40ba..4c4ca2a3fb 100644
--- a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
+++ b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
@@ -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);
diff --git a/src/java/org/apache/poi/ss/format/CellElapsedFormatter.java b/src/java/org/apache/poi/ss/format/CellElapsedFormatter.java
index 45c9b92f68..4a5e370e86 100644
--- a/src/java/org/apache/poi/ss/format/CellElapsedFormatter.java
+++ b/src/java/org/apache/poi/ss/format/CellElapsedFormatter.java
@@ -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();
}
}
diff --git a/src/java/org/apache/poi/ss/format/CellGeneralFormatter.java b/src/java/org/apache/poi/ss/format/CellGeneralFormatter.java
index 37f202c9dd..2233c284aa 100644
--- a/src/java/org/apache/poi/ss/format/CellGeneralFormatter.java
+++ b/src/java/org/apache/poi/ss/format/CellGeneralFormatter.java
@@ -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
diff --git a/src/java/org/apache/poi/ss/format/CellNumberFormatter.java b/src/java/org/apache/poi/ss/format/CellNumberFormatter.java
index 6ab581d52d..7a3070a542 100644
--- a/src/java/org/apache/poi/ss/format/CellNumberFormatter.java
+++ b/src/java/org/apache/poi/ss/format/CellNumberFormatter.java
@@ -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);
}
diff --git a/src/java/org/apache/poi/util/FontMetricsDumper.java b/src/java/org/apache/poi/util/FontMetricsDumper.java
index 46d9b127cd..321f0d5ea9 100644
--- a/src/java/org/apache/poi/util/FontMetricsDumper.java
+++ b/src/java/org/apache/poi/util/FontMetricsDumper.java
@@ -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();
}
}
}
diff --git a/src/java/org/apache/poi/util/HexRead.java b/src/java/org/apache/poi/util/HexRead.java
index a7bec002f9..c6a5fb4f73 100644
--- a/src/java/org/apache/poi/util/HexRead.java
+++ b/src/java/org/apache/poi/util/HexRead.java
@@ -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);
}
}
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java
index d972476d63..93a412225f 100644
--- a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java
+++ b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java
@@ -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();
diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java
index e807ab2f0c..3d06e46c4e 100644
--- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java
+++ b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java
@@ -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);
}
}
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
index 5227ee3742..5313ea735a 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
@@ -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);
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFEndnotes.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFEndnotes.java
index deb76de2cb..3a62ce20f3 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFEndnotes.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFEndnotes.java
@@ -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()) {
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java
index c48e35501f..07375a223b 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java
@@ -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();
- }
}
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java
index 144c692dcc..824050579c 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java
@@ -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()) {
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java
index 54c3ea9a22..fe12c8df70 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java
@@ -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();
- }
}
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
index 2c1d6b80b5..09fbe95c6e 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
@@ -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();
-
+
}
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java
index fcc484091f..1a2d6bd706 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java
index 446b33ec0c..bc00b1d0a6 100644
--- a/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java
+++ b/src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java b/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java
index d6c32bfd82..8534610eb8 100644
--- a/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java
+++ b/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java b/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java
index a9d7397965..36c96011d2 100644
--- a/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java
+++ b/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java b/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java
index 2599db4e0d..547555dce7 100644
--- a/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java
+++ b/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java
index fe20ba12ca..02505e0bb2 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java
index 2cc3b431e5..ed61a060f1 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java
@@ -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");
+ }
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java
index c383c1c7bb..947ff655fd 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java
@@ -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();
}
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java
index f6fbd85877..4bc9bd5191 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java
index f2c3d85f6f..e69aacf2d5 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java
@@ -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);
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java
index e1afacbc55..d8d7554d47 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java
index e22f707b5e..714202e599 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java
@@ -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();
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java
index 59b1a08aa0..f4a4ed0319 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java
@@ -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();
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java
index 9ba2aa9fc3..75eec4feb2 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java
@@ -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();
}
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java
index e599e1761e..9877772c65 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java
@@ -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();
}
}
}
diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
index b3025e54a5..4bc178d2ca 100644
--- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
+++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
@@ -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;
diff --git a/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java b/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java
index a7b1586821..a8798a8d2f 100644
--- a/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java
+++ b/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java
@@ -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);
}
}
diff --git a/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java b/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java
index b067ce355f..e969952648 100644
--- a/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java
+++ b/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java
@@ -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();
+ }
}
}
diff --git a/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java b/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java
index 0abcd771e9..4c95ecb19f 100644
--- a/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java
+++ b/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java
@@ -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());
}
}
}
diff --git a/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java b/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java
index 59670e1298..e4fedb4d98 100644
--- a/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java
+++ b/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java
@@ -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();
}
diff --git a/src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToFoConverter.java b/src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToFoConverter.java
index 0bdaf57c65..d9c1929e64 100644
--- a/src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToFoConverter.java
+++ b/src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToFoConverter.java
@@ -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
*/
diff --git a/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordUtils.java b/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordUtils.java
index 0e3c8695ab..b1b227c2d3 100644
--- a/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordUtils.java
+++ b/src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordUtils.java
@@ -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);
}
}
diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java b/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java
index 69f61e29fb..a1db11c170 100644
--- a/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java
+++ b/src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java
@@ -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();
}
}
}
diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java
index 959079a758..8c4edf564c 100644
--- a/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java
+++ b/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java
@@ -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);
diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java b/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java
index 90fb3ad814..0ec92bb6a2 100644
--- a/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java
+++ b/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java
@@ -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);
+ }
}
/**
diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java
index a8060e7d3a..ffecf2a58a 100644
--- a/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java
+++ b/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java
@@ -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();
- }
+ }
}
}
diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java
index 7ce0f6cbd1..e9eff122ab 100644
--- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java
+++ b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java
@@ -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
diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java
index f60b010ef7..fc6ac11bc1 100644
--- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java
+++ b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java
@@ -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);
diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
index ee69630638..349043b9c9 100644
--- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
+++ b/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
@@ -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();
}
}
diff --git a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
index 0f53548406..5d89e627d9 100644
--- a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
+++ b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
@@ -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();
}
}
}
diff --git a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
index 1bc3f4532e..4b3932bad1 100644
--- a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
+++ b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
@@ -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 {
diff --git a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java b/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java
index be2cc54cde..06c37dc025 100644
--- a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java
+++ b/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java
@@ -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();
}
}
diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java
index 6cc50e742b..462acd3115 100644
--- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java
+++ b/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java
@@ -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();
}
}
diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java
index 70ba300b71..2208cf5f49 100644
--- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java
+++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java
@@ -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();
}
}
diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java
index d7c68940ce..555a232480 100644
--- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java
+++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java
@@ -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();
}
}