]> source.dussan.org Git - poi.git/commitdiff
sonar fixes and
authorAndreas Beeker <kiwiwings@apache.org>
Sat, 2 Jun 2018 20:29:35 +0000 (20:29 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Sat, 2 Jun 2018 20:29:35 +0000 (20:29 +0000)
disable closing of outputstream in ZipPackage.saveImpl() - see https://stackoverflow.com/questions/50646538/stream-close-exception-occures

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1832746 13f79535-47bb-0310-9956-ffa450edef68

14 files changed:
src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java
src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java
src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java
src/examples/src/org/apache/poi/ss/examples/DrawingBorders.java
src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java
src/examples/src/org/apache/poi/ss/examples/ToCSV.java
src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java
src/java/org/apache/poi/POIDocument.java
src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java
src/scratchpad/src/org/apache/poi/hwpf/converter/WordToFoConverter.java
src/scratchpad/src/org/apache/poi/hwpf/converter/WordToHtmlConverter.java
src/scratchpad/src/org/apache/poi/hwpf/dev/HWPFLister.java

index 1e24660eb7f779c5ba99c3c5e51f4d570eb31966..92d8755fff6ba2e8822106b603bd1934d4cbcf1b 100644 (file)
@@ -79,82 +79,76 @@ public class ModifyDocumentSummaryInformation {
         File summaryFile = new File(args[0]);
 
         /* Open the POI filesystem. */
-        NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false);
-
-        /* Read the summary information. */
-        DirectoryEntry dir = poifs.getRoot();
-        SummaryInformation si;
-        try
-        {
-            si = (SummaryInformation)PropertySetFactory.create(
-                    dir, SummaryInformation.DEFAULT_STREAM_NAME);
+        try (NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false)) {
+
+            /* Read the summary information. */
+            DirectoryEntry dir = poifs.getRoot();
+            SummaryInformation si;
+            try {
+                si = (SummaryInformation) PropertySetFactory.create(
+                        dir, SummaryInformation.DEFAULT_STREAM_NAME);
+            } catch (FileNotFoundException ex) {
+                // There is no summary information yet. We have to create a new one
+                si = PropertySetFactory.newSummaryInformation();
+            }
+
+            /* Change the author to "Rainer Klute". Any former author value will
+             * be lost. If there has been no author yet, it will be created. */
+            si.setAuthor("Rainer Klute");
+            System.out.println("Author changed to " + si.getAuthor() + ".");
+
+
+            /* Handling the document summary information is analogous to handling
+             * the summary information. An additional feature, however, are the
+             * custom properties. */
+
+            /* Read the document summary information. */
+            DocumentSummaryInformation dsi;
+            try {
+                dsi = (DocumentSummaryInformation) PropertySetFactory.create(
+                        dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+            } catch (FileNotFoundException ex) {
+                /* There is no document summary information yet. We have to create a
+                 * new one. */
+                dsi = PropertySetFactory.newDocumentSummaryInformation();
+            }
+
+            /* Change the category to "POI example". Any former category value will
+             * be lost. If there has been no category yet, it will be created. */
+            dsi.setCategory("POI example");
+            System.out.println("Category changed to " + dsi.getCategory() + ".");
+
+            /* Read the custom properties. If there are no custom properties yet,
+             * the application has to create a new CustomProperties object. It will
+             * serve as a container for custom properties. */
+            CustomProperties customProperties = dsi.getCustomProperties();
+            if (customProperties == null)
+                customProperties = new CustomProperties();
+
+            /* Insert some custom properties into the container. */
+            customProperties.put("Key 1", "Value 1");
+            customProperties.put("Schl\u00fcssel 2", "Wert 2");
+            customProperties.put("Sample Number", new Integer(12345));
+            customProperties.put("Sample Boolean", Boolean.TRUE);
+            customProperties.put("Sample Date", new Date());
+
+            /* Read a custom property. */
+            Object value = customProperties.get("Sample Number");
+            System.out.println("Custom Sample Number is now " + value);
+
+            /* Write the custom properties back to the document summary
+             * information. */
+            dsi.setCustomProperties(customProperties);
+
+            /* Write the summary information and the document summary information
+             * to the POI filesystem. */
+            si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME);
+            dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+
+            /* Write the POI filesystem back to the original file. Please note that
+             * in production code you should take care when write directly to the
+             * origin, to make sure you don't loose things on error */
+            poifs.writeFilesystem();
         }
-        catch (FileNotFoundException ex)
-        {
-            // There is no summary information yet. We have to create a new one
-            si = PropertySetFactory.newSummaryInformation();
-        }
-
-        /* Change the author to "Rainer Klute". Any former author value will
-         * be lost. If there has been no author yet, it will be created. */
-        si.setAuthor("Rainer Klute");
-        System.out.println("Author changed to " + si.getAuthor() + ".");
-
-
-        /* Handling the document summary information is analogous to handling
-         * the summary information. An additional feature, however, are the
-         * custom properties. */
-
-        /* Read the document summary information. */
-        DocumentSummaryInformation dsi;
-        try
-        {
-            dsi = (DocumentSummaryInformation)PropertySetFactory.create(
-                    dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-        }
-        catch (FileNotFoundException ex)
-        {
-            /* There is no document summary information yet. We have to create a
-             * new one. */
-            dsi = PropertySetFactory.newDocumentSummaryInformation();
-        }
-
-        /* Change the category to "POI example". Any former category value will
-         * be lost. If there has been no category yet, it will be created. */
-        dsi.setCategory("POI example");
-        System.out.println("Category changed to " + dsi.getCategory() + ".");
-
-        /* Read the custom properties. If there are no custom properties yet,
-         * the application has to create a new CustomProperties object. It will
-         * serve as a container for custom properties. */
-        CustomProperties customProperties = dsi.getCustomProperties();
-        if (customProperties == null)
-            customProperties = new CustomProperties();
-
-        /* Insert some custom properties into the container. */
-        customProperties.put("Key 1", "Value 1");
-        customProperties.put("Schl\u00fcssel 2", "Wert 2");
-        customProperties.put("Sample Number", new Integer(12345));
-        customProperties.put("Sample Boolean", Boolean.TRUE);
-        customProperties.put("Sample Date", new Date());
-
-        /* Read a custom property. */
-        Object value = customProperties.get("Sample Number");
-        System.out.println("Custom Sample Number is now " + value);
-
-        /* Write the custom properties back to the document summary
-         * information. */
-        dsi.setCustomProperties(customProperties);
-
-        /* Write the summary information and the document summary information
-         * to the POI filesystem. */
-        si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME);
-        dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-
-        /* Write the POI filesystem back to the original file. Please note that
-         * in production code you should take care when write directly to the 
-         * origin, to make sure you don't loose things on error */
-        poifs.writeFilesystem();
-        poifs.close();
     }
 }
index bf1ba4ab7f0751bac9a051394bf9b124fadb1930..dfc4dde9f47fdf3c0bd2f8445402dbd425b996f1 100644 (file)
@@ -27,10 +27,6 @@ import org.apache.poi.hssf.usermodel.*;
 
 /**
  * This class presents the sheets to the user.
- *
- *
- * @author Andrew C. Oliver
- * @author Jason Height
  */
 public class SViewerPanel extends JPanel {
   /** This field is the magic number to convert from a Character width to a
@@ -264,15 +260,13 @@ public void paint(Graphics g) {
   }
 
   /**Main method*/
-  public static void main(String[] args) {
-    if(args.length < 1) {
+  public static void main(String[] args) throws IOException {
+    if (args.length < 1) {
       throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given");
     }
-    try {
-      FileInputStream in = new FileInputStream(args[0]);
-      HSSFWorkbook wb = new HSSFWorkbook(in);
-      in.close();
 
+    try (FileInputStream in = new FileInputStream(args[0]);
+         HSSFWorkbook wb = new HSSFWorkbook(in)) {
       SViewerPanel p = new SViewerPanel(wb, true);
       JFrame frame;
       frame = new JFrame() {
@@ -283,6 +277,7 @@ public void paint(Graphics g) {
             System.exit(0);
           }
         }
+
         @Override
         public synchronized void setTitle(String title) {
           super.setTitle(title);
@@ -291,13 +286,10 @@ public void paint(Graphics g) {
       };
       frame.setTitle("Viewer Frame");
       frame.getContentPane().add(p, BorderLayout.CENTER);
-      frame.setSize(800,640);
+      frame.setSize(800, 640);
       Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
       frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
       frame.setVisible(true);
-    } catch (IOException ex) {
-      ex.printStackTrace();
-      System.exit(1);
     }
   }
 }
index d260bdd4b3e30600f8dc269855c3966e8bcbf5ec..586243528fdde850547c38d2addce33a4e097a16 100644 (file)
@@ -85,12 +85,10 @@ public class POIBrowser extends JFrame
         /* Add the POI filesystems to the tree. */
         int displayedFiles = 0;
         for (final String filename : args) {
-            try {
-                FileInputStream fis = new FileInputStream(filename);
+            try (FileInputStream fis = new FileInputStream(filename)) {
                 POIFSReader r = new POIFSReader();
                 r.registerListener(new TreeReaderListener(filename, rootNode));
                 r.read(fis);
-                fis.close();
                 displayedFiles++;
             } catch (IOException ex) {
                 System.err.println(filename + ": " + ex);
index f85fd0ab2a4fc7e238a7f888e0a59b6acc943abb..177d0a6d9763ad05c990a4d8af870bbfb1c5ac39 100644 (file)
@@ -817,27 +817,22 @@ public class AddDimensionedImage {
      * @param args the command line arguments
      */
     public static void main(String[] args) throws IOException {
-       String imageFile;
-       String outputFile;
-        FileOutputStream fos;
-        Workbook workbook;
-        Sheet sheet;
-
         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();
+
+        final String imageFile = args[0];
+        final String outputFile = args[1];
+
+        try (final Workbook workbook = new HSSFWorkbook();
+             final FileOutputStream fos = new FileOutputStream(outputFile)) {   // OR XSSFWorkbook
+            Sheet sheet = workbook.createSheet("Picture Test");
+            new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(),
+                    new File(imageFile).toURI().toURL(), 100, 40,
+                    AddDimensionedImage.EXPAND_ROW_AND_COLUMN);
+            workbook.write(fos);
+        }
     }
 
     /**
index 105e73df7a5bf52d73624660946207e6a5f7cf4f..e23fdb73609bc36d91fe62507647d1d5acff08f9 100644 (file)
@@ -45,68 +45,60 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 public class DrawingBorders {
 
     public static void main(String[] args) throws IOException {
-        Workbook wb;
+        try (Workbook wb = (args.length > 0 && args[0].equals("-xls"))
+            ? new HSSFWorkbook() : new XSSFWorkbook()) {
+            // add a sheet, and put some values into it
+            Sheet sh1 = wb.createSheet("Sheet1");
+            Row r = sh1.createRow(0);
+            Cell c = r.createCell(1);
+            c.setCellValue("All Borders Medium Width");
+            r = sh1.createRow(4);
+            c = r.createCell(1);
+            c.setCellValue("Medium Outside / Thin Inside Borders");
+            r = sh1.createRow(8);
+            c = r.createCell(1);
+            c.setCellValue("Colored Borders");
 
-        if (args.length > 0 && args[0].equals("-xls")) {
-            wb = new HSSFWorkbook();
-        } else {
-            wb = new XSSFWorkbook();
-        }
-
-        // add a sheet, and put some values into it
-        Sheet sh1 = wb.createSheet("Sheet1");
-        Row r = sh1.createRow(0);
-        Cell c = r.createCell(1);
-        c.setCellValue("All Borders Medium Width");
-        r = sh1.createRow(4);
-        c = r.createCell(1);
-        c.setCellValue("Medium Outside / Thin Inside Borders");
-        r = sh1.createRow(8);
-        c = r.createCell(1);
-        c.setCellValue("Colored Borders");
+            // draw borders (three 3x3 grids)
+            PropertyTemplate pt = new PropertyTemplate();
+            // #1) these borders will all be medium in default color
+            pt.drawBorders(new CellRangeAddress(1, 3, 1, 3),
+                    BorderStyle.MEDIUM, BorderExtent.ALL);
+            // #2) these cells will have medium outside borders and thin inside borders
+            pt.drawBorders(new CellRangeAddress(5, 7, 1, 3),
+                    BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
+            pt.drawBorders(new CellRangeAddress(5, 7, 1, 3), BorderStyle.THIN,
+                    BorderExtent.INSIDE);
+            // #3) these cells will all be medium weight with different colors for the
+            //     outside, inside horizontal, and inside vertical borders. The center
+            //     cell will have no borders.
+            pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
+                    BorderStyle.MEDIUM, IndexedColors.RED.getIndex(),
+                    BorderExtent.OUTSIDE);
+            pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
+                    BorderStyle.MEDIUM, IndexedColors.BLUE.getIndex(),
+                    BorderExtent.INSIDE_VERTICAL);
+            pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
+                    BorderStyle.MEDIUM, IndexedColors.GREEN.getIndex(),
+                    BorderExtent.INSIDE_HORIZONTAL);
+            pt.drawBorders(new CellRangeAddress(10, 10, 2, 2),
+                    BorderStyle.NONE,
+                    BorderExtent.ALL);
 
-        // draw borders (three 3x3 grids)
-        PropertyTemplate pt = new PropertyTemplate();
-        // #1) these borders will all be medium in default color
-        pt.drawBorders(new CellRangeAddress(1, 3, 1, 3),
-                BorderStyle.MEDIUM, BorderExtent.ALL);
-        // #2) these cells will have medium outside borders and thin inside borders
-        pt.drawBorders(new CellRangeAddress(5, 7, 1, 3),
-                BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
-        pt.drawBorders(new CellRangeAddress(5, 7, 1, 3), BorderStyle.THIN,
-                BorderExtent.INSIDE);
-        // #3) these cells will all be medium weight with different colors for the
-        //     outside, inside horizontal, and inside vertical borders. The center
-        //     cell will have no borders.
-        pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
-                BorderStyle.MEDIUM, IndexedColors.RED.getIndex(),
-                BorderExtent.OUTSIDE);
-        pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
-                BorderStyle.MEDIUM, IndexedColors.BLUE.getIndex(),
-                BorderExtent.INSIDE_VERTICAL);
-        pt.drawBorders(new CellRangeAddress(9, 11, 1, 3),
-                BorderStyle.MEDIUM, IndexedColors.GREEN.getIndex(),
-                BorderExtent.INSIDE_HORIZONTAL);
-        pt.drawBorders(new CellRangeAddress(10, 10, 2, 2),
-                BorderStyle.NONE, 
-                BorderExtent.ALL);
+            // apply borders to sheet
+            pt.applyBorders(sh1);
 
-        // apply borders to sheet
-        pt.applyBorders(sh1);
-        
-        // add another sheet and apply the borders to it
-        Sheet sh2 = wb.createSheet("Sheet2");
-        pt.applyBorders(sh2);
+            // add another sheet and apply the borders to it
+            Sheet sh2 = wb.createSheet("Sheet2");
+            pt.applyBorders(sh2);
 
-        // Write the output to a file
-        String file = "db-poi.xls";
-        if (wb instanceof XSSFWorkbook)
-            file += "x";
-        FileOutputStream out = new FileOutputStream(file);
-        wb.write(out);
-        out.close();
-        wb.close();
-        System.out.println("Generated: " + file);
+            // Write the output to a file
+            String file = "db-poi.xls" + (wb instanceof XSSFWorkbook ? "x" : "");
+            try (FileOutputStream out = new FileOutputStream(file)) {
+                wb.write(out);
+            }
+            System.out.println("Generated: " + file);
+        }
     }
 
 }
index 4e29e8f8529b194349499160865e88d04e997600..c98c87ad7997f1cfc98789174006810b908bf100 100644 (file)
@@ -69,48 +69,43 @@ public class LinkedDropDownLists {
         // 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);
+        try (Workbook workbook = workbookName.endsWith(".xlsx") ? new XSSFWorkbook() : 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);
 
-        // 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();
+            // 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);
+
+            try (FileOutputStream fos = new FileOutputStream(workbookName)) {
+                workbook.write(fos);
+            }
+        }
     }
 
     /**
index 194456b90d11194ecbe302a2e4c80a8b88c55e30..eb22cc1d48ab2ad7a035eda3c50d7ceb6d2c7348 100644 (file)
@@ -451,18 +451,14 @@ public class ToCSV {
      */
     private void saveCSVFile(File file)
                                      throws FileNotFoundException, IOException {
-        FileWriter fw;
-        BufferedWriter bw = null;
         ArrayList<String> line;
         StringBuffer buffer;
         String csvLineElement;
-        try {
 
-            System.out.println("Saving the CSV file [" + file.getName() + "]");
+        // Open a writer onto the CSV file.
+        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
 
-            // Open a writer onto the CSV file.
-            fw = new FileWriter(file);
-            bw = new BufferedWriter(fw);
+            System.out.println("Saving the CSV file [" + file.getName() + "]");
 
             // Step through the elements of the ArrayList that was used to hold
             // all of the data recovered from the Excel workbooks' sheets, rows
@@ -507,12 +503,6 @@ public class ToCSV {
                 }
             }
         }
-        finally {
-            if(bw != null) {
-                bw.flush();
-                bw.close();
-            }
-        }
     }
 
     /**
index 711f6fc21f94e7d2a3cab8b7c08aff6777bac2eb..2eb9ffff65e2c46081fe9cb5590815c3edae0d4d 100644 (file)
@@ -30,15 +30,12 @@ public final class MergePresentations {
     public static void main(String args[]) throws Exception {
         try (XMLSlideShow ppt = new XMLSlideShow()) {
             for (String arg : args) {
-                FileInputStream is = new FileInputStream(arg);
-                XMLSlideShow src = new XMLSlideShow(is);
-                is.close();
-
-                for (XSLFSlide srcSlide : src.getSlides()) {
-                    ppt.createSlide().importContent(srcSlide);
+                try (FileInputStream is = new FileInputStream(arg);
+                     XMLSlideShow src = new XMLSlideShow(is)) {
+                    for (XSLFSlide srcSlide : src.getSlides()) {
+                        ppt.createSlide().importContent(srcSlide);
+                    }
                 }
-
-                src.close();
             }
 
             try (FileOutputStream out = new FileOutputStream("merged.pptx")) {
index 5c2c2015125fcb6a2c60fccc0e160f17d8b258af..bd709401852712ef2e5742261a2c4ad242e1d5e5 100644 (file)
@@ -17,6 +17,8 @@
 
 package org.apache.poi;
 
+import static org.apache.poi.hpsf.PropertySetFactory.newDocumentSummaryInformation;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.Closeable;
@@ -141,7 +143,7 @@ public abstract class POIDocument implements Closeable {
             sInf = PropertySetFactory.newSummaryInformation();
         }
         if (dsInf == null) {
-            dsInf = PropertySetFactory.newDocumentSummaryInformation();
+            dsInf = newDocumentSummaryInformation();
         }
     }
 
@@ -277,47 +279,47 @@ public abstract class POIDocument implements Closeable {
      *      {@link NPOIFSFileSystem} occurs
      */
     protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
-        EncryptionInfo ei = getEncryptionInfo();
+        final EncryptionInfo ei = getEncryptionInfo();
         final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted());
-        NPOIFSFileSystem fs = (encryptProps) ? new NPOIFSFileSystem() : outFS;
-        
-        SummaryInformation si = getSummaryInformation();
-        if (si != null) {
-            writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, si, fs);
-            if(writtenEntries != null) {
-                writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME);
+        try (NPOIFSFileSystem tmpFS = new NPOIFSFileSystem()) {
+            final NPOIFSFileSystem fs = (encryptProps) ? tmpFS : outFS;
+
+            writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, getSummaryInformation(), fs, writtenEntries);
+            writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, getDocumentSummaryInformation(), fs, writtenEntries);
+
+            if (!encryptProps) {
+                return;
             }
-        }
-        DocumentSummaryInformation dsi = getDocumentSummaryInformation();
-        if (dsi != null) {
-            writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, fs);
-            if(writtenEntries != null) {
-                writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+
+            // create empty document summary
+            writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, newDocumentSummaryInformation(), outFS);
+
+            // remove summary, if previously available
+            if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) {
+                outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
+            }
+            Encryptor encGen = ei.getEncryptor();
+            if (!(encGen instanceof CryptoAPIEncryptor)) {
+                throw new EncryptedDocumentException(
+                    "Using " + ei.getEncryptionMode() + " encryption. Only CryptoAPI encryption supports encrypted property sets!");
+            }
+            CryptoAPIEncryptor enc = (CryptoAPIEncryptor) encGen;
+            try {
+                enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
+            } catch (GeneralSecurityException e) {
+                throw new IOException(e);
             }
         }
+    }
 
-        if (!encryptProps) {
+    private void writePropertySet(String name, PropertySet ps, NPOIFSFileSystem outFS, List<String> writtenEntries)
+    throws IOException {
+        if (ps == null) {
             return;
         }
-
-        // create empty document summary
-        dsi = PropertySetFactory.newDocumentSummaryInformation();
-        writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, outFS);
-        // remove summary, if previously available
-        if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) {
-            outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
-        }
-        Encryptor encGen = ei.getEncryptor();
-        if (!(encGen instanceof CryptoAPIEncryptor)) {
-            throw new EncryptedDocumentException("Using "+ei.getEncryptionMode()+" encryption. Only CryptoAPI encryption supports encrypted property sets!");
-        }
-        CryptoAPIEncryptor enc = (CryptoAPIEncryptor)encGen;
-        try {
-            enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
-        } catch (GeneralSecurityException e) {
-            throw new IOException(e);
-        } finally {
-            fs.close();
+        writePropertySet(name, ps, outFS);
+        if (writtenEntries != null) {
+            writtenEntries.add(name);
         }
     }
        
index 37750afc6166aff8988e20edb8dc8e296e9e7305..2b2b3f7826f9739764d675af864e47105aeeea2e 100644 (file)
@@ -483,9 +483,10 @@ public final class ZipPackage extends OPCPackage {
                // Check that the document was open in write mode
                throwExceptionIfReadOnly();
 
-               try (final ZipOutputStream zos = (outputStream instanceof ZipOutputStream)
-                ? (ZipOutputStream) outputStream : new ZipOutputStream(outputStream)) {
+               final ZipOutputStream zos = (outputStream instanceof ZipOutputStream)
+            ? (ZipOutputStream) outputStream : new ZipOutputStream(outputStream);
 
+               try {
                        // If the core properties part does not exist in the part list,
                        // we save it as well
                        if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 &&
@@ -537,6 +538,8 @@ public final class ZipPackage extends OPCPackage {
                     throw new OpenXML4JException(errMsg + pm);
                 }
                        }
+
+            zos.finish();
                } catch (OpenXML4JRuntimeException e) {
                        // no need to wrap this type of Exception
                        throw e;
@@ -544,7 +547,7 @@ public final class ZipPackage extends OPCPackage {
             throw new OpenXML4JRuntimeException(
                 "Fail to save: an error occurs while saving the package : "
                                + e.getMessage(), e);
-               }
+        }
     }
 
     /**
index 285e2262008e7e943738f031b79a405ab9d069a9..86fcb58a4e71e2b47f848f29a6bac239087dc16b 100644 (file)
@@ -247,16 +247,7 @@ public class SignatureInfo implements SignatureConfigurable {
                 "system properties.");
         }
         
-        try {
-            final DigestOutputStream dos;
-            switch (algo) {
-                case md2: case md5: case sha1: case sha256: case sha384: case sha512:
-                    dos = new SignatureOutputStream(algo, key);
-                    break;
-                default:
-                    dos = new DigestOutputStream(algo, key);
-                    break;
-            }
+        try (final DigestOutputStream dos = getDigestStream(algo, key)) {
             dos.init();
 
             final Document document = (Document)xmlSignContext.getParent();
@@ -270,6 +261,15 @@ public class SignatureInfo implements SignatureConfigurable {
         }
     }
 
+    private static DigestOutputStream getDigestStream(final HashAlgorithm algo, final PrivateKey key) {
+        switch (algo) {
+            case md2: case md5: case sha1: case sha256: case sha384: case sha512:
+                return new SignatureOutputStream(algo, key);
+            default:
+                return new DigestOutputStream(algo, key);
+        }
+    }
+
     /**
      * @return a signature part for each signature document.
      * the parts can be validated independently.
index 29576c5542ba3b52488dcc4180551f53aff25c30..ad51d4b7cffb09553ad1477e70f7a97dba77810b 100644 (file)
@@ -23,6 +23,7 @@ import java.util.List;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
 
+import javax.xml.parsers.DocumentBuilder;
 import javax.xml.transform.OutputKeys;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerFactory;
@@ -95,12 +96,12 @@ public class WordToFoConverter extends AbstractWordConverter
 
     static Document process( File docFile ) throws Exception
     {
-        final HWPFDocumentCore hwpfDocument = WordToFoUtils.loadDoc( docFile );
-        WordToFoConverter wordToFoConverter = new WordToFoConverter(
-                XMLHelper.getDocumentBuilderFactory().newDocumentBuilder()
-                        .newDocument() );
-        wordToFoConverter.processDocument( hwpfDocument );
-        return wordToFoConverter.getDocument();
+        final DocumentBuilder docBuild = XMLHelper.getDocumentBuilderFactory().newDocumentBuilder();
+        try (final HWPFDocumentCore hwpfDocument = WordToFoUtils.loadDoc( docFile )) {
+            WordToFoConverter wordToFoConverter = new WordToFoConverter(docBuild.newDocument());
+            wordToFoConverter.processDocument(hwpfDocument);
+            return wordToFoConverter.getDocument();
+        }
     }
 
     private List<Element> endnotes = new ArrayList<>(0);
index 6a9cd82fe02fb45e21888232a11584c0cf41bd35..42fe7fd30d0f005010513b97eecfbf074fb797ec 100644 (file)
@@ -24,6 +24,7 @@ import java.util.Deque;
 import java.util.LinkedList;
 import java.util.List;
 
+import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.transform.OutputKeys;
 import javax.xml.transform.Transformer;
@@ -163,12 +164,12 @@ public class WordToHtmlConverter extends AbstractWordConverter
 
     static Document process( File docFile ) throws IOException, ParserConfigurationException
     {
-        final HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc( docFile );
-        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
-                XMLHelper.getDocumentBuilderFactory().newDocumentBuilder()
-                        .newDocument() );
-        wordToHtmlConverter.processDocument( wordDocument );
-        return wordToHtmlConverter.getDocument();
+        final DocumentBuilder docBuild = XMLHelper.getDocumentBuilderFactory().newDocumentBuilder();
+        try (final HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc( docFile )) {
+            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(docBuild.newDocument());
+            wordToHtmlConverter.processDocument(wordDocument);
+            return wordToHtmlConverter.getDocument();
+        }
     }
 
     @Override
index e859ad5c6cbb7d104ac4372bf1363e36a5dffb8d..8eec2af3feb4930cd3b29824801bd8a1bd76c32a 100644 (file)
@@ -79,22 +79,15 @@ public final class HWPFLister
 {
     private static HWPFDocumentCore loadDoc( File docFile ) throws IOException
     {
-        final FileInputStream istream = new FileInputStream( docFile );
-        try
-        {
+        try (final FileInputStream istream = new FileInputStream( docFile )) {
             return loadDoc( istream );
         }
-        finally
-        {
-            IOUtils.closeQuietly( istream );
-        }
     }
 
     private static HWPFDocumentCore loadDoc( InputStream inputStream )
             throws IOException
     {
-        final POIFSFileSystem poifsFileSystem = HWPFDocumentCore
-                .verifyAndBuildPOIFS( inputStream );
+        final POIFSFileSystem poifsFileSystem = HWPFDocumentCore.verifyAndBuildPOIFS( inputStream );
         try
         {
             return new HWPFDocument( poifsFileSystem );