poi-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kiwiwi...@apache.org
Subject svn commit: r1839201 [3/5] - in /poi: site/src/documentation/content/xdocs/ trunk/src/examples/src/org/apache/poi/hpsf/examples/ trunk/src/examples/src/org/apache/poi/poifs/poibrowser/ trunk/src/java/org/apache/poi/ trunk/src/java/org/apache/poi/extrac...
Date Sun, 26 Aug 2018 11:55:02 GMT
Modified: poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java (original)
+++ poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java Sun Aug 26 11:55:00 2018
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertNot
 import static org.junit.Assert.assertTrue;
 
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 
@@ -36,7 +35,6 @@ import org.apache.poi.hwpf.OldWordFileFo
 import org.apache.poi.poifs.filesystem.DirectoryNode;
 import org.apache.poi.poifs.filesystem.Entry;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
-import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.util.StringUtil;
 import org.junit.Test;
@@ -48,7 +46,7 @@ public final class TestWordExtractor {
 
     private static POIDataSamples docTests = POIDataSamples.getDocumentInstance();
     
-    public static void assertEqualsTrim( String expected, String actual )
+    private static void assertEqualsTrim( String expected, String actual )
     {
         String newExpected = expected.replaceAll( "\r\n", "\n" )
                 .replaceAll( "\r", "\n" ).trim();
@@ -188,7 +186,8 @@ public final class TestWordExtractor {
 		HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc");
 		WordExtractor extractor1 = new WordExtractor(doc1);
 
-		assertEquals("First header column!\tMid header Right header!\n", extractor1.getHeaderText());
+        //noinspection deprecation
+        assertEquals("First header column!\tMid header Right header!\n", extractor1.getHeaderText());
 		assertContains(extractor1.getText(), "First header column!");
 		extractor1.close();
 		doc1.close();
@@ -197,7 +196,8 @@ public final class TestWordExtractor {
 		HWPFDocument doc2 = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc");
 		WordExtractor extractor2 = new WordExtractor(doc2);
 
-		assertEquals("This is a simple header, with a \u20ac euro symbol in it.\n\n", extractor2.getHeaderText());
+        //noinspection deprecation
+        assertEquals("This is a simple header, with a \u20ac euro symbol in it.\n\n", extractor2.getHeaderText());
 		assertContains(extractor2.getText(), "This is a simple header");
 		extractor2.close();
 		doc2.close();
@@ -209,7 +209,8 @@ public final class TestWordExtractor {
 		HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc");
 		WordExtractor extractor1 = new WordExtractor(doc1);
 
-		assertEquals("Footer Left\tFooter Middle Footer Right\n", extractor1.getFooterText());
+        //noinspection deprecation
+        assertEquals("Footer Left\tFooter Middle Footer Right\n", extractor1.getFooterText());
 		assertContains(extractor1.getText(), "Footer Left");
         extractor1.close();
         doc1.close();
@@ -218,7 +219,8 @@ public final class TestWordExtractor {
 		HWPFDocument doc2 = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc");
 		WordExtractor extractor2 = new WordExtractor(doc2);
 
-		assertEquals("The footer, with Moli\u00e8re, has Unicode in it.\n", extractor2.getFooterText());
+        //noinspection deprecation
+        assertEquals("The footer, with Moli\u00e8re, has Unicode in it.\n", extractor2.getFooterText());
 		assertContains(extractor2.getText(), "The footer, with");
         extractor2.close();
         doc2.close();
@@ -279,6 +281,7 @@ public final class TestWordExtractor {
         assertContains(text, "Paragraph 3. Has some RED text and some BLUE BOLD text in it");
         assertContains(text, "Last (4th) paragraph");
         
+        @SuppressWarnings("deprecation")
         String[] tp = w6e.getParagraphText();
         assertEquals(7, tp.length);
         assertEquals("The quick brown fox jumps over the lazy dog\r\n", tp[0]);
@@ -299,17 +302,17 @@ public final class TestWordExtractor {
     
     @Test
     public void testWord6() throws Exception {
-        InputStream is = docTests.openResourceAsStream("Word6.doc");
-        Word6Extractor w6e = new Word6Extractor(is);
-        is.close();
-        String text = w6e.getText();
-        
-        assertContains(text, "The quick brown fox jumps over the lazy dog");
-        
-        String[] tp = w6e.getParagraphText();
-        assertEquals(1, tp.length);
-        assertEquals("The quick brown fox jumps over the lazy dog\r\n", tp[0]);
-        w6e.close();
+        try (InputStream is = docTests.openResourceAsStream("Word6.doc");
+            Word6Extractor w6e = new Word6Extractor(is)) {
+            String text = w6e.getText();
+
+            assertContains(text, "The quick brown fox jumps over the lazy dog");
+
+            @SuppressWarnings("deprecation")
+            String[] tp = w6e.getParagraphText();
+            assertEquals(1, tp.length);
+            assertEquals("The quick brown fox jumps over the lazy dog\r\n", tp[0]);
+        }
     }
 
     @Test
@@ -341,30 +344,23 @@ public final class TestWordExtractor {
     public void testDifferentPOIFS() throws Exception {
        // Open the two filesystems
        File file = docTests.getFile("test2.doc");
-       InputStream is = new FileInputStream(file);
-       OPOIFSFileSystem opoifs = new OPOIFSFileSystem(is);
-       is.close();
-       NPOIFSFileSystem npoifs = new NPOIFSFileSystem(file);
-       
-       DirectoryNode[] files = { opoifs.getRoot(), npoifs.getRoot() };
-       
-       // Open directly 
-       for(DirectoryNode dir : files) {
-          @SuppressWarnings("resource")
-          WordExtractor extractor = new WordExtractor(dir);
-          assertEqualsTrim(p_text1_block, extractor.getText());
-          // extractor.close();
-       }
+       try (NPOIFSFileSystem npoifs = new NPOIFSFileSystem(file, true)) {
+
+           DirectoryNode dir = npoifs.getRoot();
+
+           // Open directly
+           @SuppressWarnings("resource")
+           WordExtractor extractor1 = new WordExtractor(dir);
+           assertEqualsTrim(p_text1_block, extractor1.getText());
+           // extractor.close();
+
+           // Open via a HWPFDocument
+           try (HWPFDocument doc = new HWPFDocument(dir);
+                WordExtractor extractor2 = new WordExtractor(doc)) {
+               assertEqualsTrim(p_text1_block, extractor2.getText());
+           }
 
-       // Open via a HWPFDocument
-       for(DirectoryNode dir : files) {
-          HWPFDocument doc = new HWPFDocument(dir);
-          WordExtractor extractor = new WordExtractor(doc);
-          assertEqualsTrim(p_text1_block, extractor.getText());
-          extractor.close();
        }
-       
-       npoifs.close();
     }
 
     /**
@@ -381,11 +377,8 @@ public final class TestWordExtractor {
 
         for (Entry entry : fs.getRoot()) {
             if ("WordDocument".equals(entry.getName())) {
-                WordExtractor ex = new WordExtractor(fs);
-                try {
+                try (WordExtractor ex = new WordExtractor(fs)) {
                     text = ex.getText();
-                } finally {
-                    ex.close();
                 }
             }
         }
@@ -396,35 +389,22 @@ public final class TestWordExtractor {
 
     @Test
     public void testExtractorFromWord6Extractor() throws Exception {
-        InputStream is = POIDataSamples.getHPSFInstance().openResourceAsStream("TestMickey.doc");
-        POIFSFileSystem fs = new POIFSFileSystem(is);
-        is.close();
-        Word6Extractor wExt = new Word6Extractor(fs);
-        try {
-            POITextExtractor ext = wExt.getMetadataTextExtractor();
-            try {
-                // Now overall
-                String text = ext.getText();
-                assertContains(text, "TEMPLATE = Normal");
-                assertContains(text, "SUBJECT = sample subject");
-                assertContains(text, "MANAGER = sample manager");
-                assertContains(text, "COMPANY = sample company");
-            } finally {
-                ext.close();
-            }
-        } finally {
-            wExt.close();
-            fs.close();
+        try (InputStream is = POIDataSamples.getHPSFInstance().openResourceAsStream("TestMickey.doc");
+             POIFSFileSystem fs = new POIFSFileSystem(is);
+             Word6Extractor wExt = new Word6Extractor(fs);
+             POITextExtractor ext = wExt.getMetadataTextExtractor()) {
+            // Now overall
+            String text = ext.getText();
+            assertContains(text, "TEMPLATE = Normal");
+            assertContains(text, "SUBJECT = sample subject");
+            assertContains(text, "MANAGER = sample manager");
+            assertContains(text, "COMPANY = sample company");
         }
     }
     
     private WordExtractor openExtractor(String fileName) throws IOException {
-        InputStream is = docTests.openResourceAsStream(fileName);
-        try {
+        try (InputStream is = docTests.openResourceAsStream(fileName)) {
             return new WordExtractor(is);
-        } finally {
-            is.close();
         }
-        
     }
 }

Modified: poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java (original)
+++ poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java Sun Aug 26 11:55:00 2018
@@ -32,7 +32,6 @@ import org.apache.poi.hwpf.HWPFDocument;
 import org.apache.poi.hwpf.HWPFTestCase;
 import org.apache.poi.hwpf.HWPFTestDataSamples;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
-import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.TempFile;
@@ -99,16 +98,9 @@ public final class TestHWPFWrite extends
     public void testInPlaceWrite() throws Exception {
         // Setup as a copy of a known-good file
         final File file = TempFile.createTempFile("TestDocument", ".doc");
-        InputStream inputStream = SAMPLES.openResourceAsStream("SampleDoc.doc");
-        try {
-            FileOutputStream outputStream = new FileOutputStream(file);
-            try {
-                IOUtils.copy(inputStream, outputStream);
-            } finally {
-                outputStream.close();
-            }
-        } finally {
-            inputStream.close();
+        try (InputStream inputStream = SAMPLES.openResourceAsStream("SampleDoc.doc");
+             FileOutputStream outputStream = new FileOutputStream(file)) {
+            IOUtils.copy(inputStream, outputStream);
         }
 
         // Open from the temp file in read-write mode
@@ -136,29 +128,14 @@ public final class TestHWPFWrite extends
     @Test(expected=IllegalStateException.class)
     public void testInvalidInPlaceWriteInputStream() throws IOException {
         // Can't work for InputStream opened files
-        InputStream is = SAMPLES.openResourceAsStream("SampleDoc.doc");
-        HWPFDocument doc = new HWPFDocument(is);
-        is.close();
-        try {
+
+        try (InputStream is = SAMPLES.openResourceAsStream("SampleDoc.doc");
+             HWPFDocument doc = new HWPFDocument(is)) {
             doc.write();
-        } finally {
-            doc.close();
         }
     }
     
     @Test(expected=IllegalStateException.class)
-    public void testInvalidInPlaceWriteOPOIFS() throws Exception {
-        // Can't work for OPOIFS
-        OPOIFSFileSystem ofs = new OPOIFSFileSystem(SAMPLES.openResourceAsStream("SampleDoc.doc"));
-        HWPFDocument doc = new HWPFDocument(ofs.getRoot());
-        try {
-            doc.write();
-        } finally {
-            doc.close();
-        }
-    }
-
-    @Test(expected=IllegalStateException.class)
     public void testInvalidInPlaceWriteNPOIFS() throws Exception {
         // Can't work for Read-Only files
         NPOIFSFileSystem fs = new NPOIFSFileSystem(SAMPLES.getFile("SampleDoc.doc"), true);

Modified: poi/trunk/src/testcases/org/apache/poi/TestPOIDocumentMain.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/TestPOIDocumentMain.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/TestPOIDocumentMain.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/TestPOIDocumentMain.java Sun Aug 26 11:55:00 2018
@@ -31,7 +31,7 @@ import org.apache.poi.hpsf.SummaryInform
 import org.apache.poi.hssf.HSSFTestDataSamples;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
-import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -78,7 +78,7 @@ public final class TestPOIDocumentMain {
         assertNotNull(doc2.getSummaryInformation());
 
         assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
-        assertEquals(null, doc2.getSummaryInformation().getKeywords());
+        assertNull(doc2.getSummaryInformation().getKeywords());
         assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
     }
 
@@ -110,7 +110,7 @@ public final class TestPOIDocumentMain {
 
         // Create a new version
         ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-        OPOIFSFileSystem inFS = new OPOIFSFileSystem(bais);
+        POIFSFileSystem inFS = new POIFSFileSystem(bais);
 
         // Check they're still there
         POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS);

Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java Sun Aug 26 11:55:00 2018
@@ -21,6 +21,7 @@ import static org.hamcrest.core.IsEqual.
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -28,7 +29,6 @@ import static org.junit.Assert.fail;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -51,7 +51,6 @@ import org.apache.poi.hpsf.NoPropertySet
 import org.apache.poi.hpsf.Property;
 import org.apache.poi.hpsf.PropertySet;
 import org.apache.poi.hpsf.PropertySetFactory;
-import org.apache.poi.hpsf.ReadingNotSupportedException;
 import org.apache.poi.hpsf.Section;
 import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.hpsf.UnsupportedVariantTypeException;
@@ -94,8 +93,6 @@ public class TestWrite {
         "LANG environment variable to a proper value, e.g. " +
         "\"de_DE\".";
 
-    POIFile[] poiFiles;
-
     @BeforeClass
     public static void setUp() {
         VariantSupport.setLogUnsupportedTypes(false);
@@ -113,24 +110,20 @@ public class TestWrite {
 
         /* Create a mutable property set with a section that does not have the
          * formatID set: */
-        final OutputStream out = new FileOutputStream(filename);
-        final POIFSFileSystem poiFs = new POIFSFileSystem();
         final PropertySet ps = new PropertySet();
         ps.clearSections();
         ps.addSection(new Section());
 
         /* Write it to a POIFS and the latter to disk: */
-        try {
+        try (OutputStream out = new FileOutputStream(filename);
+             POIFSFileSystem poiFs = new POIFSFileSystem()) {
             final ByteArrayOutputStream psStream = new ByteArrayOutputStream();
             ps.write(psStream);
             psStream.close();
             final byte[] streamData = psStream.toByteArray();
             poiFs.createDocument(new ByteArrayInputStream(streamData),
-                                 SummaryInformation.DEFAULT_STREAM_NAME);
+                    SummaryInformation.DEFAULT_STREAM_NAME);
             poiFs.writeFilesystem(out);
-        } finally {
-            poiFs.close();
-            out.close();
         }
     }
 
@@ -170,12 +163,7 @@ public class TestWrite {
         final POIFSReader r = new POIFSReader();
         r.registerListener(new MyPOIFSReaderListener(),
                            SummaryInformation.DEFAULT_STREAM_NAME);
-        FileInputStream stream = new FileInputStream(filename);
-        try {
-            r.read(stream);
-        } finally {
-            stream.close();
-        }
+        r.read(filename);
     }
 
 
@@ -221,24 +209,16 @@ public class TestWrite {
         /* Read the POIFS: */
         final PropertySet[] psa = new PropertySet[1];
         final POIFSReader r = new POIFSReader();
-        r.registerListener(new POIFSReaderListener() {
-            @Override
-            public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
-                try {
-                    psa[0] = PropertySetFactory.create(event.getStream());
-                } catch (Exception ex) {
-                    fail(ex.getMessage());
-                }
-            }},
-            SummaryInformation.DEFAULT_STREAM_NAME
-        );
-        
-        InputStream stream = new FileInputStream(filename);
-        try {
-            r.read(stream);
-        } finally {
-            stream.close();
-        }
+        final POIFSReaderListener listener = event -> {
+            try {
+                psa[0] = PropertySetFactory.create(event.getStream());
+            } catch (Exception ex) {
+                fail(ex.getMessage());
+            }
+        };
+        r.registerListener(listener, SummaryInformation.DEFAULT_STREAM_NAME);
+
+        r.read(filename);
         assertNotNull(psa[0]);
         assertTrue(psa[0].isSummaryInformation());
 
@@ -295,23 +275,17 @@ public class TestWrite {
         /* Read the POIFS: */
         final PropertySet[] psa = new PropertySet[1];
         final POIFSReader r = new POIFSReader();
-        r.registerListener(new POIFSReaderListener() {
-                @Override
-                public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
-                    try {
-                        psa[0] = PropertySetFactory.create(event.getStream());
-                    } catch (Exception ex) {
-                        throw new RuntimeException(ex);
-                    }
-                }
-            },
-            STREAM_NAME);
-        FileInputStream stream = new FileInputStream(filename);
-        try {
-            r.read(stream);
-        } finally {
-            stream.close();
-        }
+        final POIFSReaderListener listener = (event) -> {
+            try {
+                psa[0] = PropertySetFactory.create(event.getStream());
+            } catch (Exception ex) {
+                fail(ex.getMessage());
+            }
+        };
+
+        r.registerListener(listener,STREAM_NAME);
+        r.read(filename);
+
         assertNotNull(psa[0]);
         Section s = (psa[0].getSections().get(0));
         assertEquals(s.getFormatID(), formatID);
@@ -338,12 +312,8 @@ public class TestWrite {
 
 
     /**
-     * <p>Writes and reads back various variant types and checks whether the
-     * stuff that has been read back equals the stuff that was written.</p>
-     * @throws IOException 
-     * @throws UnsupportedEncodingException 
-     * @throws UnsupportedVariantTypeException 
-     * @throws ReadingNotSupportedException 
+     * Writes and reads back various variant types and checks whether the
+     * stuff that has been read back equals the stuff that was written.
      */
     @Test
     public void variantTypes() throws Exception {
@@ -379,9 +349,8 @@ public class TestWrite {
      * was written.
      */
     @Test
-    public void codepages() throws ReadingNotSupportedException, UnsupportedVariantTypeException, IOException
+    public void codepages() throws UnsupportedVariantTypeException, IOException
     {
-        Throwable thr = null;
         final int[] validCodepages = {CODEPAGE_DEFAULT, CodePageUtil.CP_UTF8, CodePageUtil.CP_UNICODE, CodePageUtil.CP_WINDOWS_1252};
         for (final int cp : validCodepages) {
             if (cp == -1 && !hasProperDefaultCharset())
@@ -400,9 +369,8 @@ public class TestWrite {
 
         final int[] invalidCodepages = new int[] {0, 1, 2, 4711, 815};
         for (int cp : invalidCodepages) {
-            final long type = (cp == CodePageUtil.CP_UNICODE) ? Variant.VT_LPWSTR : Variant.VT_LPSTR;
             try {
-                checkString(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp);
+                checkString(Variant.VT_LPSTR, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp);
                 fail("UnsupportedEncodingException for codepage " + cp + " expected.");
             } catch (UnsupportedEncodingException ex) {
                 /* This is the expected behaviour. */
@@ -441,7 +409,7 @@ public class TestWrite {
     }
     
     private void checkString(final long variantType, final String value, final int codepage)
-    throws UnsupportedVariantTypeException, IOException, ReadingNotSupportedException, UnsupportedEncodingException {
+    throws UnsupportedVariantTypeException, IOException {
         for (int i=0; i<value.length(); i++) {
             check(variantType, value.substring(0, i), codepage);
         }
@@ -457,7 +425,7 @@ public class TestWrite {
      * @throws IOException if an I/O exception occurs.
      */
     private void check(final long variantType, final Object value, final int codepage)
-    throws UnsupportedVariantTypeException, IOException, ReadingNotSupportedException, UnsupportedEncodingException
+    throws UnsupportedVariantTypeException, IOException
     {
         final ByteArrayOutputStream out = new ByteArrayOutputStream();
         VariantSupport.write(out, variantType, value, codepage);
@@ -474,8 +442,6 @@ public class TestWrite {
 
     /**
      * <p>Tests writing and reading back a proper dictionary.</p>
-     * @throws IOException 
-     * @throws HPSFException 
      */
     @Test
     public void dictionary() throws IOException, HPSFException {
@@ -488,9 +454,9 @@ public class TestWrite {
         final PropertySet ps1 = new PropertySet();
         final Section s = ps1.getSections().get(0);
         final Map<Long,String> m = new HashMap<>(3, 1.0f);
-        m.put(Long.valueOf(1), "String 1");
-        m.put(Long.valueOf(2), "String 2");
-        m.put(Long.valueOf(3), "String 3");
+        m.put(1L, "String 1");
+        m.put(2L, "String 2");
+        m.put(3L, "String 3");
         s.setDictionary(m);
         s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]);
         int codepage = CodePageUtil.CP_UNICODE;
@@ -522,12 +488,12 @@ public class TestWrite {
      */
     @Test
     public void inPlaceNPOIFSWrite() throws Exception {
-        NPOIFSFileSystem fs = null;
-        DirectoryEntry root = null;
-        DocumentNode sinfDoc = null;
-        DocumentNode dinfDoc = null;
-        SummaryInformation sinf = null;
-        DocumentSummaryInformation dinf = null;
+        NPOIFSFileSystem fs;
+        DirectoryEntry root;
+        DocumentNode sinfDoc;
+        DocumentNode dinfDoc;
+        SummaryInformation sinf;
+        DocumentSummaryInformation dinf;
         
         // We need to work on a File for in-place changes, so create a temp one
         final File copy = TempFile.createTempFile("Test-HPSF", "ole2");
@@ -567,10 +533,13 @@ public class TestWrite {
         assertEquals("\u7b2c1\u7ae0", sinf.getTitle());
         
         assertEquals("", dinf.getCompany());
-        assertEquals(null, dinf.getManager());
+        assertNull(dinf.getManager());
         
         
         // Do an in-place replace via an InputStream
+        assertNotNull(sinfDoc);
+        assertNotNull(dinfDoc);
+
         new NPOIFSDocument(sinfDoc).replaceContents(sinf.toInputStream());
         new NPOIFSDocument(dinfDoc).replaceContents(dinf.toInputStream());
         
@@ -661,7 +630,7 @@ public class TestWrite {
         assertEquals("\u7b2c1\u7ae0", sinf.getTitle());
         
         assertEquals("", dinf.getCompany());
-        assertEquals(null, dinf.getManager());
+        assertNull(dinf.getManager());
         
 
         // Now alter a few of them
@@ -730,43 +699,37 @@ public class TestWrite {
         
         // Tidy up
         fs.close();
+        //noinspection ResultOfMethodCallIgnored
         copy.delete();
     }
 
 
     /**
-     * <p>Tests writing and reading back a proper dictionary with an invalid
-     * codepage. (HPSF writes Unicode dictionaries only.)</p>
-     * @throws IOException 
-     * @throws HPSFException 
+     * Tests writing and reading back a proper dictionary with an invalid
+     * codepage. (HPSF writes Unicode dictionaries only.)
      */
-    @Test(expected=IllegalPropertySetDataException.class)
+    @Test(expected=UnsupportedEncodingException.class)
     public void dictionaryWithInvalidCodepage() throws IOException, HPSFException {
         final File copy = TempFile.createTempFile("Test-HPSF", "ole2");
         copy.deleteOnExit();
         
         /* Write: */
-        final OutputStream out = new FileOutputStream(copy);
-        
-        final POIFSFileSystem poiFs = new POIFSFileSystem();
+
         final PropertySet ps1 = new PropertySet();
         final Section s = ps1.getSections().get(0);
         final Map<Long,String> m = new HashMap<>(3, 1.0f);
-        m.put(Long.valueOf(1), "String 1");
-        m.put(Long.valueOf(2), "String 2");
-        m.put(Long.valueOf(3), "String 3");
+        m.put(1L, "String 1");
+        m.put(2L, "String 2");
+        m.put(3L, "String 3");
 
-        try {
+        try (OutputStream out = new FileOutputStream(copy);
+             POIFSFileSystem poiFs = new POIFSFileSystem()) {
             s.setDictionary(m);
             s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]);
             int codepage = 12345;
-            s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
-                          Integer.valueOf(codepage));
+            s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage);
             poiFs.createDocument(ps1.toInputStream(), "Test");
             poiFs.writeFilesystem(out);
-        } finally {
-            poiFs.close();
-            out.close();
         }
     }
 

Modified: poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/hpsf/basic/Util.java Sun Aug 26 11:55:00 2018
@@ -18,8 +18,9 @@
 
 package org.apache.poi.hpsf.basic;
 
+import static org.junit.Assert.fail;
+
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -28,7 +29,6 @@ import java.util.List;
 
 import org.apache.poi.hpsf.PropertySet;
 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.IOUtils;
 
@@ -39,6 +39,9 @@ import org.apache.poi.util.IOUtils;
  */
 final class Util {
 
+    private Util() {
+    }
+
     /**
      * <p>Reads a set of files from a POI filesystem and returns them
      * as an array of {@link POIFile} instances. This method loads all
@@ -58,24 +61,20 @@ final class Util {
      * 
      * @exception IOException if an I/O exception occurs
      */
-    public static List<POIFile> readPOIFiles(final File poiFs, final String... poiFiles)
-    throws FileNotFoundException, IOException {
+    static List<POIFile> readPOIFiles(final File poiFs, final String... poiFiles) throws IOException {
         final List<POIFile> files = new ArrayList<>();
         POIFSReader r = new POIFSReader();
-        POIFSReaderListener pfl = new POIFSReaderListener() {
-            @Override
-            public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
-                try {
-                    final POIFile f = new POIFile();
-                    f.setName(event.getName());
-                    f.setPath(event.getPath());
-                    final InputStream in = event.getStream();
-                    f.setBytes(IOUtils.toByteArray(in));
-                    in.close();
-                    files.add(f);
-                } catch (IOException ex) {
-                    throw new RuntimeException(ex);
-                }
+        POIFSReaderListener pfl = event -> {
+            try {
+                final POIFile f = new POIFile();
+                f.setName(event.getName());
+                f.setPath(event.getPath());
+                final InputStream in = event.getStream();
+                f.setBytes(IOUtils.toByteArray(in));
+                in.close();
+                files.add(f);
+            } catch (IOException ex) {
+                fail(ex.getMessage());
             }
         };
         if (poiFiles.length == 0) {
@@ -88,12 +87,8 @@ final class Util {
         }
 
         /* Read the POI filesystem. */
-        FileInputStream stream = new FileInputStream(poiFs);
-        try {
-            r.read(stream);
-        } finally {
-            stream.close();
-        }
+        r.read(poiFs);
+
         return files;
     }
 
@@ -110,29 +105,23 @@ final class Util {
      * @return The property sets. The elements are ordered in the same way
      * as the files in the POI filesystem.
      * 
-     * @exception FileNotFoundException if the file containing the POI 
-     * filesystem does not exist
-     * 
      * @exception IOException if an I/O exception occurs
      */
-    public static List<POIFile> readPropertySets(final File poiFs) throws IOException {
+    static List<POIFile> readPropertySets(final File poiFs) throws IOException {
         final List<POIFile> files = new ArrayList<>(7);
         final POIFSReader r = new POIFSReader();
-        POIFSReaderListener pfl = new POIFSReaderListener() {
-            @Override
-            public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
-                try {
-                    final POIFile f = new POIFile();
-                    f.setName(event.getName());
-                    f.setPath(event.getPath());
-                    final InputStream in = event.getStream();
-                    if (PropertySet.isPropertySetStream(in)) {
-                        f.setBytes(IOUtils.toByteArray(in));
-                        files.add(f);
-                    }
-                } catch (Exception ex) {
-                    throw new RuntimeException(ex);
+        final POIFSReaderListener pfl = event -> {
+            try {
+                final POIFile f = new POIFile();
+                f.setName(event.getName());
+                f.setPath(event.getPath());
+                final InputStream in = event.getStream();
+                if (PropertySet.isPropertySetStream(in)) {
+                    f.setBytes(IOUtils.toByteArray(in));
+                    files.add(f);
                 }
+            } catch (Exception ex) {
+                fail(ex.getMessage());
             }
         };
 
@@ -140,12 +129,7 @@ final class Util {
         r.registerListener(pfl);
 
         /* Read the POI filesystem. */
-        InputStream is = new FileInputStream(poiFs);
-        try {
-            r.read(is);
-        } finally {
-            is.close();
-        }
+        r.read(poiFs);
 
         return files;
     }

Modified: poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java Sun Aug 26 11:55:00 2018
@@ -68,7 +68,6 @@ import org.apache.poi.hssf.record.crypto
 import org.apache.poi.poifs.filesystem.DocumentEntry;
 import org.apache.poi.poifs.filesystem.DocumentInputStream;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
-import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.ss.formula.ptg.Area3DPtg;
 import org.apache.poi.ss.formula.ptg.DeletedArea3DPtg;
@@ -89,7 +88,6 @@ import org.apache.poi.ss.usermodel.Sheet
 import org.apache.poi.ss.usermodel.Workbook;
 import org.apache.poi.ss.util.CellRangeAddress;
 import org.apache.poi.util.LocaleUtil;
-import org.junit.After;
 import org.junit.Assume;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -1022,7 +1020,7 @@ public final class TestBugs extends Base
 
         assertEquals(4, wb.getNumberOfFontsAsInt());
 
-        HSSFFont f1 = wb.getFontAt((short) 0);
+        HSSFFont f1 = wb.getFontAt(0);
         assertFalse(f1.getBold());
 
         // Check that asking for the same font
@@ -1617,7 +1615,7 @@ public final class TestBugs extends Base
     @Test
     public void bug46904() throws Exception {
         try {
-            OPOIFSFileSystem fs = new OPOIFSFileSystem(
+            POIFSFileSystem fs = new POIFSFileSystem(
                     HSSFITestDataProvider.instance.openWorkbookStream("46904.xls"));
             new HSSFWorkbook(fs.getRoot(), false).close();
             fail("Should catch exception here");
@@ -2505,7 +2503,7 @@ public final class TestBugs extends Base
 
     @Test
     public void bug53432() throws IOException {
-        Workbook wb1 = new HSSFWorkbook(); //or new HSSFWorkbook();
+        HSSFWorkbook wb1 = new HSSFWorkbook(); //or new HSSFWorkbook();
         wb1.addPicture(new byte[]{123, 22}, Workbook.PICTURE_TYPE_JPEG);
         assertEquals(wb1.getAllPictures().size(), 1);
         wb1.close();
@@ -2513,13 +2511,13 @@ public final class TestBugs extends Base
         wb1.close();
         wb1 = new HSSFWorkbook();
 
-        Workbook wb2 = writeOutAndReadBack((HSSFWorkbook) wb1);
+        HSSFWorkbook wb2 = writeOutAndReadBack(wb1);
         wb1.close();
         assertEquals(wb2.getAllPictures().size(), 0);
         wb2.addPicture(new byte[]{123, 22}, Workbook.PICTURE_TYPE_JPEG);
         assertEquals(wb2.getAllPictures().size(), 1);
 
-        Workbook wb3 = writeOutAndReadBack((HSSFWorkbook) wb2);
+        HSSFWorkbook wb3 = writeOutAndReadBack(wb2);
         wb2.close();
         assertEquals(wb3.getAllPictures().size(), 1);
 
@@ -3093,8 +3091,8 @@ public final class TestBugs extends Base
 
     @Test
     public void test61287() throws IOException {
-        final Workbook wb = HSSFTestDataSamples.openSampleWorkbook("61287.xls");
-        ExcelExtractor ex = new ExcelExtractor((HSSFWorkbook) wb);
+        final HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("61287.xls");
+        ExcelExtractor ex = new ExcelExtractor(wb);
         String text = ex.getText();
         assertContains(text, "\u8D44\u4EA7\u8D1F\u503A\u8868");
         wb.close();

Modified: poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java Sun Aug 26 11:55:00 2018
@@ -29,7 +29,6 @@ import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -38,7 +37,6 @@ import java.util.Collection;
 import java.util.List;
 
 import junit.framework.AssertionFailedError;
-
 import org.apache.poi.POIDataSamples;
 import org.apache.poi.ddf.EscherBSERecord;
 import org.apache.poi.hpsf.ClassID;
@@ -56,7 +54,6 @@ import org.apache.poi.hssf.record.Window
 import org.apache.poi.poifs.filesystem.DirectoryEntry;
 import org.apache.poi.poifs.filesystem.DirectoryNode;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
-import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.ss.formula.ptg.Area3DPtg;
 import org.apache.poi.ss.usermodel.BaseTestWorkbook;
@@ -95,7 +92,6 @@ public final class TestHSSFWorkbook exte
 
     /**
      * Tests for {@link HSSFWorkbook#isHidden()} etc
-     * @throws IOException
      */
     @Test
     public void hidden() throws IOException {
@@ -103,23 +99,23 @@ public final class TestHSSFWorkbook exte
 
         WindowOneRecord w1 = wb.getWorkbook().getWindowOne();
 
-        assertEquals(false, wb.isHidden());
-        assertEquals(false, w1.getHidden());
+        assertFalse(wb.isHidden());
+        assertFalse(w1.getHidden());
 
         wb.setHidden(true);
-        assertEquals(true, wb.isHidden());
-        assertEquals(true, w1.getHidden());
+        assertTrue(wb.isHidden());
+        assertTrue(w1.getHidden());
 
         HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
         w1 = wbBack.getWorkbook().getWindowOne();
 
         wbBack.setHidden(true);
-        assertEquals(true, wbBack.isHidden());
-        assertEquals(true, w1.getHidden());
+        assertTrue(wbBack.isHidden());
+        assertTrue(w1.getHidden());
 
         wbBack.setHidden(false);
-        assertEquals(false, wbBack.isHidden());
-        assertEquals(false, w1.getHidden());
+        assertFalse(wbBack.isHidden());
+        assertFalse(w1.getHidden());
 
         wbBack.close();
         wb.close();
@@ -257,30 +253,30 @@ public final class TestHSSFWorkbook exte
         wb.setSelectedTabs(selected);
 
         assertCollectionsEquals(selected, wb.getSelectedTabs());
-        assertEquals(true, sheet0.isSelected());
-        assertEquals(false, sheet1.isSelected());
-        assertEquals(true, sheet2.isSelected());
-        assertEquals(true, sheet3.isSelected());
-        assertEquals(false, sheet4.isSelected());
-        assertEquals(false, sheet5.isSelected());
+        assertTrue(sheet0.isSelected());
+        assertFalse(sheet1.isSelected());
+        assertTrue(sheet2.isSelected());
+        assertTrue(sheet3.isSelected());
+        assertFalse(sheet4.isSelected());
+        assertFalse(sheet5.isSelected());
 
         selected = arrayToList(new int[] { 1, 3, 5 });
         wb.setSelectedTabs(selected);
 
         // previous selection should be cleared
         assertCollectionsEquals(selected, wb.getSelectedTabs());
-        assertEquals(false, sheet0.isSelected());
-        assertEquals(true, sheet1.isSelected());
-        assertEquals(false, sheet2.isSelected());
-        assertEquals(true, sheet3.isSelected());
-        assertEquals(false, sheet4.isSelected());
-        assertEquals(true, sheet5.isSelected());
+        assertFalse(sheet0.isSelected());
+        assertTrue(sheet1.isSelected());
+        assertFalse(sheet2.isSelected());
+        assertTrue(sheet3.isSelected());
+        assertFalse(sheet4.isSelected());
+        assertTrue(sheet5.isSelected());
 
-        assertEquals(true, sheet0.isActive());
-        assertEquals(false, sheet2.isActive());
+        assertTrue(sheet0.isActive());
+        assertFalse(sheet2.isActive());
         wb.setActiveSheet(2);
-        assertEquals(false, sheet0.isActive());
-        assertEquals(true, sheet2.isActive());
+        assertFalse(sheet0.isActive());
+        assertTrue(sheet2.isActive());
 
         /*{ // helpful if viewing this workbook in excel:
             sheet0.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet0"));
@@ -383,7 +379,6 @@ public final class TestHSSFWorkbook exte
      * records to be written with invalid offset indexes.  Excel does not like this, and such
      * errors are particularly hard to track down.  This test ensures that HSSFWorkbook throws
      * a specific exception as soon as the situation is detected. See bugzilla 45066
-     * @throws IOException 
      */
     @Test
     public void sheetSerializeSizeMismatch_bug45066() throws IOException {
@@ -496,7 +491,7 @@ public final class TestHSSFWorkbook exte
      * result returned by getRecordSize() differs from result returned by serialize()
      */
     private static final class BadlyBehavedRecord extends Record {
-        public BadlyBehavedRecord() {
+        BadlyBehavedRecord() {
             //
         }
         @Override
@@ -576,7 +571,7 @@ public final class TestHSSFWorkbook exte
         POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes));
         ClassID clsid2 = fs2.getRoot().getStorageClsid();
 
-        assertTrue(clsid1.equals(clsid2));
+        assertEquals(clsid1, clsid2);
         
         fs2.close();
         wb.close();
@@ -625,108 +620,89 @@ public final class TestHSSFWorkbook exte
     public void differentPOIFS() throws Exception {
        // Open the two filesystems
        DirectoryNode[] files = new DirectoryNode[2];
-       POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("Simple.xls"));
-       try {
-           files[0] = poifsFileSystem.getRoot();
-           NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("Simple.xls"));
-           try {
-               files[1] = npoifsFileSystem.getRoot();
-               
-               // Open without preserving nodes 
-               for(DirectoryNode dir : files) {
-                  HSSFWorkbook workbook = new HSSFWorkbook(dir, false);
-                  HSSFSheet sheet = workbook.getSheetAt(0);
-                  HSSFCell cell = sheet.getRow(0).getCell(0);
-                  assertEquals("replaceMe", cell .getRichStringCellValue().getString());
-                  
-                  workbook.close();
-               }
-        
-               // Now re-check with preserving
-               for(DirectoryNode dir : files) {
-                  HSSFWorkbook workbook = new HSSFWorkbook(dir, true);
-                  HSSFSheet sheet = workbook.getSheetAt(0);
-                  HSSFCell cell = sheet.getRow(0).getCell(0);
-                  assertEquals("replaceMe", cell .getRichStringCellValue().getString());
-                  
-                  workbook.close();
-               }
-           } finally {
-               npoifsFileSystem.close();
-           }
-       } finally {
-           poifsFileSystem.close();
-       }
+        try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("Simple.xls"))) {
+            files[0] = poifsFileSystem.getRoot();
+            try (NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("Simple.xls"))) {
+                files[1] = npoifsFileSystem.getRoot();
+
+                // Open without preserving nodes
+                for (DirectoryNode dir : files) {
+                    HSSFWorkbook workbook = new HSSFWorkbook(dir, false);
+                    HSSFSheet sheet = workbook.getSheetAt(0);
+                    HSSFCell cell = sheet.getRow(0).getCell(0);
+                    assertEquals("replaceMe", cell.getRichStringCellValue().getString());
+
+                    workbook.close();
+                }
+
+                // Now re-check with preserving
+                for (DirectoryNode dir : files) {
+                    HSSFWorkbook workbook = new HSSFWorkbook(dir, true);
+                    HSSFSheet sheet = workbook.getSheetAt(0);
+                    HSSFCell cell = sheet.getRow(0).getCell(0);
+                    assertEquals("replaceMe", cell.getRichStringCellValue().getString());
+
+                    workbook.close();
+                }
+            }
+        }
     }
 
     @Test
     public void wordDocEmbeddedInXls() throws IOException {
        // Open the two filesystems
        DirectoryNode[] files = new DirectoryNode[2];
-       POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls"));
-       try {
-           files[0] = poifsFileSystem.getRoot();
-           NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("WithEmbeddedObjects.xls"));
-           try {
-               files[1] = npoifsFileSystem.getRoot();
-               
-               // Check the embedded parts
-               for(DirectoryNode root : files) {
-                  HSSFWorkbook hw = new HSSFWorkbook(root, true);
-                  List<HSSFObjectData> objects = hw.getAllEmbeddedObjects();
-                  boolean found = false;
-                   for (HSSFObjectData embeddedObject : objects) {
-                       if (embeddedObject.hasDirectoryEntry()) {
-                           DirectoryEntry dir = embeddedObject.getDirectory();
-                           if (dir instanceof DirectoryNode) {
-                               DirectoryNode dNode = (DirectoryNode) dir;
-                               if (hasEntry(dNode, "WordDocument")) {
-                                   found = true;
-                               }
-                           }
-                       }
-                   }
-                  assertTrue(found);
-                  
-                  hw.close();
-               }
-           } finally {
-               npoifsFileSystem.close();
-           }
-       } finally {
-           poifsFileSystem.close();
-       }
+        try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls"))) {
+            files[0] = poifsFileSystem.getRoot();
+            try (NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("WithEmbeddedObjects.xls"))) {
+                files[1] = npoifsFileSystem.getRoot();
+
+                // Check the embedded parts
+                for (DirectoryNode root : files) {
+                    HSSFWorkbook hw = new HSSFWorkbook(root, true);
+                    List<HSSFObjectData> objects = hw.getAllEmbeddedObjects();
+                    boolean found = false;
+                    for (HSSFObjectData embeddedObject : objects) {
+                        if (embeddedObject.hasDirectoryEntry()) {
+                            DirectoryEntry dir = embeddedObject.getDirectory();
+                            if (dir instanceof DirectoryNode) {
+                                DirectoryNode dNode = (DirectoryNode) dir;
+                                if (dNode.hasEntry("WordDocument")) {
+                                    found = true;
+                                    break;
+                                }
+                            }
+                        }
+                    }
+                    assertTrue(found);
+
+                    hw.close();
+                }
+            }
+        }
     }
 
     /**
      * Checks that we can open a workbook with NPOIFS, and write it out
      *  again (via POIFS) and have it be valid
-     * @throws IOException
      */
     @Test
     public void writeWorkbookFromNPOIFS() throws IOException {
-       InputStream is = HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls");
-       try {
-           NPOIFSFileSystem fs = new NPOIFSFileSystem(is);
-           try {
-               // Start as NPOIFS
-               HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
-               assertEquals(3, wb.getNumberOfSheets());
-               assertEquals("Root xls", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
-
-               // Will switch to POIFS
-               HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
-               assertEquals(3, wbBack.getNumberOfSheets());
-               assertEquals("Root xls", wbBack.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
-               wbBack.close();
-               
-               wb.close();
-           } finally {
-        	   fs.close();
-           }
-       } finally {
-    	   is.close();
-       }
+        try (InputStream is = HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls");
+             NPOIFSFileSystem fs = new NPOIFSFileSystem(is)) {
+            // Start as NPOIFS
+            HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
+            assertEquals(3, wb.getNumberOfSheets());
+            assertEquals("Root xls", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
+
+            // Will switch to POIFS
+            HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb);
+            assertEquals(3, wbBack.getNumberOfSheets());
+            assertEquals("Root xls", wbBack.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
+            wbBack.close();
+
+            wb.close();
+        }
     }
 
     @Test
@@ -795,7 +771,9 @@ public final class TestHSSFWorkbook exte
         wb.setSheetOrder("other sheet", 0);
 
         // names
+        //noinspection ConstantConditions
         assertEquals("'first sheet'!D1", wb.getName("name1").getRefersToFormula());
+        //noinspection ConstantConditions
         assertEquals("'other sheet'!C1", wb.getName("name2").getRefersToFormula());
 
         // cells
@@ -811,15 +789,6 @@ public final class TestHSSFWorkbook exte
         wb.close();
     }
 
-    private boolean hasEntry(DirectoryNode dirNode, String entryName) {
-       try {
-           dirNode.getEntry(entryName);
-           return true;
-       } catch (FileNotFoundException e) {
-           return false;
-       }
-   }
-
     @Test
     public void clonePictures() throws IOException {
         HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls");
@@ -854,11 +823,8 @@ public final class TestHSSFWorkbook exte
     // Should throw exception about invalid POIFSFileSystem
     @Test(expected=IllegalArgumentException.class)
     public void emptyDirectoryNode() throws IOException {
-        POIFSFileSystem fs = new POIFSFileSystem();
-        try {
+        try (POIFSFileSystem fs = new POIFSFileSystem()) {
             new HSSFWorkbook(fs).close();
-        } finally {
-            fs.close();
         }
     }
 
@@ -1093,7 +1059,8 @@ public final class TestHSSFWorkbook exte
 		wb.close();
 	}
 
-	private void expectName(HSSFWorkbook wb, String name, String expect) {
+	@SuppressWarnings("SameParameterValue")
+    private void expectName(HSSFWorkbook wb, String name, String expect) {
         final HSSFName hssfName = wb.getName(name);
         assertNotNull(hssfName);
         assertEquals(expect, hssfName.getRefersToFormula());
@@ -1149,16 +1116,13 @@ public final class TestHSSFWorkbook exte
     
             // edit the workbook
             {
-                NPOIFSFileSystem fs = new NPOIFSFileSystem(file, false);
-                try {
+                try (NPOIFSFileSystem fs = new NPOIFSFileSystem(file, false)) {
                     DirectoryNode root = fs.getRoot();
                     final Workbook workbook = new HSSFWorkbook(root, true);
                     final Sheet sheet = workbook.getSheet("foo");
                     sheet.getRow(1).createCell(2).setCellValue("baz");
-                    
+
                     writeAndCloseWorkbook(workbook, file);
-                } finally {
-                    fs.close();
                 }
             }
         } finally {
@@ -1239,18 +1203,6 @@ public final class TestHSSFWorkbook exte
         }
         wb.close();
         
-        // Can't work for OPOIFS
-        OPOIFSFileSystem ofs = new OPOIFSFileSystem(
-                POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls"));
-        wb = new HSSFWorkbook(ofs.getRoot(), true);
-        try {
-            wb.write();
-            fail("Shouldn't work for OPOIFSFileSystem");
-        } catch (IllegalStateException e) {
-            // expected here
-        }
-        wb.close();
-        
         // Can't work for Read-Only files
         NPOIFSFileSystem fs = new NPOIFSFileSystem(
                 POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls"), true);
@@ -1268,16 +1220,9 @@ public final class TestHSSFWorkbook exte
     public void inPlaceWrite() throws Exception {
         // Setup as a copy of a known-good file
         final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls");
-        InputStream inputStream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls");
-        try {
-            FileOutputStream outputStream = new FileOutputStream(file);
-            try {
-                IOUtils.copy(inputStream, outputStream);
-            } finally {
-                outputStream.close();
-            }
-        } finally {
-            inputStream.close();
+        try (InputStream inputStream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls");
+             FileOutputStream outputStream = new FileOutputStream(file)) {
+            IOUtils.copy(inputStream, outputStream);
         }
         
         // Open from the temp file in read-write mode

Modified: poi/trunk/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java Sun Aug 26 11:55:00 2018
@@ -17,20 +17,22 @@
 
 package org.apache.poi.poifs.eventfilesystem;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Set;
 
-import junit.framework.TestCase;
-
 import org.apache.poi.poifs.filesystem.POIFSDocumentPath;
+import org.junit.Test;
 
 /**
  * Class to test POIFSReaderRegistry functionality
  *
  * @author Marc Johnson
  */
-public final class TestPOIFSReaderRegistry extends TestCase {
+public final class TestPOIFSReaderRegistry {
     private final POIFSReaderListener[] listeners =
     {
         new Listener(), new Listener(), new Listener(), new Listener()
@@ -56,13 +58,14 @@ public final class TestPOIFSReaderRegist
     /**
      * Test empty registry
      */
+    @Test
     public void testEmptyRegistry() {
         POIFSReaderRegistry registry = new POIFSReaderRegistry();
 
         for (POIFSDocumentPath path : paths) {
             for (String name : names) {
                 Iterator<POIFSReaderListener> listeners =
-                    registry.getListeners(path, name);
+                    registry.getListeners(path, name).iterator();
 
                 assertTrue(!listeners.hasNext());
             }
@@ -72,6 +75,7 @@ public final class TestPOIFSReaderRegist
     /**
      * Test mixed registration operations
      */
+    @Test
     public void testMixedRegistrationOperations() {
         POIFSReaderRegistry registry = new POIFSReaderRegistry();
 
@@ -93,21 +97,20 @@ public final class TestPOIFSReaderRegist
         {
             for (int n = 0; n < names.length; n++)
             {
-                Iterator<POIFSReaderListener> listeners =
+                Iterable<POIFSReaderListener> listeners =
                     registry.getListeners(paths[ k ], names[ n ]);
 
                 if (k == n)
                 {
-                    assertTrue(!listeners.hasNext());
+                    assertTrue(!listeners.iterator().hasNext());
                 }
                 else
                 {
                     Set<POIFSReaderListener> registeredListeners =
                             new HashSet<>();
 
-                    while (listeners.hasNext())
-                    {
-                        registeredListeners.add(listeners.next());
+                    for (POIFSReaderListener rl : listeners) {
+                        registeredListeners.add(rl);
                     }
                     assertEquals(this.listeners.length - 1,
                                  registeredListeners.size());
@@ -132,14 +135,13 @@ public final class TestPOIFSReaderRegist
         }
         for (POIFSDocumentPath path : paths) {
             for (String name : names) {
-                Iterator<POIFSReaderListener> listeners =
+                Iterable<POIFSReaderListener> listeners =
                     registry.getListeners(path, name);
                 Set<POIFSReaderListener> registeredListeners =
                         new HashSet<>();
 
-                while (listeners.hasNext())
-                {
-                    registeredListeners.add(listeners.next());
+                for (POIFSReaderListener rl : listeners) {
+                    registeredListeners.add(rl);
                 }
                 assertEquals(this.listeners.length,
                              registeredListeners.size());

Modified: poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java Sun Aug 26 11:55:00 2018
@@ -21,7 +21,7 @@ import org.junit.runner.RunWith;
 import org.junit.runners.Suite;
 
 /**
- * Tests for org.apache.poi.poifs.filesystem<br>
+ * Tests for org.apache.poi.poifs.filesystem
  */
 @RunWith(Suite.class)
 @Suite.SuiteClasses({
@@ -29,7 +29,6 @@ import org.junit.runners.Suite;
     , TestDocument.class
     , TestDocumentDescriptor.class
     , TestDocumentInputStream.class
-    , TestDocumentNode.class
     , TestDocumentOutputStream.class
     , TestEmptyDocument.class
     , TestNotOLE2Exception.class

Modified: poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java Sun Aug 26 11:55:00 2018
@@ -19,7 +19,7 @@
 
 package org.apache.poi.poifs.filesystem;
 
-import java.io.FileInputStream;
+import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -38,42 +38,19 @@ import org.apache.poi.util.IOUtils;
  * @author Marc Johnson (mjohnson at apache dot org)
  */
 
-public class ReaderWriter
+public final class ReaderWriter
     implements POIFSReaderListener, POIFSWriterListener
 {
-    private final POIFSFileSystem filesystem;
     private final DirectoryEntry  root;
 
     // keys are DocumentDescriptors, values are byte[]s
-    private final Map<DocumentDescriptor, byte[]> dataMap;
+    private final Map<DocumentDescriptor, byte[]> dataMap = new HashMap<>();
 
-    /**
-     * Constructor ReaderWriter
-     *
-     *
-     * @param filesystem
-     *
-     */
-
-    ReaderWriter(final POIFSFileSystem filesystem)
-    {
-        this.filesystem = filesystem;
-        root            = this.filesystem.getRoot();
-        dataMap         = new HashMap<>();
+    private ReaderWriter(final POIFSFileSystem filesystem) {
+        root = filesystem.getRoot();
     }
 
-    /**
-     * Method main
-     *
-     *
-     * @param args
-     *
-     * @exception IOException
-     *
-     */
-
-    public static void main(String [] args)
-        throws IOException
+    public static void main(String [] args) throws IOException
     {
         if (args.length != 2)
         {
@@ -86,10 +63,8 @@ public class ReaderWriter
             POIFSFileSystem filesystem = new POIFSFileSystem();
 
             reader.registerListener(new ReaderWriter(filesystem));
-            FileInputStream istream = new FileInputStream(args[ 0 ]);
 
-            reader.read(istream);
-            istream.close();
+            reader.read(new File(args[ 0 ]));
             FileOutputStream ostream = new FileOutputStream(args[ 1 ]);
 
             filesystem.writeFilesystem(ostream);

Modified: poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java?rev=1839201&r1=1839200&r2=1839201&view=diff
==============================================================================
--- poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java (original)
+++ poi/trunk/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java Sun Aug 26 11:55:00 2018
@@ -17,218 +17,131 @@
 
 package org.apache.poi.poifs.filesystem;
 
+import static org.apache.poi.poifs.common.POIFSConstants.LARGER_BIG_BLOCK_SIZE;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.stream.IntStream;
 
 import org.apache.poi.poifs.property.DocumentProperty;
-import org.apache.poi.poifs.storage.RawDataBlock;
-
-import junit.framework.TestCase;
+import org.apache.poi.poifs.storage.RawDataUtil;
+import org.apache.poi.util.IOUtils;
+import org.junit.Test;
 
 /**
- * Class to test OPOIFSDocument functionality
+ * Class to test POIFSDocument functionality
  */
-public final class TestDocument extends TestCase {
+public class TestDocument {
 
     /**
      * Integration test -- really about all we can do
      */
-    public void testOPOIFSDocument() throws IOException {
+    @Test
+    public void testNPOIFSDocument() throws IOException {
 
-        // verify correct number of blocks get created for document
-        // that is exact multituple of block size
-        OPOIFSDocument document;
-        byte[]        array = new byte[ 4096 ];
-
-        for (int j = 0; j < array.length; j++)
-        {
-            array[ j ] = ( byte ) j;
-        }
-        document = new OPOIFSDocument("foo", new SlowInputStream(new ByteArrayInputStream(array)));
-        checkDocument(document, array);
+        try (NPOIFSFileSystem poifs = new NPOIFSFileSystem()) {
 
-        // verify correct number of blocks get created for document
-        // that is not an exact multiple of block size
-        array = new byte[ 4097 ];
-        for (int j = 0; j < array.length; j++)
-        {
-            array[ j ] = ( byte ) j;
-        }
-        document = new OPOIFSDocument("bar", new ByteArrayInputStream(array));
-        checkDocument(document, array);
+            // verify correct number of blocks get created for document
+            // that is exact multiple of block size
+            checkDocument(poifs, LARGER_BIG_BLOCK_SIZE);
 
-        // verify correct number of blocks get created for document
-        // that is small
-        array = new byte[ 4095 ];
-        for (int j = 0; j < array.length; j++)
-        {
-            array[ j ] = ( byte ) j;
-        }
-        document = new OPOIFSDocument("_bar", new ByteArrayInputStream(array));
-        checkDocument(document, array);
+            // verify correct number of blocks get created for document
+            // that is not an exact multiple of block size
+            checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1);
 
-        // verify correct number of blocks get created for document
-        // that is rather small
-        array = new byte[ 199 ];
-        for (int j = 0; j < array.length; j++)
-        {
-            array[ j ] = ( byte ) j;
-        }
-        document = new OPOIFSDocument("_bar2",
-                                     new ByteArrayInputStream(array));
-        checkDocument(document, array);
-
-        // verify that output is correct
-        array = new byte[ 4097 ];
-        for (int j = 0; j < array.length; j++)
-        {
-            array[ j ] = ( byte ) j;
-        }
-        document = new OPOIFSDocument("foobar",
-                                     new ByteArrayInputStream(array));
-        checkDocument(document, array);
-        document.setStartBlock(0x12345678);   // what a big file!!
-        DocumentProperty      property = document.getDocumentProperty();
-        ByteArrayOutputStream stream   = new ByteArrayOutputStream();
+            // verify correct number of blocks get created for document
+            // that is small
+            checkDocument(poifs, LARGER_BIG_BLOCK_SIZE - 1);
 
-        property.writeData(stream);
-        byte[] output = stream.toByteArray();
-        byte[] array2 =
-        {
-            ( byte ) 'f', ( byte ) 0, ( byte ) 'o', ( byte ) 0, ( byte ) 'o',
-            ( byte ) 0, ( byte ) 'b', ( byte ) 0, ( byte ) 'a', ( byte ) 0,
-            ( byte ) 'r', ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 14,
-            ( byte ) 0, ( byte ) 2, ( byte ) 1, ( byte ) -1, ( byte ) -1,
-            ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1,
-            ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0x78, ( byte ) 0x56, ( byte ) 0x34,
-            ( byte ) 0x12, ( byte ) 1, ( byte ) 16, ( byte ) 0, ( byte ) 0,
-            ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0
-        };
-
-        assertEquals(array2.length, output.length);
-        for (int j = 0; j < output.length; j++)
-        {
-            assertEquals("Checking property offset " + j, array2[ j ],
-                         output[ j ]);
+            // verify correct number of blocks get created for document
+            // that is rather small
+            checkDocument(poifs, 199);
+
+
+            // verify that output is correct
+            NPOIFSDocument document = checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1);
+            DocumentProperty property = document.getDocumentProperty();
+            ByteArrayOutputStream stream = new ByteArrayOutputStream();
+
+            property.writeData(stream);
+            byte[] output = stream.toByteArray();
+            byte[] array2 = RawDataUtil.decompress("H4sIAAAAAAAAAEtlyGMoYShiqGSwYCAH8DEwMf5HAsToMQdiRgEIGwCDyzEQgAAAAA==");
+
+            assertArrayEquals(array2, output);
         }
     }
 
-    private static OPOIFSDocument makeCopy(OPOIFSDocument document, byte[] input, byte[] data)
-            throws IOException {
-        OPOIFSDocument copy = null;
-
-        if (input.length >= 4096)
-        {
-            RawDataBlock[]       blocks =
-                new RawDataBlock[ (input.length + 511) / 512 ];
-            ByteArrayInputStream stream = new ByteArrayInputStream(data);
-            int                  index  = 0;
-
-            while (true)
-            {
-                RawDataBlock block = new RawDataBlock(stream);
-
-                if (block.eof())
-                {
-                    break;
-                }
-                blocks[ index++ ] = block;
-            }
-            copy = new OPOIFSDocument("test" + input.length, blocks,
-                                     input.length);
-        }
-        else
-        {
-            copy = new OPOIFSDocument("test"+input.length, document.getSmallBlocks(), input.length);
-        }
-        return copy;
+    private static NPOIFSDocument checkDocument(final NPOIFSFileSystem poifs, final int size) throws IOException {
+        final byte[] input = new byte[size];
+        IntStream.range(0, size).forEach(i -> input[i] = (byte)i);
+
+        NPOIFSDocument document = ((DocumentNode)poifs.createDocument(
+            new SlowInputStream(new ByteArrayInputStream(input)),
+        "entry"+poifs.getRoot().getEntryCount())).getDocument();
+
+        final int blockSize = (size >= 4096) ? 512 : 64;
+        final int blockCount = (size + (blockSize-1)) / blockSize;
+
+        final byte[] bytCpy = checkValues(blockCount, document, input);
+        final NPOIFSDocument copied = makeCopy(document,bytCpy);
+
+        checkValues(blockCount, copied, input);
+
+        return document;
     }
 
-    private static void checkDocument(final OPOIFSDocument document, final byte[] input)
-            throws IOException {
-        int big_blocks   = 0;
-        int small_blocks = 0;
-        int total_output = 0;
-
-        if (input.length >= 4096)
-        {
-            big_blocks   = (input.length + 511) / 512;
-            total_output = big_blocks * 512;
-        }
-        else
-        {
-            small_blocks = (input.length + 63) / 64;
-            total_output = 0;
-        }
-        checkValues(
-            big_blocks, small_blocks, total_output,
-            makeCopy(
-            document, input,
-            checkValues(
-                big_blocks, small_blocks, total_output, document,
-                input)), input);
+    private static NPOIFSDocument makeCopy(NPOIFSDocument document, byte[] input) throws IOException {
+        NPOIFSFileSystem poifs = document.getFileSystem();
+        String name = "test" + input.length;
+        DirectoryNode root = poifs.getRoot();
+        if (root.hasEntry(name)) {
+            root.deleteEntry((EntryNode)root.getEntry(name));
+        }
+        return ((DocumentNode)root
+            .createDocument(name, new ByteArrayInputStream(input)))
+            .getDocument();
     }
 
-    private static byte[] checkValues(int big_blocks, int small_blocks, int total_output,
-            OPOIFSDocument document, byte[] input) throws IOException {
+    private static byte[] checkValues(final int blockCountExp, NPOIFSDocument document, byte[] input) throws IOException {
+        assertNotNull(document);
+        assertNotNull(document.getDocumentProperty().getDocument());
         assertEquals(document, document.getDocumentProperty().getDocument());
-        int increment = ( int ) Math.sqrt(input.length);
 
-        for (int j = 1; j <= input.length; j += increment)
-        {
-            byte[] buffer = new byte[ j ];
-            int    offset = 0;
-
-            for (int k = 0; k < (input.length / j); k++)
-            {
-                document.read(buffer, offset);
-                for (int n = 0; n < buffer.length; n++)
-                {
-                    assertEquals("checking byte " + (k * j) + n,
-                                 input[ (k * j) + n ], buffer[ n ]);
-                }
-                offset += j;
-            }
-        }
-        assertEquals(big_blocks, document.countBlocks());
-        assertEquals(small_blocks, document.getSmallBlocks().length);
-        ByteArrayOutputStream stream = new ByteArrayOutputStream();
+        ByteArrayInputStream bis = new ByteArrayInputStream(input);
 
-        document.writeBlocks(stream);
-        byte[] output = stream.toByteArray();
+        int blockCountAct = 0, bytesRemaining = input.length;
+        for (ByteBuffer bb : document) {
+            assertTrue(bytesRemaining > 0);
+            int bytesAct = Math.min(bb.remaining(), bytesRemaining);
+            assertTrue(bytesAct <= document.getDocumentBlockSize());
+            byte[] bufAct = new byte[bytesAct];
+            bb.get(bufAct);
+
+            byte[] bufExp = new byte[bytesAct];
+            int bytesExp = bis.read(bufExp, 0, bytesAct);
+            assertEquals(bytesExp, bytesAct);
+
+            assertArrayEquals(bufExp, bufAct);
+            blockCountAct++;
+            bytesRemaining -= bytesAct;
+        }
 
-        assertEquals(total_output, output.length);
-        int limit = Math.min(total_output, input.length);
+        assertEquals(blockCountExp, blockCountAct);
 
-        for (int j = 0; j < limit; j++)
-        {
-            assertEquals("Checking document offset " + j, input[ j ],
-                         output[ j ]);
-        }
-        for (int j = limit; j < output.length; j++)
-        {
-            assertEquals("Checking document offset " + j, ( byte ) -1,
-                         output[ j ]);
+        ByteArrayOutputStream stream = new ByteArrayOutputStream();
+        try (DocumentInputStream dis = document.getFileSystem().createDocumentInputStream(
+                document.getDocumentProperty().getName())) {
+            IOUtils.copy(dis, stream);
         }
+
+        byte[] output = stream.toByteArray();
+        assertArrayEquals(input, stream.toByteArray());
         return output;
     }
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org


Mime
View raw message