]> source.dussan.org Git - poi.git/commitdiff
SonarQube fixes - close resources
authorAndreas Beeker <kiwiwings@apache.org>
Sun, 18 Dec 2016 22:03:31 +0000 (22:03 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Sun, 18 Dec 2016 22:03:31 +0000 (22:03 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1774969 13f79535-47bb-0310-9956-ffa450edef68

32 files changed:
src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java
src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java
src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java
src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java
src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java
src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java
src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java
src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java
src/java/org/apache/poi/hssf/record/FilePassRecord.java
src/java/org/apache/poi/hssf/record/ObjRecord.java
src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java
src/java/org/apache/poi/poifs/dev/POIFSLister.java
src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java
src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java
src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java
src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java
src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java
src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java
src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java
src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java

index 3c706e3e73de889ba702b9d9c97550826987a7e8..1997200884599c4243b97ae30459200afb2c1ec3 100644 (file)
@@ -18,6 +18,7 @@
 package org.apache.poi.hslf.examples;
 
 import java.io.FileOutputStream;
+import java.io.IOException;
 
 import org.apache.poi.hslf.usermodel.HSLFSlide;
 import org.apache.poi.hslf.usermodel.HSLFSlideShow;
@@ -27,12 +28,10 @@ import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
 /**
  * How to create a single-level bulleted list
  * and change some of the bullet attributes
- *
- * @author Yegor Kozlov
  */
 public final class BulletsDemo {
 
-    public static void main(String[] args) throws Exception {
+    public static void main(String[] args) throws IOException {
 
         HSLFSlideShow ppt = new HSLFSlideShow();
 
@@ -58,5 +57,7 @@ public final class BulletsDemo {
         FileOutputStream out = new FileOutputStream("bullets.ppt");
         ppt.write(out);
         out.close();
+        
+        ppt.close();
    }
 }
index b37aed2df66900aa732028a6a58c179aab513324..3ef5a46ab3c248cfddadb35cfabfffdfef64db33 100644 (file)
@@ -44,6 +44,7 @@ public abstract class HeadersFootersDemo {
         ppt.write(out);
         out.close();
 
+        ppt.close();
     }
 
 }
index d29635004adc336206fee6c0049dde4771ea7042..9158b0ccff519988a2f800fb1adcf5256f352b3b 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.hssf.util.HSSFColor;
-
 import java.io.FileOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.BorderStyle;
+
 /**
  * Demonstrates how to create borders around cells.
- *
- * @author Glen Stampoultzis (glens at apache.org)
  */
 public class Borders {
     public static void main(String[] args) throws IOException {
@@ -42,13 +45,13 @@ public class Borders {
 
         // Style the cell with borders all around.
         HSSFCellStyle style = wb.createCellStyle();
-        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
+        style.setBorderBottom(BorderStyle.THIN);
         style.setBottomBorderColor(HSSFColor.BLACK.index);
-        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
+        style.setBorderLeft(BorderStyle.THIN);
         style.setLeftBorderColor(HSSFColor.GREEN.index);
-        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
+        style.setBorderRight(BorderStyle.THIN);
         style.setRightBorderColor(HSSFColor.BLUE.index);
-        style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);
+        style.setBorderTop(BorderStyle.MEDIUM_DASHED);
         style.setTopBorderColor(HSSFColor.ORANGE.index);
         cell.setCellStyle(style);
 
@@ -56,5 +59,7 @@ public class Borders {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        
+        wb.close();
     }
 }
index c3a213d582ba15ef41bd63c06d4068f98ae5e83c..4109a87f481b942669ed2fc0501f57b59082d898 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
+import org.apache.poi.hssf.usermodel.HSSFComment;
+import org.apache.poi.hssf.usermodel.HSSFFont;
+import org.apache.poi.hssf.usermodel.HSSFPatriarch;
+import org.apache.poi.hssf.usermodel.HSSFRichTextString;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.hssf.util.HSSFColor;
 
-import java.io.*;
-
 /**
  * Demonstrates how to work with excel cell comments.
  *
@@ -29,8 +37,6 @@ import java.io.*;
  * Excel comment is a kind of a text shape,
  * so inserting a comment is very similar to placing a text box in a worksheet
  * </p>
- *
- * @author Yegor Kozlov
  */
 public class CellComments {
 
@@ -74,7 +80,7 @@ public class CellComments {
         HSSFFont font = wb.createFont();
         font.setFontName("Arial");
         font.setFontHeightInPoints((short)10);
-        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
+        font.setBold(true);
         font.setColor(HSSFColor.RED.index);
         string.applyFont(font);
 
@@ -94,5 +100,7 @@ public class CellComments {
         FileOutputStream out = new FileOutputStream("poi_comment.xls");
         wb.write(out);
         out.close();
+        
+        wb.close();
     }
 }
index 3e31d11f2675eb3a9857ca60ce38a96d0d458c57..80ced95ac0c37aaa1fae8350348890b7856f92b4 100644 (file)
@@ -41,5 +41,7 @@ public class CellTypes {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        
+        wb.close();
     }
 }
index 746fd536b8f87dd505830f7a50c1f6a80d6e4eeb..8afe085f1ed648236a475f20a11264dadb0a2d48 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
-
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.Date;
 
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFDataFormat;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
 /**
  * An example on how to cells with dates.  The important thing to note
  * about dates is that they are really normal numeric cells that are
  * formatted specially.
- *
- * @author Glen Stampoultzis (glens at apache.org)
  */
 public class CreateDateCells {
     public static void main(String[] args) throws IOException {
@@ -54,5 +57,7 @@ public class CreateDateCells {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        
+        wb.close();
     }
 }
index 02b7cb3e3915501bd60652b7484d2af2ea3af00c..40be15e0145fcb5b68b0da7092d27441b441850d 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.hssf.util.HSSFColor;
-
 import java.io.FileOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.FillPatternType;
+
 /**
  * Shows how to use various fills.
- *
- * @author Glen Stampoultzis (glens at apache.org)
  */
 public class FrillsAndFills {
     public static void main(String[] args) throws IOException {
@@ -39,7 +42,7 @@ public class FrillsAndFills {
         // Aqua background
         HSSFCellStyle style = wb.createCellStyle();
         style.setFillBackgroundColor(HSSFColor.AQUA.index);
-        style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
+        style.setFillPattern(FillPatternType.BIG_SPOTS);
         HSSFCell cell = row.createCell(1);
         cell.setCellValue("X");
         cell.setCellStyle(style);
@@ -47,7 +50,7 @@ public class FrillsAndFills {
         // Orange "foreground", foreground being the fill foreground not the font color.
         style = wb.createCellStyle();
         style.setFillForegroundColor(HSSFColor.ORANGE.index);
-        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
+        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
         cell = row.createCell(2);
         cell.setCellValue("X");
         cell.setCellStyle(style);
@@ -56,5 +59,7 @@ public class FrillsAndFills {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        
+        wb.close();
     }
 }
index 2f67f7f0e50ce6d596b0d726610ce3f63ac5f28a..632cd5585faf0cd6402bdbc4279833c9e7c4866b 100644 (file)
@@ -31,6 +31,7 @@ import org.apache.poi.hssf.usermodel.HSSFRow;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.ss.usermodel.BorderStyle;
+import org.apache.poi.ss.usermodel.FillPatternType;
 import org.apache.poi.ss.util.CellRangeAddress;
 
 /**
@@ -77,7 +78,7 @@ public final class HSSFReadWrite {
                cs.setFont(f);
                cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)"));
                cs2.setBorderBottom(BorderStyle.THIN);
-               cs2.setFillPattern((short) 1); // fill w fg
+               cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                cs2.setFillForegroundColor((short) 0xA);
                cs2.setFont(f2);
                wb.setSheetName(0, "HSSF Test");
@@ -128,9 +129,8 @@ public final class HSSFReadWrite {
                    wb.write(out);
                } finally {
                    out.close();
+               wb.close();
                }
-               
-               wb.close();
        }
 
        /**
index 148b2a58b0d7fe87bbc968ad52fb4d66bd4a94ea..003c09f688dfd18f652ce2d78f5913ec0960cd4a 100644 (file)
@@ -28,8 +28,6 @@ import org.apache.poi.ss.usermodel.CellType;
 
 /**
  * Test if hyperlink formula, with url that got more than 127 characters, works
- *
- * @author Bernard Chesnoy
  */
 public class HyperlinkFormula {
     public static void main(String[] args) throws IOException {
@@ -44,5 +42,6 @@ public class HyperlinkFormula {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        wb.close();
     }
 }
index c1ccad91008b30c9b64806aa4d26465fd4e18ea0..adad7da363f7d778422113f583273453baf01604 100644 (file)
@@ -29,6 +29,7 @@ import org.apache.poi.hssf.usermodel.HSSFHyperlink;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.Font;
 
 /**
  * Demonstrates how to create hyperlinks.
@@ -45,7 +46,7 @@ public class Hyperlinks {
         //by default hyperlinks are blue and underlined
         HSSFCellStyle hlink_style = wb.createCellStyle();
         HSSFFont hlink_font = wb.createFont();
-        hlink_font.setUnderline(HSSFFont.U_SINGLE);
+        hlink_font.setUnderline(Font.U_SINGLE);
         hlink_font.setColor(HSSFColor.BLUE.index);
         hlink_style.setFont(hlink_font);
 
@@ -93,5 +94,6 @@ public class Hyperlinks {
         FileOutputStream out = new FileOutputStream("hssf-links.xls");
         wb.write(out);
         out.close();
+        wb.close();
     }
 }
index 31e5215b8e432489672f170b49e15e9da838b1bb..09d08dd257dcf927ece2c3047a5da1c8888c0439 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.ss.util.CellRangeAddress;
-
-import java.io.IOException;
 import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.util.CellRangeAddress;
 
 /**
  * An example of how to merge regions of cells.
- *
- * @author Glen Stampoultzis (glens at apache.org)
  */
 public class MergedCells {
    public static void main(String[] args) throws IOException {
@@ -43,5 +44,6 @@ public class MergedCells {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        wb.close();
     }
 }
index 018556f991f0b80adcaced403363b43eb3db24f4..00f60c4dafe222eb08cbba008c9cef82bf862b88 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
-import org.apache.poi.ss.usermodel.CellType;
-
 import java.io.FileOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFFont;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.CellType;
+
 /**
  * Demonstrates how to use newlines in cells.
- *
- * @author Glen Stampoultzis (glens at apache.org)
- * @author Fauzia Lala <fauzia.lala at wcom.com>
  */
 public class NewLinesInCells {
     public static void main( String[] args ) throws IOException {
@@ -56,5 +58,6 @@ public class NewLinesInCells {
                FileOutputStream fileOut = new FileOutputStream("workbook.xls");
                wb.write(fileOut);
                fileOut.close();
+               wb.close();
     }
 }
index c1614e6c1a1eee8370ef1ae4bead712cbaaa1d39..e6e0e4137e0b87a9cec2ed49d370006f9d74530c 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-
 import java.io.FileOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
 /**
  * This example creates a new blank workbook.  This workbook will contain a single blank sheet.
- *
- * @author Glen Stampoultzis (glens at apache.org)
  */
-public class NewWorkbook
-{
-    public static void main(String[] args)
-        throws IOException
-    {
+public class NewWorkbook {
+    public static void main(String[] args) throws IOException {
         HSSFWorkbook wb = new HSSFWorkbook();
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        wb.close();
     }
 }
index 6e93a317f0596cdf90387568fedbe95a37e52818..85cba2eb98cad43ea52d9799a634341975e2e6dc 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.hssf.usermodel.HSSFSheet;
-
-import java.io.IOException;
 import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.Sheet;
 
-/**
- * @author Glen Stampoultzis (glens at apache.org)
- */
-public class SplitAndFreezePanes
-{
-    public static void main(String[] args)
-        throws IOException
-    {
+public class SplitAndFreezePanes {
+    public static void main(String[] args) throws IOException {
         HSSFWorkbook wb = new HSSFWorkbook();
         HSSFSheet sheet1 = wb.createSheet("new sheet");
         HSSFSheet sheet2 = wb.createSheet("second sheet");
@@ -46,10 +41,11 @@ public class SplitAndFreezePanes
         // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
         sheet3.createFreezePane( 2, 2 );
         // Create a split with the lower left side being the active quadrant
-        sheet4.createSplitPane( 2000, 2000, 0, 0, HSSFSheet.PANE_LOWER_LEFT );
+        sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
 
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        wb.close();
     }
 }
index 6cb15941f218989f1cc0699f4620f3bd86bb8d58..d3c674a756d0e268da467e44439fbbdb9acc5cf4 100644 (file)
 
 package org.apache.poi.hssf.usermodel.examples;
 
-import org.apache.poi.hssf.usermodel.*;
-
 import java.io.FileOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFFont;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
 /**
  * Demonstrates how to create and use fonts.
- *
- * @author Glen Stampoultzis (glens at apache.org)
  */
 public class WorkingWithFonts {
     public static void main(String[] args) throws IOException {
@@ -55,5 +58,6 @@ public class WorkingWithFonts {
         FileOutputStream fileOut = new FileOutputStream("workbook.xls");
         wb.write(fileOut);
         fileOut.close();
+        wb.close();
     }
 }
index 5eb10c242996124c6e34b8c13ef3606a4a16ce78..a7ef6d2ba2ab6b1827ec15ce00b499995464eb6e 100644 (file)
 package org.apache.poi.ss.examples;\r
 \r
 import java.io.File;\r
-import java.io.FileNotFoundException;\r
 import java.io.FileOutputStream;\r
 import java.io.IOException;\r
 import java.net.URL;\r
 import java.util.Locale;\r
 \r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
 import org.apache.poi.hssf.usermodel.HSSFSheet;\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
 import org.apache.poi.ss.usermodel.ClientAnchor;\r
 import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;\r
 import org.apache.poi.ss.usermodel.Drawing;\r
@@ -813,50 +812,28 @@ public class AddDimensionedImage {
      *\r
      * @param args the command line arguments\r
      */\r
-    public static void main(String[] args) {\r
+    public static void main(String[] args) throws IOException {\r
        String imageFile = null;\r
        String outputFile = null;\r
         FileOutputStream fos = null;\r
         Workbook workbook = null;\r
         Sheet sheet = null;\r
-        try {\r
-               if(args.length < 2){\r
-                       System.err.println("Usage: AddDimensionedImage imageFile outputFile");\r
-                       return;\r
-               }\r
-               workbook = new HSSFWorkbook();   // OR XSSFWorkbook\r
-               sheet = workbook.createSheet("Picture Test");\r
-                       imageFile = args[0];\r
-               outputFile = args[1];\r
-               new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),\r
-                       new File(imageFile).toURI().toURL(), 100, 40,\r
-                       AddDimensionedImage.EXPAND_ROW_AND_COLUMN);\r
-               fos = new FileOutputStream(outputFile);\r
-            workbook.write(fos);\r
-        }\r
-        catch(FileNotFoundException fnfEx) {\r
-            System.out.println("Caught an: " + fnfEx.getClass().getName());\r
-            System.out.println("Message: " + fnfEx.getMessage());\r
-            System.out.println("Stacktrace follows...........");\r
-            fnfEx.printStackTrace(System.out);\r
-        }\r
-        catch(IOException ioEx) {\r
-            System.out.println("Caught an: " + ioEx.getClass().getName());\r
-            System.out.println("Message: " + ioEx.getMessage());\r
-            System.out.println("Stacktrace follows...........");\r
-            ioEx.printStackTrace(System.out);\r
-        }\r
-        finally {\r
-            if(fos != null) {\r
-                try {\r
-                    fos.close();\r
-                    fos = null;\r
-                }\r
-                catch(IOException ioEx) {\r
-                    // I G N O R E\r
-                }\r
-            }\r
-        }\r
+\r
+        if(args.length < 2){\r
+               System.err.println("Usage: AddDimensionedImage imageFile outputFile");\r
+               return;\r
+       }\r
+       workbook = new HSSFWorkbook();   // OR XSSFWorkbook\r
+       sheet = workbook.createSheet("Picture Test");\r
+               imageFile = args[0];\r
+       outputFile = args[1];\r
+       new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),\r
+               new File(imageFile).toURI().toURL(), 100, 40,\r
+               AddDimensionedImage.EXPAND_ROW_AND_COLUMN);\r
+               fos = new FileOutputStream(outputFile);\r
+        workbook.write(fos);\r
+        fos.close();\r
+        workbook.close();\r
     }\r
 \r
     /**\r
index 7358edf6823e75044184f394025e050d4e084779..eba1e219f252c6ccca27bddc9e72f825fa48611a 100644 (file)
 \r
 package org.apache.poi.ss.examples;\r
 \r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.ss.usermodel.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.ss.usermodel.BuiltinFormats;\r
+import org.apache.poi.ss.usermodel.CellStyle;\r
+import org.apache.poi.ss.usermodel.ColorScaleFormatting;\r
+import org.apache.poi.ss.usermodel.ComparisonOperator;\r
+import org.apache.poi.ss.usermodel.ConditionalFormattingRule;\r
 import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType;\r
+import org.apache.poi.ss.usermodel.DataBarFormatting;\r
+import org.apache.poi.ss.usermodel.ExtendedColor;\r
+import org.apache.poi.ss.usermodel.FontFormatting;\r
+import org.apache.poi.ss.usermodel.IconMultiStateFormatting;\r
 import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet;\r
+import org.apache.poi.ss.usermodel.IndexedColors;\r
+import org.apache.poi.ss.usermodel.PatternFormatting;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.SheetConditionalFormatting;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
 import org.apache.poi.ss.util.CellRangeAddress;\r
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
 \r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
 /**\r
  * Excel Conditional Formatting -- Examples\r
  *\r
@@ -42,8 +56,11 @@ public class ConditionalFormats {
     public static void main(String[] args) throws IOException {\r
         Workbook wb;\r
 \r
-        if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();\r
-        else wb = new XSSFWorkbook();\r
+        if(args.length > 0 && args[0].equals("-xls")) {\r
+            wb = new HSSFWorkbook();\r
+        } else {\r
+            wb = new XSSFWorkbook();\r
+        }\r
 \r
         sameCell(wb.createSheet("Same Cell"));\r
         multiCell(wb.createSheet("MultiCell"));\r
@@ -61,11 +78,14 @@ public class ConditionalFormats {
 \r
         // Write the output to a file\r
         String file = "cf-poi.xls";\r
-        if(wb instanceof XSSFWorkbook) file += "x";\r
+        if(wb instanceof XSSFWorkbook) {\r
+            file += "x";\r
+        }\r
         FileOutputStream out = new FileOutputStream(file);\r
         wb.write(out);\r
         out.close();\r
         System.out.println("Generated: " + file);\r
+        wb.close();\r
     }\r
 \r
     /**\r
@@ -157,11 +177,21 @@ public class ConditionalFormats {
             Row r = sheet.createRow(i);\r
             r.createCell(0).setCellValue("This is row " + rn + " (" + i + ")");\r
             String str = "";\r
-            if (rn%2 == 0) str = str + "even ";\r
-            if (rn%3 == 0) str = str + "x3 ";\r
-            if (rn%5 == 0) str = str + "x5 ";\r
-            if (rn%10 == 0) str = str + "x10 ";\r
-            if (str.length() == 0) str = "nothing special...";\r
+            if (rn%2 == 0) {\r
+                str = str + "even ";\r
+            }\r
+            if (rn%3 == 0) {\r
+                str = str + "x3 ";\r
+            }\r
+            if (rn%5 == 0) {\r
+                str = str + "x5 ";\r
+            }\r
+            if (rn%10 == 0) {\r
+                str = str + "x10 ";\r
+            }\r
+            if (str.length() == 0) {\r
+                str = "nothing special...";\r
+            }\r
             r.createCell(1).setCellValue("It is " + str);\r
         }\r
         sheet.autoSizeColumn(0);\r
@@ -353,7 +383,9 @@ public class ConditionalFormats {
         sheet.createRow(2).createCell(0).setCellFormula("A2+1");\r
         sheet.createRow(3).createCell(0).setCellFormula("A3+1");\r
 \r
-        for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style);\r
+        for(int rownum = 1; rownum <= 3; rownum++) {\r
+            sheet.getRow(rownum).getCell(0).setCellStyle(style);\r
+        }\r
 \r
         SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();\r
 \r
index b0efc4f0ce38377beedcf50893af3ec7481ee839..7b672b792c9d469a7a96c99dec703b1b3df27e79 100644 (file)
    ==================================================================== */\r
 \r
 package org.apache.poi.ss.examples;\r
-import java.io.*;\r
-import org.apache.poi.xssf.usermodel.*;\r
-import org.apache.poi.hssf.usermodel.*;\r
-import org.apache.poi.ss.usermodel.*;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.ss.usermodel.Cell;\r
+import org.apache.poi.ss.usermodel.DataValidation;\r
+import org.apache.poi.ss.usermodel.DataValidationConstraint;\r
+import org.apache.poi.ss.usermodel.DataValidationHelper;\r
+import org.apache.poi.ss.usermodel.Name;\r
+import org.apache.poi.ss.usermodel.Row;\r
+import org.apache.poi.ss.usermodel.Sheet;\r
+import org.apache.poi.ss.usermodel.Workbook;\r
 import org.apache.poi.ss.util.CellRangeAddressList;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
 \r
 /**\r
  * Demonstrates one technique that may be used to create linked or dependent\r
@@ -56,78 +65,52 @@ import org.apache.poi.ss.util.CellRangeAddressList;
  */\r
 public class LinkedDropDownLists {\r
 \r
-    LinkedDropDownLists(String workbookName) {\r
-        File file = null;\r
-        FileOutputStream fos = null;\r
-        Workbook workbook = null;\r
-        Sheet sheet = null;\r
-        DataValidationHelper dvHelper = null;\r
-        DataValidationConstraint dvConstraint = null;\r
-        DataValidation validation = null;\r
-        CellRangeAddressList addressList = null;\r
-        try {\r
-\r
-            // Using the ss.usermodel allows this class to support both binary\r
-            // and xml based workbooks. The choice of which one to create is\r
-            // made by checking the file extension.\r
-            if (workbookName.endsWith(".xlsx")) {\r
-                workbook = new XSSFWorkbook();\r
-            } else {\r
-                workbook = new HSSFWorkbook();\r
-            }\r
-            \r
-            // Build the sheet that will hold the data for the validations. This\r
-            // must be done first as it will create names that are referenced \r
-            // later.\r
-            sheet = workbook.createSheet("Linked Validations");\r
-            LinkedDropDownLists.buildDataSheet(sheet);\r
-\r
-            // Build the first data validation to occupy cell A1. Note\r
-            // that it retrieves it's data from the named area or region called\r
-            // CHOICES. Further information about this can be found in the\r
-            // static buildDataSheet() method below.\r
-            addressList = new CellRangeAddressList(0, 0, 0, 0);\r
-            dvHelper = sheet.getDataValidationHelper();\r
-            dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");\r
-            validation = dvHelper.createValidation(dvConstraint, addressList);\r
-            sheet.addValidationData(validation);\r
-            \r
-            // Now, build the linked or dependent drop down list that will\r
-            // occupy cell B1. The key to the whole process is the use of the\r
-            // INDIRECT() function. In the buildDataSheet(0 method, a series of\r
-            // named regions are created and the names of three of them mirror\r
-            // the options available to the user in the first drop down list\r
-            // (in cell A1). Using the INDIRECT() function makes it possible\r
-            // to convert the selection the user makes in that first drop down\r
-            // into the addresses of a named region of cells and then to use\r
-            // those cells to populate the second drop down list.\r
-            addressList = new CellRangeAddressList(0, 0, 1, 1);\r
-            dvConstraint = dvHelper.createFormulaListConstraint(\r
-                    "INDIRECT(UPPER($A$1))");\r
-            validation = dvHelper.createValidation(dvConstraint, addressList);\r
-            sheet.addValidationData(validation);\r
-            \r
-            file = new File(workbookName);\r
-            fos = new FileOutputStream(file);\r
-            workbook.write(fos);\r
-        } catch (IOException ioEx) {\r
-            System.out.println("Caught a: " + ioEx.getClass().getName());\r
-            System.out.println("Message: " + ioEx.getMessage());\r
-            System.out.println("Stacktrace follws:.....");\r
-            ioEx.printStackTrace(System.out);\r
-        } finally {\r
-            try {\r
-                if (fos != null) {\r
-                    fos.close();\r
-                    fos = null;\r
-                }\r
-            } catch (IOException ioEx) {\r
-                System.out.println("Caught a: " + ioEx.getClass().getName());\r
-                System.out.println("Message: " + ioEx.getMessage());\r
-                System.out.println("Stacktrace follws:.....");\r
-                ioEx.printStackTrace(System.out);\r
-            }\r
+    LinkedDropDownLists(String workbookName) throws IOException {\r
+        // Using the ss.usermodel allows this class to support both binary\r
+        // and xml based workbooks. The choice of which one to create is\r
+        // made by checking the file extension.\r
+        Workbook workbook;\r
+        if (workbookName.endsWith(".xlsx")) {\r
+            workbook = new XSSFWorkbook();\r
+        } else {\r
+            workbook = new HSSFWorkbook();\r
         }\r
+        \r
+        // Build the sheet that will hold the data for the validations. This\r
+        // must be done first as it will create names that are referenced \r
+        // later.\r
+        Sheet sheet = workbook.createSheet("Linked Validations");\r
+        LinkedDropDownLists.buildDataSheet(sheet);\r
+\r
+        // Build the first data validation to occupy cell A1. Note\r
+        // that it retrieves it's data from the named area or region called\r
+        // CHOICES. Further information about this can be found in the\r
+        // static buildDataSheet() method below.\r
+        CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);\r
+        DataValidationHelper dvHelper = sheet.getDataValidationHelper();\r
+        DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");\r
+        DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);\r
+        sheet.addValidationData(validation);\r
+        \r
+        // Now, build the linked or dependent drop down list that will\r
+        // occupy cell B1. The key to the whole process is the use of the\r
+        // INDIRECT() function. In the buildDataSheet(0 method, a series of\r
+        // named regions are created and the names of three of them mirror\r
+        // the options available to the user in the first drop down list\r
+        // (in cell A1). Using the INDIRECT() function makes it possible\r
+        // to convert the selection the user makes in that first drop down\r
+        // into the addresses of a named region of cells and then to use\r
+        // those cells to populate the second drop down list.\r
+        addressList = new CellRangeAddressList(0, 0, 1, 1);\r
+        dvConstraint = dvHelper.createFormulaListConstraint(\r
+                "INDIRECT(UPPER($A$1))");\r
+        validation = dvHelper.createValidation(dvConstraint, addressList);\r
+        sheet.addValidationData(validation);\r
+        \r
+        FileOutputStream fos = new FileOutputStream(workbookName);\r
+        workbook.write(fos);\r
+        fos.close();\r
+        workbook.close();\r
     }\r
 \r
     /**\r
index 66ca8ba7b2417d3dd2ca885824132745fabe3dfd..2ad0347f7b454d440d1f84af566e65deb79700e4 100644 (file)
 package org.apache.poi.ss.examples;
 
 import java.io.File;
+import java.io.IOException;
 import java.io.InputStream;
 
+import org.apache.poi.EncryptedDocumentException;
 import org.apache.poi.hslf.usermodel.HSLFSlideShow;
 import org.apache.poi.hssf.usermodel.HSSFObjectData;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.hwpf.HWPFDocument;
-import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
 import org.apache.poi.openxml4j.opc.PackagePart;
 import org.apache.poi.poifs.filesystem.DirectoryNode;
 import org.apache.poi.poifs.filesystem.Entry;
 import org.apache.poi.sl.usermodel.SlideShow;
 import org.apache.poi.ss.usermodel.Workbook;
 import org.apache.poi.ss.usermodel.WorkbookFactory;
-import org.apache.poi.xslf.usermodel.XSLFSlideShow;
+import org.apache.poi.xslf.usermodel.XMLSlideShow;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.apache.xmlbeans.XmlException;
 
 /**
  * Loads embedded resources from Workbooks. Code taken from the website:
  *  https://poi.apache.org/spreadsheet/quick-guide.html#Embedded
  */
 public class LoadEmbedded {
-   public static void main(String[] args) throws Exception {
+   public static void main(String[] args) throws IOException, EncryptedDocumentException, OpenXML4JException, XmlException {
        Workbook wb = WorkbookFactory.create(new File(args[0]));
        loadEmbedded(wb);
    }
    
-   public static void loadEmbedded(Workbook wb) throws Exception {
+   public static void loadEmbedded(Workbook wb) throws IOException, InvalidFormatException, OpenXML4JException, XmlException {
        if (wb instanceof HSSFWorkbook) {
            loadEmbedded((HSSFWorkbook)wb);
        }
@@ -57,22 +61,22 @@ public class LoadEmbedded {
        }
    }
    
-   public static void loadEmbedded(HSSFWorkbook workbook) throws Exception {
+   public static void loadEmbedded(HSSFWorkbook workbook) throws IOException {
        for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) {
            //the OLE2 Class Name of the object
            String oleName = obj.getOLE2ClassName();
            if (oleName.equals("Worksheet")) {
                DirectoryNode dn = (DirectoryNode) obj.getDirectory();
                HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, false);
-               //System.out.println(entry.getName() + ": " + embeddedWorkbook.getNumberOfSheets());
+               embeddedWorkbook.close();
            } else if (oleName.equals("Document")) {
                DirectoryNode dn = (DirectoryNode) obj.getDirectory();
                HWPFDocument embeddedWordDocument = new HWPFDocument(dn);
-               //System.out.println(entry.getName() + ": " + embeddedWordDocument.getRange().text());
+               embeddedWordDocument.close();
            }  else if (oleName.equals("Presentation")) {
                DirectoryNode dn = (DirectoryNode) obj.getDirectory();
-               SlideShow<?,?> embeddedPowerPointDocument = new HSLFSlideShow(dn);
-               //System.out.println(entry.getName() + ": " + embeddedPowerPointDocument.getSlides().length);
+               SlideShow<?,?> embeddedSlieShow = new HSLFSlideShow(dn);
+               embeddedSlieShow.close();
            } else {
                if(obj.hasDirectoryEntry()){
                    // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is
@@ -89,40 +93,38 @@ public class LoadEmbedded {
        }
    }
    
-   public static void loadEmbedded(XSSFWorkbook workbook) throws Exception {
+   public static void loadEmbedded(XSSFWorkbook workbook) throws IOException, InvalidFormatException, OpenXML4JException, XmlException {
        for (PackagePart pPart : workbook.getAllEmbedds()) {
            String contentType = pPart.getContentType();
-           // Excel Workbook - either binary or OpenXML
            if (contentType.equals("application/vnd.ms-excel")) {
+               // Excel Workbook - either binary or OpenXML
                HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
-           }
-           // Excel Workbook - OpenXML file format
-           else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
-               OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
-               XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(docPackage);
-           }
-           // Word Document - binary (OLE2CDF) file format
-           else if (contentType.equals("application/msword")) {
+               embeddedWorkbook.close();
+           } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
+               // Excel Workbook - OpenXML file format
+               XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
+               embeddedWorkbook.close();
+           } else if (contentType.equals("application/msword")) {
+               // Word Document - binary (OLE2CDF) file format
                HWPFDocument document = new HWPFDocument(pPart.getInputStream());
-           }
-           // Word Document - OpenXML file format
-           else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
-               OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
-               XWPFDocument document = new XWPFDocument(docPackage);
-           }
-           // PowerPoint Document - binary file format
-           else if (contentType.equals("application/vnd.ms-powerpoint")) {
+               document.close();
+           } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
+               // Word Document - OpenXML file format
+               XWPFDocument document = new XWPFDocument(pPart.getInputStream());
+               document.close();
+           } else if (contentType.equals("application/vnd.ms-powerpoint")) {
+               // PowerPoint Document - binary file format
                HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream());
-           }
-           // PowerPoint Document - OpenXML file format
-           else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
-               OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());
-               XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);
-           }
-           // Any other type of embedded object.
-           else {
+               slideShow.close();
+           } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
+               // PowerPoint Document - OpenXML file format
+               XMLSlideShow slideShow = new XMLSlideShow(pPart.getInputStream());
+               slideShow.close();
+           } else {
+               // Any other type of embedded object.
                System.out.println("Unknown Embedded Document: " + contentType);
                InputStream inputStream = pPart.getInputStream();
+               inputStream.close();
            }
        }
    }
index 3f044c839e29c25c0d5313e3485eac74255e0d5b..5d367316b3657d8a9f0b82f6447bbfca550fd2ac 100644 (file)
 ==================================================================== */\r
 package org.apache.poi.xssf.usermodel.examples;\r
 \r
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
+import java.io.InputStream;\r
+\r
+import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;\r
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
+import org.apache.poi.hwpf.HWPFDocument;\r
 import org.apache.poi.openxml4j.opc.OPCPackage;\r
 import org.apache.poi.openxml4j.opc.PackagePart;\r
 import org.apache.poi.xslf.usermodel.XSLFSlideShow;\r
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
 import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
-import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;\r
-import org.apache.poi.hwpf.HWPFDocument;\r
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;\r
-\r
-import java.io.InputStream;\r
 \r
 /**\r
  * Demonstrates how you can extract embedded data from a .xlsx file\r
  */\r
 public class EmbeddedObjects {\r
     public static void main(String[] args) throws Exception {\r
-        OPCPackage pkg = OPCPackage.open(args[0]);\r
-        XSSFWorkbook workbook = new XSSFWorkbook(pkg);\r
+        XSSFWorkbook workbook = new XSSFWorkbook(args[0]);\r
         for (PackagePart pPart : workbook.getAllEmbedds()) {\r
             String contentType = pPart.getContentType();\r
-            // Excel Workbook - either binary or OpenXML\r
             if (contentType.equals("application/vnd.ms-excel")) {\r
+                // Excel Workbook - either binary or OpenXML\r
                 HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());\r
-            }\r
-            // Excel Workbook - OpenXML file format\r
-            else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
+                embeddedWorkbook.close();\r
+            } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {\r
+                // Excel Workbook - OpenXML file format\r
                 XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());\r
-            }\r
-            // Word Document - binary (OLE2CDF) file format\r
-            else if (contentType.equals("application/msword")) {\r
+                embeddedWorkbook.close();\r
+            } else if (contentType.equals("application/msword")) {\r
+                // Word Document - binary (OLE2CDF) file format\r
                 HWPFDocument document = new HWPFDocument(pPart.getInputStream());\r
-            }\r
-            // Word Document - OpenXML file format\r
-            else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
+                document.close();\r
+            } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {\r
+                // Word Document - OpenXML file format\r
                 XWPFDocument document = new XWPFDocument(pPart.getInputStream());\r
-            }\r
-            // PowerPoint Document - binary file format\r
-            else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
+                document.close();\r
+            } else if (contentType.equals("application/vnd.ms-powerpoint")) {\r
+                // PowerPoint Document - binary file format\r
                 HSLFSlideShowImpl slideShow = new HSLFSlideShowImpl(pPart.getInputStream());\r
-            }\r
-            // PowerPoint Document - OpenXML file format\r
-            else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
+                slideShow.close();\r
+            } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {\r
+                // PowerPoint Document - OpenXML file format\r
                 OPCPackage docPackage = OPCPackage.open(pPart.getInputStream());\r
                 XSLFSlideShow slideShow = new XSLFSlideShow(docPackage);\r
-            }\r
-            // Any other type of embedded object.\r
-            else {\r
+                slideShow.close();\r
+            } else {\r
+                // Any other type of embedded object.\r
                 System.out.println("Unknown Embedded Document: " + contentType);\r
                 InputStream inputStream = pPart.getInputStream();\r
+                inputStream.close();\r
             }\r
         }\r
-        pkg.close();\r
+        workbook.close();\r
     }\r
 }
\ No newline at end of file
index ab941fad5f79ab04d173090f5e24a199ce8cbcea..5955e6d1355f91446d2bbd877a050f0a0c681246 100644 (file)
@@ -89,7 +89,7 @@ public final class FilePassRecord extends StandardRecord implements Cloneable {
         out.writeShort(encryptionType);
 
         byte data[] = new byte[1024];
-        LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(data, 0);
+        LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(data, 0); // NOSONAR
 
         switch (encryptionInfo.getEncryptionMode()) {
             case xor:
index 8eb4e03afc04fa5636f042f3e533f88afc56790e..5220f9cc0704f6d01915f6955b034a8ebe4c9e30 100644 (file)
@@ -176,7 +176,7 @@ public final class ObjRecord extends Record implements Cloneable {
        public int serialize(int offset, byte[] data) {
                int recSize = getRecordSize();
                int dataSize = recSize - 4;
-               LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(data, offset, recSize);
+               LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(data, offset, recSize); // NOSONAR
 
                out.writeShort(sid);
                out.writeShort(dataSize);
index 7c50b6643d012443b082d82db4303cab945f90af..2f3be03de90f0d105fe0be1268e5b0e1f5738a6e 100644 (file)
@@ -435,8 +435,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
 
      private void convertLabelRecords(List<Record> records, int offset)
      {
-         if (log.check( POILogger.DEBUG ))
-             log.log(POILogger.DEBUG, "convertLabelRecords called");
+         if (log.check( POILogger.DEBUG )) {
+            log.log(POILogger.DEBUG, "convertLabelRecords called");
+        }
          for (int k = offset; k < records.size(); k++)
          {
              Record rec = records.get(k);
@@ -457,8 +458,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
                        records.add(k, newrec);
              }
          }
-         if (log.check( POILogger.DEBUG ))
-             log.log(POILogger.DEBUG, "convertLabelRecords exit");
+         if (log.check( POILogger.DEBUG )) {
+            log.log(POILogger.DEBUG, "convertLabelRecords exit");
+        }
      }
 
     /**
@@ -918,8 +920,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
             throw new IllegalArgumentException("sheetName must not be null");
         }
 
-        if (workbook.doesContainsSheetName( sheetname, _sheets.size() ))
+        if (workbook.doesContainsSheetName( sheetname, _sheets.size() )) {
             throw new IllegalArgumentException("The workbook already contains a sheet named '" + sheetname + "'");
+        }
 
         HSSFSheet sheet = new HSSFSheet(this);
 
@@ -1190,7 +1193,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
         short numberOfFonts = getNumberOfFonts();
         for (short i=0; i<=numberOfFonts; i++) {
             // Remember - there is no 4!
-            if(i == 4) continue;
+            if(i == 4) {
+                continue;
+            }
 
             HSSFFont hssfFont = getFontAt(i);
             if (hssfFont.getBoldweight() == boldWeight
@@ -1219,7 +1224,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
         short numberOfFonts = getNumberOfFonts();
         for (short i=0; i<=numberOfFonts; i++) {
             // Remember - there is no 4!
-            if(i == 4) continue;
+            if(i == 4) {
+                continue;
+            }
 
             HSSFFont hssfFont = getFontAt(i);
             if (hssfFont.getBold() == bold
@@ -1256,7 +1263,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
      */
     @Override
     public HSSFFont getFontAt(short idx) {
-        if(fonts == null) fonts = new HashMap<Short, HSSFFont>();
+        if(fonts == null) {
+            fonts = new HashMap<Short, HSSFFont>();
+        }
 
         // So we don't confuse users, give them back
         //  the same object every time, but create
@@ -1553,8 +1562,8 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
             return;
         }
         
-        LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0);
-        LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0);
+        LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0); // NOSONAR
+        LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0); // NOSONAR
         Encryptor enc = fpr.getEncryptionInfo().getEncryptor();
         enc.setChunkSize(Biff8DecryptingStream.RC4_REKEYING_INTERVAL);
         byte tmp[] = new byte[1024];
@@ -1796,8 +1805,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
      */
     @Override
     public HSSFDataFormat createDataFormat() {
-    if (formatter == null)
+    if (formatter == null) {
         formatter = new HSSFDataFormat(workbook);
+    }
     return formatter;
     }
 
@@ -1864,10 +1874,11 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
         List<EscherRecord> escherRecords = r.getEscherRecords();
         PrintWriter w = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()));
         for (EscherRecord escherRecord : escherRecords) {
-            if (fat)
+            if (fat) {
                 System.out.println(escherRecord.toString());
-            else
+            } else {
                 escherRecord.display(w, 0);
+            }
         }
         w.flush();
     }
@@ -2246,6 +2257,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
     /** 
      * @deprecated POI 3.16 beta 1. use {@link POIDocument#getDirectory()} instead
      */
+    @Deprecated
     @Removal(version="3.18")
     public DirectoryNode getRootDirectory(){
         return getDirectory();
index 357773a632f32d4fcb71d20c59e8cff0cafc5e83..cce7080c2a7019556d62c6de6e3deb1ac1a84715 100644 (file)
@@ -65,11 +65,13 @@ public class POIFSLister {
    public static void viewFile(final String filename, boolean withSizes) throws IOException {
       NPOIFSFileSystem fs = new NPOIFSFileSystem(new File(filename));
       displayDirectory(fs.getRoot(), "", withSizes);
+      fs.close();
    }
 
    public static void viewFileOld(final String filename, boolean withSizes) throws IOException {
       POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename));
       displayDirectory(fs.getRoot(), "", withSizes);
+      fs.close();
    }
 
    public static void displayDirectory(DirectoryNode dir, String indent, boolean withSizes) {
index 5220529fd3bc1bc2f1fa2f5d6e5548f0673d85ae..7fbfe779adb7635c6e9fa3c866f6d07a8808f63c 100644 (file)
@@ -254,7 +254,7 @@ public abstract class OPCPackage implements RelationshipSource, Closeable {
                        throw new IllegalArgumentException("path must not be a directory");
                }
 
-               OPCPackage pack = new ZipPackage(path, access);
+               OPCPackage pack = new ZipPackage(path, access); // NOSONAR
                boolean success = false;
                if (pack.partList == null && access != PackageAccess.WRITE) {
                        try {
@@ -561,9 +561,10 @@ public abstract class OPCPackage implements RelationshipSource, Closeable {
         }
 
         // Check if part already exist
-        if (this.getPart(thumbnailPartName) != null)
+        if (this.getPart(thumbnailPartName) != null) {
             throw new InvalidOperationException(
                     "You already add a thumbnail named '" + filename + "'");
+        }
 
         // Add the thumbnail part to this package.
         PackagePart thumbnailPart = this.createPart(thumbnailPartName,
@@ -1533,7 +1534,9 @@ public abstract class OPCPackage implements RelationshipSource, Closeable {
                        fos = new FileOutputStream(targetFile);
                        this.save(fos);
                } finally {
-                       if (fos != null) fos.close();
+                       if (fos != null) {
+                fos.close();
+            }
                }
        }
 
index 14b7706fbdadd6bc6c7dc8b69f1686105b662e06..3e313f90a0eeffc5f69e9327cf73202d8f38c115 100644 (file)
 
 package org.apache.poi.hslf.dev;
 
+import java.io.IOException;
 import java.util.List;
 
-import org.apache.poi.hslf.model.textproperties.*;
-import org.apache.poi.hslf.record.*;
+import org.apache.poi.hslf.model.textproperties.BitMaskTextProp;
+import org.apache.poi.hslf.model.textproperties.TextProp;
+import org.apache.poi.hslf.model.textproperties.TextPropCollection;
+import org.apache.poi.hslf.record.Record;
+import org.apache.poi.hslf.record.SlideListWithText;
+import org.apache.poi.hslf.record.StyleTextPropAtom;
+import org.apache.poi.hslf.record.TextBytesAtom;
+import org.apache.poi.hslf.record.TextCharsAtom;
 import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
 
 /**
@@ -28,7 +35,7 @@ import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
  * Having found them, it shows the contents
  */
 public final class TextStyleListing {
-       public static void main(String[] args) throws Exception {
+       public static void main(String[] args) throws IOException {
                if(args.length < 1) {
                        System.err.println("Need to give a filename");
                        System.exit(1);
@@ -65,6 +72,8 @@ public final class TextStyleListing {
                                }
                        }
                }
+               
+               ss.close();
        }
 
        public static void showStyleTextPropAtom(StyleTextPropAtom stpa) {
index 34759eaa6360cb1601f8b313c9c4c1e4e0759f88..5f83d5688d64cc6531d33e5c1568ca644c5e3f2c 100644 (file)
@@ -18,6 +18,7 @@
 package org.apache.poi.hslf.dev;
 
 import java.io.ByteArrayOutputStream;
+import java.io.IOException;
 import java.util.Map;
 
 import org.apache.poi.hslf.record.CurrentUserAtom;
@@ -36,7 +37,7 @@ import org.apache.poi.util.LittleEndian;
 public final class UserEditAndPersistListing {
        private static byte[] fileContents;
 
-       public static void main(String[] args) throws Exception {
+       public static void main(String[] args) throws IOException {
                if(args.length < 1) {
                        System.err.println("Need to give a filename");
                        System.exit(1);
@@ -49,11 +50,8 @@ public final class UserEditAndPersistListing {
                System.out.println("");
 
                // Find any persist ones first
-               Record[] records = ss.getRecords();
                int pos = 0;
-               for(int i=0; i<records.length; i++) {
-                       Record r = records[i];
-
+               for(Record r : ss.getRecords()) {
                        if(r.getRecordType() == 6001l) {
                                // PersistPtrFullBlock
                                System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")");
@@ -64,10 +62,8 @@ public final class UserEditAndPersistListing {
                                PersistPtrHolder pph = (PersistPtrHolder)r;
 
                                // Check the sheet offsets
-                               int[] sheetIDs = pph.getKnownSlideIDs();
                                Map<Integer,Integer> sheetOffsets = pph.getSlideLocationsLookup();
-                               for(int j=0; j<sheetIDs.length; j++) {
-                                       Integer id = sheetIDs[j];
+                               for(int id : pph.getKnownSlideIDs()) {
                                        Integer offset = sheetOffsets.get(id);
 
                                        System.out.println("  Knows about sheet " + id);
@@ -93,9 +89,7 @@ public final class UserEditAndPersistListing {
 
                pos = 0;
                // Now look for UserEditAtoms
-               for(int i=0; i<records.length; i++) {
-                       Record r = records[i];
-
+               for(Record r : ss.getRecords()) {
                        if(r instanceof UserEditAtom) {
                                UserEditAtom uea = (UserEditAtom)r;
                                System.out.println("Found UserEditAtom at " + pos + " (" + Integer.toHexString(pos) + ")");
@@ -118,8 +112,10 @@ public final class UserEditAndPersistListing {
                CurrentUserAtom cua = ss.getCurrentUserAtom();
                System.out.println("Checking Current User Atom");
                System.out.println("  Thinks the CurrentEditOffset is " + cua.getCurrentEditOffset());
-
+               
                System.out.println("");
+
+               ss.close();
        }
 
 
index 4062aeb8ee314dcccdb43ae90aa630641c830bdf..ffd3cc1083c14141be83be72f917b17571c2944b 100644 (file)
@@ -19,7 +19,6 @@ package org.apache.poi.hslf.extractor;
 
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.util.List;
 
 import org.apache.poi.hslf.usermodel.HSLFPictureData;
 import org.apache.poi.hslf.usermodel.HSLFSlideShow;
@@ -28,8 +27,6 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType;
 
 /**
  * Utility to extract pictures from a PowerPoint file.
- *
- * @author Yegor Kozlov
  */
 public final class ImageExtractor {
     public static void main(String args[]) throws IOException {
@@ -41,17 +38,17 @@ public final class ImageExtractor {
         HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(args[0]));
 
         //extract all pictures contained in the presentation
-        List<HSLFPictureData> pdata = ppt.getPictureData();
-        for (int i = 0; i < pdata.size(); i++) {
-            HSLFPictureData pict = pdata.get(i);
-
+        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);
+            FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension);
             out.write(data);
             out.close();
         }
+        
+        ppt.close();
     }
 }
index b800f3e21946db41e59c2c0e910e9f3a8112e939..85f0eb92739b492def45b2d5953a15a84e31ed09 100644 (file)
@@ -62,6 +62,7 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom
     /**
      * Return the value we were given at creation, be it 6001 or 6002
      */
+    @Override
     public long getRecordType() { return _type; }
 
        /**
@@ -181,7 +182,7 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom
         TreeMap<Integer,Integer> orderedSlideLocations = new TreeMap<Integer,Integer>(_slideLocations);
         
         @SuppressWarnings("resource")
-        BufAccessBAOS bos = new BufAccessBAOS();
+        BufAccessBAOS bos = new BufAccessBAOS(); // NOSONAR
         byte intbuf[] = new byte[4];
         int lastPersistEntry = -1;
         int lastSlideId = -1;
@@ -229,7 +230,8 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom
         * Write the contents of the record back, so it can be written
         *  to disk
         */
-       public void writeOut(OutputStream out) throws IOException {
+       @Override
+    public void writeOut(OutputStream out) throws IOException {
            normalizePersistDirectory();
                out.write(_header);
                out.write(_ptrData);
index 3dc5948be1971e7b0c45975a412c0a86dea47872..d18054ee61301b99a84970351c817afcb3bf9f82 100644 (file)
@@ -77,6 +77,7 @@ public final class TextSpecInfoAtom extends RecordAtom {
      * Gets the record type.
      * @return the record type.
      */
+    @Override
     public long getRecordType() { return _type; }
 
     /**
@@ -86,6 +87,7 @@ public final class TextSpecInfoAtom extends RecordAtom {
      * @param out the output stream to write to.
      * @throws java.io.IOException if an error occurs.
      */
+    @Override
     public void writeOut(OutputStream out) throws IOException {
         out.write(_header);
         out.write(_data);
@@ -155,12 +157,14 @@ public final class TextSpecInfoAtom extends RecordAtom {
      */
     public int getCharactersCovered(){
         int covered = 0;
-        for (TextSpecInfoRun r : getTextSpecInfoRuns()) covered += r.getLength();
+        for (TextSpecInfoRun r : getTextSpecInfoRuns()) {
+            covered += r.getLength();
+        }
         return covered;
     }
 
     public TextSpecInfoRun[] getTextSpecInfoRuns(){
-        LittleEndianByteArrayInputStream bis = new LittleEndianByteArrayInputStream(_data);
+        LittleEndianByteArrayInputStream bis = new LittleEndianByteArrayInputStream(_data); // NOSONAR
         List<TextSpecInfoRun> lst = new ArrayList<TextSpecInfoRun>();
         while (bis.available() > 0) {
             lst.add(new TextSpecInfoRun(bis));
index c2dd42098c80333911efd684c6614c813423d983..d17b87f120fde3c8301380af4171be283b884747 100644 (file)
@@ -191,7 +191,7 @@ public class HSLFSlideShowEncrypted implements Closeable {
 
         decryptInit();
         dec.setChunkSize(-1);
-        LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream(docstream, offset);
+        LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream(docstream, offset); // NOSONAR
         ChunkedCipherInputStream ccis = null;
         try {
             ccis = dec.getDataStream(lei, docstream.length-offset, 0);
@@ -309,7 +309,7 @@ public class HSLFSlideShowEncrypted implements Closeable {
 
         encryptInit();
 
-        LittleEndianByteArrayOutputStream los = new LittleEndianByteArrayOutputStream(pictstream, offset);
+        LittleEndianByteArrayOutputStream los = new LittleEndianByteArrayOutputStream(pictstream, offset); // NOSONAR
         ChunkedCipherOutputStream ccos = null;
 
         try {
@@ -572,6 +572,7 @@ public class HSLFSlideShowEncrypted implements Closeable {
         }
     }
 
+    @Override
     public void close() throws IOException {
         if (cyos != null) {
             cyos.close();
index 403db98eded9ce9a0d5734bf5e048debd22dc2fb..3f1be1654d459ae70bacae9bcfc2b7c344f4a0f0 100644 (file)
@@ -56,6 +56,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.sl.usermodel.PictureData.PictureType;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.LittleEndianConsts;
 import org.apache.poi.util.POILogFactory;
 import org.apache.poi.util.POILogger;
 import org.apache.poi.util.Removal;
@@ -91,6 +92,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
      * 
      * @deprecated POI 3.16 beta 1. use {@link POIDocument#getDirectory()} instead
      */
+    @Deprecated
     @Removal(version="3.18")
     protected DirectoryNode getPOIFSDirectory() {
         return getDirectory();
@@ -172,7 +174,9 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
     private static DirectoryNode handleDualStorage(DirectoryNode dir) throws IOException {
         // when there's a dual storage entry, use it, as the outer document can't be read quite probably ...
         String dualName = "PP97_DUALSTORAGE";
-        if (!dir.hasEntry(dualName)) return dir;
+        if (!dir.hasEntry(dualName)) {
+            return dir;
+        }
         dir = (DirectoryNode) dir.getEntry(dualName);
         return dir;
     }
@@ -221,7 +225,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
      * Builds the list of records, based on the contents
      * of the PowerPoint stream
      */
-    private void buildRecords() {
+    private void buildRecords() throws IOException {
         // The format of records in a powerpoint file are:
         //   <little endian 2 byte "info">
         //   <little endian 2 byte "type">
@@ -258,7 +262,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
         _records = read(_docstream, (int) currentUser.getCurrentEditOffset());
     }
 
-    private Record[] read(byte[] docstream, int usrOffset) {
+    private Record[] read(byte[] docstream, int usrOffset) throws IOException {
         //sort found records by offset.
         //(it is not necessary but SlideShow.findMostRecentCoreRecords() expects them sorted)
         NavigableMap<Integer, Record> records = new TreeMap<Integer, Record>(); // offset -> record
@@ -283,6 +287,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
             }
         }
 
+        decryptData.close();
         return records.values().toArray(new Record[records.size()]);
     }
 
@@ -360,77 +365,84 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
         _pictures = new ArrayList<HSLFPictureData>();
 
         // if the presentation doesn't contain pictures - will use a null set instead
-        if (!getDirectory().hasEntry("Pictures")) return;
-
-        HSLFSlideShowEncrypted decryptData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
+        if (!getDirectory().hasEntry("Pictures")) {
+            return;
+        }
 
         DocumentEntry entry = (DocumentEntry) getDirectory().getEntry("Pictures");
         DocumentInputStream is = getDirectory().createDocumentInputStream(entry);
         byte[] pictstream = IOUtils.toByteArray(is, entry.getSize());
         is.close();
 
-        int pos = 0;
-        // An empty picture record (length 0) will take up 8 bytes
-        while (pos <= (pictstream.length - 8)) {
-            int offset = pos;
-
-            decryptData.decryptPicture(pictstream, offset);
-
-            // Image signature
-            int signature = LittleEndian.getUShort(pictstream, pos);
-            pos += LittleEndian.SHORT_SIZE;
-            // Image type + 0xF018
-            int type = LittleEndian.getUShort(pictstream, pos);
-            pos += LittleEndian.SHORT_SIZE;
-            // Image size (excluding the 8 byte header)
-            int imgsize = LittleEndian.getInt(pictstream, pos);
-            pos += LittleEndian.INT_SIZE;
-
-            // When parsing the BStoreDelay stream, [MS-ODRAW] says that we
-            //  should terminate if the type isn't 0xf007 or 0xf018->0xf117
-            if (!((type == 0xf007) || (type >= 0xf018 && type <= 0xf117)))
-                break;
-
-            // The image size must be 0 or greater
-            // (0 is allowed, but odd, since we do wind on by the header each
-            //  time, so we won't get stuck)
-            if (imgsize < 0) {
-                throw new CorruptPowerPointFileException("The file contains a picture, at position " + _pictures.size() + ", which has a negatively sized data length, so we can't trust any of the picture data");
-            }
-
-            // If they type (including the bonus 0xF018) is 0, skip it
-            PictureType pt = PictureType.forNativeID(type - 0xF018);
-            if (pt == null) {
-                logger.log(POILogger.ERROR, "Problem reading picture: Invalid image type 0, on picture with length " + imgsize + ".\nYou document will probably become corrupted if you save it!");
-                logger.log(POILogger.ERROR, "" + pos);
-            } else {
-                //The pictstream can be truncated halfway through a picture.
-                //This is not a problem if the pictstream contains extra pictures
-                //that are not used in any slide -- BUG-60305
-                if (pos+imgsize > pictstream.length) {
-                    logger.log(POILogger.WARN, "\"Pictures\" stream may have ended early. In some circumstances, this is not a problem; " +
-                            "in others, this could indicate a corrupt file");
+        HSLFSlideShowEncrypted decryptData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom());
+        try {
+    
+            int pos = 0;
+            // An empty picture record (length 0) will take up 8 bytes
+            while (pos <= (pictstream.length - 8)) {
+                int offset = pos;
+    
+                decryptData.decryptPicture(pictstream, offset);
+    
+                // Image signature
+                int signature = LittleEndian.getUShort(pictstream, pos);
+                pos += LittleEndianConsts.SHORT_SIZE;
+                // Image type + 0xF018
+                int type = LittleEndian.getUShort(pictstream, pos);
+                pos += LittleEndianConsts.SHORT_SIZE;
+                // Image size (excluding the 8 byte header)
+                int imgsize = LittleEndian.getInt(pictstream, pos);
+                pos += LittleEndianConsts.INT_SIZE;
+    
+                // When parsing the BStoreDelay stream, [MS-ODRAW] says that we
+                //  should terminate if the type isn't 0xf007 or 0xf018->0xf117
+                if (!((type == 0xf007) || (type >= 0xf018 && type <= 0xf117))) {
                     break;
                 }
-                // Build the PictureData object from the data
-                try {
-                    HSLFPictureData pict = HSLFPictureData.create(pt);
-                    pict.setSignature(signature);
-
-                    // Copy the data, ready to pass to PictureData
-                    byte[] imgdata = new byte[imgsize];
-                    System.arraycopy(pictstream, pos, imgdata, 0, imgdata.length);
-                    pict.setRawData(imgdata);
-
-                    pict.setOffset(offset);
-                    pict.setIndex(_pictures.size());
-                    _pictures.add(pict);
-                } catch (IllegalArgumentException e) {
-                    logger.log(POILogger.ERROR, "Problem reading picture: " + e + "\nYou document will probably become corrupted if you save it!");
+    
+                // The image size must be 0 or greater
+                // (0 is allowed, but odd, since we do wind on by the header each
+                //  time, so we won't get stuck)
+                if (imgsize < 0) {
+                    throw new CorruptPowerPointFileException("The file contains a picture, at position " + _pictures.size() + ", which has a negatively sized data length, so we can't trust any of the picture data");
+                }
+    
+                // If they type (including the bonus 0xF018) is 0, skip it
+                PictureType pt = PictureType.forNativeID(type - 0xF018);
+                if (pt == null) {
+                    logger.log(POILogger.ERROR, "Problem reading picture: Invalid image type 0, on picture with length " + imgsize + ".\nYou document will probably become corrupted if you save it!");
+                    logger.log(POILogger.ERROR, "" + pos);
+                } else {
+                    //The pictstream can be truncated halfway through a picture.
+                    //This is not a problem if the pictstream contains extra pictures
+                    //that are not used in any slide -- BUG-60305
+                    if (pos+imgsize > pictstream.length) {
+                        logger.log(POILogger.WARN, "\"Pictures\" stream may have ended early. In some circumstances, this is not a problem; " +
+                                "in others, this could indicate a corrupt file");
+                        break;
+                    }
+                    // Build the PictureData object from the data
+                    try {
+                        HSLFPictureData pict = HSLFPictureData.create(pt);
+                        pict.setSignature(signature);
+    
+                        // Copy the data, ready to pass to PictureData
+                        byte[] imgdata = new byte[imgsize];
+                        System.arraycopy(pictstream, pos, imgdata, 0, imgdata.length);
+                        pict.setRawData(imgdata);
+    
+                        pict.setOffset(offset);
+                        pict.setIndex(_pictures.size());
+                        _pictures.add(pict);
+                    } catch (IllegalArgumentException e) {
+                        logger.log(POILogger.ERROR, "Problem reading picture: " + e + "\nYou document will probably become corrupted if you save it!");
+                    }
                 }
+    
+                pos += imgsize;
             }
-
-            pos += imgsize;
+        } finally {
+            decryptData.close();
         }
     }
 
@@ -522,7 +534,9 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
             // 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;
+            if (persistId == null) {
+                persistId = 0;
+            }
 
             // For now, we're only handling PositionDependentRecord's that
             // happen at the top level.
@@ -709,6 +723,8 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
             pict.close();
         }
 
+        encryptedSS.close();
+        
         // If requested, copy over any other streams we spot, eg Macros
         if (copyAllOtherNodes) {
             EntryUtils.copyNodes(getDirectory().getFileSystem(), outFS, writtenEntries);
@@ -722,6 +738,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
      * @param setName The property to read
      * @return The value of the given property or null if it wasn't found.
      */
+    @Override
     protected PropertySet getPropertySet(String setName) {
         DocumentEncryptionAtom dea = getDocumentEncryptionAtom();
         return (dea == null)
@@ -737,6 +754,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
      * @throws IOException if an error when writing to the
      *                     {@link POIFSFileSystem} occurs
      */
+    @Override
     protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
         super.writeProperties(outFS, writtenEntries);
         DocumentEncryptionAtom dea = getDocumentEncryptionAtom();
@@ -885,14 +903,17 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
     private static class CountingOS extends OutputStream {
         int count = 0;
 
+        @Override
         public void write(int b) throws IOException {
             count++;
         }
 
+        @Override
         public void write(byte[] b) throws IOException {
             count += b.length;
         }
 
+        @Override
         public void write(byte[] b, int off, int len) throws IOException {
             count += len;
         }