]> source.dussan.org Git - poi.git/commitdiff
Cleanup Biff8EncryptionKey usage and use HPSF constants instead of duplicated strings
authorAndreas Beeker <kiwiwings@apache.org>
Tue, 1 May 2018 18:22:00 +0000 (18:22 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Tue, 1 May 2018 18:22:00 +0000 (18:22 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1830705 13f79535-47bb-0310-9956-ffa450edef68

18 files changed:
src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestHxxFEncryption.java
src/scratchpad/testcases/org/apache/poi/TestPOIDocumentScratchpad.java
src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentEncryption.java
src/testcases/org/apache/poi/TestPOIDocumentMain.java
src/testcases/org/apache/poi/hpsf/basic/TestBasic.java
src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java
src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java
src/testcases/org/apache/poi/hssf/dev/BaseXLSIteratingTest.java
src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java
src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java
src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java
src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java
src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java
src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java
src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java
src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java
src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java

index d4f38a1d135e1ec0b7a6153bc5f7820371e554a4..7e0c447f0732304177d93d59f6f5a22707e2b4ff 100644 (file)
@@ -46,8 +46,7 @@ public class ReadTitle
     {
         final String filename = args[0];
         POIFSReader r = new POIFSReader();
-        r.registerListener(new MyPOIFSReaderListener(),
-                           "\005SummaryInformation");
+        r.registerListener(new MyPOIFSReaderListener(), SummaryInformation.DEFAULT_STREAM_NAME);
         r.read(new FileInputStream(filename));
     }
 
index 7403ecc3d71066baf3d1b175fef83e20ad145648..0ca785d8d0730dd77ae58f460f7aa25898e78120 100644 (file)
@@ -52,11 +52,6 @@ import org.junit.runners.Parameterized.Parameters;
 
 @RunWith(Parameterized.class)
 public class TestHxxFEncryption {
-    @AfterClass
-    public static void clearPass() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
     @Parameter(value = 0)
     public POIDataSamples sampleDir;
 
@@ -99,12 +94,14 @@ public class TestHxxFEncryption {
     
     @Test
     public void extract() throws IOException, OpenXML4JException, XmlException {
-        Biff8EncryptionKey.setCurrentUserPassword(password);
         File f = sampleDir.getFile(file);
-        POITextExtractor te = ExtractorFactory.createExtractor(f);
-        String actual = te.getText().trim();
-        assertEquals(expected, actual);
-        te.close();
+        Biff8EncryptionKey.setCurrentUserPassword(password);
+        try (POITextExtractor te = ExtractorFactory.createExtractor(f)) {
+            String actual = te.getText().trim();
+            assertEquals(expected, actual);
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+        }
     }
     
     @Test
@@ -118,70 +115,72 @@ public class TestHxxFEncryption {
     }
     
     public void newPassword(String newPass) throws IOException, OpenXML4JException, XmlException {
-        Biff8EncryptionKey.setCurrentUserPassword(password);
         File f = sampleDir.getFile(file);
-        POITextExtractor te1 = ExtractorFactory.createExtractor(f);
-        Biff8EncryptionKey.setCurrentUserPassword(newPass);
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        POIDocument doc = (POIDocument)te1.getDocument();
-        doc.write(bos);
-        doc.close();
-        te1.close();
-        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
-        POITextExtractor te2 = ExtractorFactory.createExtractor(bis);
-        String actual = te2.getText().trim();
-        assertEquals(expected, actual);
-        te2.close();
+        Biff8EncryptionKey.setCurrentUserPassword(password);
+        try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) {
+            Biff8EncryptionKey.setCurrentUserPassword(newPass);
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            try (POIDocument doc = (POIDocument) te1.getDocument()) {
+                doc.write(bos);
+            }
+            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+            try (POITextExtractor te2 = ExtractorFactory.createExtractor(bis)) {
+                String actual = te2.getText().trim();
+                assertEquals(expected, actual);
+            }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+        }
     }
 
     /** changing the encryption mode and key size in poor mans style - see comments below */
     @Test
     public void changeEncryption() throws IOException, OpenXML4JException, XmlException {
+        File f = sampleDir.getFile(file);
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         Biff8EncryptionKey.setCurrentUserPassword(password);
-        File f = sampleDir.getFile(file);
-        POITextExtractor te1 = ExtractorFactory.createExtractor(f);
-        // first remove encryption
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-        POIDocument doc = (POIDocument)te1.getDocument();
-        doc.write(bos);
-        doc.close();
-        te1.close();
-        // then use default setting, which is cryptoapi
-        String newPass = "newPass";
-        POITextExtractor te2 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
-        Biff8EncryptionKey.setCurrentUserPassword(newPass);
-        doc = (POIDocument)te2.getDocument();
-        bos.reset();
-        doc.write(bos);
-        doc.close();
-        te2.close();
-        // and finally update cryptoapi setting
-        POITextExtractor te3 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
-        doc = (POIDocument)te3.getDocument();
-        // need to cache data (i.e. read all data) before changing the key size
-        if (doc instanceof HSLFSlideShowImpl) {
-            HSLFSlideShowImpl hss = (HSLFSlideShowImpl)doc;
-            hss.getPictureData();
-            hss.getDocumentSummaryInformation();
+        try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) {
+            // first remove encryption
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+            try (POIDocument doc = (POIDocument) te1.getDocument()) {
+                doc.write(bos);
+            }
+            // then use default setting, which is cryptoapi
+            String newPass = "newPass";
+            try (POITextExtractor te2 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()))) {
+                Biff8EncryptionKey.setCurrentUserPassword(newPass);
+                try (POIDocument doc = (POIDocument) te2.getDocument()) {
+                    bos.reset();
+                    doc.write(bos);
+                }
+            }
+            // and finally update cryptoapi setting
+            try (POITextExtractor te3 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
+                 POIDocument doc = (POIDocument) te3.getDocument()) {
+                // need to cache data (i.e. read all data) before changing the key size
+                if (doc instanceof HSLFSlideShowImpl) {
+                    HSLFSlideShowImpl hss = (HSLFSlideShowImpl) doc;
+                    hss.getPictureData();
+                    hss.getDocumentSummaryInformation();
+                }
+                EncryptionInfo ei = doc.getEncryptionInfo();
+                assertNotNull(ei);
+                assertTrue(ei.getHeader() instanceof CryptoAPIEncryptionHeader);
+                assertEquals(0x28, ei.getHeader().getKeySize());
+                ei.getHeader().setKeySize(0x78);
+                bos.reset();
+                doc.write(bos);
+            }
+            // check the setting
+            try (POITextExtractor te4 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
+                 POIDocument doc = (POIDocument) te4.getDocument()) {
+                EncryptionInfo ei = doc.getEncryptionInfo();
+                assertNotNull(ei);
+                assertTrue(ei.getHeader() instanceof CryptoAPIEncryptionHeader);
+                assertEquals(0x78, ei.getHeader().getKeySize());
+            }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
         }
-        EncryptionInfo ei = doc.getEncryptionInfo();
-        assertNotNull(ei);
-        assertTrue(ei.getHeader() instanceof CryptoAPIEncryptionHeader);
-        assertEquals(0x28, ei.getHeader().getKeySize());
-        ei.getHeader().setKeySize(0x78);
-        bos.reset();
-        doc.write(bos);
-        doc.close();
-        te3.close();
-        // check the setting
-        POITextExtractor te4 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
-        doc = (POIDocument)te4.getDocument();
-        ei = doc.getEncryptionInfo();
-        assertNotNull(ei);
-        assertTrue(ei.getHeader() instanceof CryptoAPIEncryptionHeader);
-        assertEquals(0x78, ei.getHeader().getKeySize());
-        doc.close();
-        te4.close();
     }
 }
index 152fd0405caab2980668e5876931d20d3b76e96f..5cfb54d1065c4edbf8f53b8ce5fc2b0abfd4f6ff 100644 (file)
@@ -28,7 +28,9 @@ import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hpsf.DocumentSummaryInformation;
 import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
+import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
 import org.apache.poi.hwpf.HWPFTestDataSamples;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
@@ -91,8 +93,8 @@ public final class TestPOIDocumentScratchpad {
                doc.writeProperties(outFS);
 
                // Should now hold them
-               assertNotNull(outFS.createDocumentInputStream("\005SummaryInformation"));
-               assertNotNull(outFS.createDocumentInputStream("\005DocumentSummaryInformation"));
+               assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
+               assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME));
                outFS.close();
        }
 
index a53173a8a57ca5b0ce4fec4ae751df64d1bd21ec..4fe1c4d051794000266539c33dd04ed12fed232c 100644 (file)
@@ -59,94 +59,90 @@ import org.junit.Test;
 public class TestDocumentEncryption {
     POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
 
-    @Before
-    @After  // also afterwards to not affect other tests running in the same JVM
-    public void resetPassword() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-    
     @Test
     public void cryptoAPIDecryptionOther() throws Exception {
-        Biff8EncryptionKey.setCurrentUserPassword("hello");
         String encPpts[] = {
             "Password_Protected-56-hello.ppt",
             "Password_Protected-hello.ppt",
             "Password_Protected-np-hello.ppt",
         };
 
-        for (String pptFile : encPpts) {
-            try {
-                NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
-                HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs);
-                new HSLFSlideShow(hss).close();
-                fs.close();
-            } catch (EncryptedPowerPointFileException e) {
-                fail(pptFile+" can't be decrypted");
+        Biff8EncryptionKey.setCurrentUserPassword("hello");
+        try {
+            for (String pptFile : encPpts) {
+                try (NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
+                     HSLFSlideShow ppt = new HSLFSlideShow(fs)) {
+                    assertTrue(ppt.getSlides().size() > 0);
+                } catch (EncryptedPowerPointFileException e) {
+                    fail(pptFile + " can't be decrypted");
+                }
             }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
         }
-        // password is reset in @After
     }
 
     @Test
     public void cryptoAPIChangeKeySize() throws Exception {
         String pptFile = "cryptoapi-proc2356.ppt";
         Biff8EncryptionKey.setCurrentUserPassword("crypto");
-        NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
-        HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs);
-        // need to cache data (i.e. read all data) before changing the key size
-        List<HSLFPictureData> picsExpected = hss.getPictureData();
-        hss.getDocumentSummaryInformation();
-        DocumentEncryptionAtom documentEncryptionAtom = hss.getDocumentEncryptionAtom();
-        assertNotNull(documentEncryptionAtom);
-        EncryptionInfo ei = documentEncryptionAtom.getEncryptionInfo();
-        ((CryptoAPIEncryptionHeader) ei.getHeader()).setKeySize(0x78);
-
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        hss.write(bos);
-        hss.close();
-        fs.close();
-
-        fs = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
-        hss = new HSLFSlideShowImpl(fs);
-        List<HSLFPictureData> picsActual = hss.getPictureData();
-
-        assertEquals(picsExpected.size(), picsActual.size());
-        for (int i = 0; i < picsExpected.size(); i++) {
-            assertArrayEquals(picsExpected.get(i).getRawData(), picsActual.get(i).getRawData());
+        try (NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
+             HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) {
+            // need to cache data (i.e. read all data) before changing the key size
+            List<HSLFPictureData> picsExpected = hss.getPictureData();
+            hss.getDocumentSummaryInformation();
+            DocumentEncryptionAtom documentEncryptionAtom = hss.getDocumentEncryptionAtom();
+            assertNotNull(documentEncryptionAtom);
+            EncryptionInfo ei = documentEncryptionAtom.getEncryptionInfo();
+            ((CryptoAPIEncryptionHeader) ei.getHeader()).setKeySize(0x78);
+
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            hss.write(bos);
+
+            try (NPOIFSFileSystem fs2 = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
+                 HSLFSlideShowImpl hss2 = new HSLFSlideShowImpl(fs2)) {
+                List<HSLFPictureData> picsActual = hss2.getPictureData();
+
+                assertEquals(picsExpected.size(), picsActual.size());
+                for (int i = 0; i < picsExpected.size(); i++) {
+                    assertArrayEquals(picsExpected.get(i).getRawData(), picsActual.get(i).getRawData());
+                }
+            }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
         }
-        hss.close();
-        fs.close();
-        // password is reset in @After
     }
 
     @Test
     public void cryptoAPIEncryption() throws Exception {
         /* documents with multiple edits need to be normalized for encryption */
         String pptFile = "57272_corrupted_usereditatom.ppt";
-        NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
-        HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs);
-        hss.normalizeRecords();
-        
-        // normalized ppt
-        ByteArrayOutputStream expected = new ByteArrayOutputStream();
-        hss.write(expected);
-        
-        // encrypted
-        Biff8EncryptionKey.setCurrentUserPassword("hello");
         ByteArrayOutputStream encrypted = new ByteArrayOutputStream();
-        hss.write(encrypted);
-        hss.close();
-        fs.close();
-
-        // decrypted
-        ByteArrayInputStream bis = new ByteArrayInputStream(encrypted.toByteArray());
-        fs = new NPOIFSFileSystem(bis);
-        hss = new HSLFSlideShowImpl(fs);
-        Biff8EncryptionKey.setCurrentUserPassword(null);
+        ByteArrayOutputStream expected = new ByteArrayOutputStream();
         ByteArrayOutputStream actual = new ByteArrayOutputStream();
-        hss.write(actual);
-        hss.close();
-        fs.close();
+        try {
+            try (NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile(pptFile), true);
+                 HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) {
+                hss.normalizeRecords();
+
+                // normalized ppt
+                hss.write(expected);
+
+                // encrypted
+                Biff8EncryptionKey.setCurrentUserPassword("hello");
+                hss.write(encrypted);
+            }
+
+            // decrypted
+            ByteArrayInputStream bis = new ByteArrayInputStream(encrypted.toByteArray());
+            try (NPOIFSFileSystem fs = new NPOIFSFileSystem(bis);
+                 HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) {
+                Biff8EncryptionKey.setCurrentUserPassword(null);
+                hss.write(actual);
+            }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+        }
         
         assertArrayEquals(expected.toByteArray(), actual.toByteArray());
     }    
@@ -156,49 +152,49 @@ public class TestDocumentEncryption {
         // taken from a msdn blog:
         // http://blogs.msdn.com/b/openspecification/archive/2009/05/08/dominic-salemno.aspx
         Biff8EncryptionKey.setCurrentUserPassword("crypto");
-        NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile("cryptoapi-proc2356.ppt"));
-        HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs);
-        HSLFSlideShow ss = new HSLFSlideShow(hss);
-
-        HSLFSlide slide = ss.getSlides().get(0);
-        String rawText = HSLFTextParagraph.getRawText(slide.getTextParagraphs().get(0));
-        assertEquals("Dominic Salemno", rawText);
-
-        String picCmp[][] = {
-                {"0", "nKsDTKqxTCR8LFkVVWlP9GSTvZ0="},
-                {"95163", "SuNOR+9V1UVYZIoeD65l3VTaLoc="},
-                {"100864", "Ql3IGrr4bNq07ZTp5iPg7b+pva8="},
-                {"714114", "8pdst9NjBGSfWezSZE8+aVhIRe0="},
-                {"723752", "go6xqW7lvkCtlOO5tYLiMfb4oxw="},
-                {"770128", "gZUM8YqRNL5kGNfyyYvEEernvCc="},
-                {"957958", "CNU2iiqUFAnk3TDXsXV1ihH9eRM="},
-        };
+        try (NPOIFSFileSystem fs = new NPOIFSFileSystem(slTests.getFile("cryptoapi-proc2356.ppt"));
+             HSLFSlideShow ss = new HSLFSlideShow(fs)) {
+
+            HSLFSlide slide = ss.getSlides().get(0);
+            String rawText = HSLFTextParagraph.getRawText(slide.getTextParagraphs().get(0));
+            assertEquals("Dominic Salemno", rawText);
+
+            String picCmp[][] = {
+                    {"0", "nKsDTKqxTCR8LFkVVWlP9GSTvZ0="},
+                    {"95163", "SuNOR+9V1UVYZIoeD65l3VTaLoc="},
+                    {"100864", "Ql3IGrr4bNq07ZTp5iPg7b+pva8="},
+                    {"714114", "8pdst9NjBGSfWezSZE8+aVhIRe0="},
+                    {"723752", "go6xqW7lvkCtlOO5tYLiMfb4oxw="},
+                    {"770128", "gZUM8YqRNL5kGNfyyYvEEernvCc="},
+                    {"957958", "CNU2iiqUFAnk3TDXsXV1ihH9eRM="},
+            };
+
+            MessageDigest md = CryptoFunctions.getMessageDigest(HashAlgorithm.sha1);
+            List<HSLFPictureData> pd = ss.getSlideShowImpl().getPictureData();
+            int i = 0;
+            for (HSLFPictureData p : pd) {
+                byte hash[] = md.digest(p.getData());
+                assertEquals(Integer.parseInt(picCmp[i][0]), p.getOffset());
+                assertEquals(picCmp[i][1], Base64.encodeBase64String(hash));
+                i++;
+            }
 
-        MessageDigest md = CryptoFunctions.getMessageDigest(HashAlgorithm.sha1);
-        List<HSLFPictureData> pd = hss.getPictureData();
-        int i = 0;
-        for (HSLFPictureData p : pd) {
-            byte hash[] = md.digest(p.getData());
-            assertEquals(Integer.parseInt(picCmp[i][0]), p.getOffset());
-            assertEquals(picCmp[i][1], Base64.encodeBase64String(hash));
-            i++;
+            DocumentEncryptionAtom dea = ss.getSlideShowImpl().getDocumentEncryptionAtom();
+            assertNotNull(dea);
+
+            CryptoAPIDecryptor dec = (CryptoAPIDecryptor) dea.getEncryptionInfo().getDecryptor();
+            try (POIFSFileSystem fs2 = dec.getSummaryEntries(fs.getRoot(), "EncryptedSummary")) {
+                PropertySet ps = PropertySetFactory.create(fs2.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME);
+                assertNotNull(ps);
+                assertTrue(ps.isSummaryInformation());
+                assertEquals("RC4 CryptoAPI Encryption", ps.getProperties()[1].getValue());
+                ps = PropertySetFactory.create(fs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+                assertNotNull(ps);
+                assertTrue(ps.isDocumentSummaryInformation());
+                assertEquals("On-screen Show (4:3)", ps.getProperties()[1].getValue());
+            }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
         }
-
-        DocumentEncryptionAtom dea = hss.getDocumentEncryptionAtom();
-        assertNotNull(dea);
-
-        POIFSFileSystem fs2 = ((CryptoAPIDecryptor) dea.getEncryptionInfo().getDecryptor()).getSummaryEntries(fs.getRoot(), "EncryptedSummary");
-        PropertySet ps = PropertySetFactory.create(fs2.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME);
-        assertNotNull(ps);
-        assertTrue(ps.isSummaryInformation());
-        assertEquals("RC4 CryptoAPI Encryption", ps.getProperties()[1].getValue());
-        ps = PropertySetFactory.create(fs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-        assertNotNull(ps);
-        assertTrue(ps.isDocumentSummaryInformation());
-        assertEquals("On-screen Show (4:3)", ps.getProperties()[1].getValue());
-        ss.close();
-        fs.close();
-        fs2.close();
-        // password is reset in @After
     }
 }
index 83668b5c7090036e1055869020418d1abad21f99..8910f4ed521288006049a06e21b013fd06738e1a 100644 (file)
@@ -25,7 +25,9 @@ import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hpsf.DocumentSummaryInformation;
 import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
+import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.hssf.HSSFTestDataSamples;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
@@ -89,10 +91,10 @@ public final class TestPOIDocumentMain {
 
         // Should now hold them
         assertNotNull(
-                outFS.createDocumentInputStream("\005SummaryInformation")
+                outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)
         );
         assertNotNull(
-                outFS.createDocumentInputStream("\005DocumentSummaryInformation")
+                outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)
         );
     }
 
index dcb5c67b922d6d96f7ba80fa8f5fdacf575b202f..0bc08772ed12d10400cff4309415f53ab1130666 100644 (file)
@@ -53,8 +53,8 @@ public final class TestBasic {
     private static final POIDataSamples samples = POIDataSamples.getHPSFInstance();
 
     private static final String[] POI_FILES = {
-        "\005SummaryInformation",
-        "\005DocumentSummaryInformation",
+        SummaryInformation.DEFAULT_STREAM_NAME,
+        DocumentSummaryInformation.DEFAULT_STREAM_NAME,
         "WordDocument",
         "\001CompObj",
         "1Table"
index 4e9eec627165c488c89756949b0b6bc21a70cf7c..92e82d32e070ddf065f38c6555fd992b2c3739da 100644 (file)
@@ -56,7 +56,7 @@ public final class TestEmptyProperties {
 
        private static final String[] POI_FILES = {
         "PerfectOffice_MAIN",
-        "\005SummaryInformation",
+        SummaryInformation.DEFAULT_STREAM_NAME,
         "Main"
     };
 
index 69e4367bbf35ee5079bc457b2b01444aed961d05..3e3eafd4951bbf56c1405b51fba23ac5bff8a083 100644 (file)
@@ -43,7 +43,7 @@ public class TestUnicode {
 
     static final String POI_FS = "TestUnicode.xls";
     static final String[] POI_FILES =  {
-        "\005DocumentSummaryInformation",
+        DocumentSummaryInformation.DEFAULT_STREAM_NAME,
     };
     File data;
     POIFile[] poiFiles;
index d740a8a37ebfc41ec7aabf3f456ea2e7c54f3faf..c87bf45e678a9b7e9a19d090bafdb779c9237946 100644 (file)
@@ -90,9 +90,6 @@ public abstract class BaseXLSIteratingTest {
     
        @Test
        public void testMain() throws Exception {
-           // we had intermittent problems when this was set differently somehow, let's try to set it here so it always is set correctly for these tests
-           Biff8EncryptionKey.setCurrentUserPassword(null);
-
            String fileName = file.getName();
            if (EXCLUDED.containsKey(fileName)) {
                thrown.expect(EXCLUDED.get(fileName));
index bf66cecef449efd58a41ddf5e7b1e6a935190dcc..459cfe90ec70bf77fd0d06c61a80b01ce246ace2 100644 (file)
@@ -46,12 +46,6 @@ public final class TestHSSFEventFactory extends TestCase {
         return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
     }
 
-    // to not affect other tests running in the same JVM
-    @After
-    public void resetPassword() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
     public void testWithMissingRecords() throws Exception {
 
         HSSFRequest req = new HSSFRequest();
@@ -156,7 +150,6 @@ public final class TestHSSFEventFactory extends TestCase {
         req.addListenerForAllRecords(mockListen);
 
         // Without a password, can't be read
-        Biff8EncryptionKey.setCurrentUserPassword(null);
         POIFSFileSystem fs = new POIFSFileSystem(openSample("xor-encryption-abc.xls"));
 
         HSSFEventFactory factory = new HSSFEventFactory();
@@ -168,44 +161,47 @@ public final class TestHSSFEventFactory extends TestCase {
 
         // With the password, is properly processed
         Biff8EncryptionKey.setCurrentUserPassword("abc");
+        try {
+            req = new HSSFRequest();
+            mockListen = new MockHSSFListener();
+            req.addListenerForAllRecords(mockListen);
+            factory.processWorkbookEvents(req, fs);
 
-        req = new HSSFRequest();
-        mockListen = new MockHSSFListener();
-        req.addListenerForAllRecords(mockListen);
-        factory.processWorkbookEvents(req, fs);
-
-        // Check we got the sheet and the contents
-        Record[] recs = mockListen.getRecords();
-        assertTrue( recs.length > 50 );
-
-        // Has one sheet, with values 1,2,3 in column A rows 1-3
-        boolean hasSheet=false, hasA1=false, hasA2=false, hasA3=false;
-        for (Record r : recs) {
-            if (r instanceof BoundSheetRecord) {
-                BoundSheetRecord bsr = (BoundSheetRecord)r;
-                assertEquals("Sheet1", bsr.getSheetname());
-                hasSheet = true;
-            }
-            if (r instanceof NumberRecord) {
-                NumberRecord nr = (NumberRecord)r;
-                if (nr.getColumn() == 0 && nr.getRow() == 0) {
-                    assertEquals(1, (int)nr.getValue());
-                    hasA1 = true;
+            // Check we got the sheet and the contents
+            Record[] recs = mockListen.getRecords();
+            assertTrue(recs.length > 50);
+
+            // Has one sheet, with values 1,2,3 in column A rows 1-3
+            boolean hasSheet = false, hasA1 = false, hasA2 = false, hasA3 = false;
+            for (Record r : recs) {
+                if (r instanceof BoundSheetRecord) {
+                    BoundSheetRecord bsr = (BoundSheetRecord) r;
+                    assertEquals("Sheet1", bsr.getSheetname());
+                    hasSheet = true;
                 }
-                if (nr.getColumn() == 0 && nr.getRow() == 1) {
-                    assertEquals(2, (int)nr.getValue());
-                    hasA2 = true;
-                }
-                if (nr.getColumn() == 0 && nr.getRow() == 2) {
-                    assertEquals(3, (int)nr.getValue());
-                    hasA3 = true;
+                if (r instanceof NumberRecord) {
+                    NumberRecord nr = (NumberRecord) r;
+                    if (nr.getColumn() == 0 && nr.getRow() == 0) {
+                        assertEquals(1, (int) nr.getValue());
+                        hasA1 = true;
+                    }
+                    if (nr.getColumn() == 0 && nr.getRow() == 1) {
+                        assertEquals(2, (int) nr.getValue());
+                        hasA2 = true;
+                    }
+                    if (nr.getColumn() == 0 && nr.getRow() == 2) {
+                        assertEquals(3, (int) nr.getValue());
+                        hasA3 = true;
+                    }
                 }
             }
-        }
 
-        assertTrue("Sheet record not found", hasSheet);
-        assertTrue("Numeric record for A1 not found", hasA1);
-        assertTrue("Numeric record for A2 not found", hasA2);
-        assertTrue("Numeric record for A3 not found", hasA3);
+            assertTrue("Sheet record not found", hasSheet);
+            assertTrue("Numeric record for A1 not found", hasA1);
+            assertTrue("Numeric record for A2 not found", hasA2);
+            assertTrue("Numeric record for A3 not found", hasA3);
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+        }
     }
 }      
index faebefb84857945de9add27abf0fbd9cd6096bdc..fd9c49dc12a157233147b2e21bac0c7ff465fbc9 100644 (file)
@@ -41,12 +41,6 @@ import org.junit.Test;
  *
  */
 public final class TestExcelExtractor {
-    // to not affect other tests running in the same JVM
-    @After
-    public void resetPassword() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
     private static ExcelExtractor createExtractor(String sampleFileName) throws IOException {
                File file = HSSFTestDataSamples.getSampleFile(sampleFileName);
         POIFSFileSystem fs = new POIFSFileSystem(file);
@@ -355,9 +349,10 @@ public final class TestExcelExtractor {
                Biff8EncryptionKey.setCurrentUserPassword("password");
                try (ExcelExtractor extractor = createExtractor("password.xls")) {
                        String text = extractor.getText();
+                       assertContains(text, "ZIP");
+               } finally {
                        Biff8EncryptionKey.setCurrentUserPassword(null);
 
-                       assertContains(text, "ZIP");
                }
        }
 
index 4cfdfcf242a931ab05f75f17d7a5fc630078256c..a716717ad9937d69b8aec4f1a3f19bd79755c932 100644 (file)
@@ -36,12 +36,6 @@ import org.junit.rules.ExpectedException;
  * @author Josh Micich
  */
 public final class TestRecordFactoryInputStream {
-    // to not affect other tests running in the same JVM
-    @After
-    public void resetPassword() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
        /**
         * Hex dump of a BOF record and most of a FILEPASS record.
         * A 16 byte saltHash should be added to complete the second record
@@ -82,7 +76,6 @@ public final class TestRecordFactoryInputStream {
                                + SAMPLE_WINDOW1_ENCR1
                );
 
-        Biff8EncryptionKey.setCurrentUserPassword(null);
            expectedEx.expect(EncryptedDocumentException.class);
            expectedEx.expectMessage("Default password is invalid for salt/verifier/verifierHash");
                createRFIS(dataWrongDefault);
@@ -100,7 +93,6 @@ public final class TestRecordFactoryInputStream {
                 + SAMPLE_WINDOW1_ENCR1
         );
 
-        Biff8EncryptionKey.setCurrentUserPassword(null);
         RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault);
         confirmReadInitialRecords(rfis);
     }
@@ -121,12 +113,15 @@ public final class TestRecordFactoryInputStream {
                                + SAMPLE_WINDOW1_ENCR2
                );
 
+               expectedEx.expect(EncryptedDocumentException.class);
+               expectedEx.expectMessage("Supplied password is invalid for salt/verifier/verifierHash");
 
                Biff8EncryptionKey.setCurrentUserPassword("passw0rd");
-
-        expectedEx.expect(EncryptedDocumentException.class);
-        expectedEx.expectMessage("Supplied password is invalid for salt/verifier/verifierHash");
-        createRFIS(dataWrongDefault);
+               try {
+                       createRFIS(dataWrongDefault);
+               } finally {
+                       Biff8EncryptionKey.setCurrentUserPassword(null);
+               }
        }
 
     @Test
@@ -135,18 +130,19 @@ public final class TestRecordFactoryInputStream {
         final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00"
             + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE";
 
-        Biff8EncryptionKey.setCurrentUserPassword("passw0rd");
-
         byte[] dataCorrectDefault = HexRead.readFromString(""
                 + COMMON_HEX_DATA
                 + "C728659A C38E35E0 568A338F C3FC9D70" // correct saltHash for supplied password (and docId/saltHash)
                 + SAMPLE_WINDOW1_ENCR2
         );
 
-        RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault);
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-
-        confirmReadInitialRecords(rfis);
+               Biff8EncryptionKey.setCurrentUserPassword("passw0rd");
+               try {
+                       RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault);
+                       confirmReadInitialRecords(rfis);
+               } finally {
+                       Biff8EncryptionKey.setCurrentUserPassword(null);
+               }
     }
        
        
index 2f620eac95d3aba262d1dbcf818502f830075c38..53802f5069a181b141e2ec014bfbd189dba96dbb 100644 (file)
@@ -102,12 +102,6 @@ import org.junit.Test;
  * define the test in the base class {@link BaseTestBugzillaIssues}</b>
  */
 public final class TestBugs extends BaseTestBugzillaIssues {
-    // to not affect other tests running in the same JVM
-    @After
-    public void resetPassword() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
     public TestBugs() {
         super(HSSFITestDataProvider.instance);
     }
@@ -2207,8 +2201,6 @@ public final class TestBugs extends BaseTestBugzillaIssues {
      */
     @Test
     public void bug50833() throws Exception {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-
         HSSFWorkbook wb1 = openSample("50833.xls");
         HSSFSheet s = wb1.getSheetAt(0);
         assertEquals("Sheet1", s.getSheetName());
@@ -2602,8 +2594,8 @@ public final class TestBugs extends BaseTestBugzillaIssues {
     @Test(expected = EncryptedDocumentException.class)
     public void bug35897() throws Exception {
         // password is abc
+        Biff8EncryptionKey.setCurrentUserPassword("abc");
         try {
-            Biff8EncryptionKey.setCurrentUserPassword("abc");
             openSample("xor-encryption-abc.xls").close();
         } finally {
             Biff8EncryptionKey.setCurrentUserPassword(null);
index 3baafa8b39b6f2708c0c2a52e27892861d69ecc6..92e5f6447274f8db5a5d998a8313d8f2829952bd 100644 (file)
@@ -30,11 +30,6 @@ import org.junit.Test;
 public class TestCryptoAPI {
     final HSSFITestDataProvider ssTests = HSSFITestDataProvider.instance;
 
-    @AfterClass
-    public static void resetPW() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
     @Test
     public void bug59857() throws IOException {
         // XOR-Obfuscation
@@ -52,19 +47,17 @@ public class TestCryptoAPI {
     
     private void validateContent(String wbFile, String password, String textExpected) throws IOException {
         Biff8EncryptionKey.setCurrentUserPassword(password);
-        HSSFWorkbook wb = ssTests.openSampleWorkbook(wbFile);
-        ExcelExtractor ee1 = new ExcelExtractor(wb);
-        String textActual = ee1.getText();
-        assertContains(textActual, textExpected);
-
-        Biff8EncryptionKey.setCurrentUserPassword("bla");
-        HSSFWorkbook wbBla = ssTests.writeOutAndReadBack(wb);
-        ExcelExtractor ee2 = new ExcelExtractor(wbBla);
-        textActual = ee2.getText();
-        assertContains(textActual, textExpected);
-        ee2.close();
-        ee1.close();
-        wbBla.close();
-        wb.close();
+        try (HSSFWorkbook wb = ssTests.openSampleWorkbook(wbFile);
+             ExcelExtractor ee1 = new ExcelExtractor(wb)
+        ) {
+            Biff8EncryptionKey.setCurrentUserPassword("bla");
+            try (HSSFWorkbook wbBla = ssTests.writeOutAndReadBack(wb);
+                 ExcelExtractor ee2 = new ExcelExtractor(wbBla)) {
+                assertContains(ee1.getText(), textExpected);
+                assertContains(ee2.getText(), textExpected);
+            }
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+        }
     }
 }
index 0a84947b4c67e6ba35168a08d88263e13ba7b127..80c0750c42f513e93c662dcc29f03729e36cb635 100644 (file)
@@ -23,8 +23,12 @@ import static org.junit.Assert.assertTrue;
 import java.io.IOException;
 import java.io.InputStream;
 
+import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.hssf.HSSFTestDataSamples;
+import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
 import org.apache.poi.poifs.filesystem.DirectoryNode;
+import org.apache.poi.poifs.filesystem.Entry;
+import org.junit.BeforeClass;
 import org.junit.Test;
 
 /**
@@ -49,7 +53,7 @@ public final class TestNonStandardWorkbookStreamNames {
 
                // Ensure that we have a WORKBOOK entry and a summary
                assertTrue(root.hasEntry("WORKBOOK"));
-               assertTrue(root.hasEntry("\005SummaryInformation"));
+               assertTrue(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME));
 
                // But not a Workbook one
                assertFalse(root.hasEntry("Workbook"));
@@ -73,7 +77,7 @@ public final class TestNonStandardWorkbookStreamNames {
 
       // But not a Workbook one and not a Summary one
       assertFalse(root.hasEntry("Workbook"));
-      assertFalse(root.hasEntry("\\005SummaryInformation"));
+      assertFalse(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME));
       
       wb.close();
    }
@@ -127,7 +131,7 @@ public final class TestNonStandardWorkbookStreamNames {
         assertFalse(root.hasEntry("WORKBOOK"));
 
         // As we preserved, should also have a few other streams
-        assertTrue(root.hasEntry("\005SummaryInformation"));
+        assertTrue(root.hasEntry(SummaryInformation.DEFAULT_STREAM_NAME));
         wb2.close();
        }
 }
index 20dec4552f105b7ff2010b805deba4c481935043..002318b0ebfa3bea16476c7b6ef04a8e7990ef47 100644 (file)
@@ -21,6 +21,7 @@ import static org.hamcrest.core.IsEqual.equalTo;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
 
+import java.io.File;
 import java.io.IOException;
 
 import org.apache.poi.hssf.HSSFTestDataSamples;
@@ -36,12 +37,6 @@ public class TestXorEncryption {
     
     private static final HSSFTestDataSamples samples = new HSSFTestDataSamples();
     
-    // to not affect other tests running in the same JVM
-    @After
-    public void resetPassword() {
-        Biff8EncryptionKey.setCurrentUserPassword(null);
-    }
-
     @Test
     public void testXorEncryption() throws IOException {
         // Xor-Password: abc
@@ -61,15 +56,16 @@ public class TestXorEncryption {
     @SuppressWarnings("static-access")
     @Test
     public void testUserFile() throws IOException {
+        File f = samples.getSampleFile("xor-encryption-abc.xls");
         Biff8EncryptionKey.setCurrentUserPassword("abc");
-        NPOIFSFileSystem fs = new NPOIFSFileSystem(samples.getSampleFile("xor-encryption-abc.xls"), true);
-        HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true);
-        
-        HSSFSheet sh = hwb.getSheetAt(0);
-        assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0);
-        assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0);
-        assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0);
-        hwb.close();
-        fs.close();
+        try (NPOIFSFileSystem fs = new NPOIFSFileSystem(f, true);
+             HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true)) {
+            HSSFSheet sh = hwb.getSheetAt(0);
+            assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0);
+            assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0);
+            assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0);
+        } finally {
+            Biff8EncryptionKey.setCurrentUserPassword(null);
+        }
     }
 }
index bd0b30eddec5472a8cd2e6e0383a3db757947ff2..d4442e859a9fd9da413ab4b59d663bae97aceaf2 100644 (file)
@@ -20,6 +20,8 @@ package org.apache.poi.poifs.property;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hpsf.DocumentSummaryInformation;
+import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.poifs.storage.RawDataUtil;
 import org.apache.poi.util.LocaleUtil;
 
@@ -68,8 +70,8 @@ public final class TestDocumentProperty extends TestCase {
         byte[] input = RawDataUtil.decode(hexData);
 
         verifyReadingProperty(1, input, 128, "Workbook");
-        verifyReadingProperty(2, input, 256, "\005SummaryInformation");
-        verifyReadingProperty(3, input, 384, "\005DocumentSummaryInformation");
+        verifyReadingProperty(2, input, 256, SummaryInformation.DEFAULT_STREAM_NAME);
+        verifyReadingProperty(3, input, 384, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
     }
 
     private void verifyReadingProperty(int index, byte[] input, int offset, String name)
index 3950ce07e2cf83243089610b9728c1f6b6406812..74cc83f8796891af8cb2021c8b71a0b6de7c0292 100644 (file)
@@ -25,6 +25,8 @@ import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
+import org.apache.poi.hpsf.DocumentSummaryInformation;
+import org.apache.poi.hpsf.SummaryInformation;
 import org.apache.poi.poifs.common.POIFSConstants;
 import org.apache.poi.poifs.storage.BlockAllocationTableReader;
 import org.apache.poi.poifs.storage.HeaderBlock;
@@ -79,11 +81,10 @@ public final class TestPropertyTable {
                DocumentProperty workbook = new DocumentProperty("Workbook", 0x00046777);
 
                workbook.setStartBlock(0);
-               DocumentProperty summary1 = new DocumentProperty("\005SummaryInformation", 0x00001000);
+               DocumentProperty summary1 = new DocumentProperty(SummaryInformation.DEFAULT_STREAM_NAME, 0x00001000);
 
                summary1.setStartBlock(0x00000234);
-               DocumentProperty summary2 = new DocumentProperty("\005DocumentSummaryInformation",
-                               0x00001000);
+               DocumentProperty summary2 = new DocumentProperty(DocumentSummaryInformation.DEFAULT_STREAM_NAME, 0x00001000);
 
                summary2.setStartBlock(0x0000023C);
                table.addProperty(workbook);