From: Dominik Stadler Date: Sat, 23 Feb 2019 07:52:24 +0000 (+0000) Subject: Close file-handles for slideshows also when construction fails or when dual-storage... X-Git-Tag: REL_4_1_0~62 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=6a93b3a9ed1ed99055b79db35c2f460208f6f505;p=poi.git Close file-handles for slideshows also when construction fails or when dual-storage is used Also avoid file-leak reports in some tests git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1854192 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java b/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java index 5a5ac39ffa..09ade054f2 100644 --- a/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java +++ b/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java @@ -40,7 +40,7 @@ import org.junit.Test; public class TestDetectAsOOXML { @Test public void testOpensProperly() throws IOException, InvalidFormatException { - OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("sample.xlsx")); + OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("sample.xlsx")).close(); } @Test diff --git a/src/ooxml/testcases/org/apache/poi/TestEmbedded.java b/src/ooxml/testcases/org/apache/poi/TestEmbedded.java index 35b2642a06..c50c22f38e 100644 --- a/src/ooxml/testcases/org/apache/poi/TestEmbedded.java +++ b/src/ooxml/testcases/org/apache/poi/TestEmbedded.java @@ -67,5 +67,7 @@ public class TestEmbedded extends TestCase byte[] b = IOUtils.toByteArray(pp.getInputStream()); assertTrue(b.length > 0); } + + doc.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java index a9776ae89b..f0e9e19997 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java @@ -81,15 +81,10 @@ public final class TestListParts extends TestCase { /** * List all parts of a package. */ - public void testListParts() throws InvalidFormatException { + public void testListParts() throws InvalidFormatException, IOException { InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx"); - OPCPackage p; - try { - p = OPCPackage.open(is); - } catch (IOException e) { - throw new RuntimeException(e); - } + OPCPackage p = OPCPackage.open(is); for (PackagePart part : p.getParts()) { values.put(part.getPartName(), part.getContentType()); logger.log(POILogger.DEBUG, part.getPartName()); @@ -100,5 +95,7 @@ public final class TestListParts extends TestCase { assertNotNull(values.get(partName)); assertEquals(expectedValues.get(partName), values.get(partName)); } + + p.close(); } } diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java index 40b703c93b..a9b7d52c12 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java @@ -30,7 +30,6 @@ import junit.framework.TestCase; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; -import org.apache.poi.xwpf.usermodel.XWPFRelation; public class TestRelationships extends TestCase { @@ -51,18 +50,19 @@ public class TestRelationships extends TestCase { */ public void testLoadRelationships() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - logger.log(POILogger.DEBUG, "1: " + pkg); - PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - PackageRelationship coreDocRelationship = rels.getRelationship(0); - PackagePart corePart = pkg.getPart(coreDocRelationship); - String[] relIds = {"rId1", "rId2", "rId3"}; - for (String relId : relIds) { - PackageRelationship rel = corePart.getRelationship(relId); - assertNotNull(rel); - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - PackagePart sheetPart = pkg.getPart(relName); - assertEquals("Number of relationships1 for " + sheetPart.getPartName(), 1, sheetPart.getRelationships().size()); + try (OPCPackage pkg = OPCPackage.open(is)) { + logger.log(POILogger.DEBUG, "1: " + pkg); + PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); + PackageRelationship coreDocRelationship = rels.getRelationship(0); + PackagePart corePart = pkg.getPart(coreDocRelationship); + String[] relIds = {"rId1", "rId2", "rId3"}; + for (String relId : relIds) { + PackageRelationship rel = corePart.getRelationship(relId); + assertNotNull(rel); + PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); + PackagePart sheetPart = pkg.getPart(relName); + assertEquals("Number of relationships1 for " + sheetPart.getPartName(), 1, sheetPart.getRelationships().size()); + } } } @@ -72,39 +72,40 @@ public class TestRelationships extends TestCase { */ public void testFetchFromCollection() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - assertTrue(sheet.hasRelationships()); - assertEquals(6, sheet.getRelationships().size()); - - // Should have three hyperlinks, and one comment - PackageRelationshipCollection hyperlinks = - sheet.getRelationshipsByType(HYPERLINK_REL_TYPE); - PackageRelationshipCollection comments = - sheet.getRelationshipsByType(COMMENTS_REL_TYPE); - assertEquals(3, hyperlinks.size()); - assertEquals(1, comments.size()); - - // Check we can get bits out by id - // Hyperlinks are rId1, rId2 and rId3 - // Comment is rId6 - assertNotNull(hyperlinks.getRelationshipByID("rId1")); - assertNotNull(hyperlinks.getRelationshipByID("rId2")); - assertNotNull(hyperlinks.getRelationshipByID("rId3")); - assertNull(hyperlinks.getRelationshipByID("rId6")); - - assertNull(comments.getRelationshipByID("rId1")); - assertNull(comments.getRelationshipByID("rId2")); - assertNull(comments.getRelationshipByID("rId3")); - assertNotNull(comments.getRelationshipByID("rId6")); - - assertNotNull(sheet.getRelationship("rId1")); - assertNotNull(sheet.getRelationship("rId2")); - assertNotNull(sheet.getRelationship("rId3")); - assertNotNull(sheet.getRelationship("rId6")); + try (OPCPackage pkg = OPCPackage.open(is)) { + PackagePart sheet = pkg.getPart( + PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); + assertNotNull(sheet); + + assertTrue(sheet.hasRelationships()); + assertEquals(6, sheet.getRelationships().size()); + + // Should have three hyperlinks, and one comment + PackageRelationshipCollection hyperlinks = + sheet.getRelationshipsByType(HYPERLINK_REL_TYPE); + PackageRelationshipCollection comments = + sheet.getRelationshipsByType(COMMENTS_REL_TYPE); + assertEquals(3, hyperlinks.size()); + assertEquals(1, comments.size()); + + // Check we can get bits out by id + // Hyperlinks are rId1, rId2 and rId3 + // Comment is rId6 + assertNotNull(hyperlinks.getRelationshipByID("rId1")); + assertNotNull(hyperlinks.getRelationshipByID("rId2")); + assertNotNull(hyperlinks.getRelationshipByID("rId3")); + assertNull(hyperlinks.getRelationshipByID("rId6")); + + assertNull(comments.getRelationshipByID("rId1")); + assertNull(comments.getRelationshipByID("rId2")); + assertNull(comments.getRelationshipByID("rId3")); + assertNotNull(comments.getRelationshipByID("rId6")); + + assertNotNull(sheet.getRelationship("rId1")); + assertNotNull(sheet.getRelationship("rId2")); + assertNotNull(sheet.getRelationship("rId3")); + assertNotNull(sheet.getRelationship("rId6")); + } } /** @@ -113,31 +114,32 @@ public class TestRelationships extends TestCase { */ public void testLoadExcelHyperlinkRelations() throws Exception { InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - // rId1 is url - PackageRelationship url = sheet.getRelationship("rId1"); - assertNotNull(url); - assertEquals("rId1", url.getId()); - assertEquals("/xl/worksheets/sheet1.xml", url.getSourceURI().toString()); - assertEquals("http://poi.apache.org/", url.getTargetURI().toString()); - - // rId2 is file - PackageRelationship file = sheet.getRelationship("rId2"); - assertNotNull(file); - assertEquals("rId2", file.getId()); - assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); - assertEquals("WithVariousData.xlsx", file.getTargetURI().toString()); - - // rId3 is mailto - PackageRelationship mailto = sheet.getRelationship("rId3"); - assertNotNull(mailto); - assertEquals("rId3", mailto.getId()); - assertEquals("/xl/worksheets/sheet1.xml", mailto.getSourceURI().toString()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.getTargetURI().toString()); + try (OPCPackage pkg = OPCPackage.open(is)) { + PackagePart sheet = pkg.getPart( + PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); + assertNotNull(sheet); + + // rId1 is url + PackageRelationship url = sheet.getRelationship("rId1"); + assertNotNull(url); + assertEquals("rId1", url.getId()); + assertEquals("/xl/worksheets/sheet1.xml", url.getSourceURI().toString()); + assertEquals("http://poi.apache.org/", url.getTargetURI().toString()); + + // rId2 is file + PackageRelationship file = sheet.getRelationship("rId2"); + assertNotNull(file); + assertEquals("rId2", file.getId()); + assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); + assertEquals("WithVariousData.xlsx", file.getTargetURI().toString()); + + // rId3 is mailto + PackageRelationship mailto = sheet.getRelationship("rId3"); + assertNotNull(mailto); + assertEquals("rId3", mailto.getId()); + assertEquals("/xl/worksheets/sheet1.xml", mailto.getSourceURI().toString()); + assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.getTargetURI().toString()); + } } /* @@ -217,74 +219,73 @@ public class TestRelationships extends TestCase { } public void testCreateRelationsFromScratch() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OPCPackage pkg = OPCPackage.create(baos); - - PackagePart partA = - pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); - PackagePart partB = - pkg.createPart(PackagingURIHelper.createPartName("/partB"), "image/png"); - assertNotNull(partA); - assertNotNull(partB); - - // Internal - partA.addRelationship(partB.getPartName(), TargetMode.INTERNAL, "http://example/Rel"); - - // External - partA.addExternalRelationship("http://poi.apache.org/", "http://example/poi"); - partB.addExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss"); - - // Check as expected currently - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - - - // Save, and re-load - pkg.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); - partB = pkg.getPart(PackagingURIHelper.createPartName("/partB")); - - - // Check the relations - assertEquals(2, partA.getRelationships().size()); - assertEquals(1, partB.getRelationships().size()); - - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - // Check core too - assertEquals("/docProps/core.xml", - pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0).getTargetURI().toString()); - - - // Add some more - partB.addExternalRelationship("http://poi.apache.org/new", "http://example/poi/new"); - partB.addExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt"); - - // Check the relations - assertEquals(2, partA.getRelationships().size()); - assertEquals(3, partB.getRelationships().size()); - - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OPCPackage pkg = OPCPackage.create(baos); + + PackagePart partA = + pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); + PackagePart partB = + pkg.createPart(PackagingURIHelper.createPartName("/partB"), "image/png"); + assertNotNull(partA); + assertNotNull(partB); + + // Internal + partA.addRelationship(partB.getPartName(), TargetMode.INTERNAL, "http://example/Rel"); + + // External + partA.addExternalRelationship("http://poi.apache.org/", "http://example/poi"); + partB.addExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss"); + + // Check as expected currently + assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); + assertEquals("http://poi.apache.org/", + partA.getRelationship("rId2").getTargetURI().toString()); + assertEquals("http://poi.apache.org/ss/", + partB.getRelationship("rId1").getTargetURI().toString()); + + + // Save, and re-load + pkg.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + pkg = OPCPackage.open(bais); + + partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); + partB = pkg.getPart(PackagingURIHelper.createPartName("/partB")); + + + // Check the relations + assertEquals(2, partA.getRelationships().size()); + assertEquals(1, partB.getRelationships().size()); + + assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); + assertEquals("http://poi.apache.org/", + partA.getRelationship("rId2").getTargetURI().toString()); + assertEquals("http://poi.apache.org/ss/", + partB.getRelationship("rId1").getTargetURI().toString()); + // Check core too + PackageRelationship relationship = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0); + assertNotNull(relationship); + assertEquals("/docProps/core.xml", relationship.getTargetURI().toString()); + + // Add some more + partB.addExternalRelationship("http://poi.apache.org/new", "http://example/poi/new"); + partB.addExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt"); + + // Check the relations + assertEquals(2, partA.getRelationships().size()); + assertEquals(3, partB.getRelationships().size()); + + assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); + assertEquals("http://poi.apache.org/", partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", + assertEquals("http://poi.apache.org/ss/", partB.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/new", + assertEquals("http://poi.apache.org/new", partB.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/alt", + assertEquals("http://poi.apache.org/alt", partB.getRelationship("rId3").getTargetURI().toString()); } - public void testTargetWithSpecialChars() throws Exception{ OPCPackage pkg; @@ -371,7 +372,8 @@ public class TestRelationships extends TestCase { PackageRelationship rel2 = partA.getRelationships().getRelationship(0); - assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType()); + assertNotNull(rel2); + assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType()); assertEquals(rel1.getId(), rel2.getId()); assertEquals(rel1.getSourceURI(), rel2.getSourceURI()); assertEquals(rel1.getTargetURI(), rel2.getTargetURI()); diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java index 542f1c0131..dc0bff3201 100644 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java +++ b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java @@ -119,17 +119,18 @@ public final class TestOPCComplianceCoreProperties { // We will use the first core properties, and ignore the others InputStream is = OpenXML4JTestDataSamples.openSampleStream("MultipleCoreProperties.docx"); - OPCPackage pkg = OPCPackage.open(is); - - // We can see 2 by type - assertEquals(2, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - // But only the first one by relationship - assertEquals(1, pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size()); - // It should be core.xml not the older core1.xml - assertEquals( - "/docProps/core.xml", - pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).get(0).getPartName().toString() - ); + try (OPCPackage pkg = OPCPackage.open(is)) { + + // We can see 2 by type + assertEquals(2, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); + // But only the first one by relationship + assertEquals(1, pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size()); + // It should be core.xml not the older core1.xml + assertEquals( + "/docProps/core.xml", + pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).get(0).getPartName().toString() + ); + } } private static URI createURI(String text) { diff --git a/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java b/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java index fd1c8d8a10..607954233b 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java +++ b/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.io.IOException; import java.util.Locale; import java.util.TimeZone; import java.util.regex.Matcher; @@ -27,6 +28,7 @@ import java.util.regex.Pattern; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.util.LocaleUtil; import org.apache.poi.xssf.XSSFITestDataProvider; import org.junit.AfterClass; @@ -58,7 +60,7 @@ public class TestCellFormatPart extends CellFormatTestBase { } @Test - public void testGeneralFormat() { + public void testGeneralFormat() throws IOException { runFormatTests("GeneralFormatTests.xlsx", new CellValue() { @Override public Object getValue(Cell cell) { @@ -75,7 +77,7 @@ public class TestCellFormatPart extends CellFormatTestBase { } @Test - public void testNumberFormat() { + public void testNumberFormat() throws IOException { runFormatTests("NumberFormatTests.xlsx", new CellValue() { @Override public Object getValue(Cell cell) { @@ -85,7 +87,7 @@ public class TestCellFormatPart extends CellFormatTestBase { } @Test - public void testNumberApproxFormat() { + public void testNumberApproxFormat() throws IOException { runFormatTests("NumberFormatApproxTests.xlsx", new CellValue() { @Override public Object getValue(Cell cell) { @@ -106,7 +108,7 @@ public class TestCellFormatPart extends CellFormatTestBase { } @Test - public void testDateFormat() { + public void testDateFormat() throws IOException { TimeZone tz = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); try { @@ -122,7 +124,7 @@ public class TestCellFormatPart extends CellFormatTestBase { } @Test - public void testElapsedFormat() { + public void testElapsedFormat() throws IOException { runFormatTests("ElapsedFormatTests.xlsx", new CellValue() { @Override public Object getValue(Cell cell) { @@ -132,22 +134,20 @@ public class TestCellFormatPart extends CellFormatTestBase { } @Test - public void testTextFormat() { + public void testTextFormat() throws IOException { runFormatTests("TextFormatTests.xlsx", new CellValue() { @Override public Object getValue(Cell cell) { - switch(CellFormat.ultimateType(cell)) { - case BOOLEAN: - return cell.getBooleanCellValue(); - default: - return cell.getStringCellValue(); + if (CellFormat.ultimateType(cell) == CellType.BOOLEAN) { + return cell.getBooleanCellValue(); } + return cell.getStringCellValue(); } }); } @Test - public void testConditions() { + public void testConditions() throws IOException { runFormatTests("FormatConditionTests.xlsx", new CellValue() { @Override Object getValue(Cell cell) { diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java index c00ca5e56c..7929a95669 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java @@ -28,6 +28,8 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.XSSFTestDataSamples; import org.junit.Test; +import java.io.IOException; + /** * */ @@ -37,14 +39,15 @@ public class TestSumifsXSSF { * handle null cell predicate */ @Test - public void testBug60858() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("bug60858.xlsx"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - Cell cell = sheet.getRow(1).getCell(5); - fe.evaluate(cell); - assertEquals(0.0, cell.getNumericCellValue(), 0.0000000000000001); + public void testBug60858() throws IOException { + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("bug60858.xlsx")) { + FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); + + Sheet sheet = wb.getSheetAt(0); + Cell cell = sheet.getRow(1).getCell(5); + fe.evaluate(cell); + assertEquals(0.0, cell.getNumericCellValue(), 0.0000000000000001); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFRangeCopier.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFRangeCopier.java index 405390fbda..25b0d94022 100644 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFRangeCopier.java +++ b/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFRangeCopier.java @@ -26,9 +26,12 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFRangeCopier; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + public class TestXSSFRangeCopier extends TestRangeCopier { public TestXSSFRangeCopier() { super(); @@ -44,6 +47,11 @@ public class TestXSSFRangeCopier extends TestRangeCopier { transSheetRangeCopier = new XSSFRangeCopier(sheet1, sheet2); } + @After + public void shutdown() throws IOException { + workbook.close(); + } + @Test // XSSF only. HSSF version wouldn't be so simple. And also this test is contained in following, more complex tests, so it's not really important. public void copyRow() { Row existingRow = sheet1.getRow(4); diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java index c0acc2cca2..ab28bae825 100644 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java +++ b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java @@ -33,6 +33,7 @@ import org.apache.poi.xslf.usermodel.XSLFRelation; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.apache.poi.xslf.usermodel.XSLFSlideShow; import org.apache.xmlbeans.XmlException; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; @@ -50,6 +51,11 @@ public class TestXSLFSlideShow { pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); } + @After + public void tearDown() throws IOException { + pack.close(); + } + @Test public void testContainsMainContentType() throws Exception { boolean found = false; diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java index 9e126097c3..bc0269ebe3 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java @@ -16,21 +16,34 @@ ==================================================================== */ package org.apache.poi.xssf; -import junit.framework.TestCase; - import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -public class TestSheetProtection extends TestCase { +public class TestSheetProtection { + private XSSFWorkbook workbook; private XSSFSheet sheet; - @Override - protected void setUp() throws Exception { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); + @Before + public void setUp() { + workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); sheet = workbook.getSheetAt(0); } - - public void testShouldReadWorkbookProtection() throws Exception { + + @After + public void tearDown() throws IOException { + workbook.close(); + } + + @Test + public void testShouldReadWorkbookProtection() throws IOException { assertFalse(sheet.isAutoFilterLocked()); assertFalse(sheet.isDeleteColumnsLocked()); assertFalse(sheet.isDeleteRowsLocked()); @@ -48,27 +61,30 @@ public class TestSheetProtection extends TestCase { assertFalse(sheet.isSelectUnlockedCellsLocked()); assertFalse(sheet.isSheetLocked()); - sheet = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx").getSheetAt(0); + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { + sheet = workbook.getSheetAt(0); - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); + assertTrue(sheet.isAutoFilterLocked()); + assertTrue(sheet.isDeleteColumnsLocked()); + assertTrue(sheet.isDeleteRowsLocked()); + assertTrue(sheet.isFormatCellsLocked()); + assertTrue(sheet.isFormatColumnsLocked()); + assertTrue(sheet.isFormatRowsLocked()); + assertTrue(sheet.isInsertColumnsLocked()); + assertTrue(sheet.isInsertHyperlinksLocked()); + assertTrue(sheet.isInsertRowsLocked()); + assertTrue(sheet.isPivotTablesLocked()); + assertTrue(sheet.isSortLocked()); + assertTrue(sheet.isObjectsLocked()); + assertTrue(sheet.isScenariosLocked()); + assertTrue(sheet.isSelectLockedCellsLocked()); + assertTrue(sheet.isSelectUnlockedCellsLocked()); + assertTrue(sheet.isSheetLocked()); + } } - - public void testWriteAutoFilter() throws Exception { + + @Test + public void testWriteAutoFilter() { assertFalse(sheet.isAutoFilterLocked()); sheet.lockAutoFilter(true); assertFalse(sheet.isAutoFilterLocked()); @@ -77,8 +93,9 @@ public class TestSheetProtection extends TestCase { sheet.lockAutoFilter(false); assertFalse(sheet.isAutoFilterLocked()); } - - public void testWriteDeleteColumns() throws Exception { + + @Test + public void testWriteDeleteColumns() { assertFalse(sheet.isDeleteColumnsLocked()); sheet.lockDeleteColumns(true); assertFalse(sheet.isDeleteColumnsLocked()); @@ -87,8 +104,9 @@ public class TestSheetProtection extends TestCase { sheet.lockDeleteColumns(false); assertFalse(sheet.isDeleteColumnsLocked()); } - - public void testWriteDeleteRows() throws Exception { + + @Test + public void testWriteDeleteRows() { assertFalse(sheet.isDeleteRowsLocked()); sheet.lockDeleteRows(true); assertFalse(sheet.isDeleteRowsLocked()); @@ -97,8 +115,9 @@ public class TestSheetProtection extends TestCase { sheet.lockDeleteRows(false); assertFalse(sheet.isDeleteRowsLocked()); } - - public void testWriteFormatCells() throws Exception { + + @Test + public void testWriteFormatCells() { assertFalse(sheet.isFormatCellsLocked()); sheet.lockFormatCells(true); assertFalse(sheet.isFormatCellsLocked()); @@ -107,8 +126,9 @@ public class TestSheetProtection extends TestCase { sheet.lockFormatCells(false); assertFalse(sheet.isFormatCellsLocked()); } - - public void testWriteFormatColumns() throws Exception { + + @Test + public void testWriteFormatColumns() { assertFalse(sheet.isFormatColumnsLocked()); sheet.lockFormatColumns(true); assertFalse(sheet.isFormatColumnsLocked()); @@ -117,8 +137,9 @@ public class TestSheetProtection extends TestCase { sheet.lockFormatColumns(false); assertFalse(sheet.isFormatColumnsLocked()); } - - public void testWriteFormatRows() throws Exception { + + @Test + public void testWriteFormatRows() { assertFalse(sheet.isFormatRowsLocked()); sheet.lockFormatRows(true); assertFalse(sheet.isFormatRowsLocked()); @@ -127,8 +148,9 @@ public class TestSheetProtection extends TestCase { sheet.lockFormatRows(false); assertFalse(sheet.isFormatRowsLocked()); } - - public void testWriteInsertColumns() throws Exception { + + @Test + public void testWriteInsertColumns() { assertFalse(sheet.isInsertColumnsLocked()); sheet.lockInsertColumns(true); assertFalse(sheet.isInsertColumnsLocked()); @@ -137,8 +159,9 @@ public class TestSheetProtection extends TestCase { sheet.lockInsertColumns(false); assertFalse(sheet.isInsertColumnsLocked()); } - - public void testWriteInsertHyperlinks() throws Exception { + + @Test + public void testWriteInsertHyperlinks() { assertFalse(sheet.isInsertHyperlinksLocked()); sheet.lockInsertHyperlinks(true); assertFalse(sheet.isInsertHyperlinksLocked()); @@ -147,8 +170,9 @@ public class TestSheetProtection extends TestCase { sheet.lockInsertHyperlinks(false); assertFalse(sheet.isInsertHyperlinksLocked()); } - - public void testWriteInsertRows() throws Exception { + + @Test + public void testWriteInsertRows() { assertFalse(sheet.isInsertRowsLocked()); sheet.lockInsertRows(true); assertFalse(sheet.isInsertRowsLocked()); @@ -157,8 +181,9 @@ public class TestSheetProtection extends TestCase { sheet.lockInsertRows(false); assertFalse(sheet.isInsertRowsLocked()); } - - public void testWritePivotTables() throws Exception { + + @Test + public void testWritePivotTables() { assertFalse(sheet.isPivotTablesLocked()); sheet.lockPivotTables(true); assertFalse(sheet.isPivotTablesLocked()); @@ -167,8 +192,9 @@ public class TestSheetProtection extends TestCase { sheet.lockPivotTables(false); assertFalse(sheet.isPivotTablesLocked()); } - - public void testWriteSort() throws Exception { + + @Test + public void testWriteSort() { assertFalse(sheet.isSortLocked()); sheet.lockSort(true); assertFalse(sheet.isSortLocked()); @@ -177,8 +203,9 @@ public class TestSheetProtection extends TestCase { sheet.lockSort(false); assertFalse(sheet.isSortLocked()); } - - public void testWriteObjects() throws Exception { + + @Test + public void testWriteObjects() { assertFalse(sheet.isObjectsLocked()); sheet.lockObjects(true); assertFalse(sheet.isObjectsLocked()); @@ -187,8 +214,9 @@ public class TestSheetProtection extends TestCase { sheet.lockObjects(false); assertFalse(sheet.isObjectsLocked()); } - - public void testWriteScenarios() throws Exception { + + @Test + public void testWriteScenarios() { assertFalse(sheet.isScenariosLocked()); sheet.lockScenarios(true); assertFalse(sheet.isScenariosLocked()); @@ -197,8 +225,9 @@ public class TestSheetProtection extends TestCase { sheet.lockScenarios(false); assertFalse(sheet.isScenariosLocked()); } - - public void testWriteSelectLockedCells() throws Exception { + + @Test + public void testWriteSelectLockedCells() { assertFalse(sheet.isSelectLockedCellsLocked()); sheet.lockSelectLockedCells(true); assertFalse(sheet.isSelectLockedCellsLocked()); @@ -207,8 +236,9 @@ public class TestSheetProtection extends TestCase { sheet.lockSelectLockedCells(false); assertFalse(sheet.isSelectLockedCellsLocked()); } - - public void testWriteSelectUnlockedCells() throws Exception { + + @Test + public void testWriteSelectUnlockedCells() { assertFalse(sheet.isSelectUnlockedCellsLocked()); sheet.lockSelectUnlockedCells(true); assertFalse(sheet.isSelectUnlockedCellsLocked()); @@ -218,43 +248,46 @@ public class TestSheetProtection extends TestCase { assertFalse(sheet.isSelectUnlockedCellsLocked()); } - public void testWriteSelectEnableLocking() throws Exception { - sheet = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx").getSheetAt(0); - - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); - - sheet.disableLocking(); - - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); + @Test + public void testWriteSelectEnableLocking() throws IOException { + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx")) { + sheet = workbook.getSheetAt(0); + + assertTrue(sheet.isAutoFilterLocked()); + assertTrue(sheet.isDeleteColumnsLocked()); + assertTrue(sheet.isDeleteRowsLocked()); + assertTrue(sheet.isFormatCellsLocked()); + assertTrue(sheet.isFormatColumnsLocked()); + assertTrue(sheet.isFormatRowsLocked()); + assertTrue(sheet.isInsertColumnsLocked()); + assertTrue(sheet.isInsertHyperlinksLocked()); + assertTrue(sheet.isInsertRowsLocked()); + assertTrue(sheet.isPivotTablesLocked()); + assertTrue(sheet.isSortLocked()); + assertTrue(sheet.isObjectsLocked()); + assertTrue(sheet.isScenariosLocked()); + assertTrue(sheet.isSelectLockedCellsLocked()); + assertTrue(sheet.isSelectUnlockedCellsLocked()); + assertTrue(sheet.isSheetLocked()); + + sheet.disableLocking(); + + assertFalse(sheet.isAutoFilterLocked()); + assertFalse(sheet.isDeleteColumnsLocked()); + assertFalse(sheet.isDeleteRowsLocked()); + assertFalse(sheet.isFormatCellsLocked()); + assertFalse(sheet.isFormatColumnsLocked()); + assertFalse(sheet.isFormatRowsLocked()); + assertFalse(sheet.isInsertColumnsLocked()); + assertFalse(sheet.isInsertHyperlinksLocked()); + assertFalse(sheet.isInsertRowsLocked()); + assertFalse(sheet.isPivotTablesLocked()); + assertFalse(sheet.isSortLocked()); + assertFalse(sheet.isObjectsLocked()); + assertFalse(sheet.isScenariosLocked()); + assertFalse(sheet.isSelectLockedCellsLocked()); + assertFalse(sheet.isSelectUnlockedCellsLocked()); + assertFalse(sheet.isSheetLocked()); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java index 9c7e9355dd..cc0eb9eab7 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java @@ -42,151 +42,162 @@ import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Ignore; import org.junit.Test; public class TestWorkbookProtection { @Test public void workbookAndRevisionPassword() throws Exception { - XSSFWorkbook workbook; String password = "test"; // validate password with an actual office file (Excel 2010) - workbook = openSampleWorkbook("workbookProtection-workbook_password_user_range-2010.xlsx"); - assertTrue(workbook.validateWorkbookPassword(password)); + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection-workbook_password_user_range-2010.xlsx")) { + assertTrue(workbook.validateWorkbookPassword(password)); + } // validate with another office file (Excel 2013) - workbook = openSampleWorkbook("workbookProtection-workbook_password-2013.xlsx"); - assertTrue(workbook.validateWorkbookPassword(password)); + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection-workbook_password-2013.xlsx")){ + assertTrue(workbook.validateWorkbookPassword(password)); + } - - workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - - // setting a null password shouldn't introduce the protection element - workbook.setWorkbookPassword(null, null); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // compare the hashes - workbook.setWorkbookPassword(password, null); - int hashVal = CryptoFunctions.createXorVerifier1(password); - int actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetWorkbookPassword().getStringValue(),16); - assertEquals(hashVal, actualVal); - assertTrue(workbook.validateWorkbookPassword(password)); - - // removing the password again - workbook.setWorkbookPassword(null, null); - assertFalse(workbook.getCTWorkbook().getWorkbookProtection().isSetWorkbookPassword()); - - // removing the whole protection structure - workbook.unLock(); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // setting a null password shouldn't introduce the protection element - workbook.setRevisionsPassword(null, null); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // compare the hashes - password = "T\u0400ST\u0100passwordWhichIsLongerThan15Chars"; - workbook.setRevisionsPassword(password, null); - hashVal = CryptoFunctions.createXorVerifier1(password); - actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetRevisionsPassword().getStringValue(),16); - assertEquals(hashVal, actualVal); - assertTrue(workbook.validateRevisionsPassword(password)); + + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { + // setting a null password shouldn't introduce the protection element + workbook.setWorkbookPassword(null, null); + assertNull(workbook.getCTWorkbook().getWorkbookProtection()); + + // compare the hashes + workbook.setWorkbookPassword(password, null); + int hashVal = CryptoFunctions.createXorVerifier1(password); + int actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetWorkbookPassword().getStringValue(), 16); + assertEquals(hashVal, actualVal); + assertTrue(workbook.validateWorkbookPassword(password)); + + // removing the password again + workbook.setWorkbookPassword(null, null); + assertFalse(workbook.getCTWorkbook().getWorkbookProtection().isSetWorkbookPassword()); + + // removing the whole protection structure + workbook.unLock(); + assertNull(workbook.getCTWorkbook().getWorkbookProtection()); + + // setting a null password shouldn't introduce the protection element + workbook.setRevisionsPassword(null, null); + assertNull(workbook.getCTWorkbook().getWorkbookProtection()); + + // compare the hashes + password = "T\u0400ST\u0100passwordWhichIsLongerThan15Chars"; + workbook.setRevisionsPassword(password, null); + hashVal = CryptoFunctions.createXorVerifier1(password); + actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetRevisionsPassword().getStringValue(), 16); + assertEquals(hashVal, actualVal); + assertTrue(workbook.validateRevisionsPassword(password)); + } } @Test public void shouldReadWorkbookProtection() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isStructureLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isRevisionLocked()); - - workbook = openSampleWorkbook("workbookProtection_workbook_structure_protected.xlsx"); - assertTrue(workbook.isStructureLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isRevisionLocked()); - - workbook = openSampleWorkbook("workbookProtection_workbook_windows_protected.xlsx"); - assertTrue(workbook.isWindowsLocked()); - assertFalse(workbook.isStructureLocked()); - assertFalse(workbook.isRevisionLocked()); - - workbook = openSampleWorkbook("workbookProtection_workbook_revision_protected.xlsx"); - assertTrue(workbook.isRevisionLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isStructureLocked()); + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { + assertFalse(workbook.isStructureLocked()); + assertFalse(workbook.isWindowsLocked()); + assertFalse(workbook.isRevisionLocked()); + } + + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_workbook_structure_protected.xlsx")) { + assertTrue(workbook.isStructureLocked()); + assertFalse(workbook.isWindowsLocked()); + assertFalse(workbook.isRevisionLocked()); + } + + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_workbook_windows_protected.xlsx")) { + assertTrue(workbook.isWindowsLocked()); + assertFalse(workbook.isStructureLocked()); + assertFalse(workbook.isRevisionLocked()); + } + + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_workbook_revision_protected.xlsx")) { + assertTrue(workbook.isRevisionLocked()); + assertFalse(workbook.isWindowsLocked()); + assertFalse(workbook.isStructureLocked()); + } } @Test public void shouldWriteStructureLock() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isStructureLocked()); + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { + assertFalse(workbook.isStructureLocked()); - workbook.lockStructure(); + workbook.lockStructure(); - assertTrue(workbook.isStructureLocked()); + assertTrue(workbook.isStructureLocked()); - workbook.unLockStructure(); + workbook.unLockStructure(); - assertFalse(workbook.isStructureLocked()); + assertFalse(workbook.isStructureLocked()); + } } @Test public void shouldWriteWindowsLock() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isWindowsLocked()); + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { + assertFalse(workbook.isWindowsLocked()); - workbook.lockWindows(); + workbook.lockWindows(); - assertTrue(workbook.isWindowsLocked()); + assertTrue(workbook.isWindowsLocked()); - workbook.unLockWindows(); + workbook.unLockWindows(); - assertFalse(workbook.isWindowsLocked()); + assertFalse(workbook.isWindowsLocked()); + } } @Test public void shouldWriteRevisionLock() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isRevisionLocked()); + try (XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx")) { + assertFalse(workbook.isRevisionLocked()); - workbook.lockRevision(); + workbook.lockRevision(); - assertTrue(workbook.isRevisionLocked()); + assertTrue(workbook.isRevisionLocked()); - workbook.unLockRevision(); + workbook.unLockRevision(); - assertFalse(workbook.isRevisionLocked()); + assertFalse(workbook.isRevisionLocked()); + } } @SuppressWarnings("resource") @Test public void testHashPassword() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.lockRevision(); - wb.setRevisionsPassword("test", HashAlgorithm.sha1); - - wb = writeOutAndReadBack(wb); - - assertTrue(wb.isRevisionLocked()); - assertTrue(wb.validateRevisionsPassword("test")); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + wb.lockRevision(); + wb.setRevisionsPassword("test", HashAlgorithm.sha1); + + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { + + assertTrue(wbBack.isRevisionLocked()); + assertTrue(wbBack.validateRevisionsPassword("test")); + } + } } @SuppressWarnings("resource") @Test public void testIntegration() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("Testing purpose sheet"); - assertFalse(wb.isRevisionLocked()); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + wb.createSheet("Testing purpose sheet"); + assertFalse(wb.isRevisionLocked()); - wb.lockRevision(); - wb.setRevisionsPassword("test", null); + wb.lockRevision(); + wb.setRevisionsPassword("test", null); - wb = writeOutAndReadBack(wb); - - assertTrue(wb.isRevisionLocked()); - assertTrue(wb.validateRevisionsPassword("test")); + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { + + assertTrue(wbBack.isRevisionLocked()); + assertTrue(wbBack.validateRevisionsPassword("test")); + } + } } @Test @@ -194,43 +205,43 @@ public class TestWorkbookProtection { final String password = "abc123"; final String sheetName = "TestSheet1"; final String cellValue = "customZipEntrySource"; - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet1 = workbook.createSheet(sheetName); - XSSFRow row1 = sheet1.createRow(1); - XSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - File tf1 = TempFile.createTempFile("poitest", ".xlsx"); - FileOutputStream fos1 = new FileOutputStream(tf1); - workbook.write(fos1); - IOUtils.closeQuietly(fos1); - POIFSFileSystem poiFileSystem = new POIFSFileSystem(); - EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = encryptionInfo.getEncryptor(); - enc.confirmPassword(password); - FileInputStream fis = new FileInputStream(tf1); - OPCPackage opc = OPCPackage.open(fis); - IOUtils.closeQuietly(fis); - try { - OutputStream os = enc.getDataStream(poiFileSystem); - opc.save(os); - IOUtils.closeQuietly(os); - } finally { - IOUtils.closeQuietly(opc); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet1 = workbook.createSheet(sheetName); + XSSFRow row1 = sheet1.createRow(1); + XSSFCell cell1 = row1.createCell(1); + cell1.setCellValue(cellValue); + File tf1 = TempFile.createTempFile("poitest", ".xlsx"); + FileOutputStream fos1 = new FileOutputStream(tf1); + workbook.write(fos1); + IOUtils.closeQuietly(fos1); + POIFSFileSystem poiFileSystem = new POIFSFileSystem(); + EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.agile); + Encryptor enc = encryptionInfo.getEncryptor(); + enc.confirmPassword(password); + FileInputStream fis = new FileInputStream(tf1); + OPCPackage opc = OPCPackage.open(fis); + IOUtils.closeQuietly(fis); + try { + OutputStream os = enc.getDataStream(poiFileSystem); + opc.save(os); + IOUtils.closeQuietly(os); + } finally { + IOUtils.closeQuietly(opc); + } + assertTrue(tf1.delete()); + FileOutputStream fos2 = new FileOutputStream(tf1); + poiFileSystem.writeFilesystem(fos2); + IOUtils.closeQuietly(fos2); + workbook.close(); + fis = new FileInputStream(tf1); + POIFSFileSystem poiFileSystem2 = new POIFSFileSystem(fis); + IOUtils.closeQuietly(fis); + EncryptionInfo encryptionInfo2 = new EncryptionInfo(poiFileSystem2); + Decryptor decryptor = encryptionInfo2.getDecryptor(); + decryptor.verifyPassword(password); + XSSFWorkbook workbook2 = new XSSFWorkbook(decryptor.getDataStream(poiFileSystem2)); + workbook2.close(); + assertTrue(tf1.delete()); } - tf1.delete(); - FileOutputStream fos2 = new FileOutputStream(tf1); - poiFileSystem.writeFilesystem(fos2); - IOUtils.closeQuietly(fos2); - workbook.close(); - fis = new FileInputStream(tf1); - POIFSFileSystem poiFileSystem2 = new POIFSFileSystem(fis); - IOUtils.closeQuietly(fis); - EncryptionInfo encryptionInfo2 = new EncryptionInfo(poiFileSystem2); - Decryptor decryptor = encryptionInfo2.getDecryptor(); - decryptor.verifyPassword(password); - XSSFWorkbook workbook2 = new XSSFWorkbook(decryptor.getDataStream(poiFileSystem2)); - workbook2.close(); - tf1.delete(); } - } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java index 7bf1cf391f..d0ea0f5989 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java @@ -28,29 +28,24 @@ import org.apache.poi.openxml4j.opc.PackagePart; import org.junit.Test; public class TestXSSFBSharedStringsTable { - - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); @Test public void testBasic() throws Exception { + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsb"))) { + List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.bin")); + assertEquals(1, parts.size()); - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsb")); - List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.bin")); - assertEquals(1, parts.size()); - - XSSFBSharedStringsTable rtbl = new XSSFBSharedStringsTable(parts.get(0)); - List strings = rtbl.getItems(); - assertEquals(49, strings.size()); + XSSFBSharedStringsTable rtbl = new XSSFBSharedStringsTable(parts.get(0)); + List strings = rtbl.getItems(); + assertEquals(49, strings.size()); - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getEntryAt(3)); - assertEquals(55, rtbl.getCount()); - assertEquals(49, rtbl.getUniqueCount()); - - //TODO: add in tests for phonetic runs + assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); + assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getEntryAt(3)); + assertEquals(55, rtbl.getCount()); + assertEquals(49, rtbl.getUniqueCount()); + //TODO: add in tests for phonetic runs + } } - - } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java index 992517dfc6..00f9e5984b 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java @@ -30,25 +30,21 @@ import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.junit.Test; public class TestXSSFBSheetHyperlinkManager { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); @Test public void testBasic() throws Exception { - - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("hyperlink.xlsb")); - XSSFBReader reader = new XSSFBReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) reader.getSheetsData(); - it.next(); - XSSFBHyperlinksTable manager = new XSSFBHyperlinksTable(it.getSheetPart()); - List records = manager.getHyperLinks().get(new CellAddress(0, 0)); - assertNotNull(records); - assertEquals(1, records.size()); - XSSFHyperlinkRecord record = records.get(0); - assertEquals("http://tika.apache.org/", record.getLocation()); - assertEquals("rId2", record.getRelId()); - + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("hyperlink.xlsb"))) { + XSSFBReader reader = new XSSFBReader(pkg); + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) reader.getSheetsData(); + it.next(); + XSSFBHyperlinksTable manager = new XSSFBHyperlinksTable(it.getSheetPart()); + List records = manager.getHyperLinks().get(new CellAddress(0, 0)); + assertNotNull(records); + assertEquals(1, records.size()); + XSSFHyperlinkRecord record = records.get(0); + assertEquals("http://tika.apache.org/", record.getLocation()); + assertEquals("rId2", record.getRelId()); + } } - - } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java index 4b5e62cc5c..be6db36d42 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java @@ -39,47 +39,47 @@ public final class TestReadOnlySharedStringsTable extends TestCase { private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); public void testParse() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); - assertEquals(1, parts.size()); - - SharedStringsTable stbl = new SharedStringsTable(parts.get(0)); - ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0)); - - assertEquals(stbl.getCount(), rtbl.getCount()); - assertEquals(stbl.getUniqueCount(), rtbl.getUniqueCount()); - - assertEquals(stbl.getItems().size(), stbl.getUniqueCount()); - assertEquals(rtbl.getItems().size(), rtbl.getUniqueCount()); - for(int i=0; i < stbl.getUniqueCount(); i++){ - CTRst i1 = stbl.getEntryAt(i); - String i2 = rtbl.getEntryAt(i); - assertEquals(i1.getT(), i2); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { + List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); + assertEquals(1, parts.size()); + + SharedStringsTable stbl = new SharedStringsTable(parts.get(0)); + ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0)); + + assertEquals(stbl.getCount(), rtbl.getCount()); + assertEquals(stbl.getUniqueCount(), rtbl.getUniqueCount()); + + assertEquals(stbl.getItems().size(), stbl.getUniqueCount()); + assertEquals(rtbl.getItems().size(), rtbl.getUniqueCount()); + for (int i = 0; i < stbl.getUniqueCount(); i++) { + CTRst i1 = stbl.getEntryAt(i); + String i2 = rtbl.getEntryAt(i); + assertEquals(i1.getT(), i2); + } } - } //51519 public void testPhoneticRuns() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsx")); - List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); - assertEquals(1, parts.size()); - - ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0), true); - List strings = rtbl.getItems(); - assertEquals(49, strings.size()); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsx"))) { + List < PackagePart > parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); + assertEquals(1, parts.size()); - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3", rtbl.getEntryAt(3)); + ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0), true); + List strings = rtbl.getItems(); + assertEquals(49, strings.size()); - //now do not include phonetic runs - rtbl = new ReadOnlySharedStringsTable(parts.get(0), false); - strings = rtbl.getItems(); - assertEquals(49, strings.size()); + assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); + assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3", rtbl.getEntryAt(3)); - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getEntryAt(3)); + //now do not include phonetic runs + rtbl =new ReadOnlySharedStringsTable(parts.get(0),false); + strings = rtbl.getItems(); + assertEquals(49, strings.size()); + assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); + assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getEntryAt(3)); + } } public void testEmptySSTOnPackageObtainedViaWorkbook() throws Exception { @@ -90,8 +90,9 @@ public final class TestReadOnlySharedStringsTable extends TestCase { } public void testEmptySSTOnPackageDirect() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("noSharedStringTable.xlsx")); - assertEmptySST(pkg); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("noSharedStringTable.xlsx"))) { + assertEmptySST(pkg); + } } private void assertEmptySST(OPCPackage pkg) throws IOException, SAXException { @@ -100,5 +101,4 @@ public final class TestReadOnlySharedStringsTable extends TestCase { assertEquals(0, sst.getUniqueCount()); assertNull(sst.getItems()); // same state it's left in if fed a package which has no SST part. } - } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java index a35bbdd133..f51b47a548 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java @@ -120,40 +120,41 @@ public class TestXSSFBReader { @Test public void testAbsPath() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("testVarious.xlsb")); - XSSFBReader r = new XSSFBReader(pkg); - assertEquals("C:\\Users\\tallison\\Desktop\\working\\xlsb\\", r.getAbsPathMetadata()); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("testVarious.xlsb"))) { + XSSFBReader r = new XSSFBReader(pkg); + assertEquals("C:\\Users\\tallison\\Desktop\\working\\xlsb\\", r.getAbsPathMetadata()); + } } private List getSheets(String testFileName) throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream(testFileName)); - List sheetTexts = new ArrayList<>(); - XSSFBReader r = new XSSFBReader(pkg); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream(testFileName))) { + List sheetTexts = new ArrayList<>(); + XSSFBReader r = new XSSFBReader(pkg); // assertNotNull(r.getWorkbookData()); - // assertNotNull(r.getSharedStringsData()); - assertNotNull(r.getXSSFBStylesTable()); - XSSFBSharedStringsTable sst = new XSSFBSharedStringsTable(pkg); - XSSFBStylesTable xssfbStylesTable = r.getXSSFBStylesTable(); - XSSFBReader.SheetIterator it = (XSSFBReader.SheetIterator) r.getSheetsData(); - - while (it.hasNext()) { - InputStream is = it.next(); - String name = it.getSheetName(); - TestSheetHandler testSheetHandler = new TestSheetHandler(); - testSheetHandler.startSheet(name); - XSSFBSheetHandler sheetHandler = new XSSFBSheetHandler(is, - xssfbStylesTable, - it.getXSSFBSheetComments(), - sst, testSheetHandler, - new DataFormatter(), - false); - sheetHandler.parse(); - testSheetHandler.endSheet(); - sheetTexts.add(testSheetHandler.toString()); + // assertNotNull(r.getSharedStringsData()); + assertNotNull(r.getXSSFBStylesTable()); + XSSFBSharedStringsTable sst = new XSSFBSharedStringsTable(pkg); + XSSFBStylesTable xssfbStylesTable = r.getXSSFBStylesTable(); + XSSFBReader.SheetIterator it = (XSSFBReader.SheetIterator) r.getSheetsData(); + + while (it.hasNext()) { + InputStream is = it.next(); + String name = it.getSheetName(); + TestSheetHandler testSheetHandler = new TestSheetHandler(); + testSheetHandler.startSheet(name); + XSSFBSheetHandler sheetHandler = new XSSFBSheetHandler(is, + xssfbStylesTable, + it.getXSSFBSheetComments(), + sst, testSheetHandler, + new DataFormatter(), + false); + sheetHandler.parse(); + testSheetHandler.endSheet(); + sheetTexts.add(testSheetHandler.toString()); + } + return sheetTexts; } - return sheetTexts; - } @Test diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java index b25d5f478b..272f0c9974 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java @@ -51,72 +51,76 @@ public final class TestXSSFReader { @Test public void testGetBits() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - XSSFReader r = new XSSFReader(pkg); + XSSFReader r = new XSSFReader(pkg); - assertNotNull(r.getWorkbookData()); - assertNotNull(r.getSharedStringsData()); - assertNotNull(r.getStylesData()); + assertNotNull(r.getWorkbookData()); + assertNotNull(r.getSharedStringsData()); + assertNotNull(r.getStylesData()); - assertNotNull(r.getSharedStringsTable()); - assertNotNull(r.getStylesTable()); + assertNotNull(r.getSharedStringsTable()); + assertNotNull(r.getStylesTable()); + } } @Test public void testStyles() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - - assertEquals(3, r.getStylesTable().getFonts().size()); - assertEquals(0, r.getStylesTable().getNumDataFormats()); - - // The Styles Table should have the themes associated with it too - assertNotNull(r.getStylesTable().getTheme()); - - // Check we get valid data for the two - assertNotNull(r.getStylesData()); - assertNotNull(r.getThemesData()); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { + + XSSFReader r = new XSSFReader(pkg); + + assertEquals(3, r.getStylesTable().getFonts().size()); + assertEquals(0, r.getStylesTable().getNumDataFormats()); + + // The Styles Table should have the themes associated with it too + assertNotNull(r.getStylesTable().getTheme()); + + // Check we get valid data for the two + assertNotNull(r.getStylesData()); + assertNotNull(r.getThemesData()); + } } @Test public void testStrings() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { - XSSFReader r = new XSSFReader(pkg); + XSSFReader r = new XSSFReader(pkg); - assertEquals(11, r.getSharedStringsTable().getItems().size()); - assertEquals("Test spreadsheet", new XSSFRichTextString(r.getSharedStringsTable().getEntryAt(0)).toString()); + assertEquals(11, r.getSharedStringsTable().getItems().size()); + assertEquals("Test spreadsheet", new XSSFRichTextString(r.getSharedStringsTable().getEntryAt(0)).toString()); + } } @Test public void testSheets() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - byte[] data = new byte[4096]; - - // By r:id - assertNotNull(r.getSheet("rId2")); - int read = IOUtils.readFully(r.getSheet("rId2"), data); - assertEquals(974, read); - - // All - Iterator it = r.getSheetsData(); - - int count = 0; - while(it.hasNext()) { - count++; - InputStream inp = it.next(); - assertNotNull(inp); - read = IOUtils.readFully(inp, data); - inp.close(); - - assertTrue(read > 400); - assertTrue(read < 1500); - } - assertEquals(3, count); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx"))) { + + XSSFReader r = new XSSFReader(pkg); + byte[] data = new byte[4096]; + + // By r:id + assertNotNull(r.getSheet("rId2")); + int read = IOUtils.readFully(r.getSheet("rId2"), data); + assertEquals(974, read); + + // All + Iterator it = r.getSheetsData(); + + int count = 0; + while (it.hasNext()) { + count++; + InputStream inp = it.next(); + assertNotNull(inp); + read = IOUtils.readFully(inp, data); + inp.close(); + + assertTrue(read > 400); + assertTrue(read < 1500); + } + assertEquals(3, count); + } } /** @@ -125,82 +129,82 @@ public final class TestXSSFReader { */ @Test public void testOrderOfSheets() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("reordered_sheets.xlsx")); + try (OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("reordered_sheets.xlsx"))) { - XSSFReader r = new XSSFReader(pkg); + XSSFReader r = new XSSFReader(pkg); - String[] sheetNames = {"Sheet4", "Sheet2", "Sheet3", "Sheet1"}; - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator)r.getSheetsData(); + String[] sheetNames = {"Sheet4", "Sheet2", "Sheet3", "Sheet1"}; + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - int count = 0; - while(it.hasNext()) { - InputStream inp = it.next(); - assertNotNull(inp); - inp.close(); + int count = 0; + while (it.hasNext()) { + InputStream inp = it.next(); + assertNotNull(inp); + inp.close(); - assertEquals(sheetNames[count], it.getSheetName()); - count++; - } - assertEquals(4, count); + assertEquals(sheetNames[count], it.getSheetName()); + count++; + } + assertEquals(4, count); + } } @Test public void testComments() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("comments.xlsx"); - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator)r.getSheetsData(); - - int count = 0; - while(it.hasNext()) { - count++; - InputStream inp = it.next(); - inp.close(); - - if(count == 1) { - assertNotNull(it.getSheetComments()); - CommentsTable ct = it.getSheetComments(); - assertEquals(1, ct.getNumberOfAuthors()); - assertEquals(3, ct.getNumberOfComments()); - } else { - assertNull(it.getSheetComments()); - } + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("comments.xlsx")) { + XSSFReader r = new XSSFReader(pkg); + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); + + int count = 0; + while (it.hasNext()) { + count++; + InputStream inp = it.next(); + inp.close(); + + if (count == 1) { + assertNotNull(it.getSheetComments()); + CommentsTable ct = it.getSheetComments(); + assertEquals(1, ct.getNumberOfAuthors()); + assertEquals(3, ct.getNumberOfComments()); + } else { + assertNull(it.getSheetComments()); + } + } + assertEquals(3, count); } - assertEquals(3, count); } /** * Iterating over a workbook with chart sheets in it, using the * XSSFReader method - * @throws Exception */ @Test public void test50119() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithChartSheet.xlsx"); - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator)r.getSheetsData(); - - while(it.hasNext()) - { - InputStream stream = it.next(); - stream.close(); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithChartSheet.xlsx")) { + XSSFReader r = new XSSFReader(pkg); + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); + + while (it.hasNext()) { + InputStream stream = it.next(); + stream.close(); + } } } /** * Test text extraction from text box using getShapes() - * - * @throws Exception */ @Test public void testShapes() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithTextBox.xlsx"); - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - String text = getShapesString(it); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithTextBox.xlsx")) { + XSSFReader r = new XSSFReader(pkg); + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); + + String text = getShapesString(it); + assertContains(text, "Line 1"); + assertContains(text, "Line 2"); + assertContains(text, "Line 3"); + } } private String getShapesString(XSSFReader.SheetIterator it) { @@ -222,25 +226,26 @@ public final class TestXSSFReader { @Test public void testBug57914() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("57914.xlsx"); - final XSSFReader r; - - // for now expect this to fail, when we fix 57699, this one should fail so we know we should adjust - // this test as well - try { - r = new XSSFReader(pkg); - fail("This will fail until bug 57699 is fixed"); - } catch (POIXMLException e) { - assertContains(e.getMessage(), "57699"); - return; - } + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("57914.xlsx")) { + final XSSFReader r; + + // for now expect this to fail, when we fix 57699, this one should fail so we know we should adjust + // this test as well + try { + r = new XSSFReader(pkg); + fail("This will fail until bug 57699 is fixed"); + } catch (POIXMLException e) { + assertContains(e.getMessage(), "57699"); + return; + } - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); + XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - String text = getShapesString(it); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); + String text = getShapesString(it); + assertContains(text, "Line 1"); + assertContains(text, "Line 2"); + assertContains(text, "Line 3"); + } } /** @@ -249,21 +254,20 @@ public final class TestXSSFReader { */ @Test public void test58747() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("58747.xlsx"); - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); - assertNotNull(strings); - XSSFReader reader = new XSSFReader(pkg); - StylesTable styles = reader.getStylesTable(); - assertNotNull(styles); - - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - assertEquals(true, iter.hasNext()); - iter.next(); - - assertEquals(false, iter.hasNext()); - assertEquals("Orders", iter.getSheetName()); - - pkg.close(); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("58747.xlsx")) { + ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); + assertNotNull(strings); + XSSFReader reader = new XSSFReader(pkg); + StylesTable styles = reader.getStylesTable(); + assertNotNull(styles); + + XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); + assertTrue(iter.hasNext()); + iter.next(); + + assertFalse(iter.hasNext()); + assertEquals("Orders", iter.getSheetName()); + } } /** @@ -272,18 +276,17 @@ public final class TestXSSFReader { */ @Test public void testSheetWithNoRelationshipId() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("60825.xlsx"); - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); - assertNotNull(strings); - XSSFReader reader = new XSSFReader(pkg); - StylesTable styles = reader.getStylesTable(); - assertNotNull(styles); - - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - assertNotNull(iter.next()); - assertFalse(iter.hasNext()); - - pkg.close(); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("60825.xlsx")) { + ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); + assertNotNull(strings); + XSSFReader reader = new XSSFReader(pkg); + StylesTable styles = reader.getStylesTable(); + assertNotNull(styles); + + XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); + assertNotNull(iter.next()); + assertFalse(iter.hasNext()); + } } /** @@ -300,18 +303,18 @@ public final class TestXSSFReader { */ @Test public void test61034() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("61034.xlsx"); - XSSFReader reader = new XSSFReader(pkg); - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - Set seen = new HashSet<>(); - while (iter.hasNext()) { - InputStream stream = iter.next(); - String sheetName = iter.getSheetName(); - assertNotContained(seen, sheetName); - seen.add(sheetName); - stream.close(); + try (OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("61034.xlsx")) { + XSSFReader reader = new XSSFReader(pkg); + XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); + Set seen = new HashSet<>(); + while (iter.hasNext()) { + InputStream stream = iter.next(); + String sheetName = iter.getSheetName(); + assertNotContained(seen, sheetName); + seen.add(sheetName); + stream.close(); + } } - pkg.close(); } @Test diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java index 45738116fe..492aad3106 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java @@ -17,8 +17,10 @@ package org.apache.poi.xwpf.usermodel; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -104,23 +106,23 @@ public class TestXWPFRun { // True values: "true", "1", "on" bold.setVal(STOnOff.TRUE); - assertEquals(true, run.isBold()); + assertTrue(run.isBold()); bold.setVal(STOnOff.X_1); - assertEquals(true, run.isBold()); + assertTrue(run.isBold()); bold.setVal(STOnOff.ON); - assertEquals(true, run.isBold()); + assertTrue(run.isBold()); // False values: "false", "0", "off" bold.setVal(STOnOff.FALSE); - assertEquals(false, run.isBold()); + assertFalse(run.isBold()); bold.setVal(STOnOff.X_0); - assertEquals(false, run.isBold()); + assertFalse(run.isBold()); bold.setVal(STOnOff.OFF); - assertEquals(false, run.isBold()); + assertFalse(run.isBold()); } @Test @@ -129,7 +131,7 @@ public class TestXWPFRun { rpr.addNewB().setVal(STOnOff.TRUE); XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(true, run.isBold()); + assertTrue(run.isBold()); run.setBold(false); // Implementation detail: POI natively prefers , @@ -143,7 +145,7 @@ public class TestXWPFRun { rpr.addNewI().setVal(STOnOff.TRUE); XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(true, run.isItalic()); + assertTrue(run.isItalic()); run.setItalic(false); assertEquals(STOnOff.FALSE, rpr.getI().getVal()); @@ -155,7 +157,7 @@ public class TestXWPFRun { rpr.addNewStrike().setVal(STOnOff.TRUE); XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(true, run.isStrikeThrough()); + assertTrue(run.isStrikeThrough()); run.setStrikeThrough(false); assertEquals(STOnOff.FALSE, rpr.getStrike().getVal()); @@ -297,17 +299,17 @@ public class TestXWPFRun { run = p.getRuns().get(0); assertEquals("This is a test document", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); run = p.getRuns().get(1); assertEquals(".", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); // Next paragraph is all in one style, but a different one @@ -317,11 +319,11 @@ public class TestXWPFRun { run = p.getRuns().get(0); assertEquals("This bit is in bold and italic", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(true, run.getCTR().getRPr().isSetB()); - assertEquals(false, run.getCTR().getRPr().getB().isSetVal()); + assertTrue(run.isBold()); + assertTrue(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertTrue(run.getCTR().getRPr().isSetB()); + assertFalse(run.getCTR().getRPr().getB().isSetVal()); // Back to normal @@ -331,10 +333,10 @@ public class TestXWPFRun { run = p.getRuns().get(0); assertEquals("Back to normal", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); // Different styles in one paragraph @@ -344,75 +346,75 @@ public class TestXWPFRun { run = p.getRuns().get(0); assertEquals("This contains ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); run = p.getRuns().get(1); assertEquals("BOLD", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); + assertTrue(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); run = p.getRuns().get(2); assertEquals(", ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); run = p.getRuns().get(3); assertEquals("ITALIC", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); + assertFalse(run.isBold()); + assertTrue(run.isItalic()); + assertFalse(run.isStrikeThrough()); run = p.getRuns().get(4); assertEquals(" and ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); run = p.getRuns().get(5); assertEquals("BOTH", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); + assertTrue(run.isBold()); + assertTrue(run.isItalic()); + assertFalse(run.isStrikeThrough()); run = p.getRuns().get(6); assertEquals(", as well as ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); run = p.getRuns().get(7); assertEquals("RED", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); run = p.getRuns().get(8); assertEquals(" and ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); run = p.getRuns().get(9); assertEquals("YELLOW", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); run = p.getRuns().get(10); assertEquals(" text.", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); + assertFalse(run.isBold()); + assertFalse(run.isItalic()); + assertFalse(run.isStrikeThrough()); + assertNull(run.getCTR().getRPr()); doc.close(); } @@ -643,7 +645,7 @@ public class TestXWPFRun { } @Test - public void testSetters() throws IOException { + public void testSetters() { XWPFDocument document = new XWPFDocument(); final XWPFRun run = document.createParagraph().createRun(); @@ -679,12 +681,12 @@ public class TestXWPFRun { XWPFDocument document = new XWPFDocument(); final XWPFRun run = document.createParagraph().createRun(); assertEquals(STHighlightColor.NONE, run.getTextHightlightColor()); - assertEquals(false, run.isHighlighted()); + assertFalse(run.isHighlighted()); run.setTextHighlightColor("darkGreen"); // See 17.18.40 ST_HighlightColor (Text Highlight Colors) assertEquals(STHighlightColor.DARK_GREEN, run.getTextHightlightColor()); - assertEquals(true, run.isHighlighted()); + assertTrue(run.isHighlighted()); run.setTextHighlightColor("none"); - assertEquals(false, run.isHighlighted()); + assertFalse(run.isHighlighted()); document.close(); } @@ -693,11 +695,11 @@ public class TestXWPFRun { public void testSetGetVanish() throws IOException { XWPFDocument document = new XWPFDocument(); final XWPFRun run = document.createParagraph().createRun(); - assertEquals(false, run.isVanish()); + assertFalse(run.isVanish()); run.setVanish(true); - assertEquals(true, run.isVanish()); + assertTrue(run.isVanish()); run.setVanish(false); - assertEquals(false, run.isVanish()); + assertFalse(run.isVanish()); document.close(); } @@ -727,7 +729,6 @@ public class TestXWPFRun { assertEquals(STVerticalAlignRun.BASELINE, rpr.getVertAlign().getVal()); } - @Test public void testSetGetEmphasisMark() throws IOException { XWPFDocument document = new XWPFDocument(); @@ -780,7 +781,9 @@ public class TestXWPFRun { run.setStyle(styleId); String candStyleId = run.getCTR().getRPr().getRStyle().getVal(); assertNotNull("Expected to find a run style ID", candStyleId); - assertEquals(styleId, candStyleId); + assertEquals(styleId, candStyleId); + + document.close(); } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowDumper.java b/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowDumper.java index 0d9664ba97..2612c3f4bb 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowDumper.java +++ b/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowDumper.java @@ -77,19 +77,19 @@ public final class SlideShowDumper { filename = args[1]; } - POIFSFileSystem poifs = new POIFSFileSystem(new File(filename)); - SlideShowDumper foo = new SlideShowDumper(poifs, System.out); - poifs.close(); - - if(args.length > 1) { - if(args[0].equalsIgnoreCase("-escher")) { - foo.setDDFEscher(true); - } else { - foo.setBasicEscher(true); + try (POIFSFileSystem poifs = new POIFSFileSystem(new File(filename))) { + SlideShowDumper foo = new SlideShowDumper(poifs, System.out); + + if(args.length > 1) { + if(args[0].equalsIgnoreCase("-escher")) { + foo.setDDFEscher(true); + } else { + foo.setBasicEscher(true); + } } - } - foo.printDump(); + foo.printDump(); + } } /** diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java index 7d001b2716..c040499b0d 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java +++ b/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java @@ -41,38 +41,36 @@ public final class TextStyleListing { System.exit(1); } - HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0]); + try (HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0])) { + // Find the documents, and then their SLWT + Record[] records = ss.getRecords(); + for (Record record : records) { + if (record.getRecordType() == 1000L) { + Record[] docChildren = record.getChildRecords(); + for (Record docChild : docChildren) { + if (docChild instanceof SlideListWithText) { + Record[] slwtChildren = docChild.getChildRecords(); - // Find the documents, and then their SLWT - Record[] records = ss.getRecords(); - for (Record record : records) { - if (record.getRecordType() == 1000L) { - Record[] docChildren = record.getChildRecords(); - for (Record docChild : docChildren) { - if (docChild instanceof SlideListWithText) { - Record[] slwtChildren = docChild.getChildRecords(); + int lastTextLen = -1; + for (Record slwtChild : slwtChildren) { + if (slwtChild instanceof TextCharsAtom) { + lastTextLen = ((TextCharsAtom) slwtChild).getText().length(); + } + if (slwtChild instanceof TextBytesAtom) { + lastTextLen = ((TextBytesAtom) slwtChild).getText().length(); + } - int lastTextLen = -1; - for (Record slwtChild : slwtChildren) { - if (slwtChild instanceof TextCharsAtom) { - lastTextLen = ((TextCharsAtom) slwtChild).getText().length(); - } - if (slwtChild instanceof TextBytesAtom) { - lastTextLen = ((TextBytesAtom) slwtChild).getText().length(); - } - - if (slwtChild instanceof StyleTextPropAtom) { - StyleTextPropAtom stpa = (StyleTextPropAtom) slwtChild; - stpa.setParentTextSize(lastTextLen); - showStyleTextPropAtom(stpa); + if (slwtChild instanceof StyleTextPropAtom) { + StyleTextPropAtom stpa = (StyleTextPropAtom) slwtChild; + stpa.setParentTextSize(lastTextLen); + showStyleTextPropAtom(stpa); + } } } } } } } - - ss.close(); } public static void showStyleTextPropAtom(StyleTextPropAtom stpa) { diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java index bf3641eb82..e50a23aac9 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java +++ b/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java @@ -43,79 +43,77 @@ public final class UserEditAndPersistListing { System.exit(1); } - // Create the slideshow object, for normal working with - HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0]); - fileContents = ss.getUnderlyingBytes(); - System.out.println(); - - // Find any persist ones first - int pos = 0; - for(Record r : ss.getRecords()) { - if(r.getRecordType() == 6001l) { - // PersistPtrFullBlock - System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")"); - } - if(r.getRecordType() == 6002l) { - // PersistPtrIncrementalBlock - System.out.println("Found PersistPtrIncrementalBlock at " + pos + " (" + Integer.toHexString(pos) + ")"); - PersistPtrHolder pph = (PersistPtrHolder)r; - - // Check the sheet offsets - Map sheetOffsets = pph.getSlideLocationsLookup(); - for(int id : pph.getKnownSlideIDs()) { - Integer offset = sheetOffsets.get(id); - - System.out.println(" Knows about sheet " + id); - System.out.println(" That sheet lives at " + offset); - - Record atPos = findRecordAtPos(offset.intValue()); - System.out.println(" The record at that pos is of type " + atPos.getRecordType()); - System.out.println(" The record at that pos has class " + atPos.getClass().getName()); - - if(! (atPos instanceof PositionDependentRecord)) { - System.out.println(" ** The record class isn't position aware! **"); + try (HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0])) { + fileContents = ss.getUnderlyingBytes(); + System.out.println(); + + // Find any persist ones first + int pos = 0; + for (Record r : ss.getRecords()) { + if (r.getRecordType() == 6001L) { + // PersistPtrFullBlock + System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")"); + } + if (r.getRecordType() == 6002L) { + // PersistPtrIncrementalBlock + System.out.println("Found PersistPtrIncrementalBlock at " + pos + " (" + Integer.toHexString(pos) + ")"); + PersistPtrHolder pph = (PersistPtrHolder) r; + + // Check the sheet offsets + Map sheetOffsets = pph.getSlideLocationsLookup(); + for (int id : pph.getKnownSlideIDs()) { + Integer offset = sheetOffsets.get(id); + + System.out.println(" Knows about sheet " + id); + System.out.println(" That sheet lives at " + offset); + + Record atPos = findRecordAtPos(offset.intValue()); + System.out.println(" The record at that pos is of type " + atPos.getRecordType()); + System.out.println(" The record at that pos has class " + atPos.getClass().getName()); + + if (!(atPos instanceof PositionDependentRecord)) { + System.out.println(" ** The record class isn't position aware! **"); + } } } + + // Increase the position by the on disk size + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + r.writeOut(baos); + pos += baos.size(); } - // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - pos += baos.size(); - } + System.out.println(); + + pos = 0; + // Now look for UserEditAtoms + for (Record r : ss.getRecords()) { + if (r instanceof UserEditAtom) { + UserEditAtom uea = (UserEditAtom) r; + System.out.println("Found UserEditAtom at " + pos + " (" + Integer.toHexString(pos) + ")"); + System.out.println(" lastUserEditAtomOffset = " + uea.getLastUserEditAtomOffset()); + System.out.println(" persistPointersOffset = " + uea.getPersistPointersOffset()); + System.out.println(" docPersistRef = " + uea.getDocPersistRef()); + System.out.println(" maxPersistWritten = " + uea.getMaxPersistWritten()); + } - System.out.println(); - - pos = 0; - // Now look for UserEditAtoms - for(Record r : ss.getRecords()) { - if(r instanceof UserEditAtom) { - UserEditAtom uea = (UserEditAtom)r; - System.out.println("Found UserEditAtom at " + pos + " (" + Integer.toHexString(pos) + ")"); - System.out.println(" lastUserEditAtomOffset = " + uea.getLastUserEditAtomOffset() ); - System.out.println(" persistPointersOffset = " + uea.getPersistPointersOffset() ); - System.out.println(" docPersistRef = " + uea.getDocPersistRef() ); - System.out.println(" maxPersistWritten = " + uea.getMaxPersistWritten() ); + // Increase the position by the on disk size + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + r.writeOut(baos); + pos += baos.size(); } - // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - pos += baos.size(); - } - - System.out.println(); + System.out.println(); - // Query the CurrentUserAtom - CurrentUserAtom cua = ss.getCurrentUserAtom(); - System.out.println("Checking Current User Atom"); - System.out.println(" Thinks the CurrentEditOffset is " + cua.getCurrentEditOffset()); - - System.out.println(); + // Query the CurrentUserAtom + CurrentUserAtom cua = ss.getCurrentUserAtom(); + System.out.println("Checking Current User Atom"); + System.out.println(" Thinks the CurrentEditOffset is " + cua.getCurrentEditOffset()); - ss.close(); + System.out.println(); + } } diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java index 420ae47484..cc926c9f08 100644 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java +++ b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java @@ -66,13 +66,14 @@ import org.apache.poi.util.POILogger; * "reader". It is only a very basic class for now */ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { + private static final POILogger logger = POILogFactory.getLogger(HSLFSlideShowImpl.class); + static final int UNSET_OFFSET = -1; //arbitrarily selected; may need to increase private static final int MAX_RECORD_LENGTH = 200_000_000; - // For logging - private POILogger logger = POILogFactory.getLogger(this.getClass()); + private static final String DUAL_STORAGE_NAME = "PP97_DUALSTORAGE"; // Holds metadata on where things are in our document private CurrentUserAtom currentUser; @@ -136,29 +137,35 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { public HSLFSlideShowImpl(DirectoryNode dir) throws IOException { super(handleDualStorage(dir)); - // First up, grab the "Current User" stream - // We need this before we can detect Encrypted Documents - readCurrentUserStream(); + try { + // First up, grab the "Current User" stream + // We need this before we can detect Encrypted Documents + readCurrentUserStream(); + + // Next up, grab the data that makes up the + // PowerPoint stream + readPowerPointStream(); - // Next up, grab the data that makes up the - // PowerPoint stream - readPowerPointStream(); + // Now, build records based on the PowerPoint stream + buildRecords(); - // Now, build records based on the PowerPoint stream - buildRecords(); + // Look for any other streams + readOtherStreams(); + } catch (RuntimeException | IOException e) { + // clean up the filesystem when we cannot read it here to avoid + // leaking file handles + dir.getFileSystem().close(); - // Look for any other streams - readOtherStreams(); + throw e; + } } private static DirectoryNode handleDualStorage(DirectoryNode dir) throws IOException { // when there's a dual storage entry, use it, as the outer document can't be read quite probably ... - String dualName = "PP97_DUALSTORAGE"; - if (!dir.hasEntry(dualName)) { + if (!dir.hasEntry(DUAL_STORAGE_NAME)) { return dir; } - dir = (DirectoryNode) dir.getEntry(dualName); - return dir; + return (DirectoryNode) dir.getEntry(DUAL_STORAGE_NAME); } /** @@ -834,7 +841,8 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { public void close() throws IOException { // only close the filesystem, if we are based on the root node. // embedded documents/slideshows shouldn't close the parent container - if (getDirectory().getParent() == null) { + if (getDirectory().getParent() == null || + getDirectory().getName().equals(DUAL_STORAGE_NAME)) { POIFSFileSystem fs = getDirectory().getFileSystem(); if (fs != null) { fs.close(); diff --git a/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java b/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java index 1b659d4f26..c6abb30117 100644 --- a/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java +++ b/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java @@ -96,7 +96,7 @@ public class CellFormatTestBase { } } - protected void runFormatTests(String workbookName, CellValue valueGetter) { + protected void runFormatTests(String workbookName, CellValue valueGetter) throws IOException { openWorkbook(workbookName); @@ -127,6 +127,8 @@ public class CellFormatTestBase { tryFormat(row.getRowNum(), expectedText, format, valueGetter, value); } } + + workbook.close(); } /**