From b4b661acc1538933aba0b9aecb9c86dfbf81fe12 Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Sat, 30 Nov 2019 23:00:08 +0000 Subject: [PATCH] Sonar fixes - use try-with-resources git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1870653 13f79535-47bb-0310-9956-ffa450edef68 --- .../poi/crypt/examples/OOXMLPasswordsTry.java | 49 +-- .../poi/hslf/examples/DataExtraction.java | 130 ++++---- .../apache/poi/hslf/examples/Hyperlinks.java | 49 ++- .../src/org/apache/poi/hssf/view/SViewer.java | 287 ++++++++++-------- .../poi/ss/examples/ConditionalFormats.java | 63 ++-- .../poi/xslf/usermodel/ChartFromScratch.java | 8 +- .../apache/poi/hssf/dev/BiffDrawingToXml.java | 54 ++-- .../poi/hssf/extractor/ExcelExtractor.java | 27 +- .../crypt/standard/StandardDecryptor.java | 2 +- .../crypt/standard/StandardEncryptor.java | 2 +- .../org/apache/poi/poifs/dev/POIFSLister.java | 11 +- .../poi/poifs/filesystem/Ole10Native.java | 12 +- .../poi/poifs/macros/VBAMacroExtractor.java | 18 +- .../apache/poi/ooxml/util/PackageHelper.java | 60 ++-- .../crypt/temp/AesZipFileZipEntrySource.java | 53 ++-- .../org/apache/poi/xslf/util/PPTX2PNG.java | 1 + .../org/apache/poi/hdgf/dev/VSDDumper.java | 8 +- .../apache/poi/hslf/dev/SlideIdListing.java | 172 +++++------ .../poi/hslf/extractor/ImageExtractor.java | 28 +- .../hslf/extractor/PowerPointExtractor.java | 6 +- .../poi/hslf/record/CurrentUserAtom.java | 13 +- .../poi/hslf/usermodel/HSLFSlideShowImpl.java | 127 ++++---- .../org/apache/poi/hwpf/HWPFDocumentCore.java | 53 ++-- .../poi/hssf/dev/TestBiffDrawingToXml.java | 14 +- 24 files changed, 607 insertions(+), 640 deletions(-) diff --git a/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java b/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java index aaeea354ab..033a4cdda8 100644 --- a/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java +++ b/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java @@ -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) { diff --git a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java b/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java index 9da099eb42..818580a955 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java +++ b/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java @@ -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(){ diff --git a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java index e0936de3f7..a3010bf132 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java +++ b/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java @@ -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 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 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewer.java b/src/examples/src/org/apache/poi/hssf/view/SViewer.java index 3d83c6aace..3e9daf34ff 100644 --- a/src/examples/src/org/apache/poi/hssf/view/SViewer.java +++ b/src/examples/src/org/apache/poi/hssf/view/SViewer.java @@ -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.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); + } } diff --git a/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java b/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java index dc6e6a54e6..654e837a42 100644 --- a/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java +++ b/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java @@ -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(); } /** diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java b/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java index 2c941e868c..3d1f7c7b9c 100644 --- a/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java +++ b/src/examples/src/org/apache/poi/xslf/usermodel/ChartFromScratch.java @@ -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"); } diff --git a/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java b/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java index 0a9f78b0c3..3fc3f5d3be 100644 --- a/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java +++ b/src/java/org/apache/poi/hssf/dev/BiffDrawingToXml.java @@ -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("\n"); - String tab = "\t"; - if (!excludeWorkbookRecords && r != null) { - r.decode(); - List escherRecords = r.getEscherRecords(); - for (EscherRecord record : escherRecords) { - builder.append(record.toXml(tab)); + StringBuilder builder = new StringBuilder(); + builder.append("\n"); + String tab = "\t"; + if (!excludeWorkbookRecords && r != null) { + r.decode(); + List escherRecords = r.getEscherRecords(); + for (EscherRecord record : escherRecords) { + builder.append(record.toXml(tab)); + } } - } - List sheets = getSheetsIndexes(params, workbook); - for (Integer i : sheets) { - HSSFPatriarch p = workbook.getSheetAt(i).getDrawingPatriarch(); - if(p != null ) { - builder.append(tab).append("\n"); - builder.append(p.getBoundAggregate().toXml(tab + "\t")); - builder.append(tab).append("\n"); + List sheets = getSheetsIndexes(params, workbook); + for (Integer i : sheets) { + HSSFPatriarch p = workbook.getSheetAt(i).getDrawingPatriarch(); + if (p != null) { + builder.append(tab).append("\n"); + builder.append(p.getBoundAggregate().toXml(tab + "\t")); + builder.append(tab).append("\n"); + } } + builder.append("\n"); + fos.write(builder.toString().getBytes(StringUtil.UTF8)); } - builder.append("\n"); - fos.write(builder.toString().getBytes(StringUtil.UTF8)); - fos.close(); - workbook.close(); } } diff --git a/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java b/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java index 55c32fb4f5..ec40f097f1 100644 --- a/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java +++ b/src/java/org/apache/poi/hssf/extractor/ExcelExtractor.java @@ -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 diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java index 67da57129a..9c7926033d 100644 --- a/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java +++ b/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java @@ -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); diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java index 7de19b9a7b..e3662b40ba 100644 --- a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java +++ b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java @@ -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 diff --git a/src/java/org/apache/poi/poifs/dev/POIFSLister.java b/src/java/org/apache/poi/poifs/dev/POIFSLister.java index 5ed20c75ab..f9696bccfb 100644 --- a/src/java/org/apache/poi/poifs/dev/POIFSLister.java +++ b/src/java/org/apache/poi/poifs/dev/POIFSLister.java @@ -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(); } } diff --git a/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java b/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java index 57084e6391..81481d3f65 100644 --- a/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java +++ b/src/java/org/apache/poi/poifs/filesystem/Ole10Native.java @@ -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); + } } /** diff --git a/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java b/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java index 57a7b1486f..9874270a9d 100644 --- a/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java +++ b/src/java/org/apache/poi/poifs/macros/VBAMacroExtractor.java @@ -78,10 +78,11 @@ public class VBAMacroExtractor { } else { System.err.println("STDOUT"); } - - VBAMacroReader reader = new VBAMacroReader(input); - Map macros = reader.readMacros(); - reader.close(); + + final Map macros; + try (VBAMacroReader reader = new VBAMacroReader(input)) { + macros = reader.readMacros(); + } final String divider = "---------------------------------------"; for (Entry 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); } } diff --git a/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java b/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java index 9da60dbef9..d357ab1f7f 100644 --- a/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java +++ b/src/ooxml/java/org/apache/poi/ooxml/util/PackageHelper.java @@ -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(); + 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(); diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java b/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java index 699fbe1fb8..454d17f82a 100644 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java +++ b/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java @@ -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 { diff --git a/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java b/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java index d1ba0167df..cd92196ac1 100644 --- a/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java +++ b/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java @@ -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); diff --git a/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java b/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java index f7f7570e4c..a7b1586821 100644 --- a/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java +++ b/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java @@ -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(); } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java index 5fdd48e090..7e5f3e26bc 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java +++ b/src/scratchpad/src/org/apache/poi/hslf/dev/SlideIdListing.java @@ -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 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 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(); } diff --git a/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java b/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java index 17a7c1bdf7..926aada0ec 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java +++ b/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java @@ -35,20 +35,20 @@ public final class ImageExtractor { System.err.println("\tImageExtractor "); 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(); } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java b/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java index 20f43f9403..b08d87c6a3 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java +++ b/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java @@ -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) { diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java index 2c673a22e8..99b991fa11 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java +++ b/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java @@ -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 diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java index cc926c9f08..7e0860573b 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java +++ b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java @@ -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 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 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) { diff --git a/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java b/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java index a94730ddb3..8910d6d669 100644 --- a/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java +++ b/src/scratchpad/src/org/apache/poi/hwpf/HWPFDocumentCore.java @@ -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.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 diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java index 064e29839e..f493036cf3 100644 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java +++ b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java @@ -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]); + } } } -- 2.39.5