]> source.dussan.org Git - poi.git/commitdiff
Ensure streams are closed always, reformat code somewhat
authorDominik Stadler <centic@apache.org>
Fri, 30 Dec 2016 22:12:06 +0000 (22:12 +0000)
committerDominik Stadler <centic@apache.org>
Fri, 30 Dec 2016 22:12:06 +0000 (22:12 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1776647 13f79535-47bb-0310-9956-ffa450edef68

src/java/org/apache/poi/hssf/extractor/OldExcelExtractor.java
src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java
src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
src/java/org/apache/poi/util/FontMetricsDumper.java
src/java/org/apache/poi/util/HexRead.java
src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java
src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java

index c62a3c226fac07875703f06c37de2a60a3b164bc..8cc1d96bd8068f86b16b9a07dfa99caa578ad948 100644 (file)
@@ -90,8 +90,22 @@ public class OldExcelExtractor implements Closeable {
             if (poifs != null) {
                 poifs.close();
             }
+        } catch (IOException e) {
+            // ensure streams are closed correctly
+            if (poifs != null) {
+                poifs.close();
+            }
+
+            throw e;
+        } catch (RuntimeException e) {
+            // ensure streams are closed correctly
+            if (poifs != null) {
+                poifs.close();
+            }
+
+            throw e;
         }
-        
+
         @SuppressWarnings("resource")
         FileInputStream biffStream = new FileInputStream(f); // NOSONAR
         try {
index a8e920dc1179d20718320c8ed236b4f9174f4bb9..6b18f0d9f288c652edce474fc4e79aa2f22c75b7 100644 (file)
@@ -57,9 +57,9 @@ public abstract class ChunkedCipherOutputStream extends FilterOutputStream {
     private final File fileOut;\r
     private final DirectoryNode dir;\r
 \r
-    private long pos = 0;\r
-    private long totalPos = 0;\r
-    private long written = 0;\r
+    private long pos;\r
+    private long totalPos;\r
+    private long written;\r
     \r
     // the cipher can't be final, because for the last chunk we change the padding\r
     // and therefore need to change the cipher too\r
@@ -206,7 +206,7 @@ public abstract class ChunkedCipherOutputStream extends FilterOutputStream {
      *\r
      * @throws BadPaddingException \r
      * @throws IllegalBlockSizeException \r
-     * @throws ShortBufferException \r
+     * @throws ShortBufferException\r
      */\r
     protected int invokeCipher(int posInChunk, boolean doFinal) throws GeneralSecurityException {\r
         byte plain[] = (plainByteFlags.isEmpty()) ? null : chunk.clone();\r
@@ -281,8 +281,11 @@ public abstract class ChunkedCipherOutputStream extends FilterOutputStream {
                 os.write(buf);\r
 \r
                 FileInputStream fis = new FileInputStream(fileOut);\r
-                IOUtils.copy(fis, os);\r
-                fis.close();\r
+                try {\r
+                    IOUtils.copy(fis, os);\r
+                } finally {\r
+                    fis.close();\r
+                }\r
 \r
                 os.close();\r
 \r
index 5372c2af8e656e051d36fdca7d08d0f9bb36be89..2fcd912a9559936cc49b73fa693f6e682a3bbdcf 100644 (file)
@@ -119,8 +119,7 @@ public class StandardEncryptor extends Encryptor implements Cloneable {
     throws IOException, GeneralSecurityException {\r
         createEncryptionInfoEntry(dir);\r
         DataSpaceMapUtils.addDefaultDataSpace(dir);\r
-        OutputStream countStream = new StandardCipherOutputStream(dir);\r
-        return countStream;\r
+        return new StandardCipherOutputStream(dir);\r
     }\r
     \r
     protected class StandardCipherOutputStream extends FilterOutputStream implements POIFSWriterListener {\r
@@ -188,8 +187,11 @@ public class StandardEncryptor extends Encryptor implements Cloneable {
                 leos.writeLong(countBytes);\r
 \r
                 FileInputStream fis = new FileInputStream(fileOut);\r
-                IOUtils.copy(fis, leos);\r
-                fis.close();\r
+                try {\r
+                    IOUtils.copy(fis, leos);\r
+                } finally {\r
+                    fis.close();\r
+                }\r
                 if (!fileOut.delete()) {\r
                     logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+fileOut);\r
                 }\r
index 5147646571b429ade58c639a946b84862340c49d..46d9b127cd9a539019fd40f583db3a8c46fbff47 100644 (file)
@@ -24,15 +24,13 @@ import java.awt.GraphicsEnvironment;
 import java.awt.Toolkit;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.util.Properties;
 
 @SuppressWarnings("deprecation")
-public class FontMetricsDumper
-{
+public class FontMetricsDumper {
     @SuppressForbidden("command line tool")
-    public static void main( String[] args ) throws IOException
-    {
-
+    public static void main(String[] args) throws IOException {
         Properties props = new Properties();
 
         Font[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
@@ -68,13 +66,10 @@ public class FontMetricsDumper
             props.setProperty("font." + fontName + ".widths", widths.toString());
         }
 
-        FileOutputStream fileOut = new FileOutputStream("font_metrics.properties");
-        try
-        {
+        OutputStream fileOut = new FileOutputStream("font_metrics.properties");
+        try {
             props.store(fileOut, "Font Metrics");
-        }
-        finally
-        {
+        } finally {
             fileOut.close();
         }
     }
index 4d9ac97525e788acfe7a8b7d74f7a11716f039f2..e191f5c7d99c9efc83da9690f1a9a042d4e9e8d7 100644 (file)
@@ -25,8 +25,7 @@ import java.util.ArrayList;
  * Utilities to read hex from files.
  * TODO - move to test packages
  */
-public class HexRead
-{
+public class HexRead {
     /**
      * This method reads hex data from a filename and returns a byte array.
      * The file may contain line comments that are preceeded with a # symbol.
@@ -35,16 +34,12 @@ public class HexRead
      * @return The bytes read from the file.
      * @throws IOException If there was a problem while reading the file.
      */
-    public static byte[] readData( String filename ) throws IOException
-    {
+    public static byte[] readData( String filename ) throws IOException {
         File file = new File( filename );
-        FileInputStream stream = new FileInputStream( file );
-        try
-        {
+        InputStream stream = new FileInputStream( file );
+        try {
             return readData( stream, -1 );
-        }
-        finally
-        {
+        } finally {
             stream.close();
         }
     }
@@ -59,16 +54,12 @@ public class HexRead
      * @see #readData(String)
      */
     public static byte[] readData(InputStream stream, String section ) throws IOException {
-
-        try
-        {
+        try {
             StringBuffer sectionText = new StringBuffer();
             boolean inSection = false;
             int c = stream.read();
-            while ( c != -1 )
-            {
-                switch ( c )
-                {
+            while ( c != -1 ) {
+                switch ( c ) {
                     case '[':
                         inSection = true;
                         break;
@@ -87,18 +78,15 @@ public class HexRead
                 }
                 c = stream.read();
             }
-        }
-        finally
-        {
+        } finally {
             stream.close();
         }
+
         throw new IOException( "Section '" + section + "' not found" );
     }
-    public static byte[] readData( String filename, String section ) throws IOException
-    {
-        File file = new File( filename );
-        FileInputStream stream = new FileInputStream( file );
-        return readData(stream, section);
+
+    public static byte[] readData( String filename, String section ) throws IOException {
+        return readData(new FileInputStream( filename ), section);
     }
 
     @SuppressWarnings("fallthrough")
@@ -110,8 +98,7 @@ public class HexRead
         List<Byte> bytes = new ArrayList<Byte>();
         final char a = 'a' - 10;
         final char A = 'A' - 10;
-        while ( true )
-        {
+        while ( true ) {
             int count = stream.read();
             int digitValue = -1;
             if ( '0' <= count && count <= '9' ) {
@@ -131,8 +118,7 @@ public class HexRead
                 b <<= 4;
                 b += (byte) digitValue;
                 characterCount++;
-                if ( characterCount == 2 )
-                {
+                if ( characterCount == 2 ) {
                     bytes.add( Byte.valueOf( b ) );
                     characterCount = 0;
                     b = (byte) 0;
@@ -141,8 +127,7 @@ public class HexRead
         }
         Byte[] polished = bytes.toArray(new Byte[bytes.size()]);
         byte[] rval = new byte[polished.length];
-        for ( int j = 0; j < polished.length; j++ )
-        {
+        for ( int j = 0; j < polished.length; j++ ) {
             rval[j] = polished[j].byteValue();
         }
         return rval;
@@ -156,11 +141,9 @@ public class HexRead
         }
     }
 
-    static private void readToEOL( InputStream stream ) throws IOException
-    {
+    static private void readToEOL( InputStream stream ) throws IOException {
         int c = stream.read();
-        while ( c != -1 && c != '\n' && c != '\r' )
-        {
+        while ( c != -1 && c != '\n' && c != '\r' ) {
             c = stream.read();
         }
     }
index 9ab71ea8ccabc423e3e34a3b813752d400f7099e..c5d2ba325ca12a09e66a8934e1d89378ee96db0a 100644 (file)
@@ -95,8 +95,11 @@ public class VsdxToPng {
         graphics.dispose();
 
         FileOutputStream out = new FileOutputStream(outFile);
-        ImageIO.write(img, "png", out);
-        out.close();
+        try {
+            ImageIO.write(img, "png", out);
+        } finally {
+            out.close();
+        }
     }
 
     public static void renderToPng(XmlVisioDocument document,
index 8a150323f736f1fd8930f4ea309e4f5a91c28b9a..c46867d2ede50b214a7037dab39534967c861032 100644 (file)
@@ -235,6 +235,14 @@ public final class TestOldExcelExtractor {
         } catch (RecordFormatException e) {
             // expected here
         }
+
+        // a POIFS file which is not a Workbook
+        try {
+            new OldExcelExtractor(POIDataSamples.getDocumentInstance().getFile("47304.doc"));
+            fail("Should catch Exception here");
+        } catch (FileNotFoundException e) {
+            // expected here
+        }
     }
 
     @Test