Author: kiwiwings
Date: Sat Apr 18 21:31:18 2020
New Revision: 1876704

URL: http://svn.apache.org/viewvc?rev=1876704&view=rev
Log:
Sonar fixes - Ignore System.out-calls and args checks in examples
Remove superfluous internal methods

Removed:
    
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java
Modified:
    
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java
    poi/trunk/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java
    poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java
    
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
    
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java
    poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java
    
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java
    poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java
    
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java
    poi/trunk/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java
    
poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java
    
poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java
    poi/trunk/src/java/org/apache/poi/hpsf/ClipboardData.java
    poi/trunk/src/java/org/apache/poi/hpsf/PropertySetFactory.java
    poi/trunk/src/java/org/apache/poi/hssf/dev/BiffViewer.java
    poi/trunk/src/java/org/apache/poi/poifs/filesystem/POIFSDocumentPath.java
    poi/trunk/src/java/org/apache/poi/util/HexDump.java
    poi/trunk/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java
    poi/trunk/src/testcases/org/apache/poi/util/TestHexDump.java

Modified: 
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java 
(original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/crypt/examples/OOXMLPasswordsTry.java 
Sat Apr 18 21:31:18 2020
@@ -19,13 +19,12 @@
 
 package org.apache.poi.crypt.examples;
 
-import java.io.BufferedReader;
-import java.io.Closeable;
 import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.security.GeneralSecurityException;
+import java.util.Optional;
+import java.util.function.Predicate;
 
 import org.apache.poi.poifs.crypt.Decryptor;
 import org.apache.poi.poifs.crypt.EncryptionInfo;
@@ -33,88 +32,55 @@ import org.apache.poi.poifs.filesystem.P
 
 /**
  * Tries a list of possible passwords for an OOXML protected file
- * 
+ *
  * Note that this isn't very fast, and is aimed at when you have
  *  just a few passwords to check.
  * For serious processing, you'd be best off grabbing the hash
  *  out with POI or office2john.py, then running that against
  *  "John The Ripper" or GPU enabled version of "hashcat"
  */
-public class OOXMLPasswordsTry implements Closeable {
-    private POIFSFileSystem fs;
-    private EncryptionInfo info;
-    private Decryptor d;
-    
-    private OOXMLPasswordsTry(POIFSFileSystem fs) throws IOException {
-        info = new EncryptionInfo(fs);
-        d = Decryptor.getInstance(info);
-        this.fs = fs;
-    }
-    private OOXMLPasswordsTry(File file) throws IOException {
-        this(new POIFSFileSystem(file, true));
-    }
-    private OOXMLPasswordsTry(InputStream is) throws IOException {
-        this(new POIFSFileSystem(is));
-    }
-    
-    public void close() throws IOException {
-        fs.close();
-    }
-    
-    public String tryAll(File wordfile) throws IOException, 
GeneralSecurityException {
-        String valid = null;
-        // Load
-        try (BufferedReader r = new BufferedReader(new FileReader(wordfile))) {
-            long start = System.currentTimeMillis();
-            int count = 0;
+public final class OOXMLPasswordsTry {
 
-            // Try each password in turn, reporting progress
-            String password;
-            while ((password = r.readLine()) != null) {
-                if (isValid(password)) {
-                    valid = password;
-                    break;
-                }
-                count++;
+    private OOXMLPasswordsTry() {}
 
-                if (count % 1000 == 0) {
-                    int secs = (int) ((System.currentTimeMillis() - start) / 
1000);
-                    System.out.println("Done " + count + " passwords, " +
-                                               secs + " seconds, last password 
" + password);
-                }
-            }
-
-        }
-        // Tidy and return (null if no match)
-        return valid;
-    }
-    public boolean isValid(String password) throws GeneralSecurityException {
-        return d.verifyPassword(password);
-    }
-    
+    @SuppressWarnings({"java:S106","java:S4823"})
     public static void main(String[] args) throws Exception {
         if (args.length < 2) {
             System.err.println("Use:");
             System.err.println("  OOXMLPasswordsTry <file.ooxml> <wordlist>");
             System.exit(1);
         }
-        File ooxml = new File(args[0]);
-        File words = new File(args[1]);
-        
+        String ooxml = args[0], words = args[1];
+
         System.out.println("Trying passwords from " + words + " against " + 
ooxml);
         System.out.println();
 
-        String password;
-        try (OOXMLPasswordsTry pt = new OOXMLPasswordsTry(ooxml)) {
-            password = pt.tryAll(words);
+        try (POIFSFileSystem fs = new POIFSFileSystem(new File(ooxml), true)) {
+            EncryptionInfo info = new EncryptionInfo(fs);
+            Decryptor d = Decryptor.getInstance(info);
+
+            final long start = System.currentTimeMillis();
+            final int[] count = { 0 };
+            Predicate<String> counter = (s) -> {
+                if (++count[0] % 1000 == 0) {
+                    int secs = (int) ((System.currentTimeMillis() - start) / 
1000);
+                    System.out.println("Done " + count[0] + " passwords, " + 
secs + " seconds, last password " + s);
+                }
+                return true;
+            };
+
+            // Try each password in turn, reporting progress
+            Optional<String> found = 
Files.lines(Paths.get(words)).filter(counter).filter(w -> isValid(d, 
w)).findFirst();
+
+            System.out.println(found.map(s -> "Password found: " + 
s).orElse("Error - No password matched"));
         }
-        
-        System.out.println();
-        if (password == null) {
-            System.out.println("Error - No password matched");
-        } else {
-            System.out.println("Password found!");
-            System.out.println(password);
+    }
+
+    private static boolean isValid(Decryptor dec, String password) {
+        try {
+            return dec.verifyPassword(password);
+        } catch (GeneralSecurityException e) {
+            return false;
         }
     }
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java 
Sat Apr 18 21:31:18 2020
@@ -20,15 +20,15 @@
 package org.apache.poi.examples.util;
 
 import java.io.File;
-import java.io.IOException;
 
 import org.apache.poi.util.TempFile;
 
-public class TempFileUtils {
+public final class TempFileUtils {
     private TempFileUtils() {
     }
-    
-    public static void checkTempFiles() throws IOException {
+
+    @SuppressWarnings("java:S106")
+    public static void checkTempFiles() {
         String tmpDir = System.getProperty(TempFile.JAVA_IO_TMPDIR) + 
"/poifiles";
         File tempDir = new File(tmpDir);
         if(tempDir.exists()) {

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java 
Sat Apr 18 21:31:18 2020
@@ -18,11 +18,9 @@
 package org.apache.poi.hpsf.examples;
 
 import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.util.HashMap;
@@ -45,6 +43,7 @@ import org.apache.poi.poifs.filesystem.D
 import org.apache.poi.poifs.filesystem.EntryUtils;
 import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
+import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.TempFile;
 
 /**
@@ -66,6 +65,7 @@ import org.apache.poi.util.TempFile;
  * with the same attributes, and the sections must contain the same properties.
  * Details like the ordering of the properties do not matter.</p>
  */
+@SuppressWarnings({"java:S106","java:S4823"})
 public final class CopyCompare {
     private CopyCompare() {}
 
@@ -85,8 +85,7 @@ public final class CopyCompare {
      * @throws UnsupportedEncodingException if a character encoding is not
      *                                      supported.
      */
-    public static void main(final String[] args)
-            throws UnsupportedEncodingException, IOException {
+    public static void main(final String[] args) throws IOException {
         String originalFileName = null;
         String copyFileName = null;
 
@@ -137,9 +136,8 @@ public final class CopyCompare {
      * PropertySet#PropertySet(PropertySet)} constructor.</p>
      */
     static class CopyFile implements POIFSReaderListener {
-        private String dstName;
-        private OutputStream out;
-        private POIFSFileSystem poiFs;
+        private final String dstName;
+        private final POIFSFileSystem poiFs;
 
 
         /**
@@ -166,23 +164,16 @@ public final class CopyCompare {
              * "event" object. */
             final POIFSDocumentPath path = event.getPath();
             final String name = event.getName();
-            final DocumentInputStream stream = event.getStream();
 
             Throwable t = null;
 
-            try {
+            try (final DocumentInputStream stream = event.getStream()) {
                 /* Find out whether the current document is a property set
                  * stream or not. */
                 if (stream != null && PropertySet.isPropertySetStream(stream)) 
{
                     /* Yes, the current document is a property set stream.
                      * Let's create a PropertySet instance from it. */
-                    PropertySet ps = null;
-                    try {
-                        ps = PropertySetFactory.create(stream);
-                    } catch (NoPropertySetStreamException ex) {
-                        /* This exception will not be thrown because we already
-                         * checked above. */
-                    }
+                    PropertySet ps = PropertySetFactory.create(stream);
 
                     /* Copy the property set to the destination POI file
                      * system. */
@@ -192,7 +183,7 @@ public final class CopyCompare {
                      * copy it unmodified to the destination POIFS. */
                     copy(poiFs, path, name, stream);
                 }
-            } catch (MarkUnsupportedException | WritingNotSupportedException | 
IOException ex) {
+            } catch (MarkUnsupportedException | WritingNotSupportedException | 
IOException | NoPropertySetStreamException ex) {
                 t = ex;
             }
 
@@ -254,20 +245,10 @@ public final class CopyCompare {
             // create the directories to the document
             final DirectoryEntry de = getPath(poiFs, path);
             // check the parameters after the directories have been created
-            if (stream == null || name == null) {
-                // Empty directory
-                return;
-            }
-            final ByteArrayOutputStream out = new ByteArrayOutputStream();
-            int c;
-            while ((c = stream.read()) != -1) {
-                out.write(c);
+            if (stream != null && name != null) {
+                byte[] data = IOUtils.toByteArray(stream);
+                de.createDocument(name, new ByteArrayInputStream(data));
             }
-            stream.close();
-            out.close();
-            final InputStream in =
-                    new ByteArrayInputStream(out.toByteArray());
-            de.createDocument(name, in);
         }
 
 
@@ -275,9 +256,9 @@ public final class CopyCompare {
          * Writes the POI file system to a disk file.
          */
         public void close() throws IOException {
-            out = new FileOutputStream(dstName);
-            poiFs.writeFilesystem(out);
-            out.close();
+            try (OutputStream fos = new FileOutputStream(dstName)) {
+                poiFs.writeFilesystem(fos);
+            }
         }
 
 
@@ -318,9 +299,10 @@ public final class CopyCompare {
                 /* Check whether this directory has already been created. */
                 final String s = path.toString();
                 DirectoryEntry de = paths.get(s);
-                if (de != null)
+                if (de != null) {
                     /* Yes: return the corresponding DirectoryEntry. */
                     return de;
+                }
 
                 /* No: We have to create the directory - or return the root's
                  * DirectoryEntry. */
@@ -334,8 +316,7 @@ public final class CopyCompare {
                      * ensure that the parent directory exists: */
                     de = getPath(poiFs, path.getParent());
                     /* Now create the target directory: */
-                    de = de.createDirectory(path.getComponent
-                            (path.length() - 1));
+                    de = de.createDirectory(path.getComponent(path.length() - 
1));
                 }
                 paths.put(s, de);
                 return de;

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
 (original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
 Sat Apr 18 21:31:18 2020
@@ -65,7 +65,10 @@ import org.apache.poi.poifs.filesystem.P
  *
  * </ol>
  */
-public class ModifyDocumentSummaryInformation {
+@SuppressWarnings({"java:S106","java:S4823"})
+public final class ModifyDocumentSummaryInformation {
+
+    private ModifyDocumentSummaryInformation() {}
 
     /**
      * <p>Main method - see class description.</p>
@@ -91,6 +94,7 @@ public class ModifyDocumentSummaryInform
                 // There is no summary information yet. We have to create a 
new one
                 si = PropertySetFactory.newSummaryInformation();
             }
+            assert(si != null);
 
             /* Change the author to "Rainer Klute". Any former author value 
will
              * be lost. If there has been no author yet, it will be created. */
@@ -112,6 +116,7 @@ public class ModifyDocumentSummaryInform
                  * new one. */
                 dsi = PropertySetFactory.newDocumentSummaryInformation();
             }
+            assert(dsi != null);
 
             /* Change the category to "POI example". Any former category value 
will
              * be lost. If there has been no category yet, it will be created. 
*/

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java
 (original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java
 Sat Apr 18 21:31:18 2020
@@ -28,8 +28,6 @@ import org.apache.poi.hpsf.PropertySetFa
 import org.apache.poi.hpsf.Section;
 import org.apache.poi.poifs.eventfilesystem.POIFSReader;
 import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
-import org.apache.poi.util.HexDump;
 
 /**
  * <p>Sample application showing how to read a document's custom property set.
@@ -37,6 +35,7 @@ import org.apache.poi.util.HexDump;
  *
  * <p>Explanations can be found in the HPSF HOW-TO.</p>
  */
+@SuppressWarnings({"java:S106","java:S4823"})
 public final class ReadCustomPropertySets {
 
     private ReadCustomPropertySets() {}
@@ -47,85 +46,63 @@ public final class ReadCustomPropertySet
      * @param args Command-line arguments (unused).
      * @throws IOException if any I/O exception occurs.
      */
-    public static void main(final String[] args)
-        throws IOException
-    {
+    public static void main(final String[] args) throws IOException {
         final String filename = args[0];
         POIFSReader r = new POIFSReader();
 
         /* Register a listener for *all* documents. */
-        r.registerListener(new MyPOIFSReaderListener());
+        r.registerListener(ReadCustomPropertySets::processPOIFSReaderEvent);
         r.read(new File(filename));
     }
 
 
-    static class MyPOIFSReaderListener implements POIFSReaderListener
-    {
-        @Override
-        public void processPOIFSReaderEvent(final POIFSReaderEvent event)
-        {
-            PropertySet ps;
-            try
-            {
-                ps = PropertySetFactory.create(event.getStream());
-            }
-            catch (NoPropertySetStreamException ex)
-            {
-                out("No property set stream: \"" + event.getPath() +
-                    event.getName() + "\"");
-                return;
-            }
-            catch (Exception ex)
-            {
-                throw new RuntimeException
-                    ("Property set stream \"" +
-                     event.getPath() + event.getName() + "\": " + ex);
-            }
+    public static void processPOIFSReaderEvent(final POIFSReaderEvent event) {
+        final String streamName = event.getPath() + event.getName();
+        PropertySet ps;
+        try {
+            ps = PropertySetFactory.create(event.getStream());
+        } catch (NoPropertySetStreamException ex) {
+            out("No property set stream: \"" + streamName + "\"");
+            return;
+        } catch (Exception ex) {
+            throw new RuntimeException("Property set stream \"" + streamName + 
"\": " + ex);
+        }
 
-            /* Print the name of the property set stream: */
-            out("Property set stream \"" + event.getPath() +
-                event.getName() + "\":");
-
-            /* Print the number of sections: */
-            final long sectionCount = ps.getSectionCount();
-            out("   No. of sections: " + sectionCount);
-
-            /* Print the list of sections: */
-            List<Section> sections = ps.getSections();
-            int nr = 0;
-            for (Section sec : sections) {
-                /* Print a single section: */
-                out("   Section " + nr++ + ":");
-                String s = hex(sec.getFormatID().getBytes());
-                s = s.substring(0, s.length() - 1);
-                out("      Format ID: " + s);
-
-                /* Print the number of properties in this section. */
-                int propertyCount = sec.getPropertyCount();
-                out("      No. of properties: " + propertyCount);
-
-                /* Print the properties: */
-                Property[] properties = sec.getProperties();
-                for (Property p : properties) {
-                    /* Print a single property: */
-                    long id = p.getID();
-                    long type = p.getType();
-                    Object value = p.getValue();
-                    out("      Property ID: " + id + ", type: " + type +
-                            ", value: " + value);
-                }
+        /* Print the name of the property set stream: */
+        out("Property set stream \"" + streamName + "\":");
+
+        /* Print the number of sections: */
+        final long sectionCount = ps.getSectionCount();
+        out("   No. of sections: " + sectionCount);
+
+        /* Print the list of sections: */
+        List<Section> sections = ps.getSections();
+        int nr = 0;
+        for (Section sec : sections) {
+            /* Print a single section: */
+            out("   Section " + nr++ + ":");
+            String s = sec.getFormatID().toString();
+            s = s.substring(0, s.length() - 1);
+            out("      Format ID: " + s);
+
+            /* Print the number of properties in this section. */
+            int propertyCount = sec.getPropertyCount();
+            out("      No. of properties: " + propertyCount);
+
+            /* Print the properties: */
+            Property[] properties = sec.getProperties();
+            for (Property p : properties) {
+                /* Print a single property: */
+                long id = p.getID();
+                long type = p.getType();
+                Object value = p.getValue();
+                out("      Property ID: " + id + ", type: " + type +
+                        ", value: " + value);
             }
         }
     }
 
-    private static void out(final String msg)
-    {
+    private static void out(final String msg) {
         System.out.println(msg);
     }
-
-    private static String hex(final byte[] bytes)
-    {
-        return HexDump.dump(bytes, 0L, 0);
-    }
-
 }

Modified: poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java Sat 
Apr 18 21:31:18 2020
@@ -24,7 +24,6 @@ import org.apache.poi.hpsf.PropertySetFa
 import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.poifs.eventfilesystem.POIFSReader;
 import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
 
 /**
  * <p>Sample application showing how to read a OLE 2 document's
@@ -33,8 +32,8 @@ import org.apache.poi.poifs.eventfilesys
  *
  * <p>Explanations can be found in the HPSF HOW-TO.</p>
  */
-public final class ReadTitle
-{
+@SuppressWarnings({"java:S106","java:S4823"})
+public final class ReadTitle {
     private ReadTitle() {}
 
     /**
@@ -44,38 +43,22 @@ public final class ReadTitle
      * be the name of a POI filesystem to read.
      * @throws IOException if any I/O exception occurs.
      */
-    public static void main(final String[] args) throws IOException
-    {
+    public static void main(final String[] args) throws IOException {
         final String filename = args[0];
         POIFSReader r = new POIFSReader();
-        r.registerListener(new MyPOIFSReaderListener(), 
SummaryInformation.DEFAULT_STREAM_NAME);
+        r.registerListener(ReadTitle::processPOIFSReaderEvent, 
SummaryInformation.DEFAULT_STREAM_NAME);
         r.read(new File(filename));
     }
 
 
-    static class MyPOIFSReaderListener implements POIFSReaderListener
-    {
-        @Override
-        public void processPOIFSReaderEvent(final POIFSReaderEvent event)
-        {
-            SummaryInformation si;
-            try
-            {
-                si = (SummaryInformation)
-                    PropertySetFactory.create(event.getStream());
-            }
-            catch (Exception ex)
-            {
-                throw new RuntimeException
-                    ("Property set stream \"" +
-                     event.getPath() + event.getName() + "\": " + ex);
-            }
-            final String title = si.getTitle();
-            if (title != null)
-                System.out.println("Title: \"" + title + "\"");
-            else
-                System.out.println("Document has no title.");
+    private static void processPOIFSReaderEvent(final POIFSReaderEvent event) {
+        SummaryInformation si;
+        try {
+            si = (SummaryInformation) 
PropertySetFactory.create(event.getStream());
+        } catch (Exception ex) {
+            throw new RuntimeException("Property set stream \"" + 
event.getPath() + event.getName() + "\": " + ex);
         }
+        final String title = si.getTitle();
+        System.out.println(title != null ? "Title: \"" + title + "\"" : 
"Document has no title.");
     }
-
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java
 (original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java
 Sat Apr 18 21:31:18 2020
@@ -17,15 +17,11 @@
 
 package org.apache.poi.hpsf.examples;
 
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.Map;
 
 import org.apache.poi.hpsf.HPSFRuntimeException;
 import org.apache.poi.hpsf.MarkUnsupportedException;
@@ -39,7 +35,6 @@ import org.apache.poi.hpsf.WritingNotSup
 import org.apache.poi.hpsf.wellknown.PropertyIDMap;
 import org.apache.poi.poifs.eventfilesystem.POIFSReader;
 import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
-import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
 import org.apache.poi.poifs.filesystem.DirectoryEntry;
 import org.apache.poi.poifs.filesystem.DocumentInputStream;
 import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
@@ -49,15 +44,15 @@ import org.apache.poi.poifs.filesystem.P
  * <p>This class is a sample application which shows how to write or modify the
  * author and title property of an OLE 2 document. This could be done in two
  * different ways:</p>
- * 
+ *
  * <ul>
- * 
+ *
  * <li><p>The first approach is to open the OLE 2 file as a POI filesystem
  * (see class {@link POIFSFileSystem}), read the summary information property
  * set (see classes {@link SummaryInformation} and {@link PropertySet}), write
  * the author and title properties into it and write the property set back into
  * the POI filesystem.</p></li>
- * 
+ *
  * <li><p>The second approach does not modify the original POI filesystem, but
  * instead creates a new one. All documents from the original POIFS are copied
  * to the destination POIFS, except for the summary information stream. The
@@ -65,9 +60,9 @@ import org.apache.poi.poifs.filesystem.P
  * it to the destination POIFS. It there are several summary information 
streams
  * in the original POIFS - e.g. in subordinate directories - they are modified
  * just the same.</p></li>
- * 
+ *
  * </ul>
- * 
+ *
  * <p>This sample application takes the second approach. It expects the name of
  * the existing POI filesystem's name as its first command-line parameter and
  * the name of the output POIFS as the second command-line argument. The
@@ -76,9 +71,10 @@ import org.apache.poi.poifs.filesystem.P
  * encounters a summary information stream it reads its properties. Then it 
sets
  * the "author" and "title" properties to new values and writes the modified
  * summary information stream into the output file.</p>
- * 
+ *
  * <p>Further explanations can be found in the HPSF HOW-TO.</p>
  */
+@SuppressWarnings({"java:S106","java:S4823"})
 public final class WriteAuthorAndTitle {
     private WriteAuthorAndTitle() {}
 
@@ -89,301 +85,89 @@ public final class WriteAuthorAndTitle {
      * be the name of a POI filesystem to read.
      * @throws IOException if any I/O exception occurs.
      */
-    public static void main(final String[] args) throws IOException
-    {
+    public static void main(final String[] args) throws IOException {
         /* Check whether we have exactly two command-line arguments. */
-        if (args.length != 2)
-        {
-            System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() 
+
-                               " originPOIFS destinationPOIFS");
+        if (args.length != 2) {
+            System.err.println("Usage: WriteAuthorAndTitle originPOIFS 
destinationPOIFS");
             System.exit(1);
         }
-        
+
         /* Read the names of the origin and destination POI filesystems. */
-        final String srcName = args[0];
-        final String dstName = args[1];
+        final String srcName = args[0], dstName = args[1];
 
         /* Read the origin POIFS using the eventing API. The real work is done
          * in the class ModifySICopyTheRest which is registered here as a
          * POIFSReader. */
-        final POIFSReader r = new POIFSReader();
-        final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName);
-        r.registerListener(msrl);
-        r.read(new File(srcName));
+        try (POIFSFileSystem poifs = new POIFSFileSystem();
+             OutputStream out = new FileOutputStream(dstName)) {
+            final POIFSReader r = new POIFSReader();
+            r.registerListener((e) -> handleEvent(poifs, e));
+            r.read(new File(srcName));
 
-        /* Write the new POIFS to disk. */
-        msrl.close();
+            /* Write the new POIFS to disk. */
+            poifs.writeFilesystem(out);
+        }
     }
 
-
+    private interface InputStreamSupplier {
+        InputStream get() throws IOException, WritingNotSupportedException;
+    }
 
     /**
-     * <p>This class does all the work. As its name implies it modifies a
-     * summary information property set and copies everything else unmodified
-     * to the destination POI filesystem. Since an instance of it is registered
-     * as a {@link POIFSReader} its method {@link 
-     * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each document
-     * in the origin POIFS.</p>
+     * The method is called by POI's eventing API for each file in the origin 
POIFS.
      */
-    static class ModifySICopyTheRest implements POIFSReaderListener
-    {
-        private String dstName;
-        private OutputStream out;
-        private POIFSFileSystem poiFs;
-
-
-        /**
-         * The constructor of a {@link ModifySICopyTheRest} instance creates
-         * the target POIFS. It also stores the name of the file the POIFS will
-         * be written to once it is complete.
-         * 
-         * @param dstName The name of the disk file the destination POIFS is to
-         * be written to.
-         */
-        ModifySICopyTheRest(final String dstName)
-        {
-            this.dstName = dstName;
-            poiFs = new POIFSFileSystem();
-        }
-
-
-        /**
-         * The method is called by POI's eventing API for each file in the
-         * origin POIFS.
-         */
-        @Override
-        public void processPOIFSReaderEvent(final POIFSReaderEvent event)
-        {
-            /* The following declarations are shortcuts for accessing the
-             * "event" object. */
-            final POIFSDocumentPath path = event.getPath();
-            final String name = event.getName();
-            final DocumentInputStream stream = event.getStream();
-
-            Throwable t = null;
-
-            try {
-                /* Find out whether the current document is a property set
-                 * stream or not. */
-                if (PropertySet.isPropertySetStream(stream)) {
-                    try {
-                        /* Yes, the current document is a property set stream.
-                         * Let's create a PropertySet instance from it. */
-                        PropertySet ps = PropertySetFactory.create(stream);
-
-                        /* Now we know that we really have a property set. The 
next
-                         * step is to find out whether it is a summary 
information
-                         * or not. */
-                        if (ps.isSummaryInformation()) {
-                            /* Yes, it is a summary information. We will 
modify it
-                             * and write the result to the destination POIFS. 
*/
-                            editSI(poiFs, path, name, ps);
-                        } else {
-                            /* No, it is not a summary information. We don't 
care
-                             * about its internals and copy it unmodified to 
the
-                             * destination POIFS. */
-                            copy(poiFs, path, name, ps);
-                        }
-                    } catch (NoPropertySetStreamException ex) {
-                        /* This exception will not be thrown because we already
-                         * checked above. */
-                    }
-                } else {
-                    /* No, the current document is not a property set stream. 
We
-                     * copy it unmodified to the destination POIFS. */
-                    copy(poiFs, event.getPath(), event.getName(), stream);
+    private static void handleEvent(final POIFSFileSystem poiFs, final 
POIFSReaderEvent event) {
+        // The following declarations are shortcuts for accessing the "event" 
object.
+        final DocumentInputStream stream = event.getStream();
+
+        try {
+            final InputStreamSupplier isSup;
+
+            // Find out whether the current document is a property set stream 
or not.
+            if (PropertySet.isPropertySetStream(stream)) {
+                // Yes, the current document is a property set stream. Let's 
create a PropertySet instance from it.
+                PropertySet ps = PropertySetFactory.create(stream);
+
+                // Now we know that we really have a property set.
+                // The next step is to find out whether it is a summary 
information or not.
+                if (ps.isSummaryInformation()) {
+                    // Create a mutable property set as a copy of the original 
read-only property set.
+                    ps = new PropertySet(ps);
+
+                    // Retrieve the section containing the properties to 
modify.
+                    // A summary information property set contains exactly one 
section.
+                    final Section s = ps.getSections().get(0);
+
+                    // Set the properties.
+                    s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, 
"Rainer Klute");
+                    s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, 
"Test");
                 }
-            } catch (MarkUnsupportedException | WritingNotSupportedException | 
IOException ex) {
-                t = ex;
-            }
 
-            /* According to the definition of the processPOIFSReaderEvent 
method
-             * we cannot pass checked exceptions to the caller. The following
-             * lines check whether a checked exception occurred and throws an
-             * unchecked exception. The message of that exception is that of
-             * the underlying checked exception. */
-            if (t != null) {
-                throw new HPSFRuntimeException("Could not read file \"" + path 
+ "/" + name, t);
+                isSup = ps::toInputStream;
+            } else {
+                // No, the current document is not a property set stream. We 
copy it unmodified to the destination POIFS.
+                isSup = event::getStream;
             }
-        }
-
-
-        /**
-         * <p>Receives a summary information property set modifies (or creates)
-         * its "author" and "title" properties and writes the result under the
-         * same path and name as the origin to a destination POI 
filesystem.</p>
-         *
-         * @param poiFs The POI filesystem to write to.
-         * @param path The original (and destination) stream's path.
-         * @param name The original (and destination) stream's name.
-         * @param si The property set. It should be a summary information
-         * property set.
-         */
-        void editSI(final POIFSFileSystem poiFs,
-                           final POIFSDocumentPath path,
-                           final String name,
-                           final PropertySet si)
-        throws WritingNotSupportedException, IOException
-            
-        {
-            /* Get the directory entry for the target stream. */
-            final DirectoryEntry de = getPath(poiFs, path);
-
-            /* Create a mutable property set as a copy of the original 
read-only
-             * property set. */
-            final PropertySet mps = new PropertySet(si);
-            
-            /* Retrieve the section containing the properties to modify. A
-             * summary information property set contains exactly one section. 
*/
-            final Section s = mps.getSections().get(0);
-
-            /* Set the properties. */
-            s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR,
-                          "Rainer Klute");
-            s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR,
-                          "Test");
-
-            /* Create an input stream containing the bytes the property set
-             * stream consists of. */
-            final InputStream pss = mps.toInputStream();
-
-            /* Write the property set stream to the POIFS. */
-            de.createDocument(name, pss);
-        }
-
-
-        /**
-         * <p>Writes a {@link PropertySet} to a POI filesystem. This method is
-         * simpler than {@link #editSI} because the origin property set has 
just
-         * to be copied.</p>
-         *
-         * @param poiFs The POI filesystem to write to.
-         * @param path The file's path in the POI filesystem.
-         * @param name The file's name in the POI filesystem.
-         * @param ps The property set to write.
-         */
-        public void copy(final POIFSFileSystem poiFs,
-                         final POIFSDocumentPath path,
-                         final String name,
-                         final PropertySet ps)
-            throws WritingNotSupportedException, IOException
-        {
-            final DirectoryEntry de = getPath(poiFs, path);
-            final PropertySet mps = new PropertySet(ps);
-            de.createDocument(name, mps.toInputStream());
-        }
 
+            try (InputStream is = isSup.get()) {
+                final POIFSDocumentPath path = event.getPath();
 
-
-        /**
-         * <p>Copies the bytes from a {@link DocumentInputStream} to a new
-         * stream in a POI filesystem.</p>
-         *
-         * @param poiFs The POI filesystem to write to.
-         * @param path The source document's path.
-         * @param name The source document's name.
-         * @param stream The stream containing the source document.
-         */
-        public void copy(final POIFSFileSystem poiFs,
-                         final POIFSDocumentPath path,
-                         final String name,
-                         final DocumentInputStream stream) throws IOException
-        {
-            final DirectoryEntry de = getPath(poiFs, path);
-            final ByteArrayOutputStream out = new ByteArrayOutputStream();
-            int c;
-            while ((c = stream.read()) != -1)
-                out.write(c);
-            stream.close();
-            out.close();
-            final InputStream in =
-                new ByteArrayInputStream(out.toByteArray());
-            de.createDocument(name, in);
-        }
-
-
-        /**
-         * Writes the POI file system to a disk file.
-         */
-        public void close() throws IOException
-        {
-            out = new FileOutputStream(dstName);
-            poiFs.writeFilesystem(out);
-            out.close();
-        }
-
-
-
-        /** Contains the directory paths that have already been created in the
-         * output POI filesystem and maps them to their corresponding
-         * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */
-        private final Map<String, DirectoryEntry> paths = new HashMap<>();
-
-
-
-        /**
-         * <p>Ensures that the directory hierarchy for a document in a POI
-         * fileystem is in place. When a document is to be created somewhere in
-         * a POI filesystem its directory must be created first. This method
-         * creates all directories between the POI filesystem root and the
-         * directory the document should belong to which do not yet exist.</p>
-         * 
-         * <p>Unfortunately POI does not offer a simple method to interrogate
-         * the POIFS whether a certain child node (file or directory) exists in
-         * a directory. However, since we always start with an empty POIFS 
which
-         * contains the root directory only and since each directory in the
-         * POIFS is created by this method we can maintain the POIFS's 
directory
-         * hierarchy ourselves: The {@link DirectoryEntry} of each directory
-         * created is stored in a {@link Map}. The directories' path names map
-         * to the corresponding {@link DirectoryEntry} instances.</p>
-         *
-         * @param poiFs The POI filesystem the directory hierarchy is created
-         * in, if needed.
-         * @param path The document's path. This method creates those directory
-         * components of this hierarchy which do not yet exist.
-         * @return The directory entry of the document path's parent. The 
caller
-         * should use this {@link DirectoryEntry} to create documents in it.
-         */
-        public DirectoryEntry getPath(final POIFSFileSystem poiFs,
-                                      final POIFSDocumentPath path)
-        {
-            try
-            {
-                /* Check whether this directory has already been created. */
-                final String s = path.toString();
-                DirectoryEntry de = paths.get(s);
-                if (de != null)
-                    /* Yes: return the corresponding DirectoryEntry. */
-                    return de;
-
-                /* No: We have to create the directory - or return the root's
-                 * DirectoryEntry. */
-                int l = path.length();
-                if (l == 0)
-                    /* Get the root directory. It does not have to be created
-                     * since it always exists in a POIFS. */
-                    de = poiFs.getRoot();
-                else
-                {
-                    /* Create a subordinate directory. The first step is to
-                     * ensure that the parent directory exists: */
-                    de = getPath(poiFs, path.getParent());
-                    /* Now create the target directory: */
-                    de = de.createDirectory(path.getComponent
-                                            (path.length() - 1));
+                // Ensures that the directory hierarchy for a document in a 
POI fileystem is in place.
+                // Get the root directory. It does not have to be created 
since it always exists in a POIFS.
+                DirectoryEntry de = poiFs.getRoot();
+
+                for (int i=0; i<path.length(); i++) {
+                    String subDir = path.getComponent(i);
+                    de = (de.hasEntry(subDir)) ? 
(DirectoryEntry)de.getEntry(subDir) : de.createDirectory(subDir);
                 }
-                paths.put(s, de);
-                return de;
-            }
-            catch (IOException ex)
-            {
-                /* This exception will be thrown if the directory already
-                 * exists. However, since we have full control about directory
-                 * creation we can ensure that this will never happen. */
-                ex.printStackTrace(System.err);
-                throw new RuntimeException(ex);
+
+                de.createDocument(event.getName(), is);
             }
+
+        } catch (MarkUnsupportedException | WritingNotSupportedException | 
IOException | NoPropertySetStreamException ex) {
+            // According to the definition of the processPOIFSReaderEvent 
method we cannot pass checked
+            // exceptions to the caller.
+            throw new HPSFRuntimeException("Could not read file " + 
event.getPath() + "/" + event.getName(), ex);
         }
     }
-
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java Sat 
Apr 18 21:31:18 2020
@@ -34,15 +34,18 @@ import org.apache.poi.poifs.filesystem.P
  * <p>This class is a simple sample application showing how to create a 
property
  * set and write it to disk.</p>
  */
-public class WriteTitle
-{
+@SuppressWarnings({"java:S106","java:S4823"})
+public final class WriteTitle {
+
+    private WriteTitle() {}
+
     /**
      * <p>Runs the example program.</p>
      *
-     * @param args Command-line arguments. The first and only command-line 
+     * @param args Command-line arguments. The first and only command-line
      * argument is the name of the POI file system to create.
      * @throws IOException if any I/O exception occurs.
-     * @throws WritingNotSupportedException if HPSF does not (yet) support 
+     * @throws WritingNotSupportedException if HPSF does not (yet) support
      * writing a certain property type.
      */
     public static void main(final String[] args)
@@ -51,8 +54,7 @@ public class WriteTitle
         /* Check whether we have exactly one command-line argument. */
         if (args.length != 1)
         {
-            System.err.println("Usage: " + WriteTitle.class.getName() +
-                               "destinationPOIFS");
+            System.err.println("Usage: " + WriteTitle.class.getName() + 
"destinationPOIFS");
             System.exit(1);
         }
 
@@ -70,7 +72,7 @@ public class WriteTitle
          * SectionIDMap.SUMMARY_INFORMATION_ID. */
         ms.setFormatID(SummaryInformation.FORMAT_ID);
 
-        /* Create an empty property. */    
+        /* Create an empty property. */
         final Property p = new Property();
 
         /* Fill the property with appropriate settings so that it specifies the
@@ -82,12 +84,13 @@ public class WriteTitle
         /* Place the property into the section. */
         ms.setProperty(p);
 
-        /* Create the POI file system the property set is to be written to. */
-        try (final POIFSFileSystem poiFs = new POIFSFileSystem()) {
-            /* For writing the property set into a POI file system it has to be
-             * handed over to the POIFS.createDocument() method as an input 
stream
-             * which produces the bytes making out the property set stream. */
-            final InputStream is = mps.toInputStream();
+        /* Create the POI file system the property set is to be written to.
+         * For writing the property set into a POI file system it has to be
+         * handed over to the POIFS.createDocument() method as an input stream
+         * which produces the bytes making out the property set stream. */
+        try (final POIFSFileSystem poiFs = new POIFSFileSystem();
+             final InputStream is = mps.toInputStream();
+             final FileOutputStream fos = new FileOutputStream(fileName)) {
 
             /* Create the summary information property set in the POI file
              * system. It is given the default name most (if not all) summary
@@ -95,9 +98,7 @@ public class WriteTitle
             poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME);
 
             /* Write the whole POI file system to a disk file. */
-            try (FileOutputStream fos = new FileOutputStream(fileName)) {
-                poiFs.writeFilesystem(fos);
-            }
+            poiFs.writeFilesystem(fos);
         }
     }
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java 
Sat Apr 18 21:31:18 2020
@@ -51,9 +51,11 @@ import org.apache.poi.sl.usermodel.Verti
 @SuppressWarnings("java:S1192")
 public final class ApacheconEU08 {
 
+    private ApacheconEU08() {}
+
     public static void main(String[] args) throws IOException {
+        // use HSLFSlideShow or XMLSlideShow
         try (SlideShow<?,?> ppt = new HSLFSlideShow()) {
-            // SlideShow<?,?> ppt = new XMLSlideShow();
             ppt.setPageSize(new Dimension(720, 540));
 
             slide1(ppt);
@@ -394,7 +396,7 @@ public final class ApacheconEU08 {
         graphics.setFont(new Font("Arial", Font.BOLD, 10));
         for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {
             graphics.setColor(Color.black);
-            int width = ((Integer)def[i+1]).intValue();
+            int width = (Integer) def[i + 1];
             graphics.drawString("Q" + idx, x-20, y+20);
             graphics.drawString(width + "%", x + width + 10, y + 20);
             graphics.setColor((Color)def[i]);

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java 
(original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java 
Sat Apr 18 21:31:18 2020
@@ -29,8 +29,10 @@ import org.apache.poi.hslf.usermodel.HSL
 /**
  * Demonstrates how to create hyperlinks in PowerPoint presentations
  */
-public abstract class CreateHyperlink {
-    
+public final class CreateHyperlink {
+
+    private CreateHyperlink() {}
+
     public static void main(String[] args) throws IOException {
         try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             HSLFSlide slideA = ppt.createSlide();

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java 
Sat Apr 18 21:31:18 2020
@@ -19,6 +19,7 @@ package org.apache.poi.hslf.examples;
 
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
+import java.io.IOException;
 import java.io.InputStream;
 
 import org.apache.poi.hslf.usermodel.HSLFObjectData;
@@ -33,12 +34,16 @@ import org.apache.poi.hssf.usermodel.HSS
 import org.apache.poi.hwpf.HWPFDocument;
 import org.apache.poi.hwpf.usermodel.Paragraph;
 import org.apache.poi.hwpf.usermodel.Range;
+import org.apache.poi.util.IOUtils;
 
 /**
  * Demonstrates how you can extract misc embedded data from a ppt file
  */
+@SuppressWarnings({"java:S106","java:S4823"})
 public final class DataExtraction {
 
+    private DataExtraction() {}
+
     public static void main(String[] args) throws Exception {
 
         if (args.length == 0) {
@@ -46,20 +51,13 @@ public final class DataExtraction {
             return;
         }
 
-        try (FileInputStream is = new FileInputStream(args[0]);
-            HSLFSlideShow ppt = new HSLFSlideShow(is)) {
+        try (FileInputStream fis = new FileInputStream(args[0]);
+            HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
 
             //extract all sound files embedded in this presentation
             HSLFSoundData[] sound = ppt.getSoundData();
             for (HSLFSoundData aSound : sound) {
-                String type = aSound.getSoundType();  //*.wav
-                String name = aSound.getSoundName();  //typically file name
-                byte[] data = aSound.getData();       //raw bytes
-
-                //save the sound  on disk
-                try (FileOutputStream out = new FileOutputStream(name + type)) 
{
-                    out.write(data);
-                }
+                handleSound(aSound);
             }
 
             int oleIdx = -1, picIdx = -1;
@@ -71,35 +69,18 @@ public final class DataExtraction {
                         HSLFObjectShape ole = (HSLFObjectShape) shape;
                         HSLFObjectData data = ole.getObjectData();
                         String name = ole.getInstanceName();
-                        if ("Worksheet".equals(name)) {
-
-                            //read xls
-                            @SuppressWarnings({"unused", "resource"})
-                            HSSFWorkbook wb = new 
HSSFWorkbook(data.getInputStream());
-
-                        } else if ("Document".equals(name)) {
-                            try (HWPFDocument doc = new 
HWPFDocument(data.getInputStream())) {
+                        switch (name == null ? "" : name) {
+                            case "Worksheet":
+                                //read xls
+                                handleWorkbook(data, name, oleIdx);
+                                break;
+                            case "Document":
                                 //read the word document
-                                Range r = doc.getRange();
-                                for (int k = 0; k < r.numParagraphs(); k++) {
-                                    Paragraph p = r.getParagraph(k);
-                                    System.out.println(p.text());
-                                }
-
-                                //save on disk
-                                try (FileOutputStream out = new 
FileOutputStream(name + "-(" + (oleIdx) + ").doc")) {
-                                    doc.write(out);
-                                }
-                            }
-                        } else {
-                            try (FileOutputStream out = new 
FileOutputStream(ole.getProgId() + "-" + (oleIdx + 1) + ".dat");
-                                InputStream dis = data.getInputStream()) {
-                                byte[] chunk = new byte[2048];
-                                int count;
-                                while ((count = dis.read(chunk)) >= 0) {
-                                    out.write(chunk, 0, count);
-                                }
-                            }
+                                handleDocument(data, name, oleIdx);
+                                break;
+                            default:
+                                handleUnknown(data, ole.getProgId(), oleIdx);
+                                break;
                         }
                     }
 
@@ -108,16 +89,60 @@ public final class DataExtraction {
                         picIdx++;
                         HSLFPictureShape p = (HSLFPictureShape) shape;
                         HSLFPictureData data = p.getPictureData();
-                        String ext = data.getType().extension;
-                        try (FileOutputStream out = new 
FileOutputStream("pict-" + picIdx + ext)) {
-                            out.write(data.getData());
-                        }
+                        handlePicture(data, picIdx);
                     }
                 }
             }
         }
     }
 
+    private static void handleWorkbook(HSLFObjectData data, String name, int 
oleIdx) throws IOException {
+        try (InputStream is = data.getInputStream();
+             HSSFWorkbook wb = new HSSFWorkbook(is);
+             FileOutputStream out = new FileOutputStream(name + "-(" + 
(oleIdx) + ").xls")) {
+            wb.write(out);
+        }
+    }
+
+    private static void handleDocument(HSLFObjectData data, String name, int 
oleIdx) throws IOException {
+        try (InputStream is = data.getInputStream();
+             HWPFDocument doc = new HWPFDocument(is);
+             FileOutputStream out = new FileOutputStream(name + "-(" + 
(oleIdx) + ").doc")) {
+            Range r = doc.getRange();
+            for (int k = 0; k < r.numParagraphs(); k++) {
+                Paragraph p = r.getParagraph(k);
+                System.out.println(p.text());
+            }
+
+            //save on disk
+            doc.write(out);
+        }
+    }
+
+    private static void handleUnknown(HSLFObjectData data, String name, int 
oleIdx) throws IOException {
+        try (InputStream is = data.getInputStream();
+             FileOutputStream out = new FileOutputStream(name + "-" + (oleIdx 
+ 1) + ".dat")) {
+            IOUtils.copy(is, out);
+        }
+    }
+
+    private static void handlePicture(HSLFPictureData data, int picIdx) throws 
IOException {
+        String ext = data.getType().extension;
+        try (FileOutputStream out = new FileOutputStream("pict-" + picIdx + 
ext)) {
+            out.write(data.getData());
+        }
+    }
+
+    private static void handleSound(HSLFSoundData aSound) throws IOException {
+        String type = aSound.getSoundType();  //*.wav
+        String name = aSound.getSoundName();  //typically file name
+
+        //save the sound  on disk
+        try (FileOutputStream out = new FileOutputStream(name + type)) {
+            out.write(aSound.getData());
+        }
+    }
+
     private static void usage(){
         System.out.println("Usage: DataExtraction  ppt");
     }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java 
Sat Apr 18 21:31:18 2020
@@ -23,23 +23,24 @@ import java.awt.Graphics2D;
 import java.awt.Rectangle;
 import java.io.FileOutputStream;
 
-import org.apache.poi.hslf.model.PPGraphics2D;
 import org.apache.poi.hslf.usermodel.HSLFGroupShape;
 import org.apache.poi.hslf.usermodel.HSLFSlide;
 import org.apache.poi.hslf.usermodel.HSLFSlideShow;
+import org.apache.poi.sl.draw.SLGraphics;
 
 /**
  * Demonstrates how to draw into a slide using the HSLF Graphics2D driver.
- *
- * @author Yegor Kozlov
  */
 public final class Graphics2DDemo {
 
+    private Graphics2DDemo() {}
+
     /**
      * A simple bar chart demo
      */
     public static void main(String[] args) throws Exception {
-        try (HSLFSlideShow ppt = new HSLFSlideShow()) {
+        try (HSLFSlideShow ppt = new HSLFSlideShow();
+             FileOutputStream out = new FileOutputStream("hslf-graphics.ppt")) 
{
             //bar chart data. The first value is the bar color, the second is 
the width
             Object[] def = new Object[]{
                     Color.yellow, 40,
@@ -56,14 +57,14 @@ public final class Graphics2DDemo {
             group.setAnchor(bounds);
             group.setInteriorAnchor(new Rectangle(0, 0, 100, 100));
             slide.addShape(group);
-            Graphics2D graphics = new PPGraphics2D(group);
+            Graphics2D graphics = new SLGraphics(group);
 
             //draw a simple bar graph
             int x = 10, y = 10;
             graphics.setFont(new Font("Arial", Font.BOLD, 10));
             for (int i = 0, idx = 1; i < def.length; i += 2, idx++) {
                 graphics.setColor(Color.black);
-                int width = ((Integer) def[i + 1]).intValue();
+                int width = (Integer) def[i + 1];
                 graphics.drawString("Q" + idx, x - 5, y + 10);
                 graphics.drawString(width + "%", x + width + 3, y + 10);
                 graphics.setColor((Color) def[i]);
@@ -75,9 +76,7 @@ public final class Graphics2DDemo {
             graphics.draw(group.getInteriorAnchor());
             graphics.drawString("Performance", x + 30, y + 10);
 
-            try (FileOutputStream out = new 
FileOutputStream("hslf-graphics.ppt")) {
-                ppt.write(out);
-            }
+            ppt.write(out);
         }
     }
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java 
(original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java 
Sat Apr 18 21:31:18 2020
@@ -25,7 +25,9 @@ import org.apache.poi.hslf.usermodel.HSL
 /**
  * Demonstrates how to set headers / footers
  */
-public abstract class HeadersFootersDemo {
+public final class HeadersFootersDemo {
+    private HeadersFootersDemo() {}
+
     public static void main(String[] args) throws IOException {
         try (HSLFSlideShow ppt = new HSLFSlideShow()) {
             HeadersFooters slideHeaders = ppt.getSlideHeadersFooters();

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java Sat 
Apr 18 21:31:18 2020
@@ -22,7 +22,6 @@ import java.util.List;
 import java.util.Locale;
 
 import org.apache.poi.hslf.usermodel.HSLFHyperlink;
-import org.apache.poi.hslf.usermodel.HSLFShape;
 import org.apache.poi.hslf.usermodel.HSLFSimpleShape;
 import org.apache.poi.hslf.usermodel.HSLFSlide;
 import org.apache.poi.hslf.usermodel.HSLFSlideShow;
@@ -32,49 +31,47 @@ import org.apache.poi.hslf.usermodel.HSL
 /**
  * Demonstrates how to read hyperlinks from  a presentation
  */
+@SuppressWarnings({"java:S106", "java:S4823"})
 public final class Hyperlinks {
 
+    private Hyperlinks() {}
+
     public static void main(String[] args) throws Exception {
         for (String arg : args) {
             try (FileInputStream is = new FileInputStream(arg);
-                HSLFSlideShow ppt = new HSLFSlideShow(is)) {
+                 HSLFSlideShow ppt = new HSLFSlideShow(is)) {
 
                 for (HSLFSlide slide : ppt.getSlides()) {
                     System.out.println("\nslide " + slide.getSlideNumber());
 
                     // read hyperlinks from the slide's text runs
                     System.out.println("- reading hyperlinks from the text 
runs");
-                    for (List<HSLFTextParagraph> paras : 
slide.getTextParagraphs()) {
-                        for (HSLFTextParagraph para : paras) {
-                            for (HSLFTextRun run : para) {
-                                HSLFHyperlink link = run.getHyperlink();
-                                if (link != null) {
-                                    System.out.println(toStr(link, 
run.getRawText()));
-                                }
-                            }
-                        }
-                    }
+                    slide.getTextParagraphs().stream().
+                        flatMap(List::stream).
+                        map(HSLFTextParagraph::getTextRuns).
+                        flatMap(List::stream).
+                        forEach(run -> out(run.getHyperlink(), run));
 
                     // in PowerPoint you can assign a hyperlink to a shape 
without text,
                     // for example to a Line object. The code below 
demonstrates how to
                     // read such hyperlinks
                     System.out.println("- reading hyperlinks from the slide's 
shapes");
-                    for (HSLFShape sh : slide.getShapes()) {
-                        if (sh instanceof HSLFSimpleShape) {
-                            HSLFHyperlink link = ((HSLFSimpleShape) 
sh).getHyperlink();
-                            if (link != null) {
-                                System.out.println(toStr(link, null));
-                            }
-                        }
-                    }
+                    slide.getShapes().stream().
+                        filter(sh -> sh instanceof HSLFSimpleShape).
+                        forEach(sh -> out(((HSLFSimpleShape) 
sh).getHyperlink(), null));
                 }
             }
         }
-   }
+    }
 
-    static String toStr(HSLFHyperlink link, String rawText) {
+    private static void out(HSLFHyperlink link, HSLFTextRun run) {
+        if (link == null) {
+            return;
+        }
+        String rawText = run == null ? null : run.getRawText();
         //in ppt end index is inclusive
         String formatStr = "title: %1$s, address: %2$s" + (rawText == null ? 
"" : ", start: %3$s, end: %4$s, substring: %5$s");
-        return String.format(Locale.ROOT, formatStr, link.getLabel(), 
link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText);
+        String line = String.format(Locale.ROOT, formatStr, link.getLabel(), 
link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText);
+        System.out.println(line);
     }
 }

Modified: 
poi/trunk/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java 
(original)
+++ poi/trunk/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java 
Sat Apr 18 21:31:18 2020
@@ -28,7 +28,10 @@ import org.apache.poi.hslf.usermodel.HSL
 /**
  * For each slide iterate over shapes and found associated sound data.
  */
-public class SoundFinder {
+@SuppressWarnings({"java:S106", "java:S4823"})
+public final class SoundFinder {
+    private SoundFinder() {}
+
     public static void main(String[] args) throws IOException {
         try (FileInputStream fis = new FileInputStream(args[0])) {
             try (HSLFSlideShow ppt = new HSLFSlideShow(fis)) {
@@ -54,7 +57,7 @@ public class SoundFinder {
      * @return 0-based reference to a sound in the sound collection
      * or -1 if the shape is not associated with a sound
      */
-    protected static int getSoundReference(HSLFShape shape){
+    private static int getSoundReference(HSLFShape shape){
         int soundRef = -1;
         //dive into the shape container and search for InteractiveInfoAtom
         InteractiveInfoAtom info = 
shape.getClientDataRecord(RecordTypes.InteractiveInfo.typeID);

Modified: 
poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java
 (original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java
 Sat Apr 18 21:31:18 2020
@@ -19,15 +19,13 @@
 
 package org.apache.poi.xssf.eventusermodel.examples;
 
-import java.io.FileInputStream;
 import java.io.InputStream;
 
-import org.apache.poi.crypt.examples.EncryptionUtils;
-import org.apache.poi.examples.util.TempFileUtils;
 import org.apache.poi.openxml4j.opc.OPCPackage;
 import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource;
 import org.apache.poi.xssf.eventusermodel.XSSFReader;
 import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator;
+import org.apache.poi.xssf.usermodel.examples.LoadPasswordProtectedXlsx;
 
 /**
  * An example that loads a password protected workbook and counts the sheets.
@@ -37,23 +35,16 @@ import org.apache.poi.xssf.eventusermode
  * <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files 
are encrypted.
  * </ul><p>
  */
-public class LoadPasswordProtectedXlsxStreaming {
+public final class LoadPasswordProtectedXlsxStreaming {
+
+    private LoadPasswordProtectedXlsxStreaming() {
+    }
 
     public static void main(String[] args) throws Exception {
-        if(args.length != 2) {
-            throw new IllegalArgumentException("Expected 2 params: filename 
and password");
-        }
-        TempFileUtils.checkTempFiles();
-        String filename = args[0];
-        String password = args[1];
-        try (FileInputStream fis = new FileInputStream(filename);
-             InputStream unencryptedStream = EncryptionUtils.decrypt(fis, 
password)) {
-            printSheetCount(unencryptedStream);
-        }
-        TempFileUtils.checkTempFiles();
+        LoadPasswordProtectedXlsx.execute(args, 
LoadPasswordProtectedXlsxStreaming::printSheetCount);
     }
 
-    public static void printSheetCount(final InputStream inputStream) throws 
Exception {
+    private static void printSheetCount(final InputStream inputStream) throws 
Exception {
         try (AesZipFileZipEntrySource source = 
AesZipFileZipEntrySource.createZipEntrySource(inputStream);
              OPCPackage pkg = OPCPackage.open(source)) {
             XSSFReader reader = new XSSFReader(pkg);

Modified: 
poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- 
poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java
 (original)
+++ 
poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java
 Sat Apr 18 21:31:18 2020
@@ -22,10 +22,12 @@ package org.apache.poi.xssf.usermodel.ex
 import java.io.FileInputStream;
 import java.io.InputStream;
 
-import org.apache.poi.crypt.examples.EncryptionUtils;
 import org.apache.poi.examples.util.TempFileUtils;
 import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.poifs.crypt.Decryptor;
+import org.apache.poi.poifs.crypt.EncryptionInfo;
 import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
 /**
@@ -35,9 +37,17 @@ import org.apache.poi.xssf.usermodel.XSS
  * <li><code>AesZipFileZipEntrySource</code> is used to ensure that temp files 
are encrypted.
  * </ul><p>
  */
-public class LoadPasswordProtectedXlsx {
-    
+public final class LoadPasswordProtectedXlsx {
+
+    public interface EncryptionHandler {
+        void handle(final InputStream inputStream) throws Exception;
+    }
+
     public static void main(String[] args) throws Exception {
+        execute(args, LoadPasswordProtectedXlsx::printSheetCount);
+    }
+
+    public static void execute(String[] args, EncryptionHandler handler) 
throws Exception {
         if(args.length != 2) {
             throw new IllegalArgumentException("Expected 2 params: filename 
and password");
         }
@@ -45,13 +55,21 @@ public class LoadPasswordProtectedXlsx {
         String filename = args[0];
         String password = args[1];
         try (FileInputStream fis = new FileInputStream(filename);
-             InputStream unencryptedStream = EncryptionUtils.decrypt(fis, 
password)) {
-            printSheetCount(unencryptedStream);
+             POIFSFileSystem fs = new POIFSFileSystem(fis)) {
+            EncryptionInfo info = new EncryptionInfo(fs);
+            Decryptor d = Decryptor.getInstance(info);
+            if (!d.verifyPassword(password)) {
+                throw new RuntimeException("incorrect password");
+            }
+            try (InputStream unencryptedStream = d.getDataStream(fs)) {
+                handler.handle(unencryptedStream);
+            }
         }
         TempFileUtils.checkTempFiles();
     }
-    
-    public static void printSheetCount(final InputStream inputStream) throws 
Exception {
+
+
+    private static void printSheetCount(final InputStream inputStream) throws 
Exception {
         try (AesZipFileZipEntrySource source = 
AesZipFileZipEntrySource.createZipEntrySource(inputStream);
              OPCPackage pkg = OPCPackage.open(source);
              XSSFWorkbook workbook = new XSSFWorkbook(pkg)) {

Modified: poi/trunk/src/java/org/apache/poi/hpsf/ClipboardData.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hpsf/ClipboardData.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hpsf/ClipboardData.java (original)
+++ poi/trunk/src/java/org/apache/poi/hpsf/ClipboardData.java Sat Apr 18 
21:31:18 2020
@@ -18,8 +18,8 @@ package org.apache.poi.hpsf;
 
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.Internal;
+import org.apache.poi.util.LittleEndian;
 import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;
 import org.apache.poi.util.LittleEndianConsts;
 import org.apache.poi.util.POILogFactory;
 import org.apache.poi.util.POILogger;
@@ -39,7 +39,7 @@ public class ClipboardData {
         int size = lei.readInt();
 
         if ( size < 4 ) {
-            String msg = 
+            String msg =
                 "ClipboardData at offset "+offset+" size less than 4 bytes "+
                 "(doesn't even have format field!). Setting to format == 0 and 
hope for the best";
             LOG.log( POILogger.WARN, msg);
@@ -59,15 +59,10 @@ public class ClipboardData {
 
     public byte[] toByteArray() {
         byte[] result = new byte[LittleEndianConsts.INT_SIZE*2+_value.length];
-        LittleEndianByteArrayOutputStream bos = new 
LittleEndianByteArrayOutputStream(result,0);
-        try {
-            bos.writeInt(LittleEndianConsts.INT_SIZE + _value.length);
-            bos.writeInt(_format);
-            bos.write(_value);
-            return result;
-        } finally {
-            IOUtils.closeQuietly(bos);
-        }
+        LittleEndian.putInt(result, 0, LittleEndianConsts.INT_SIZE + 
_value.length);
+        LittleEndian.putInt(result, 4, _format);
+        System.arraycopy(_value, 0, result, 8, _value.length);
+        return result;
     }
 
     public void setValue( byte[] value ) {

Modified: poi/trunk/src/java/org/apache/poi/hpsf/PropertySetFactory.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hpsf/PropertySetFactory.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hpsf/PropertySetFactory.java (original)
+++ poi/trunk/src/java/org/apache/poi/hpsf/PropertySetFactory.java Sat Apr 18 
21:31:18 2020
@@ -23,7 +23,7 @@ import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
 
 import org.apache.poi.poifs.filesystem.DirectoryEntry;
-import org.apache.poi.poifs.filesystem.DocumentEntry;
+import org.apache.poi.poifs.filesystem.DirectoryNode;
 import org.apache.poi.poifs.filesystem.DocumentInputStream;
 import org.apache.poi.util.LittleEndianInputStream;
 
@@ -36,7 +36,7 @@ public class PropertySetFactory {
      * Creates the most specific {@link PropertySet} from an entry
      *  in the specified POIFS Directory. This is preferrably a {@link
      * DocumentSummaryInformation} or a {@link SummaryInformation}. If
-     * the specified entry does not contain a property set stream, an 
+     * the specified entry does not contain a property set stream, an
      * exception is thrown. If no entry is found with the given name,
      * an exception is thrown.
      *
@@ -52,19 +52,10 @@ public class PropertySetFactory {
      */
     public static PropertySet create(final DirectoryEntry dir, final String 
name)
     throws FileNotFoundException, NoPropertySetStreamException, IOException, 
UnsupportedEncodingException {
-        InputStream inp = null;
-        try {
-            DocumentEntry entry = (DocumentEntry)dir.getEntry(name);
-            inp = new DocumentInputStream(entry);
-            try {
-                return create(inp);
-            } catch (MarkUnsupportedException e) {
-                return null;
-            }
-        } finally {
-            if (inp != null) {
-                inp.close();
-            }
+        try (DocumentInputStream inp = 
((DirectoryNode)dir).createDocumentInputStream(name)) {
+            return create(inp);
+        } catch (MarkUnsupportedException e) {
+            return null;
         }
     }
 
@@ -96,18 +87,18 @@ public class PropertySetFactory {
         byte[] clsIdBuf = new byte[ClassID.LENGTH];
         leis.readFully(clsIdBuf);
         int sectionCount = (int)leis.readUInt();
-        
+
         if (byteOrder != PropertySet.BYTE_ORDER_ASSERTION ||
             format != PropertySet.FORMAT_ASSERTION ||
             sectionCount < 0) {
             throw new NoPropertySetStreamException();
         }
-        
+
         if (sectionCount > 0) {
             leis.readFully(clsIdBuf);
         }
         stream.reset();
-        
+
         ClassID clsId = new ClassID(clsIdBuf, 0);
         if (sectionCount > 0 && PropertySet.matchesSummary(clsId, 
SummaryInformation.FORMAT_ID)) {
             return new SummaryInformation(stream);

Modified: poi/trunk/src/java/org/apache/poi/hssf/dev/BiffViewer.java
URL: 
http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hssf/dev/BiffViewer.java?rev=1876704&r1=1876703&r2=1876704&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hssf/dev/BiffViewer.java (original)
+++ poi/trunk/src/java/org/apache/poi/hssf/dev/BiffViewer.java Sat Apr 18 
21:31:18 2020
@@ -19,6 +19,7 @@ package org.apache.poi.hssf.dev;
 
 import java.io.DataInputStream;
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -393,21 +394,10 @@ public final class BiffViewer {
                // args = new String[] { "--out", "", };
                CommandArgs cmdArgs = CommandArgs.parse(args);
 
-               PrintWriter pw;
-               if (cmdArgs.shouldOutputToFile()) {
-                       OutputStream os = new 
FileOutputStream(cmdArgs.getFile().getAbsolutePath() + ".out");
-                       pw = new PrintWriter(new OutputStreamWriter(os, 
StringUtil.UTF8));
-               } else {
-                   // Use the system default encoding when sending to System 
Out
-                       pw = new PrintWriter(new OutputStreamWriter(System.out, 
Charset.defaultCharset()));
-               }
-
-               POIFSFileSystem fs = null;
-               InputStream is = null;
-        try {
-            fs = new POIFSFileSystem(cmdArgs.getFile(), true);
-            is = getPOIFSInputStream(fs);
-
+        try (POIFSFileSystem fs = new POIFSFileSystem(cmdArgs.getFile(), true);
+             InputStream is = getPOIFSInputStream(fs);
+             PrintWriter pw = getOutputStream(cmdArgs.shouldOutputToFile() ? 
cmdArgs.getFile().getAbsolutePath() : null)
+         ) {
             if (cmdArgs.shouldOutputRawHexOnly()) {
                 byte[] data = IOUtils.toByteArray(is);
                 HexDump.dump(data, 0, System.out, 0);
@@ -417,13 +407,21 @@ public final class BiffViewer {
                 runBiffViewer(pw, is, dumpInterpretedRecords, dumpHex, 
dumpInterpretedRecords,
                         cmdArgs.suppressHeader());
             }
-        } finally {
-            IOUtils.closeQuietly(is);
-            IOUtils.closeQuietly(fs);
-            IOUtils.closeQuietly(pw);
         }
        }
 
+       static PrintWriter getOutputStream(String outputPath) throws 
FileNotFoundException {
+        // Use the system default encoding when sending to System Out
+        OutputStream os = System.out;
+        Charset cs = Charset.defaultCharset();
+        if (outputPath != null) {
+            cs = StringUtil.UTF8;
+            os = new FileOutputStream(outputPath + ".out");
+        }
+        return new PrintWriter(new OutputStreamWriter(os, cs));
+    }
+
+
        static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws 
IOException {
                String workbookName = 
HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot());
                return fs.createDocumentInputStream(workbookName);



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to