]> source.dussan.org Git - poi.git/commitdiff
Replace manual close with try-with-resources
authorDominik Stadler <centic@apache.org>
Sun, 15 Dec 2019 14:53:11 +0000 (14:53 +0000)
committerDominik Stadler <centic@apache.org>
Sun, 15 Dec 2019 14:53:11 +0000 (14:53 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1871590 13f79535-47bb-0310-9956-ffa450edef68

53 files changed:
src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java
src/java/org/apache/poi/hssf/dev/FormulaViewer.java
src/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java
src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
src/java/org/apache/poi/ss/format/CellElapsedFormatter.java
src/java/org/apache/poi/ss/format/CellGeneralFormatter.java
src/java/org/apache/poi/ss/format/CellNumberFormatter.java
src/java/org/apache/poi/util/FontMetricsDumper.java
src/java/org/apache/poi/util/HexRead.java
src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java
src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFEndnotes.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java
src/ooxml/testcases/org/apache/poi/ooxml/TestPOIXMLDocument.java
src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java
src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java
src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java
src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java
src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java
src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java
src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java
src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSheetDataWriter.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java
src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java
src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java
src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java
src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java
src/scratchpad/src/org/apache/poi/hssf/converter/ExcelToFoConverter.java
src/scratchpad/src/org/apache/poi/hwpf/converter/AbstractWordUtils.java
src/scratchpad/testcases/org/apache/poi/hdgf/extractor/TestVisioExtractor.java
src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java
src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java
src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java
src/scratchpad/testcases/org/apache/poi/hslf/record/TestCurrentUserAtom.java
src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java
src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java
src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
src/testcases/org/apache/poi/poifs/nio/TestDataSource.java
src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java
src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java

index 6c097df1065085e0d9b06e57d268dd2064d813ac..83d470128919bb6e2a5b483df7e901a74485c3af 100644 (file)
@@ -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());
+        }
        }
        
        /**
index ce4935230c1b4e484c3579407b86f45838341de5..39b388ea32c0439a7c51933345636287a2e523c9 100644 (file)
@@ -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;
     }
index b5f0d3f5f02e1f964cfb08037fdd5f386bbf1864..90a30151661c2e61ef6eaf78a785cb2a721ec065 100644 (file)
@@ -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();
         }
     }
     
index 32463a55e2383a585695608abedeed91b24c3280..1283ae517bb6f7b1af8fcb6de9718adf0f918462 100644 (file)
@@ -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);
+        }
        }
 
        /**
index e3662b40ba2acc8e02ace339d3a2aaa336b882bf..4c4ca2a3fb360cb7f4d00a6a3b18aeb8252272da 100644 (file)
@@ -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);
index 45c9b92f687ac51884ef1903b3cdefcb0b0b327b..4a5e370e86c0b292d8391f6c3f8932999eefad70 100644 (file)
@@ -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();
         }
     }
 
index 37f202c9dd111454dd9ca28828512ad41189c88c..2233c284aaf5a391fc5f85ef11a4a244efc07bb7 100644 (file)
@@ -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
index 6ab581d52d40c9d9db2937e1f0b573ae44a6a3d1..7a3070a542db04f091ff9f22213a4b8166abf580 100644 (file)
@@ -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);
     }
index 46d9b127cd9a539019fd40f583db3a8c46fbff47..321f0d5ea912dda33c2afa1e24c4bddcc84f53c2 100644 (file)
@@ -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();
         }
     }
 }
index a7bec002f9269bf30e05667270cc4f9139175234..c6a5fb4f73f80ab230528198959ebbf3312704b5 100644 (file)
@@ -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);
         }
     }
 
index d972476d6385a2f712c0d41ffab3679629295e9b..93a412225f04b6ea458b0901c034a1d15741e07e 100644 (file)
@@ -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();
index e807ab2f0c5f61f0a5e6d9c168e250f819e66017..3d06e46c4e871e7ee63a935037b7ec8480d8dbe2 100644 (file)
@@ -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);
         }
     }
 }
index 5227ee37428a6e9d840a9f6d4915a159b2a59776..5313ea735a9a2c5b55682c999a8697c9322e59d2 100644 (file)
@@ -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);
index deb76de2cb1378745c48f3f19502d7f48310b96e..3a62ce20f3626b284c7bbd5022e1de3a9a52de1d 100644 (file)
@@ -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()) {
index c48e35501fd1c3d0bbee2dab91097d359e328aef..07375a223bc1c088f8e712a9bb3a2751296c52c2 100644 (file)
@@ -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();
-            }
         }
     }
 
index 144c692dcc1265d63ba9902151c7a5e7f8bd3564..824050579ccae20d7a124f974a354aee9b8a6596 100644 (file)
@@ -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()) {
index 54c3ea9a225e362712832460f096dbac61f62e9a..fe12c8df70aed19f8b084077a821adb696cab34d 100644 (file)
@@ -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();
-            }
         }
     }
 
index 2c1d6b80b59ddf48bce33f8aaa9da306c8eedaf0..09fbe95c6e57ec398766190c4cf71eb9b28da902 100644 (file)
@@ -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();
-        
+
     }
 }
index fcc484091ff9a772fe6727b9b6fc7ddff2206ae2..1a2d6bd7065aebb26e4551e9dc3b17c82db31056 100644 (file)
@@ -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();
         }
     }
 
index 446b33ec0ca5fa11b1f4c2bfc9f122916afbb7a2..bc00b1d0a6ec40d8686359027d34f9a3abe621bf 100644 (file)
@@ -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();
         }
     }
 
index d6c32bfd82c1d01f6318ca8ec60a067c4162f1e2..8534610eb8035c1a6cb9a4d49cfb45856a96a884 100644 (file)
@@ -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();
         }
     }
 
index a9d739796531efa297a71b1d36cebb52dce9ce6b..36c96011d27e5ecc4e4ebd216216e992e778c387 100644 (file)
@@ -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();
         }
     }
     
index 2599db4e0db37a6aeaa9a1feb4abc2ee61284b30..547555dce7be3bde0709b724f8ddc207284272e3 100644 (file)
@@ -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();
         }
     }
 
index fe20ba12ca4e7b932f5f7d50ef633fff592b65ac..02505e0bb22b7292e9e4a63a8c581e197bb8199d 100644 (file)
@@ -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();
         }
     }
 
index 2cc3b431e55413370a68cd525a854bd6b866ea6d..ed61a060f1a70ba0b5cab2c922552669c49f50e4 100644 (file)
@@ -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");
+        }
 
        }
 }
index c383c1c7bb7d0ddc814bfa78af5263ae594365cf..947ff655fda00041b6e4184bace6df0f3d173645 100644 (file)
@@ -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();
         }
     }
 }
index f6fbd85877c11fa579ccf078da38e90c509d39c3..4bc9bd519161c8d7bd6bcaae41d7d0d9c2859c12 100644 (file)
@@ -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();
         }
     }
 
index f2c3d85f6f94548f6f1e3fac672a8048ff18e4f0..e69aacf2d5c69e77ea5380ee466b1946f78c86c5 100644 (file)
@@ -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);
         }
index e1afacbc55f21e358c995873ff22fea1e69134c9..d8d7554d4707694b1c2f6e8ee2c613f57bec7257 100644 (file)
@@ -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();
         }
     }
 
index e22f707b5ec47a3b55fc8c1ffd44549d611e6f7e..714202e599b38b9a0bde2a6fa0dae91e4382ea2e 100644 (file)
@@ -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();
     }
index 59b1a08aa0e11e6264fce2d8d52c7c7fe8f81b90..f4a4ed03199ded17b0d2d0f9434f754fb9465b5c 100644 (file)
@@ -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();
         }
     }
 
index 9ba2aa9fc3b1c301e9bb3e499945e570df256f69..75eec4feb2c9ea7d58e10808386b8010a33bc478 100644 (file)
@@ -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();
         }
     }
 }
index e599e1761e43733018f383b343c0f90383b614fe..9877772c658023b66d7b9ef414b05bb04cffdced 100644 (file)
@@ -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();
         }
     }
 }
index b3025e54a5a53c2bac37c9745359828d03a811b1..4bc178d2ca27054d428b436a0f9fbb89f40b08c2 100644 (file)
@@ -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;
index a7b1586821df7deb76ed2252627f194cfa0d8ab8..a8798a8d2fec4254705ba258b7fdf6690da345de 100644 (file)
@@ -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);
     }
 }
index b067ce355f2de7d664e2cebca323261be5be4d47..e9699526482d21e84dc1b97f78ad3952b34fc972 100644 (file)
@@ -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();
+          }
       }
    }
 
index 0abcd771e9c72e5ce45958b2e449f472dad88161..4c95ecb19f16bb627002da4800300580d2281eb4 100644 (file)
@@ -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());
             }
         }
     }
index 59670e1298e9b293c66ab4f9c4c71882f9a0dd48..e4fedb4d981b1e1bd6af63283dd30dd72f1087fe 100644 (file)
@@ -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)) >=) {
-                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();
     }
index 0bdaf57c65d2aae7893e4c3ef336f0df276fb911..d9c1929e64152e1bea99b5330a3412f5ce7e4301 100644 (file)
@@ -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
      */
index 0e3c8695ab9cc20003ecfea959ee8a727e10cad2..b1b227c2d39b7706a3614dcce009f4866d114bd5 100644 (file)
@@ -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);
         }
     }
 
index 69f61e29fb840251a0d5aec9e449a26751206770..a1db11c170c9a82cfdc7bf277e8138cd458ca85b 100644 (file)
@@ -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();
         }
     }
 }
index 959079a758eade66dfb28347a549e2869f353fee..8c4edf564cdc273598d83506427959a2c696d949 100644 (file)
@@ -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);
index 90fb3ad81441292fc5a7bc98c6b5b13e93b9326c..0ec92bb6a20393e7573e3fe3653cb3c6d5ef191e 100644 (file)
@@ -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);
+        }
        }
 
        /**
index a8060e7d3ad7972bcb47ec5eb2bf7b87a1d4bd93..ffecf2a58a1e0dfdb17bf389831946c2036222e7 100644 (file)
@@ -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();
-               }
+        }
        }
 }
index 7ce0f6cbd18f93036bcb29024d53b9179bed0f2d..e9eff122abf6e361653a5f787c4b22fb50301016 100644 (file)
@@ -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
index f60b010ef76d1711c3af256b15814b2825d64e96..fc6ac11bc13d5e683098a5b8db12ae8b818450e6 100644 (file)
@@ -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);
index ee6963063882b37c04155f7ac2c01794d5f128bf..349043b9c9e2834899d19fce1501e9745710c3ce 100644 (file)
@@ -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();
         }
     }
 
index 0f535484064d8a8d560486e40de885cd046f1730..5d89e627d931dfa1124462d36b193eb07ff9039b 100644 (file)
@@ -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();
         }
     }
 }
index 1bc3f4532eb780f3cc91017a8012208f0ef0c1b9..4b3932bad17ee7e78f47889e6a33e089ef72eac1 100644 (file)
@@ -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 {
index be2cc54cde07d493bebb2fe5b392aec9ad15c257..06c37dc0250641105446b26d21e1412063043327 100644 (file)
@@ -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();
         }
     }
 
index 6cc50e742bccbef0b1d84a81b3e955a4d8231efa..462acd3115fea9ba9bb58d9f9dddc0b81735cc1c 100644 (file)
@@ -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();
         }
     }
 
index 70ba300b7147624f248c4246c91c7a5907148543..2208cf5f49359dae79b4c581fba02d3e11179d04 100644 (file)
@@ -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();
         }
     }
 
index d7c68940ce5dc95d73935e86989c7004ecd70a4b..555a2324804e3a8678693e2b009b7811b2fecfe1 100644 (file)
@@ -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();
         }
     }