From b8bfe77718d26887ddccc7be4f5332aafad9e287 Mon Sep 17 00:00:00 2001 From: Andreas Beeker Date: Sun, 18 Dec 2016 22:03:31 +0000 Subject: [PATCH] SonarQube fixes - close resources git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1774969 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/poi/hslf/examples/BulletsDemo.java | 7 +- .../poi/hslf/examples/HeadersFootersDemo.java | 1 + .../poi/hssf/usermodel/examples/Borders.java | 23 +-- .../hssf/usermodel/examples/CellComments.java | 20 ++- .../hssf/usermodel/examples/CellTypes.java | 2 + .../usermodel/examples/CreateDateCells.java | 13 +- .../usermodel/examples/FrillsAndFills.java | 19 ++- .../usermodel/examples/HSSFReadWrite.java | 6 +- .../usermodel/examples/HyperlinkFormula.java | 3 +- .../hssf/usermodel/examples/Hyperlinks.java | 4 +- .../hssf/usermodel/examples/MergedCells.java | 14 +- .../usermodel/examples/NewLinesInCells.java | 15 +- .../hssf/usermodel/examples/NewWorkbook.java | 14 +- .../examples/SplitAndFreezePanes.java | 22 ++- .../usermodel/examples/WorkingWithFonts.java | 12 +- .../poi/ss/examples/AddDimensionedImage.java | 59 +++---- .../poi/ss/examples/ConditionalFormats.java | 60 +++++-- .../poi/ss/examples/LinkedDropDownLists.java | 133 +++++++-------- .../apache/poi/ss/examples/LoadEmbedded.java | 72 +++++---- .../usermodel/examples/EmbeddedObjects.java | 56 +++---- .../poi/hssf/record/FilePassRecord.java | 2 +- .../org/apache/poi/hssf/record/ObjRecord.java | 2 +- .../poi/hssf/usermodel/HSSFWorkbook.java | 38 +++-- .../org/apache/poi/poifs/dev/POIFSLister.java | 2 + .../apache/poi/openxml4j/opc/OPCPackage.java | 9 +- .../apache/poi/hslf/dev/TextStyleListing.java | 15 +- .../hslf/dev/UserEditAndPersistListing.java | 20 +-- .../poi/hslf/extractor/ImageExtractor.java | 13 +- .../poi/hslf/record/PersistPtrHolder.java | 6 +- .../poi/hslf/record/TextSpecInfoAtom.java | 8 +- .../usermodel/HSLFSlideShowEncrypted.java | 5 +- .../poi/hslf/usermodel/HSLFSlideShowImpl.java | 151 ++++++++++-------- 32 files changed, 448 insertions(+), 378 deletions(-) diff --git a/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java b/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java index 3c706e3e73..1997200884 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java +++ b/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java @@ -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(); } } diff --git a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java b/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java index b37aed2df6..3ef5a46ab3 100644 --- a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java +++ b/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java @@ -44,6 +44,7 @@ public abstract class HeadersFootersDemo { ppt.write(out); out.close(); + ppt.close(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java index d29635004a..9158b0ccff 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java @@ -17,16 +17,19 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java index c3a213d582..4109a87f48 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java @@ -17,11 +17,19 @@ 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 *

- * - * @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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java index 3e31d11f26..80ced95ac0 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java @@ -41,5 +41,7 @@ public class CellTypes { FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close(); + + wb.close(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java index 746fd536b8..8afe085f1e 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java @@ -17,18 +17,21 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java index 02b7cb3e39..40be15e014 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java @@ -17,16 +17,19 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java index 2f67f7f0e5..632cd5585f 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java @@ -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(); } /** diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java index 148b2a58b0..003c09f688 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java @@ -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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java index c1ccad9100..adad7da363 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java @@ -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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java index 31e5215b8e..09d08dd257 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java @@ -17,16 +17,17 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java index 018556f991..00f60c4daf 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java @@ -17,17 +17,19 @@ 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 */ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java index c1614e6c1a..e6e0e4137e 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java @@ -19,24 +19,20 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java index 6e93a317f0..85cba2eb98 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java @@ -19,20 +19,15 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java index 6cb15941f2..d3c674a756 100644 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java +++ b/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java @@ -17,15 +17,18 @@ 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(); } } diff --git a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java index 5eb10c2429..a7ef6d2ba2 100644 --- a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java +++ b/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java @@ -19,14 +19,13 @@ package org.apache.poi.ss.examples; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.Locale; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; import org.apache.poi.ss.usermodel.Drawing; @@ -813,50 +812,28 @@ public class AddDimensionedImage { * * @param args the command line arguments */ - public static void main(String[] args) { + public static void main(String[] args) throws IOException { String imageFile = null; String outputFile = null; FileOutputStream fos = null; Workbook workbook = null; Sheet sheet = null; - try { - if(args.length < 2){ - System.err.println("Usage: AddDimensionedImage imageFile outputFile"); - return; - } - workbook = new HSSFWorkbook(); // OR XSSFWorkbook - sheet = workbook.createSheet("Picture Test"); - imageFile = args[0]; - outputFile = args[1]; - new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), - new File(imageFile).toURI().toURL(), 100, 40, - AddDimensionedImage.EXPAND_ROW_AND_COLUMN); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - } - catch(FileNotFoundException fnfEx) { - System.out.println("Caught an: " + fnfEx.getClass().getName()); - System.out.println("Message: " + fnfEx.getMessage()); - System.out.println("Stacktrace follows..........."); - fnfEx.printStackTrace(System.out); - } - catch(IOException ioEx) { - System.out.println("Caught an: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); - } - finally { - if(fos != null) { - try { - fos.close(); - fos = null; - } - catch(IOException ioEx) { - // I G N O R E - } - } - } + + if(args.length < 2){ + System.err.println("Usage: AddDimensionedImage imageFile outputFile"); + return; + } + workbook = new HSSFWorkbook(); // OR XSSFWorkbook + sheet = workbook.createSheet("Picture Test"); + imageFile = args[0]; + outputFile = args[1]; + new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), + new File(imageFile).toURI().toURL(), 100, 40, + AddDimensionedImage.EXPAND_ROW_AND_COLUMN); + fos = new FileOutputStream(outputFile); + workbook.write(fos); + fos.close(); + workbook.close(); } /** 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 7358edf682..eba1e219f2 100644 --- a/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java +++ b/src/examples/src/org/apache/poi/ss/examples/ConditionalFormats.java @@ -19,16 +19,30 @@ package org.apache.poi.ss.examples; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.BuiltinFormats; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.ColorScaleFormatting; +import org.apache.poi.ss.usermodel.ComparisonOperator; +import org.apache.poi.ss.usermodel.ConditionalFormattingRule; import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; +import org.apache.poi.ss.usermodel.DataBarFormatting; +import org.apache.poi.ss.usermodel.ExtendedColor; +import org.apache.poi.ss.usermodel.FontFormatting; +import org.apache.poi.ss.usermodel.IconMultiStateFormatting; import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.PatternFormatting; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.SheetConditionalFormatting; +import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import java.io.FileOutputStream; -import java.io.IOException; - /** * Excel Conditional Formatting -- Examples * @@ -42,8 +56,11 @@ public class ConditionalFormats { 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(); + if(args.length > 0 && args[0].equals("-xls")) { + wb = new HSSFWorkbook(); + } else { + wb = new XSSFWorkbook(); + } sameCell(wb.createSheet("Same Cell")); multiCell(wb.createSheet("MultiCell")); @@ -61,11 +78,14 @@ public class ConditionalFormats { // Write the output to a file String file = "cf-poi.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; + if(wb instanceof XSSFWorkbook) { + file += "x"; + } FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); System.out.println("Generated: " + file); + wb.close(); } /** @@ -157,11 +177,21 @@ public class ConditionalFormats { Row r = sheet.createRow(i); r.createCell(0).setCellValue("This is row " + rn + " (" + i + ")"); String str = ""; - if (rn%2 == 0) str = str + "even "; - if (rn%3 == 0) str = str + "x3 "; - if (rn%5 == 0) str = str + "x5 "; - if (rn%10 == 0) str = str + "x10 "; - if (str.length() == 0) str = "nothing special..."; + if (rn%2 == 0) { + str = str + "even "; + } + if (rn%3 == 0) { + str = str + "x3 "; + } + if (rn%5 == 0) { + str = str + "x5 "; + } + if (rn%10 == 0) { + str = str + "x10 "; + } + if (str.length() == 0) { + str = "nothing special..."; + } r.createCell(1).setCellValue("It is " + str); } sheet.autoSizeColumn(0); @@ -353,7 +383,9 @@ public class ConditionalFormats { sheet.createRow(2).createCell(0).setCellFormula("A2+1"); sheet.createRow(3).createCell(0).setCellFormula("A3+1"); - for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style); + for(int rownum = 1; rownum <= 3; rownum++) { + sheet.getRow(rownum).getCell(0).setCellStyle(style); + } SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); diff --git a/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java b/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java index b0efc4f0ce..7b672b792c 100644 --- a/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java +++ b/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java @@ -16,11 +16,20 @@ ==================================================================== */ package org.apache.poi.ss.examples; -import java.io.*; -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DataValidation; +import org.apache.poi.ss.usermodel.DataValidationConstraint; +import org.apache.poi.ss.usermodel.DataValidationHelper; +import org.apache.poi.ss.usermodel.Name; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * Demonstrates one technique that may be used to create linked or dependent @@ -56,78 +65,52 @@ import org.apache.poi.ss.util.CellRangeAddressList; */ public class LinkedDropDownLists { - LinkedDropDownLists(String workbookName) { - File file = null; - FileOutputStream fos = null; - Workbook workbook = null; - Sheet sheet = null; - DataValidationHelper dvHelper = null; - DataValidationConstraint dvConstraint = null; - DataValidation validation = null; - CellRangeAddressList addressList = null; - try { - - // Using the ss.usermodel allows this class to support both binary - // and xml based workbooks. The choice of which one to create is - // made by checking the file extension. - if (workbookName.endsWith(".xlsx")) { - workbook = new XSSFWorkbook(); - } else { - workbook = new HSSFWorkbook(); - } - - // Build the sheet that will hold the data for the validations. This - // must be done first as it will create names that are referenced - // later. - sheet = workbook.createSheet("Linked Validations"); - LinkedDropDownLists.buildDataSheet(sheet); - - // Build the first data validation to occupy cell A1. Note - // that it retrieves it's data from the named area or region called - // CHOICES. Further information about this can be found in the - // static buildDataSheet() method below. - addressList = new CellRangeAddressList(0, 0, 0, 0); - dvHelper = sheet.getDataValidationHelper(); - dvConstraint = dvHelper.createFormulaListConstraint("CHOICES"); - validation = dvHelper.createValidation(dvConstraint, addressList); - sheet.addValidationData(validation); - - // Now, build the linked or dependent drop down list that will - // occupy cell B1. The key to the whole process is the use of the - // INDIRECT() function. In the buildDataSheet(0 method, a series of - // named regions are created and the names of three of them mirror - // the options available to the user in the first drop down list - // (in cell A1). Using the INDIRECT() function makes it possible - // to convert the selection the user makes in that first drop down - // into the addresses of a named region of cells and then to use - // those cells to populate the second drop down list. - addressList = new CellRangeAddressList(0, 0, 1, 1); - dvConstraint = dvHelper.createFormulaListConstraint( - "INDIRECT(UPPER($A$1))"); - validation = dvHelper.createValidation(dvConstraint, addressList); - sheet.addValidationData(validation); - - file = new File(workbookName); - fos = new FileOutputStream(file); - workbook.write(fos); - } catch (IOException ioEx) { - System.out.println("Caught a: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follws:....."); - ioEx.printStackTrace(System.out); - } finally { - try { - if (fos != null) { - fos.close(); - fos = null; - } - } catch (IOException ioEx) { - System.out.println("Caught a: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follws:....."); - ioEx.printStackTrace(System.out); - } + LinkedDropDownLists(String workbookName) throws IOException { + // Using the ss.usermodel allows this class to support both binary + // and xml based workbooks. The choice of which one to create is + // made by checking the file extension. + Workbook workbook; + if (workbookName.endsWith(".xlsx")) { + workbook = new XSSFWorkbook(); + } else { + workbook = new HSSFWorkbook(); } + + // Build the sheet that will hold the data for the validations. This + // must be done first as it will create names that are referenced + // later. + Sheet sheet = workbook.createSheet("Linked Validations"); + LinkedDropDownLists.buildDataSheet(sheet); + + // Build the first data validation to occupy cell A1. Note + // that it retrieves it's data from the named area or region called + // CHOICES. Further information about this can be found in the + // static buildDataSheet() method below. + CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); + DataValidationHelper dvHelper = sheet.getDataValidationHelper(); + DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES"); + DataValidation validation = dvHelper.createValidation(dvConstraint, addressList); + sheet.addValidationData(validation); + + // Now, build the linked or dependent drop down list that will + // occupy cell B1. The key to the whole process is the use of the + // INDIRECT() function. In the buildDataSheet(0 method, a series of + // named regions are created and the names of three of them mirror + // the options available to the user in the first drop down list + // (in cell A1). Using the INDIRECT() function makes it possible + // to convert the selection the user makes in that first drop down + // into the addresses of a named region of cells and then to use + // those cells to populate the second drop down list. + addressList = new CellRangeAddressList(0, 0, 1, 1); + dvConstraint = dvHelper.createFormulaListConstraint( + "INDIRECT(UPPER($A$1))"); + validation = dvHelper.createValidation(dvConstraint, addressList); + sheet.addValidationData(validation); + + FileOutputStream fos = new FileOutputStream(workbookName); + workbook.write(fos); + fos.close(); + workbook.close(); } /** diff --git a/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java b/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java index 66ca8ba7b2..2ad0347f7b 100644 --- a/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java +++ b/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java @@ -18,34 +18,38 @@ 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(); } } } diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java index 3f044c839e..5d367316b3 100644 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java +++ b/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java @@ -16,57 +16,57 @@ ==================================================================== */ package org.apache.poi.xssf.usermodel.examples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import java.io.InputStream; + +import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; +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.opc.PackagePart; import org.apache.poi.xslf.usermodel.XSLFSlideShow; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.InputStream; /** * Demonstrates how you can extract embedded data from a .xlsx file */ public class EmbeddedObjects { public static void main(String[] args) throws Exception { - OPCPackage pkg = OPCPackage.open(args[0]); - XSSFWorkbook workbook = new XSSFWorkbook(pkg); + XSSFWorkbook workbook = new XSSFWorkbook(args[0]); 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")) { + embeddedWorkbook.close(); + } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { + // Excel Workbook - OpenXML file format XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream()); - } - // Word Document - binary (OLE2CDF) file format - else if (contentType.equals("application/msword")) { + 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")) { + document.close(); + } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) { + // Word Document - OpenXML file format XWPFDocument document = new XWPFDocument(pPart.getInputStream()); - } - // PowerPoint Document - binary file format - else if (contentType.equals("application/vnd.ms-powerpoint")) { + document.close(); + } else if (contentType.equals("application/vnd.ms-powerpoint")) { + // PowerPoint Document - binary file format HSLFSlideShowImpl slideShow = new HSLFSlideShowImpl(pPart.getInputStream()); - } - // PowerPoint Document - OpenXML file format - else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { + slideShow.close(); + } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { + // PowerPoint Document - OpenXML file format OPCPackage docPackage = OPCPackage.open(pPart.getInputStream()); XSLFSlideShow slideShow = new XSLFSlideShow(docPackage); - } - // Any other type of embedded object. - else { + slideShow.close(); + } else { + // Any other type of embedded object. System.out.println("Unknown Embedded Document: " + contentType); InputStream inputStream = pPart.getInputStream(); + inputStream.close(); } } - pkg.close(); + workbook.close(); } } \ No newline at end of file diff --git a/src/java/org/apache/poi/hssf/record/FilePassRecord.java b/src/java/org/apache/poi/hssf/record/FilePassRecord.java index ab941fad5f..5955e6d135 100644 --- a/src/java/org/apache/poi/hssf/record/FilePassRecord.java +++ b/src/java/org/apache/poi/hssf/record/FilePassRecord.java @@ -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: diff --git a/src/java/org/apache/poi/hssf/record/ObjRecord.java b/src/java/org/apache/poi/hssf/record/ObjRecord.java index 8eb4e03afc..5220f9cc07 100644 --- a/src/java/org/apache/poi/hssf/record/ObjRecord.java +++ b/src/java/org/apache/poi/hssf/record/ObjRecord.java @@ -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); diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java b/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java index 7c50b6643d..2f3be03de9 100644 --- a/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java +++ b/src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java @@ -435,8 +435,9 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss private void convertLabelRecords(List 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(); + if(fonts == null) { + fonts = new HashMap(); + } // 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 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(); diff --git a/src/java/org/apache/poi/poifs/dev/POIFSLister.java b/src/java/org/apache/poi/poifs/dev/POIFSLister.java index 357773a632..cce7080c2a 100644 --- a/src/java/org/apache/poi/poifs/dev/POIFSLister.java +++ b/src/java/org/apache/poi/poifs/dev/POIFSLister.java @@ -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) { diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java index 5220529fd3..7fbfe779ad 100644 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java +++ b/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java @@ -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(); + } } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java index 14b7706fbd..3e313f90a0 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java +++ b/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java @@ -17,10 +17,17 @@ 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) { diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java index 34759eaa63..5f83d5688d 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java +++ b/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java @@ -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 sheetOffsets = pph.getSlideLocationsLookup(); - for(int j=0; j 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(); } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java b/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java index b800f3e219..85f0eb9273 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java +++ b/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java @@ -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 orderedSlideLocations = new TreeMap(_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); diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java index 3dc5948be1..d18054ee61 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java +++ b/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java @@ -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 lst = new ArrayList(); while (bis.available() > 0) { lst.add(new TextSpecInfoRun(bis)); diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java index c2dd42098c..d17b87f120 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java +++ b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java @@ -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(); 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 403db98ede..3f1be1654d 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java +++ b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java @@ -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: // // @@ -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 records = new TreeMap(); // 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(); // 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 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; } -- 2.39.5