]> source.dussan.org Git - poi.git/commitdiff
Sonar fixes - use try-with-resources
authorAndreas Beeker <kiwiwings@apache.org>
Sat, 30 Nov 2019 23:00:08 +0000 (23:00 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Sat, 30 Nov 2019 23:00:08 +0000 (23:00 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1870653 13f79535-47bb-0310-9956-ffa450edef68

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

index aaeea354abbddd0140069a3025c48825ce2ba9fd..033a4cdda809c3e1e8d6df9bd434b14291e736e6 100644 (file)
@@ -62,30 +62,30 @@ public class OOXMLPasswordsTry implements Closeable {
     }
     
     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 implements Closeable {
         
         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) {
index 9da099eb4202e0db4a562409216ac0407e2db107..818580a955931a91cbe82a1160c29dee77bbc904 100644 (file)
@@ -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(){
index e0936de3f7c32e18c3e8e43e577a32ffaaf7ce5b..a3010bf132a011a5eb58824466a0922f3b13e822 100644 (file)
@@ -31,47 +31,44 @@ import org.apache.poi.hslf.usermodel.HSLFTextRun;
 
 /**
  * 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();
+            try (FileInputStream is = new FileInputStream(arg);
+                HSLFSlideShow ppt = new HSLFSlideShow(is)) {
 
-            for (HSLFSlide slide : ppt.getSlides()) {
-                System.out.println("\nslide " + slide.getSlideNumber());
+                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()));
+                    // 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();
         }
    }
 
index 3d83c6aace04e1a0f0d1d78133db9dfad5f0a12a..3e9daf34ffecc82171c2d31d0a3e1bc2237381f9 100644 (file)
    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.HSSFWorkbook;
  * @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();
+    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);
     }
-    catch(Exception e) {
-      e.printStackTrace();
-      System.exit(1);
+
+    /**
+     * 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);
     }
-  }
-
-  /**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);
+
+    /**
+     * 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";
     }
 
-    HSSFWorkbook wb = null;
-    if (isurl) {
-      wb = constructWorkbook(i);
-    } else {
-      wb = constructWorkbook(filename);
+    /**
+     * Get parameter info
+     */
+    @Override
+    public String[][] getParameterInfo() {
+        return null;
     }
-    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");
+
+    /**
+     * 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());
     }
 
-    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);
+
+    /**
+     * 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");
         }
-      }
-      @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);
-  }
+
+        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);
+    }
 }
index dc6e6a54e6991a6a910ca2a34c3611b5bde04f51..654e837a42bc15829f0fca55329449efafc3ad81 100644 (file)
@@ -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;
-
-        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"));
-
-        // print overlapping rule results
-        evaluateRules(wb, "Overlapping");
-
-        // Write the output to a file
-        String file = "cf-poi.xls";
-        if(wb instanceof XSSFWorkbook) {
-            file += "x";
+        final boolean isHSSF = args.length > 0 && args[0].equals("-xls");
+        try (Workbook wb = isHSSF ? new HSSFWorkbook() : 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"));
+
+            // print overlapping rule results
+            evaluateRules(wb, "Overlapping");
+
+            // 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();
     }
 
     /**
index 2c941e868c9772caa9b36b16561a0429296178ce..3d1f7c7b9cdfd02fa345bb96f789b31948ff103f 100644 (file)
@@ -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");
     }
index 0a9f78b0c369f25513aaca86cddbd0878c44a436..3fc3f5d3be5c3973f92ec4d012084586b0f3d257 100644 (file)
@@ -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();
     }
 
 }
index 55c32fb4f55743797ff444d386a80dc8accd8d2a..ec40f097f1d905e6143b1515d4d4de609f83da9d 100644 (file)
@@ -223,24 +223,17 @@ public class ExcelExtractor extends POIOLE2TextExtractor implements org.apache.p
                        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
index 67da57129ae20cfc32fad753db5707b4bb8f5d2b..9c7926033d9f3ce9396ccbf352191ad06628e2f3 100644 (file)
@@ -121,7 +121,7 @@ public class StandardDecryptor extends Decryptor implements Cloneable {
     }
 
     @Override
-    @SuppressWarnings("resource")
+    @SuppressWarnings({"resource", "squid:S2095"})
     public InputStream getDataStream(DirectoryNode dir) throws IOException {
         DocumentInputStream dis = dir.createDocumentInputStream(DEFAULT_POIFS_ENTRY);
 
index 7de19b9a7bbd34edc28a847bccf28de7d7ccc1a3..e3662b40ba2acc8e02ace339d3a2aaa336b882bf 100644 (file)
@@ -127,7 +127,7 @@ public class StandardEncryptor extends Encryptor implements Cloneable {
         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
index 5ed20c75ab4873fa565f9f33fb42db60a4234ff5..f9696bccfb76a1f48eac8294bc6f6baab892d93f 100644 (file)
@@ -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();
       }
    }
 
index 57084e6391cbf7f4852d245a5e3c2732fc59749a..81481d3f6561949491f6531132e1428af065ece1 100644 (file)
@@ -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);
+       }
     }
     
     /**
index 57a7b1486fc6f7ca76c1b550f122b14475110f59..9874270a9db3d348b565aed09f5caaae53a8fd14 100644 (file)
@@ -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);
             }
         }
index 9da60dbef9f4c24de4f7663edd618b9d88634050..d357ab1f7faec469bd21d021948276d512d88b80 100644 (file)
 
 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();
+        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);
+                if (part.hasRelationships()) {
+                    copy(pkg, part, dest, part_tgt);
+                }
             }
         }
-        dest.close();
 
         //the temp file will be deleted when JVM terminates
         new File(path).deleteOnExit();
index 699fbe1fb8525fd4fc91c22ef68ec8d31f7dae6c..454d17f82a6ce00975a883671608d8f20d488bb1 100644 (file)
@@ -120,34 +120,33 @@ public final class AesZipFileZipEntrySource implements ZipEntrySource {
         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 {
index d1ba0167dfed12dbb77a227231d45945d78e9b9d..cd92196ac1a573c1bc5e4304d570870bcd5d641a 100644 (file)
@@ -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);
index f7f7570e4cb4badb3b98dd5620d147922e3fabdb..a7b1586821df7deb76ed2252627f194cfa0d8ab8 100644 (file)
@@ -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();
                }
        }
 
index 5fdd48e090cd745b3238993b399a4e182fcf667b..7e5f3e26bccd999b93c1eb743f6c5508080c7d34 100644 (file)
@@ -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);
-
-        // 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;
+        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;
+                }
             }
-        }
 
-        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();
-
-        // 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();
+
+            // 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();
+            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());
-
-                    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();
     }
 
index 17a7c1bdf7c80aca64b8c17217e8f777845b2375..926aada0ec6087d44e2f0da524dd8672483bb609 100644 (file)
@@ -35,20 +35,20 @@ public final class ImageExtractor {
             System.err.println("\tImageExtractor <file>");
             return;
         }
-        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();
-
-            PictureType type = pict.getType();
-            FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension);
-            out.write(data);
-            out.close();
+        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();
+
+                PictureType type = pict.getType();
+                try (FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension)) {
+                    out.write(data);
+                }
+            }
+
         }
-        
-        ppt.close();
     }
 }
index 20f43f9403919108fe56f8070133f73cde0359db..b08d87c6a3a3437a7a1e944d93c667bf3ffb53f5 100644 (file)
@@ -79,9 +79,9 @@ public final class PowerPointExtractor extends POIOLE2TextExtractor {
                        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) {
index 2c673a22e8192c5686c38678ee486f701dbb619e..99b991fa11d63ea60222b9d8ed8914f190d581fc 100644 (file)
@@ -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
index cc926c9f08795b6f2e0be7c1df91a8cc36935fd5..7e0860573bf295e7ef136e156b091df072a6a82c 100644 (file)
@@ -511,33 +511,31 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
             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;
-            }
+        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);
+                // 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));
+                // 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 extends POIDocument implements Closeable {
         }
         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);
-
-        // Write out the Property Streams
-        writeProperties(outFS, writtenEntries);
-
-        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);
+        final List<String> writtenEntries = new ArrayList<>(1);
 
-        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(
+        // set new encryption settings
+        try (HSLFSlideShowEncrypted encryptedSS = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom())) {
+            _records = encryptedSS.updateEncryptionRecord(_records);
+
+            // Write out the Property Streams
+            writeProperties(outFS, writtenEntries);
+
+            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) {
index a94730ddb3a139de16f7948dbbb02b643ee88441..8910d6d669df4f6d5dbe98a8d4803bd7337fdec2 100644 (file)
 
 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.DocumentEntry;
 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 extends POIDocument {
      * @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
index 064e29839e7aa22b31766925344a0218a89b2ef9..f493036cf3450591ba8023c14f66f520615142b0 100644 (file)
@@ -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 extends BaseXLSIteratingTest {
        
        @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]);
+        }
        }
 }