Author: kiwiwings
Date: Sat Nov 30 23:00:08 2019
New Revision: 1870653

URL: http://svn.apache.org/viewvc?rev=1870653&view=rev
Log:
Sonar fixes - use try-with-resources

Modified:
    
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java
    poi/trunk/src/examples/src/org/apache/poi/hssf/view/SViewer.java
    
poi/trunk/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java
    
poi/trunk/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java
    poi/trunk/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java
    poi/trunk/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java
    
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java
    
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
    poi/trunk/src/java/org/apache/poi/poifs/dev/POIFSLister.java
    poi/trunk/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java
    poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java
    poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java
    
poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java
    poi/trunk/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java
    poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java
    poi/trunk/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java
    
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java
    
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java
    poi/trunk/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java
    
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
    poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java
    poi/trunk/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java

Modified: 
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java 
(original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java 
Sat Nov 30 23:00:08 2019
@@ -62,30 +62,30 @@ public class OOXMLPasswordsTry implement
     }
     
     public String tryAll(File wordfile) throws IOException, 
GeneralSecurityException {
-        // Load
-        BufferedReader r = new BufferedReader(new FileReader(wordfile));
-        long start = System.currentTimeMillis();
-        int count = 0;
-        
-        // Try each password in turn, reporting progress
         String valid = null;
-        String password;
-        while ((password = r.readLine()) != null) {
-            if (isValid(password)) {
-                valid = password;
-                break;
-            }
-            count++;
-            
-            if (count % 1000 == 0) {
-                int secs = (int)((System.currentTimeMillis() - start) / 1000);
-                System.out.println("Done " + count + " passwords, " +
-                                   secs + " seconds, last password " + 
password);
+        // Load
+        try (BufferedReader r = new BufferedReader(new FileReader(wordfile))) {
+            long start = System.currentTimeMillis();
+            int count = 0;
+
+            // Try each password in turn, reporting progress
+            String password;
+            while ((password = r.readLine()) != null) {
+                if (isValid(password)) {
+                    valid = password;
+                    break;
+                }
+                count++;
+
+                if (count % 1000 == 0) {
+                    int secs = (int) ((System.currentTimeMillis() - start) / 
1000);
+                    System.out.println("Done " + count + " passwords, " +
+                                               secs + " seconds, last password 
" + password);
+                }
             }
+
         }
-        
         // Tidy and return (null if no match)
-        r.close();
         return valid;
     }
     public boolean isValid(String password) throws GeneralSecurityException {
@@ -103,10 +103,11 @@ public class OOXMLPasswordsTry implement
         
         System.out.println("Trying passwords from " + words + " against " + 
ooxml);
         System.out.println();
-        
-        OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml);
-        String password = pt.tryAll(words);
-        pt.close();
+
+        String password;
+        try (OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml)) {
+            password = pt.tryAll(words);
+        }
         
         System.out.println();
         if (password == null) {

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java 
Sat Nov 30 23:00:08 2019
@@ -46,78 +46,76 @@ public final class DataExtraction {
             return;
         }
 
-        FileInputStream is = new FileInputStream(args[0]);
-        HSLFSlideShow ppt = new HSLFSlideShow(is);
-        is.close();
-
-        //extract all sound files embedded in this presentation
-        HSLFSoundData[] sound = ppt.getSoundData();
-        for (HSLFSoundData aSound : sound) {
-            String type = aSound.getSoundType();  //*.wav
-            String name = aSound.getSoundName();  //typically file name
-            byte[] data = aSound.getData();       //raw bytes
-
-            //save the sound  on disk
-            FileOutputStream out = new FileOutputStream(name + type);
-            out.write(data);
-            out.close();
-        }
+        try (FileInputStream is = new FileInputStream(args[0]);
+            HSLFSlideShow ppt = new HSLFSlideShow(is)) {
+
+            //extract all sound files embedded in this presentation
+            HSLFSoundData[] sound = ppt.getSoundData();
+            for (HSLFSoundData aSound : sound) {
+                String type = aSound.getSoundType();  //*.wav
+                String name = aSound.getSoundName();  //typically file name
+                byte[] data = aSound.getData();       //raw bytes
+
+                //save the sound  on disk
+                try (FileOutputStream out = new FileOutputStream(name + type)) 
{
+                    out.write(data);
+                }
+            }
 
-        int oleIdx=-1, picIdx=-1;
-        for (HSLFSlide slide : ppt.getSlides()) {
-            //extract embedded OLE documents
-            for (HSLFShape shape : slide.getShapes()) {
-                if (shape instanceof HSLFObjectShape) {
-                    oleIdx++;
-                    HSLFObjectShape ole = (HSLFObjectShape) shape;
-                    HSLFObjectData data = ole.getObjectData();
-                    String name = ole.getInstanceName();
-                    if ("Worksheet".equals(name)) {
-
-                        //read xls
-                        @SuppressWarnings({ "unused", "resource" })
-                        HSSFWorkbook wb = new 
HSSFWorkbook(data.getInputStream());
-
-                    } else if ("Document".equals(name)) {
-                        HWPFDocument doc = new 
HWPFDocument(data.getInputStream());
-                        //read the word document
-                        Range r = doc.getRange();
-                        for(int k = 0; k < r.numParagraphs(); k++) {
-                            Paragraph p = r.getParagraph(k);
-                            System.out.println(p.text());
-                         }
-
-                        //save on disk
-                        FileOutputStream out = new FileOutputStream(name + 
"-("+(oleIdx)+").doc");
-                        doc.write(out);
-                        out.close();
-                        doc.close();
-                     }  else {
-                        FileOutputStream out = new 
FileOutputStream(ole.getProgId() + "-"+(oleIdx+1)+".dat");
-                        InputStream dis = data.getInputStream();
-                        byte[] chunk = new byte[2048];
-                        int count;
-                        while ((count = dis.read(chunk)) >= 0) {
-                          out.write(chunk,0,count);
+            int oleIdx = -1, picIdx = -1;
+            for (HSLFSlide slide : ppt.getSlides()) {
+                //extract embedded OLE documents
+                for (HSLFShape shape : slide.getShapes()) {
+                    if (shape instanceof HSLFObjectShape) {
+                        oleIdx++;
+                        HSLFObjectShape ole = (HSLFObjectShape) shape;
+                        HSLFObjectData data = ole.getObjectData();
+                        String name = ole.getInstanceName();
+                        if ("Worksheet".equals(name)) {
+
+                            //read xls
+                            @SuppressWarnings({"unused", "resource"})
+                            HSSFWorkbook wb = new 
HSSFWorkbook(data.getInputStream());
+
+                        } else if ("Document".equals(name)) {
+                            try (HWPFDocument doc = new 
HWPFDocument(data.getInputStream())) {
+                                //read the word document
+                                Range r = doc.getRange();
+                                for (int k = 0; k < r.numParagraphs(); k++) {
+                                    Paragraph p = r.getParagraph(k);
+                                    System.out.println(p.text());
+                                }
+
+                                //save on disk
+                                try (FileOutputStream out = new 
FileOutputStream(name + "-(" + (oleIdx) + ").doc")) {
+                                    doc.write(out);
+                                }
+                            }
+                        } else {
+                            try (FileOutputStream out = new 
FileOutputStream(ole.getProgId() + "-" + (oleIdx + 1) + ".dat");
+                                InputStream dis = data.getInputStream()) {
+                                byte[] chunk = new byte[2048];
+                                int count;
+                                while ((count = dis.read(chunk)) >= 0) {
+                                    out.write(chunk, 0, count);
+                                }
+                            }
+                        }
+                    }
+
+                    //Pictures
+                    else if (shape instanceof HSLFPictureShape) {
+                        picIdx++;
+                        HSLFPictureShape p = (HSLFPictureShape) shape;
+                        HSLFPictureData data = p.getPictureData();
+                        String ext = data.getType().extension;
+                        try (FileOutputStream out = new 
FileOutputStream("pict-" + picIdx + ext)) {
+                            out.write(data.getData());
                         }
-                        is.close();
-                        out.close();
                     }
-                }
-                
-                //Pictures
-                else if (shape instanceof HSLFPictureShape) {
-                    picIdx++;
-                    HSLFPictureShape p = (HSLFPictureShape) shape;
-                    HSLFPictureData data = p.getPictureData();
-                    String ext = data.getType().extension;
-                    FileOutputStream out = new FileOutputStream("pict-" + 
picIdx + ext);
-                    out.write(data.getData());
-                    out.close();
                 }
             }
         }
-        ppt.close();
     }
 
     private static void usage(){

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java Sat 
Nov 30 23:00:08 2019
@@ -31,47 +31,44 @@ import org.apache.poi.hslf.usermodel.HSL
 
 /**
  * Demonstrates how to read hyperlinks from  a presentation
- *
- * @author Yegor Kozlov
  */
 public final class Hyperlinks {
 
     public static void main(String[] args) throws Exception {
         for (String arg : args) {
-            FileInputStream is = new FileInputStream(arg);
-            HSLFSlideShow ppt = new HSLFSlideShow(is);
-            is.close();
-
-            for (HSLFSlide slide : ppt.getSlides()) {
-                System.out.println("\nslide " + slide.getSlideNumber());
-
-                // read hyperlinks from the slide's text runs
-                System.out.println("- reading hyperlinks from the text runs");
-                for (List<HSLFTextParagraph> paras : 
slide.getTextParagraphs()) {
-                    for (HSLFTextParagraph para : paras) {
-                        for (HSLFTextRun run : para) {
-                            HSLFHyperlink link = run.getHyperlink();
-                            if (link != null) {
-                                System.out.println(toStr(link, 
run.getRawText()));
+            try (FileInputStream is = new FileInputStream(arg);
+                HSLFSlideShow ppt = new HSLFSlideShow(is)) {
+
+                for (HSLFSlide slide : ppt.getSlides()) {
+                    System.out.println("\nslide " + slide.getSlideNumber());
+
+                    // read hyperlinks from the slide's text runs
+                    System.out.println("- reading hyperlinks from the text 
runs");
+                    for (List<HSLFTextParagraph> paras : 
slide.getTextParagraphs()) {
+                        for (HSLFTextParagraph para : paras) {
+                            for (HSLFTextRun run : para) {
+                                HSLFHyperlink link = run.getHyperlink();
+                                if (link != null) {
+                                    System.out.println(toStr(link, 
run.getRawText()));
+                                }
                             }
                         }
                     }
-                }
 
-                // in PowerPoint you can assign a hyperlink to a shape without 
text,
-                // for example to a Line object. The code below demonstrates 
how to
-                // read such hyperlinks
-                System.out.println("- reading hyperlinks from the slide's 
shapes");
-                for (HSLFShape sh : slide.getShapes()) {
-                    if (sh instanceof HSLFSimpleShape) {
-                        HSLFHyperlink link = ((HSLFSimpleShape) 
sh).getHyperlink();
-                        if (link != null) {
-                            System.out.println(toStr(link, null));
+                    // in PowerPoint you can assign a hyperlink to a shape 
without text,
+                    // for example to a Line object. The code below 
demonstrates how to
+                    // read such hyperlinks
+                    System.out.println("- reading hyperlinks from the slide's 
shapes");
+                    for (HSLFShape sh : slide.getShapes()) {
+                        if (sh instanceof HSLFSimpleShape) {
+                            HSLFHyperlink link = ((HSLFSimpleShape) 
sh).getHyperlink();
+                            if (link != null) {
+                                System.out.println(toStr(link, null));
+                            }
                         }
                     }
                 }
             }
-            ppt.close();
         }
    }
 

Modified: poi/trunk/src/examples/src/org/apache/poi/hssf/view/SViewer.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hssf/view/SViewer.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hssf/view/SViewer.java (original)
+++ poi/trunk/src/examples/src/org/apache/poi/hssf/view/SViewer.java Sat Nov 30 
23:00:08 2019
@@ -15,16 +15,25 @@
    See the License for the specific language governing permissions and
    limitations under the License.
 ==================================================================== */
-        
 
 
 package org.apache.poi.hssf.view;
 
-import java.awt.*;
-import java.awt.event.*;
-import java.net.*;
-import java.io.*;
-import javax.swing.*;
+import java.awt.AWTEvent;
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.Frame;
+import java.awt.Toolkit;
+import java.awt.event.WindowEvent;
+import java.io.BufferedInputStream;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import javax.swing.JApplet;
 
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 
@@ -39,141 +48,149 @@ import org.apache.poi.hssf.usermodel.HSS
  * @author Jason Height
  */
 public class SViewer extends JApplet {
-  private SViewerPanel panel;
-  boolean isStandalone;
-  String filename;
-
-  /**Get a parameter value*/
-  public String getParameter(String key, String def) {
-    return isStandalone ? System.getProperty(key, def) :
-      (getParameter(key) != null ? getParameter(key) : def);
-  }
-
-  /**Construct the applet*/
-  public SViewer() {
-  }
-
-  /**Initialize the applet*/
-  @Override
-public void init() {
-    try {
-      jbInit();
-    }
-    catch(Exception e) {
-      e.printStackTrace();
-      System.exit(1);
-    }
-  }
-
-  /**Component initialization*/
-  private void jbInit() throws Exception {
-    InputStream i = null;
-    boolean isurl = false;
-    if (filename == null) filename = getParameter("filename");
-
-    if (filename == null || filename.substring(0,7).equals("http://";)) {
-      isurl = true;
-      if (filename == null) filename = getParameter("url");
-      i = getXLSFromURL(filename);
-    }
-
-    HSSFWorkbook wb = null;
-    if (isurl) {
-      wb = constructWorkbook(i);
-    } else {
-      wb = constructWorkbook(filename);
-    }
-    panel = new SViewerPanel(wb, false);
-    getContentPane().setLayout(new BorderLayout());
-    getContentPane().add(panel, BorderLayout.CENTER);
-  }
-
-  private HSSFWorkbook constructWorkbook(String filename) throws 
FileNotFoundException, IOException {
-    HSSFWorkbook wb = null;
-      FileInputStream in = new FileInputStream(filename);
-      wb = new HSSFWorkbook(in);
-      in.close();
-    return wb;
-  }
-
-  private HSSFWorkbook constructWorkbook(InputStream in) throws IOException {
-    HSSFWorkbook wb = null;
-
-      wb = new HSSFWorkbook(in);
-      in.close();
-    return wb;
-  }
-
-  /**Start the applet*/
-  @Override
-public void start() {
-  }
-  /**Stop the applet*/
-  @Override
-public void stop() {
-  }
-  /**Destroy the applet*/
-  @Override
-public void destroy() {
-  }
-  /**Get Applet information*/
-  @Override
-public String getAppletInfo() {
-    return "Applet Information";
-  }
-  /**Get parameter info*/
-  @Override
-public String[][] getParameterInfo() {
-    return null;
-  }
-
-  /**
-   * opens a url and returns an inputstream
-   *
-   */
-  private InputStream getXLSFromURL(String urlstring) throws 
MalformedURLException, IOException {
-    URL url = new URL(urlstring);
-    URLConnection uc = url.openConnection();
-    String field = uc.getHeaderField(0);
-    for (int i=0;field != null; i++) {
-      System.out.println(field);
-      field = uc.getHeaderField(i);
-  }
-      return new BufferedInputStream(uc.getInputStream());
-  }
-
-
-  /**Main method*/
-  public static void main(String[] args) {
-    if(args.length < 1) {
-      throw new IllegalArgumentException("A filename to view must be supplied 
as the first argument, but none was given");
-    }
-
-    SViewer applet = new SViewer();
-    applet.isStandalone = true;
-    applet.filename = args[0];
-    Frame frame;
-    frame = new Frame() {
-      @Override
-    protected void processWindowEvent(WindowEvent e) {
-        super.processWindowEvent(e);
-        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
-          System.exit(0);
-        }
-      }
-      @Override
-    public synchronized void setTitle(String title) {
-        super.setTitle(title);
-        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
-      }
-    };
-    frame.setTitle("Applet Frame");
-    frame.add(applet, BorderLayout.CENTER);
-    applet.init();
-    applet.start();
-    frame.setSize(400,320);
-    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
-    frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - 
frame.getSize().height) / 2);
-    frame.setVisible(true);
-  }
+    private SViewerPanel panel;
+    boolean isStandalone;
+    String filename;
+
+    /**
+     * Get a parameter value
+     */
+    public String getParameter(String key, String def) {
+        return isStandalone ? System.getProperty(key, def) :
+                (getParameter(key) != null ? getParameter(key) : def);
+    }
+
+    /**
+     * Construct the applet
+     */
+    public SViewer() {
+    }
+
+    /**
+     * Initialize the applet
+     */
+    @Override
+    public void init() {
+        try {
+            jbInit();
+        } catch (Exception e) {
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+    /**
+     * Component initialization
+     */
+    private void jbInit() throws Exception {
+        boolean isurl = false;
+        if (filename == null) {
+            filename = getParameter("filename");
+        }
+
+        if (filename == null || filename.contains("://")) {
+            isurl = true;
+            if (filename == null) {
+                filename = getParameter("url");
+            }
+        }
+
+        final HSSFWorkbook wb;
+        try (InputStream is = isurl ? getXLSFromURL(filename) : new 
FileInputStream(filename)) {
+            wb = new HSSFWorkbook(is);
+        }
+
+        panel = new SViewerPanel(wb, false);
+        getContentPane().setLayout(new BorderLayout());
+        getContentPane().add(panel, BorderLayout.CENTER);
+    }
+
+    /**
+     * Start the applet
+     */
+    @Override
+    public void start() {
+    }
+
+    /**
+     * Stop the applet
+     */
+    @Override
+    public void stop() {
+    }
+
+    /**
+     * Destroy the applet
+     */
+    @Override
+    public void destroy() {
+    }
+
+    /**
+     * Get Applet information
+     */
+    @Override
+    public String getAppletInfo() {
+        return "Applet Information";
+    }
+
+    /**
+     * Get parameter info
+     */
+    @Override
+    public String[][] getParameterInfo() {
+        return null;
+    }
+
+    /**
+     * opens a url and returns an inputstream
+     */
+    private InputStream getXLSFromURL(String urlstring) throws 
MalformedURLException, IOException {
+        URL url = new URL(urlstring);
+        URLConnection uc = url.openConnection();
+        String field = uc.getHeaderField(0);
+        for (int i = 0; field != null; i++) {
+            System.out.println(field);
+            field = uc.getHeaderField(i);
+        }
+        return new BufferedInputStream(uc.getInputStream());
+    }
+
+
+    /**
+     * Main method
+     */
+    public static void main(String[] args) {
+        if (args.length < 1) {
+            throw new IllegalArgumentException("A filename to view must be 
supplied as the first argument, but none was given");
+        }
+
+        SViewer applet = new SViewer();
+        applet.isStandalone = true;
+        applet.filename = args[0];
+        Frame frame;
+        frame = new Frame() {
+            @Override
+            protected void processWindowEvent(WindowEvent e) {
+                super.processWindowEvent(e);
+                if (e.getID() == WindowEvent.WINDOW_CLOSING) {
+                    System.exit(0);
+                }
+            }
+
+            @Override
+            public synchronized void setTitle(String title) {
+                super.setTitle(title);
+                enableEvents(AWTEvent.WINDOW_EVENT_MASK);
+            }
+        };
+        frame.setTitle("Applet Frame");
+        frame.add(applet, BorderLayout.CENTER);
+        applet.init();
+        applet.start();
+        frame.setSize(400, 320);
+        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
+        frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - 
frame.getSize().height) / 2);
+        frame.setVisible(true);
+    }
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java 
(original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java 
Sat Nov 30 23:00:08 2019
@@ -65,41 +65,36 @@ public class ConditionalFormats {
      * @param args pass "-xls" to generate an HSSF workbook, default is XSSF
      */
     public static void main(String[] args) throws IOException {
-        Workbook wb;
+        final boolean isHSSF = args.length > 0 && args[0].equals("-xls");
+        try (Workbook wb = isHSSF ? new HSSFWorkbook() : new XSSFWorkbook()) {
 
-        if(args.length > 0 && args[0].equals("-xls")) {
-            wb = new HSSFWorkbook();
-        } else {
-            wb = new XSSFWorkbook();
-        }
-
-        sameCell(wb.createSheet("Same Cell"));
-        multiCell(wb.createSheet("MultiCell"));
-        overlapping(wb.createSheet("Overlapping"));
-        errors(wb.createSheet("Errors"));
-        hideDupplicates(wb.createSheet("Hide Dups"));
-        formatDuplicates(wb.createSheet("Duplicates"));
-        inList(wb.createSheet("In List"));
-        expiry(wb.createSheet("Expiry"));
-        shadeAlt(wb.createSheet("Shade Alt"));
-        shadeBands(wb.createSheet("Shade Bands"));
-        iconSets(wb.createSheet("Icon Sets"));
-        colourScales(wb.createSheet("Colour Scales"));
-        dataBars(wb.createSheet("Data Bars"));
+            sameCell(wb.createSheet("Same Cell"));
+            multiCell(wb.createSheet("MultiCell"));
+            overlapping(wb.createSheet("Overlapping"));
+            errors(wb.createSheet("Errors"));
+            hideDupplicates(wb.createSheet("Hide Dups"));
+            formatDuplicates(wb.createSheet("Duplicates"));
+            inList(wb.createSheet("In List"));
+            expiry(wb.createSheet("Expiry"));
+            shadeAlt(wb.createSheet("Shade Alt"));
+            shadeBands(wb.createSheet("Shade Bands"));
+            iconSets(wb.createSheet("Icon Sets"));
+            colourScales(wb.createSheet("Colour Scales"));
+            dataBars(wb.createSheet("Data Bars"));
 
-        // print overlapping rule results
-        evaluateRules(wb, "Overlapping");
+            // print overlapping rule results
+            evaluateRules(wb, "Overlapping");
 
-        // Write the output to a file
-        String file = "cf-poi.xls";
-        if(wb instanceof XSSFWorkbook) {
-            file += "x";
+            // Write the output to a file
+            String file = "cf-poi.xls";
+            if (wb instanceof XSSFWorkbook) {
+                file += "x";
+            }
+            try (FileOutputStream out = new FileOutputStream(file)) {
+                wb.write(out);
+            }
+            System.out.println("Generated: " + file);
         }
-        FileOutputStream out = new FileOutputStream(file);
-        wb.write(out);
-        out.close();
-        System.out.println("Generated: " + file);
-        wb.close();
     }
 
     /**

Modified: 
poi/trunk/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java 
(original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java 
Sat Nov 30 23:00:08 2019
@@ -83,9 +83,7 @@ public class ChartFromScratch {
             Double[] values1 = listCountries.toArray(new Double[0]);
             Double[] values2 = listSpeakers.toArray(new Double[0]);
 
-            try {
-
-                XMLSlideShow ppt = new XMLSlideShow();
+            try (XMLSlideShow ppt = new XMLSlideShow()) {
                 XSLFSlide slide = ppt.createSlide();
                 XSLFChart chart = ppt.createChart();
                 Rectangle2D rect2D = new 
java.awt.Rectangle(XDDFChart.DEFAULT_X, XDDFChart.DEFAULT_Y,
@@ -97,10 +95,6 @@ public class ChartFromScratch {
                     ppt.write(out);
                 }
             }
-            catch(Exception e)
-            {
-                e.printStackTrace();
-            }
         }
         System.out.println("Done");
     }

Modified: poi/trunk/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java (original)
+++ poi/trunk/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java Sat Nov 30 
23:00:08 2019
@@ -123,42 +123,40 @@ public class BiffDrawingToXml {
             return;
         }
         String input = getInputFileName(params);
-        FileInputStream inp = new FileInputStream(input);
         String output = getOutputFileName(input);
-        FileOutputStream outputStream = new FileOutputStream(output);
-        writeToFile(outputStream, inp, isExcludeWorkbookRecords(params), 
params);
-        inp.close();
-        outputStream.close();
+        try (FileInputStream inp = new FileInputStream(input);
+            FileOutputStream outputStream = new FileOutputStream(output)) {
+            writeToFile(outputStream, inp, isExcludeWorkbookRecords(params), 
params);
+        }
     }
 
     public static void writeToFile(OutputStream fos, InputStream xlsWorkbook, 
boolean excludeWorkbookRecords, String[] params) throws IOException {
-        HSSFWorkbook workbook = new HSSFWorkbook(xlsWorkbook);
-        InternalWorkbook internalWorkbook = workbook.getInternalWorkbook();
-        DrawingGroupRecord r = (DrawingGroupRecord) 
internalWorkbook.findFirstRecordBySid(DrawingGroupRecord.sid);
+        try (HSSFWorkbook workbook = new HSSFWorkbook(xlsWorkbook)) {
+            InternalWorkbook internalWorkbook = workbook.getInternalWorkbook();
+            DrawingGroupRecord r = (DrawingGroupRecord) 
internalWorkbook.findFirstRecordBySid(DrawingGroupRecord.sid);
 
-        StringBuilder builder = new StringBuilder();
-        builder.append("<workbook>\n");
-        String tab = "\t";
-        if (!excludeWorkbookRecords && r != null) {
-            r.decode();
-            List<EscherRecord> escherRecords = r.getEscherRecords();
-            for (EscherRecord record : escherRecords) {
-                builder.append(record.toXml(tab));
+            StringBuilder builder = new StringBuilder();
+            builder.append("<workbook>\n");
+            String tab = "\t";
+            if (!excludeWorkbookRecords && r != null) {
+                r.decode();
+                List<EscherRecord> escherRecords = r.getEscherRecords();
+                for (EscherRecord record : escherRecords) {
+                    builder.append(record.toXml(tab));
+                }
             }
-        }
-        List<Integer> sheets = getSheetsIndexes(params, workbook);
-        for (Integer i : sheets) {
-            HSSFPatriarch p = workbook.getSheetAt(i).getDrawingPatriarch();
-            if(p != null ) {
-                builder.append(tab).append("<sheet").append(i).append(">\n");
-                builder.append(p.getBoundAggregate().toXml(tab + "\t"));
-                builder.append(tab).append("</sheet").append(i).append(">\n");
+            List<Integer> sheets = getSheetsIndexes(params, workbook);
+            for (Integer i : sheets) {
+                HSSFPatriarch p = workbook.getSheetAt(i).getDrawingPatriarch();
+                if (p != null) {
+                    
builder.append(tab).append("<sheet").append(i).append(">\n");
+                    builder.append(p.getBoundAggregate().toXml(tab + "\t"));
+                    
builder.append(tab).append("</sheet").append(i).append(">\n");
+                }
             }
+            builder.append("</workbook>\n");
+            fos.write(builder.toString().getBytes(StringUtil.UTF8));
         }
-        builder.append("</workbook>\n");
-        fos.write(builder.toString().getBytes(StringUtil.UTF8));
-        fos.close();
-        workbook.close();
     }
 
 }

Modified: poi/trunk/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java 
(original)
+++ poi/trunk/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java Sat 
Nov 30 23:00:08 2019
@@ -223,24 +223,17 @@ public class ExcelExtractor extends POIO
                        return;
                }
 
-               InputStream is;
-               if(cmdArgs.getInputFile() == null) {
-                       is = System.in;
-               } else {
-                       is = new FileInputStream(cmdArgs.getInputFile());
+               try (InputStream is = cmdArgs.getInputFile() == null ? 
System.in : new FileInputStream(cmdArgs.getInputFile());
+                        HSSFWorkbook wb = new HSSFWorkbook(is);
+                        ExcelExtractor extractor = new ExcelExtractor(wb);
+               ) {
+                       
extractor.setIncludeSheetNames(cmdArgs.shouldShowSheetNames());
+                       
extractor.setFormulasNotResults(!cmdArgs.shouldEvaluateFormulas());
+                       
extractor.setIncludeCellComments(cmdArgs.shouldShowCellComments());
+                       
extractor.setIncludeBlankCells(cmdArgs.shouldShowBlankCells());
+                       
extractor.setIncludeHeadersFooters(cmdArgs.shouldIncludeHeadersFooters());
+                       System.out.println(extractor.getText());
                }
-               HSSFWorkbook wb = new HSSFWorkbook(is);
-               is.close();
-
-               ExcelExtractor extractor = new ExcelExtractor(wb);
-               extractor.setIncludeSheetNames(cmdArgs.shouldShowSheetNames());
-               
extractor.setFormulasNotResults(!cmdArgs.shouldEvaluateFormulas());
-               
extractor.setIncludeCellComments(cmdArgs.shouldShowCellComments());
-               extractor.setIncludeBlankCells(cmdArgs.shouldShowBlankCells());
-               
extractor.setIncludeHeadersFooters(cmdArgs.shouldIncludeHeadersFooters());
-               System.out.println(extractor.getText());
-               extractor.close();
-               wb.close();
        }
 
        @Override

Modified: 
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java 
(original)
+++ 
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java 
Sat Nov 30 23:00:08 2019
@@ -121,7 +121,7 @@ public class StandardDecryptor extends D
     }
 
     @Override
-    @SuppressWarnings("resource")
+    @SuppressWarnings({"resource", "squid:S2095"})
     public InputStream getDataStream(DirectoryNode dir) throws IOException {
         DocumentInputStream dis = 
dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);
 

Modified: 
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java 
(original)
+++ 
poi/trunk/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java 
Sat Nov 30 23:00:08 2019
@@ -127,7 +127,7 @@ public class StandardEncryptor extends E
         protected final File fileOut;
         protected final DirectoryNode dir;
 
-        @SuppressWarnings("resource")
+        @SuppressWarnings({"resource", "squid:S2095"})
         private StandardCipherOutputStream(DirectoryNode dir, File fileOut) 
throws IOException {
             // although not documented, we need the same padding as with agile 
encryption
             // and instead of calculating the missing bytes for the block size 
ourselves

Modified: poi/trunk/src/java/org/apache/poi/poifs/dev/POIFSLister.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/dev/POIFSLister.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/poifs/dev/POIFSLister.java (original)
+++ poi/trunk/src/java/org/apache/poi/poifs/dev/POIFSLister.java Sat Nov 30 
23:00:08 2019
@@ -62,16 +62,15 @@ public class POIFSLister {
    }
 
    public static void viewFile(final String filename, boolean withSizes) 
throws IOException {
-      POIFSFileSystem fs = new POIFSFileSystem(new File(filename));
-      displayDirectory(fs.getRoot(), "", withSizes);
-      fs.close();
+      try (POIFSFileSystem fs = new POIFSFileSystem(new File(filename))) {
+         displayDirectory(fs.getRoot(), "", withSizes);
+      }
    }
 
    public static void viewFileOld(final String filename, boolean withSizes) 
throws IOException {
-      try (FileInputStream fis = new FileInputStream(filename)) {
-         POIFSFileSystem fs = new POIFSFileSystem(fis);
+      try (FileInputStream fis = new FileInputStream(filename);
+           POIFSFileSystem fs = new POIFSFileSystem(fis)) {
          displayDirectory(fs.getRoot(), "", withSizes);
-         fs.close();
       }
    }
 

Modified: poi/trunk/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java 
(original)
+++ poi/trunk/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java Sat Nov 
30 23:00:08 2019
@@ -107,13 +107,11 @@ public class Ole10Native {
      * @throws Ole10NativeException on invalid or unexcepted data format
      */
     public static Ole10Native createFromEmbeddedOleObject(DirectoryNode 
directory) throws IOException, Ole10NativeException {
-       DocumentEntry nativeEntry = 
-          (DocumentEntry)directory.getEntry(OLE10_NATIVE);
-       byte[] data = IOUtils.safelyAllocate(nativeEntry.getSize(), 
MAX_RECORD_LENGTH);
-       int readBytes = 
directory.createDocumentInputStream(nativeEntry).read(data);
-       assert(readBytes == data.length);
-  
-       return new Ole10Native(data, 0);
+       DocumentEntry nativeEntry = 
(DocumentEntry)directory.getEntry(OLE10_NATIVE);
+       try (DocumentInputStream dis = 
directory.createDocumentInputStream(nativeEntry)) {
+           byte[] data = IOUtils.toByteArray(dis, nativeEntry.getSize(), 
MAX_RECORD_LENGTH);
+           return new Ole10Native(data, 0);
+       }
     }
     
     /**

Modified: poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java 
(original)
+++ poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java Sat 
Nov 30 23:00:08 2019
@@ -78,10 +78,11 @@ public class VBAMacroExtractor {
         } else {
             System.err.println("STDOUT");
         }
-        
-        VBAMacroReader reader = new VBAMacroReader(input);
-        Map<String,String> macros = reader.readMacros();
-        reader.close();
+
+        final Map<String,String> macros;
+        try (VBAMacroReader reader = new VBAMacroReader(input)) {
+            macros = reader.readMacros();
+        }
         
         final String divider = "---------------------------------------";
         for (Entry<String, String> entry : macros.entrySet()) {
@@ -94,11 +95,10 @@ public class VBAMacroExtractor {
                 System.out.println(moduleCode);
             } else {
                 File out = new File(outputDir, moduleName + extension);
-                FileOutputStream fout = new FileOutputStream(out);
-                OutputStreamWriter fwriter = new OutputStreamWriter(fout, 
StringUtil.UTF8);
-                fwriter.write(moduleCode);
-                fwriter.close();
-                fout.close();
+                try (FileOutputStream fout = new FileOutputStream(out);
+                    OutputStreamWriter fwriter = new OutputStreamWriter(fout, 
StringUtil.UTF8)) {
+                    fwriter.write(moduleCode);
+                }
                 System.out.println("Extracted " + out);
             }
         }

Modified: poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java 
(original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java Sat 
Nov 30 23:00:08 2019
@@ -17,16 +17,26 @@
 
 package org.apache.poi.ooxml.util;
 
-import org.apache.poi.openxml4j.opc.*;
-import org.apache.poi.openxml4j.opc.OPCPackage;
-import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
-import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+
 import org.apache.poi.ooxml.POIXMLException;
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.PackagePartName;
+import org.apache.poi.openxml4j.opc.PackageProperties;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
+import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
+import org.apache.poi.openxml4j.opc.PackagingURIHelper;
+import org.apache.poi.openxml4j.opc.TargetMode;
 import org.apache.poi.util.IOUtils;
 
-import java.io.*;
-import java.net.URI;
-
 /**
  * Provides handy methods to work with OOXML packages
  */
@@ -51,27 +61,27 @@ public final class PackageHelper {
 
         String path = file.getAbsolutePath();
 
-        OPCPackage dest = OPCPackage.create(path);
-        PackageRelationshipCollection rels = pkg.getRelationships();
-        for (PackageRelationship rel : rels) {
-            PackagePart part = pkg.getPart(rel);
-            PackagePart part_tgt;
-            if 
(rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) {
-                copyProperties(pkg.getPackageProperties(), 
dest.getPackageProperties());
-                continue;
-            }
-            dest.addRelationship(part.getPartName(), rel.getTargetMode(), 
rel.getRelationshipType());
-            part_tgt = dest.createPart(part.getPartName(), 
part.getContentType());
-
-            OutputStream out = part_tgt.getOutputStream();
-            IOUtils.copy(part.getInputStream(), out);
-            out.close();
-
-            if(part.hasRelationships()) {
-                copy(pkg, part, dest, part_tgt);
+        try (OPCPackage dest = OPCPackage.create(path)) {
+            PackageRelationshipCollection rels = pkg.getRelationships();
+            for (PackageRelationship rel : rels) {
+                PackagePart part = pkg.getPart(rel);
+                PackagePart part_tgt;
+                if 
(rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) {
+                    copyProperties(pkg.getPackageProperties(), 
dest.getPackageProperties());
+                    continue;
+                }
+                dest.addRelationship(part.getPartName(), rel.getTargetMode(), 
rel.getRelationshipType());
+                part_tgt = dest.createPart(part.getPartName(), 
part.getContentType());
+
+                OutputStream out = part_tgt.getOutputStream();
+                IOUtils.copy(part.getInputStream(), out);
+                out.close();
+
+                if (part.hasRelationships()) {
+                    copy(pkg, part, dest, part_tgt);
+                }
             }
         }
-        dest.close();
 
         //the temp file will be deleted when JVM terminates
         new File(path).deleteOnExit();

Modified: 
poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java
 (original)
+++ 
poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java
 Sat Nov 30 23:00:08 2019
@@ -120,34 +120,33 @@ public final class AesZipFileZipEntrySou
         SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, 
CipherAlgorithm.aes128.jceId);
         Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, 
CipherAlgorithm.aes128, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, 
PADDING);
         
-        ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
-        FileOutputStream fos = new FileOutputStream(tmpFile);
-        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
-        
-        ZipArchiveEntry ze;
-        while ((ze = zis.getNextZipEntry()) != null) {
-            // the cipher output stream pads the data, therefore we can't 
reuse the ZipEntry with set sizes
-            // as those will be validated upon close()
-            ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
-            zeNew.setComment(ze.getComment());
-            zeNew.setExtra(ze.getExtra());
-            zeNew.setTime(ze.getTime());
-            // zeNew.setMethod(ze.getMethod());
-            zos.putArchiveEntry(zeNew);
-            FilterOutputStream fos2 = new FilterOutputStream(zos) {
-                // don't close underlying ZipOutputStream
-                @Override
-                public void close() {}
-            };
-            CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc);
-            IOUtils.copy(zis, cos);
-            cos.close();
-            fos2.close();
-            zos.closeArchiveEntry();
+        try (ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
+            FileOutputStream fos = new FileOutputStream(tmpFile);
+            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) {
+
+            ZipArchiveEntry ze;
+            while ((ze = zis.getNextZipEntry()) != null) {
+                // the cipher output stream pads the data, therefore we can't 
reuse the ZipEntry with set sizes
+                // as those will be validated upon close()
+                ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
+                zeNew.setComment(ze.getComment());
+                zeNew.setExtra(ze.getExtra());
+                zeNew.setTime(ze.getTime());
+                // zeNew.setMethod(ze.getMethod());
+                zos.putArchiveEntry(zeNew);
+                FilterOutputStream fos2 = new FilterOutputStream(zos) {
+                    // don't close underlying ZipOutputStream
+                    @Override
+                    public void close() {
+                    }
+                };
+                CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc);
+                IOUtils.copy(zis, cos);
+                cos.close();
+                fos2.close();
+                zos.closeArchiveEntry();
+            }
         }
-        zos.close();
-        fos.close();
-        zis.close();
     }
 
     private static AesZipFileZipEntrySource fileToSource(File tmpFile, byte[] 
keyBytes, byte[] ivBytes) throws IOException {

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java Sat Nov 30 
23:00:08 2019
@@ -337,6 +337,7 @@ public final class PPTX2PNG {
         }
     }
 
+    @SuppressWarnings({"resource", "squid:S2095"})
     private MFProxy initProxy(File file) throws IOException {
         MFProxy proxy;
         final String fileName = file.getName().toLowerCase(Locale.ROOT);

Modified: poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java 
(original)
+++ poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java Sat Nov 
30 23:00:08 2019
@@ -51,16 +51,12 @@ public final class VSDDumper {
                        System.exit(1);
                }
 
-               POIFSFileSystem poifs = new POIFSFileSystem(new File(args[0]));
-               try {
-                       HDGFDiagram hdgf = new HDGFDiagram(poifs);
-
+               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();
-               } finally {
-                       poifs.close();
                }
        }
 

Modified: 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java 
(original)
+++ poi/trunk/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java 
Sat Nov 30 23:00:08 2019
@@ -51,109 +51,109 @@ public final class SlideIdListing {
 
 
         // Create the slideshow object, for normal working with
-        HSLFSlideShowImpl hss = new HSLFSlideShowImpl(args[0]);
-        HSLFSlideShow ss = new HSLFSlideShow(hss);
+        try (HSLFSlideShowImpl hss = new HSLFSlideShowImpl(args[0]);
+             HSLFSlideShow ss = new HSLFSlideShow(hss)) {
 
-        // Grab the base contents
-        fileContents = hss.getUnderlyingBytes();
-        Record[] records = hss.getRecords();
-        Record[] latestRecords = ss.getMostRecentCoreRecords();
-
-        // Grab any records that interest us
-        Document document = null;
-        for (Record latestRecord : latestRecords) {
-            if (latestRecord instanceof Document) {
-                document = (Document) latestRecord;
+            // Grab the base contents
+            fileContents = hss.getUnderlyingBytes();
+            Record[] records = hss.getRecords();
+            Record[] latestRecords = ss.getMostRecentCoreRecords();
+
+            // Grab any records that interest us
+            Document document = null;
+            for (Record latestRecord : latestRecords) {
+                if (latestRecord instanceof Document) {
+                    document = (Document) latestRecord;
+                }
             }
-        }
 
-        System.out.println();
+            System.out.println();
 
 
-        // Look for SlidePersistAtoms, and report what they have to
-        //  say about possible slide IDs
-        SlideListWithText[] slwts = document.getSlideListWithTexts();
-        for (SlideListWithText slwt : slwts) {
-            Record[] cr = slwt.getChildRecords();
-            for (Record record : cr) {
-                if (record instanceof SlidePersistAtom) {
-                    SlidePersistAtom spa = (SlidePersistAtom) record;
-                    System.out.println("SlidePersistAtom knows about slide:");
-                    System.out.println("\t" + spa.getRefID());
-                    System.out.println("\t" + spa.getSlideIdentifier());
+            // Look for SlidePersistAtoms, and report what they have to
+            //  say about possible slide IDs
+            SlideListWithText[] slwts = document.getSlideListWithTexts();
+            for (SlideListWithText slwt : slwts) {
+                Record[] cr = slwt.getChildRecords();
+                for (Record record : cr) {
+                    if (record instanceof SlidePersistAtom) {
+                        SlidePersistAtom spa = (SlidePersistAtom) record;
+                        System.out.println("SlidePersistAtom knows about 
slide:");
+                        System.out.println("\t" + spa.getRefID());
+                        System.out.println("\t" + spa.getSlideIdentifier());
+                    }
                 }
             }
-        }
 
-        System.out.println();
+            System.out.println();
 
-        // Look for latest core records that are slides or notes
-        for (int i=0; i<latestRecords.length; i++) {
-            if (latestRecords[i] instanceof Slide) {
-                Slide s = (Slide)latestRecords[i];
-                SlideAtom sa = s.getSlideAtom();
-                System.out.println("Found the latest version of a slide 
record:");
-                System.out.println("\tCore ID is " + s.getSheetId());
-                System.out.println("\t(Core Records count is " + i + ")");
-                System.out.println("\tDisk Position is " + 
s.getLastOnDiskOffset());
-                System.out.println("\tMaster ID is " + sa.getMasterID());
-                System.out.println("\tNotes ID is " + sa.getNotesID());
+            // Look for latest core records that are slides or notes
+            for (int i = 0; i < latestRecords.length; i++) {
+                if (latestRecords[i] instanceof Slide) {
+                    Slide s = (Slide) latestRecords[i];
+                    SlideAtom sa = s.getSlideAtom();
+                    System.out.println("Found the latest version of a slide 
record:");
+                    System.out.println("\tCore ID is " + s.getSheetId());
+                    System.out.println("\t(Core Records count is " + i + ")");
+                    System.out.println("\tDisk Position is " + 
s.getLastOnDiskOffset());
+                    System.out.println("\tMaster ID is " + sa.getMasterID());
+                    System.out.println("\tNotes ID is " + sa.getNotesID());
+                }
             }
-        }
-        System.out.println();
-        for (int i=0; i<latestRecords.length; i++) {
-            if (latestRecords[i] instanceof Notes) {
-                Notes n = (Notes)latestRecords[i];
-                NotesAtom na = n.getNotesAtom();
-                System.out.println("Found the latest version of a notes 
record:");
-                System.out.println("\tCore ID is " + n.getSheetId());
-                System.out.println("\t(Core Records count is " + i + ")");
-                System.out.println("\tDisk Position is " + 
n.getLastOnDiskOffset());
-                System.out.println("\tMatching slide is " + na.getSlideID());
+            System.out.println();
+            for (int i = 0; i < latestRecords.length; i++) {
+                if (latestRecords[i] instanceof Notes) {
+                    Notes n = (Notes) latestRecords[i];
+                    NotesAtom na = n.getNotesAtom();
+                    System.out.println("Found the latest version of a notes 
record:");
+                    System.out.println("\tCore ID is " + n.getSheetId());
+                    System.out.println("\t(Core Records count is " + i + ")");
+                    System.out.println("\tDisk Position is " + 
n.getLastOnDiskOffset());
+                    System.out.println("\tMatching slide is " + 
na.getSlideID());
+                }
             }
-        }
-
-        System.out.println();
 
-        // Find any persist ones first
-        int pos = 0;
-        for (Record r : records) {
-            if (r.getRecordType() == 6001L) {
-                // PersistPtrFullBlock
-                System.out.println("Found PersistPtrFullBlock at " + pos + " 
(" + Integer.toHexString(pos) + ")");
-            }
-            if (r.getRecordType() == 6002L) {
-                // PersistPtrIncrementalBlock
-                System.out.println("Found PersistPtrIncrementalBlock at " + 
pos + " (" + Integer.toHexString(pos) + ")");
-                PersistPtrHolder pph = (PersistPtrHolder) r;
-
-                // Check the sheet offsets
-                int[] sheetIDs = pph.getKnownSlideIDs();
-                Map<Integer, Integer> sheetOffsets = 
pph.getSlideLocationsLookup();
-                for (Integer id : sheetIDs) {
-                    Integer offset = sheetOffsets.get(id);
-
-                    System.out.println("  Knows about sheet " + id);
-                    System.out.println("    That sheet lives at " + offset);
-
-                    Record atPos = findRecordAtPos(offset.intValue());
-                    System.out.println("    The record at that pos is of type 
" + atPos.getRecordType());
-                    System.out.println("    The record at that pos has class " 
+ atPos.getClass().getName());
+            System.out.println();
 
-                    if (!(atPos instanceof PositionDependentRecord)) {
-                        System.out.println("    ** The record class isn't 
position aware! **");
+            // Find any persist ones first
+            int pos = 0;
+            for (Record r : records) {
+                if (r.getRecordType() == 6001L) {
+                    // PersistPtrFullBlock
+                    System.out.println("Found PersistPtrFullBlock at " + pos + 
" (" + Integer.toHexString(pos) + ")");
+                }
+                if (r.getRecordType() == 6002L) {
+                    // PersistPtrIncrementalBlock
+                    System.out.println("Found PersistPtrIncrementalBlock at " 
+ pos + " (" + Integer.toHexString(pos) + ")");
+                    PersistPtrHolder pph = (PersistPtrHolder) r;
+
+                    // Check the sheet offsets
+                    int[] sheetIDs = pph.getKnownSlideIDs();
+                    Map<Integer, Integer> sheetOffsets = 
pph.getSlideLocationsLookup();
+                    for (Integer id : sheetIDs) {
+                        Integer offset = sheetOffsets.get(id);
+
+                        System.out.println("  Knows about sheet " + id);
+                        System.out.println("    That sheet lives at " + 
offset);
+
+                        Record atPos = findRecordAtPos(offset.intValue());
+                        System.out.println("    The record at that pos is of 
type " + atPos.getRecordType());
+                        System.out.println("    The record at that pos has 
class " + atPos.getClass().getName());
+
+                        if (!(atPos instanceof PositionDependentRecord)) {
+                            System.out.println("    ** The record class isn't 
position aware! **");
+                        }
                     }
                 }
+
+                // Increase the position by the on disk size
+                ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                r.writeOut(baos);
+                pos += baos.size();
             }
 
-            // Increase the position by the on disk size
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            r.writeOut(baos);
-            pos += baos.size();
         }
 
-        ss.close();
-
         System.out.println();
     }
 

Modified: 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java 
(original)
+++ 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java 
Sat Nov 30 23:00:08 2019
@@ -35,20 +35,20 @@ public final class ImageExtractor {
             System.err.println("\tImageExtractor <file>");
             return;
         }
-        HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(args[0]));
+        try (HSLFSlideShow ppt = new HSLFSlideShow(new 
HSLFSlideShowImpl(args[0]))) {
 
-        //extract all pictures contained in the presentation
-        int i = 0;
-        for (HSLFPictureData pict : ppt.getPictureData()) {
-            // picture data
-            byte[] data = pict.getData();
+            //extract all pictures contained in the presentation
+            int i = 0;
+            for (HSLFPictureData pict : ppt.getPictureData()) {
+                // picture data
+                byte[] data = pict.getData();
+
+                PictureType type = pict.getType();
+                try (FileOutputStream out = new FileOutputStream("pict_" + i++ 
+ type.extension)) {
+                    out.write(data);
+                }
+            }
 
-            PictureType type = pict.getType();
-            FileOutputStream out = new FileOutputStream("pict_" + i++ + 
type.extension);
-            out.write(data);
-            out.close();
         }
-        
-        ppt.close();
     }
 }

Modified: 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java
 (original)
+++ 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java
 Sat Nov 30 23:00:08 2019
@@ -79,9 +79,9 @@ public final class PowerPointExtractor e
                        file = args[0];
                }
 
-               PowerPointExtractor ppe = new PowerPointExtractor(file);
-               System.out.println(ppe.getText(true, notes, comments, master));
-               ppe.close();
+               try (PowerPointExtractor ppe = new PowerPointExtractor(file)) {
+                       System.out.println(ppe.getText(true, notes, comments, 
master));
+               }
        }
 
        public PowerPointExtractor(final HSLFSlideShow slideShow) {

Modified: 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java 
(original)
+++ 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java 
Sat Nov 30 23:00:08 2019
@@ -131,16 +131,9 @@ public class CurrentUserAtom
                }
 
                // Grab the contents
-               int len = docProps.getSize();
-               _contents = IOUtils.safelyAllocate(len, MAX_RECORD_LENGTH);
-               InputStream in = dir.createDocumentInputStream("Current User");
-               int readLen = in.read(_contents);
-               in.close();
-
-        if (len != readLen) {
-            throw new IOException("Current User input stream ended prematurely 
- expected "+len+" bytes - received "+readLen+" bytes");
-        }
-
+               try (InputStream in = dir.createDocumentInputStream("Current 
User")) {
+                       _contents = IOUtils.toByteArray(in, docProps.getSize(), 
MAX_RECORD_LENGTH);
+               }
 
                // See how long it is. If it's under 28 bytes long, we can't
                //  read it

Modified: 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
 (original)
+++ 
poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
 Sat Nov 30 23:00:08 2019
@@ -511,33 +511,31 @@ public final class HSLFSlideShowImpl ext
             persistIds.put(oldToNewPositions.get(entry.getValue()), 
entry.getKey());
         }
 
-        HSLFSlideShowEncrypted encData = new 
HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
-
-        for (Record record : _records) {
-            assert (record instanceof PositionDependentRecord);
-            // We've already figured out their new location, and
-            // told them that
-            // Tell them of the positions of the other records though
-            PositionDependentRecord pdr = (PositionDependentRecord) record;
-            Integer persistId = persistIds.get(pdr.getLastOnDiskOffset());
-            if (persistId == null) {
-                persistId = 0;
-            }
-
-            // For now, we're only handling PositionDependentRecord's that
-            // happen at the top level.
-            // In future, we'll need the handle them everywhere, but that's
-            // a bit trickier
-            pdr.updateOtherRecordReferences(oldToNewPositions);
-
-            // Whatever happens, write out that record tree
-            if (os != null) {
-                record.writeOut(encData.encryptRecord(os, persistId, record));
+        try (HSLFSlideShowEncrypted encData = new 
HSLFSlideShowEncrypted(getDocumentEncryptionAtom())) {
+            for (Record record : _records) {
+                assert (record instanceof PositionDependentRecord);
+                // We've already figured out their new location, and
+                // told them that
+                // Tell them of the positions of the other records though
+                PositionDependentRecord pdr = (PositionDependentRecord) record;
+                Integer persistId = persistIds.get(pdr.getLastOnDiskOffset());
+                if (persistId == null) {
+                    persistId = 0;
+                }
+
+                // For now, we're only handling PositionDependentRecord's that
+                // happen at the top level.
+                // In future, we'll need the handle them everywhere, but that's
+                // a bit trickier
+                pdr.updateOtherRecordReferences(oldToNewPositions);
+
+                // Whatever happens, write out that record tree
+                if (os != null) {
+                    record.writeOut(encData.encryptRecord(os, persistId, 
record));
+                }
             }
         }
 
-        encData.close();
-
         // Update and write out the Current User atom
         int oldLastUserEditAtomPos = (int) currentUser.getCurrentEditOffset();
         Integer newLastUserEditAtomPos = 
oldToNewPositions.get(oldLastUserEditAtomPos);
@@ -657,53 +655,52 @@ public final class HSLFSlideShowImpl ext
         }
         getDocumentSummaryInformation();
 
-        // set new encryption settings
-        HSLFSlideShowEncrypted encryptedSS = new 
HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
-        _records = encryptedSS.updateEncryptionRecord(_records);
-
         // The list of entries we've written out
-        List<String> writtenEntries = new ArrayList<>(1);
+        final List<String> writtenEntries = new ArrayList<>(1);
 
-        // Write out the Property Streams
-        writeProperties(outFS, writtenEntries);
+        // set new encryption settings
+        try (HSLFSlideShowEncrypted encryptedSS = new 
HSLFSlideShowEncrypted(getDocumentEncryptionAtom())) {
+            _records = encryptedSS.updateEncryptionRecord(_records);
 
-        BufAccessBAOS baos = new BufAccessBAOS();
+            // Write out the Property Streams
+            writeProperties(outFS, writtenEntries);
 
-        // For position dependent records, hold where they were and now are
-        // As we go along, update, and hand over, to any Position Dependent
-        // records we happen across
-        updateAndWriteDependantRecords(baos, null);
-
-        // Update our cached copy of the bytes that make up the PPT stream
-        _docstream = new byte[baos.size()];
-        System.arraycopy(baos.getBuf(), 0, _docstream, 0, baos.size());
-        baos.close();
-
-        // Write the PPT stream into the POIFS layer
-        ByteArrayInputStream bais = new ByteArrayInputStream(_docstream);
-        outFS.createOrUpdateDocument(bais, POWERPOINT_DOCUMENT);
-        writtenEntries.add(POWERPOINT_DOCUMENT);
-
-        currentUser.setEncrypted(encryptedSS.getDocumentEncryptionAtom() != 
null);
-        currentUser.writeToFS(outFS);
-        writtenEntries.add("Current User");
-
-
-        if (_pictures.size() > 0) {
-            BufAccessBAOS pict = new BufAccessBAOS();
-            for (HSLFPictureData p : _pictures) {
-                int offset = pict.size();
-                p.write(pict);
-                encryptedSS.encryptPicture(pict.getBuf(), offset);
-            }
-            outFS.createOrUpdateDocument(
+            BufAccessBAOS baos = new BufAccessBAOS();
+
+            // For position dependent records, hold where they were and now are
+            // As we go along, update, and hand over, to any Position Dependent
+            // records we happen across
+            updateAndWriteDependantRecords(baos, null);
+
+            // Update our cached copy of the bytes that make up the PPT stream
+            _docstream = new byte[baos.size()];
+            System.arraycopy(baos.getBuf(), 0, _docstream, 0, baos.size());
+            baos.close();
+
+            // Write the PPT stream into the POIFS layer
+            ByteArrayInputStream bais = new ByteArrayInputStream(_docstream);
+            outFS.createOrUpdateDocument(bais, POWERPOINT_DOCUMENT);
+            writtenEntries.add(POWERPOINT_DOCUMENT);
+
+            currentUser.setEncrypted(encryptedSS.getDocumentEncryptionAtom() 
!= null);
+            currentUser.writeToFS(outFS);
+            writtenEntries.add("Current User");
+
+            if (_pictures.size() > 0) {
+                BufAccessBAOS pict = new BufAccessBAOS();
+                for (HSLFPictureData p : _pictures) {
+                    int offset = pict.size();
+                    p.write(pict);
+                    encryptedSS.encryptPicture(pict.getBuf(), offset);
+                }
+                outFS.createOrUpdateDocument(
                     new ByteArrayInputStream(pict.getBuf(), 0, pict.size()), 
"Pictures"
-            );
-            writtenEntries.add("Pictures");
-            pict.close();
-        }
+                );
+                writtenEntries.add("Pictures");
+                pict.close();
+            }
 
-        encryptedSS.close();
+        }
         
         // If requested, copy over any other streams we spot, eg Macros
         if (copyAllOtherNodes) {

Modified: poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java 
(original)
+++ poi/trunk/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java Sat 
Nov 30 23:00:08 2019
@@ -17,9 +17,10 @@
 
 package org.apache.poi.hwpf;
 
-import java.io.ByteArrayOutputStream;
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.SequenceInputStream;
 import java.security.GeneralSecurityException;
 
 import org.apache.poi.EncryptedDocumentException;
@@ -48,7 +49,6 @@ import org.apache.poi.poifs.filesystem.D
 import org.apache.poi.poifs.filesystem.DocumentInputStream;
 import org.apache.poi.poifs.filesystem.FileMagic;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.BoundedInputStream;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.Internal;
 import org.apache.poi.util.LittleEndianByteArrayInputStream;
@@ -320,40 +320,29 @@ public abstract class HWPFDocumentCore e
      * @return the read bytes
      * @throws IOException if the stream can't be found
      */
-    protected byte[] getDocumentEntryBytes(String name, int encryptionOffset, 
int len) throws IOException {
+    protected byte[] getDocumentEntryBytes(String name, int encryptionOffset, 
final int len) throws IOException {
         DirectoryNode dir = getDirectory();
         DocumentEntry documentProps = (DocumentEntry)dir.getEntry(name);
-        DocumentInputStream dis = dir.createDocumentInputStream(documentProps);
-        EncryptionInfo ei = (encryptionOffset > -1) ? getEncryptionInfo() : 
null;
         int streamSize = documentProps.getSize();
-        ByteArrayOutputStream bos = new 
ByteArrayOutputStream(Math.min(streamSize,len));
+        boolean isEncrypted = (encryptionOffset > -1 && getEncryptionInfo() != 
null);
 
-        InputStream is = dis;
-        try {
-            if (ei != null) {
-                try {
-                    Decryptor dec = ei.getDecryptor();
-                    is = dec.getDataStream(dis, streamSize, 0);
-                    if (encryptionOffset > 0) {
-                        ChunkedCipherInputStream cis = 
(ChunkedCipherInputStream)is;
-                        byte[] plain = 
IOUtils.safelyAllocate(encryptionOffset, MAX_RECORD_LENGTH);
-                        cis.readPlain(plain, 0, encryptionOffset);
-                        bos.write(plain);
-                    }
-                } catch (GeneralSecurityException e) {
-                    throw new IOException(e.getMessage(), e);
-                }
-            }
-            // This simplifies a few combinations, so we actually always try 
to copy len bytes
-            // regardless if encryptionOffset is greater than 0
-            if (len < Integer.MAX_VALUE) {
-                is = new BoundedInputStream(is, len);
-            }
-            IOUtils.copy(is, bos);
-            return bos.toByteArray();
-        } finally {
-            IOUtils.closeQuietly(is);
-            IOUtils.closeQuietly(dis);
+        try (DocumentInputStream dis = 
dir.createDocumentInputStream(documentProps);
+             InputStream is = isEncrypted ? getDecryptedStream(dis, 
streamSize, encryptionOffset) : dis) {
+            return IOUtils.toByteArray(is, Math.min(streamSize, len));
+        } catch (GeneralSecurityException e) {
+            throw new IOException("Unable to decrypt data for entry: "+name, 
e);
+        }
+    }
+
+    private InputStream getDecryptedStream(DocumentInputStream dis, int 
streamSize, int encryptionOffset)
+    throws IOException, GeneralSecurityException {
+        Decryptor dec = getEncryptionInfo().getDecryptor();
+        ChunkedCipherInputStream cis = 
(ChunkedCipherInputStream)dec.getDataStream(dis, streamSize, 0);
+        byte[] plain = {};
+        if (encryptionOffset > 0) {
+            plain = IOUtils.safelyAllocate(encryptionOffset, 
MAX_RECORD_LENGTH);
+            cis.readPlain(plain, 0, encryptionOffset);
         }
+        return new SequenceInputStream(new ByteArrayInputStream(plain), cis);
     }
 }
\ No newline at end of file

Modified: 
poi/trunk/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java?rev=1870653&r1=1870652&r2=1870653&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java 
(original)
+++ poi/trunk/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java 
Sat Nov 30 23:00:08 2019
@@ -19,7 +19,6 @@ package org.apache.poi.hssf.dev;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
-import java.io.PrintStream;
 
 import org.apache.poi.EncryptedDocumentException;
 import org.apache.poi.hssf.OldExcelFormatException;
@@ -50,15 +49,8 @@ public class TestBiffDrawingToXml extend
        
        @Override
        void runOneFile(File pFile) throws Exception {
-               PrintStream save = System.out;
-               try {
-                       //System.setOut(new 
PrintStream(TestBiffViewer.NULL_OUTPUT_STREAM));
-                       // use a NullOutputStream to not write the bytes 
anywhere for best runtime 
-            try (InputStream wb = new FileInputStream(pFile)) {
-                BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, 
new String[]{});
-            }
-               } finally {
-                       System.setOut(save);
-               }
+        try (InputStream wb = new FileInputStream(pFile)) {
+            BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new 
String[0]);
+        }
        }
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@poi.apache.org
For additional commands, e-mail: commits-h...@poi.apache.org

Reply via email to