diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2021-05-14 00:37:50 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2021-05-14 00:37:50 +0000 |
commit | 0614835c55f44ab6f3e9b0850ca51e0e53a65a49 (patch) | |
tree | 586c68c89edb0978a441facf0066ff56d84fa2c7 | |
parent | fe753d473788fc24030d7066654c56c33fff23b5 (diff) | |
download | poi-0614835c55f44ab6f3e9b0850ca51e0e53a65a49.tar.gz poi-0614835c55f44ab6f3e9b0850ca51e0e53a65a49.zip |
#65304 - Add commons-io as a dependency
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1889871 13f79535-47bb-0310-9956-ffa450edef68
288 files changed, 8170 insertions, 9147 deletions
diff --git a/build.gradle b/build.gradle index 2ee40a3092..debb97b3bf 100644 --- a/build.gradle +++ b/build.gradle @@ -100,6 +100,7 @@ subprojects { bouncyCastleVersion = '1.68' commonsCodecVersion = '1.15' commonsCompressVersion = '1.20' + commonsIoVersion = '2.8.0' commonsMathVersion = '3.6.1' junitVersion = '5.7.1' log4jVersion = '2.14.0' @@ -117,6 +118,8 @@ subprojects { tasks.withType(JavaCompile) { options.encoding = 'UTF-8' + options.compilerArgs << '-Xlint:unchecked' + options.deprecation = true } tasks.withType(Jar) { @@ -371,6 +374,7 @@ rat { excludes.add("**/out/**") excludes.add("**/*.iml") excludes.add("**/*.log") + excludes.add("**/gradle-wrapper.properties") excludes.add("**/main/java/org/apache/poi/**/*-chart-data.txt") excludes.add("poi/src/main/resources/org/apache/poi/sl/draw/geom/presetShapeDefinitions.xml") excludes.add("poi-ooxml/src/main/resources/org/apache/poi/xslf/usermodel/notesMaster.xml") @@ -266,6 +266,7 @@ under the License. <dependency prefix="main.commons-codec" artifact="commons-codec:commons-codec:1.15" usage="main"/> <dependency prefix="main.commons-collections4" artifact="org.apache.commons:commons-collections4:4.4" usage="main"/> <dependency prefix="main.commons-math3" artifact="org.apache.commons:commons-math3:3.6.1" usage="main"/> + <dependency prefix="main.commons-io" artifact="commons-io:commons-io:2.8.0" usage="main"/> <dependency prefix="main.com.zaxxer" artifact="com.zaxxer:SparseBitSet:1.2" usage="main"/> <dependency prefix="main.log4j-api" artifact="org.apache.logging.log4j:log4j-api:2.14.0" usage="main"/> @@ -430,6 +431,7 @@ under the License. <pathelement location="${main.commons-codec.jar}"/> <pathelement location="${main.commons-collections4.jar}"/> <pathelement location="${main.commons-math3.jar}"/> + <pathelement location="${main.commons-io.jar}"/> <pathelement location="${main.com.zaxxer.jar}"/> <pathelement location="${main.log4j-api.jar}"/> </path> @@ -737,6 +739,7 @@ under the License. <available file="${dsig.xmlsec.jar}"/> <available file="${main.commons-collections4.jar}"/> <available file="${main.commons-math3.jar}"/> + <available file="${main.commons-io.jar}"/> <available file="${main.com.zaxxer.jar}"/> <!-- we had some CI failures when the extracted files for JaCoCo were missing somehow... --> @@ -778,6 +781,7 @@ under the License. <downloadfile src="${jacoco.url}" dest="${jacoco.zip}"/> <downloadfile src="${main.commons-collections4.url}" dest="${main.commons-collections4.jar}"/> <downloadfile src="${main.commons-math3.url}" dest="${main.commons-math3.jar}"/> + <downloadfile src="${main.commons-io.url}" dest="${main.commons-io.jar}"/> <downloadfile src="${main.com.zaxxer.url}" dest="${main.com.zaxxer.jar}"/> <unzip src="${jacoco.zip}" dest="${util.lib}"> <patternset> @@ -2328,6 +2332,7 @@ under the License. <include name="commons-codec-*.jar"/> <include name="commons-collections4-*.jar"/> <include name="commons-math3-*.jar"/> + <include name="commons-io-*.jar"/> <include name="log4j-api-*.jar"/> <include name="SparseBitSet-*.jar"/> </fileset> @@ -2687,6 +2692,7 @@ under the License. <auxClasspath path="${ooxml.commons-compress.jar}" /> <auxClasspath path="${main.commons-collections4.jar}" /> <auxClasspath path="${main.commons-math3.jar}" /> + <auxClasspath path="${main.commons-io.jar}" /> <auxClasspath path="${main.commons-codec.jar}" /> <auxClasspath path="${main.commons-logging.jar}" /> <auxClasspath path="${main.log4j-api.jar}" /> diff --git a/maven/poi.pom b/maven/poi.pom index 743a3f3d79..13d7344021 100644 --- a/maven/poi.pom +++ b/maven/poi.pom @@ -77,6 +77,11 @@ <version>3.6.1</version> </dependency> <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>2.8.0</version> + </dependency> + <dependency> <groupId>com.zaxxer</groupId> <artifactId>SparseBitSet</artifactId> <version>1.2</version> diff --git a/osgi/README.md b/osgi/README.md index 01bbc68f49..f241dc973b 100644 --- a/osgi/README.md +++ b/osgi/README.md @@ -9,6 +9,7 @@ The bundle embeds all the jars from lib/main: - SparseBitSet - curvesapi - commons-math3 +- commons-io - commons-compress - commons-collections4 - commons-codec diff --git a/osgi/pom.xml b/osgi/pom.xml index 97afc8b4bb..b16e9f9302 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -101,6 +101,7 @@ SparseBitSet, curvesapi, commons-math3, + commons-io, commons-compress, commons-collections4, commons-codec, diff --git a/osgi/src/test/java/org/apache/poi/osgi/OSGiExtractorsIT.java b/osgi/src/test/java/org/apache/poi/osgi/OSGiExtractorsIT.java index 8ee1258fa4..3bf58a2b61 100755 --- a/osgi/src/test/java/org/apache/poi/osgi/OSGiExtractorsIT.java +++ b/osgi/src/test/java/org/apache/poi/osgi/OSGiExtractorsIT.java @@ -36,7 +36,7 @@ import org.ops4j.pax.exam.spi.reactors.PerClass; import java.awt.*; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import static org.junit.Assert.assertEquals; @@ -57,7 +57,7 @@ public class OSGiExtractorsIT extends BaseOSGiTestCase { box.setText("Hello, World!"); box.setAnchor(new Rectangle(36, 15, 648, 65)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ppt.write(out); return out.toByteArray(); } @@ -66,7 +66,7 @@ public class OSGiExtractorsIT extends BaseOSGiTestCase { Sheet s = wb.createSheet("OSGi"); s.createRow(0).createCell(0).setCellValue("Hello, World!"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); wb.write(out); return out.toByteArray(); diff --git a/osgi/src/test/java/org/apache/poi/osgi/OSGiSlideShowIT.java b/osgi/src/test/java/org/apache/poi/osgi/OSGiSlideShowIT.java index ef18f1cc95..9744c36ca9 100755 --- a/osgi/src/test/java/org/apache/poi/osgi/OSGiSlideShowIT.java +++ b/osgi/src/test/java/org/apache/poi/osgi/OSGiSlideShowIT.java @@ -28,7 +28,7 @@ import org.ops4j.pax.exam.spi.reactors.PerClass; import java.awt.*; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import java.util.List; import static org.junit.Assert.assertEquals; @@ -75,11 +75,12 @@ public class OSGiSlideShowIT extends BaseOSGiTestCase { } box2.setAnchor(new Rectangle(36, 80, 648, 400)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ppt.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - ppt = SlideShowFactory.create(bais); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + ppt.write(baos); + try (InputStream bais = baos.toInputStream()) { + ppt = SlideShowFactory.create(bais); + } + } assertEquals(1, ppt.getSlides().size()); slide = (Slide) ppt.getSlides().iterator().next(); assertEquals(2, slide.getShapes().size()); diff --git a/osgi/src/test/java/org/apache/poi/osgi/OSGiSpreadsheetIT.java b/osgi/src/test/java/org/apache/poi/osgi/OSGiSpreadsheetIT.java index 0ea95602c9..618b76e36c 100644 --- a/osgi/src/test/java/org/apache/poi/osgi/OSGiSpreadsheetIT.java +++ b/osgi/src/test/java/org/apache/poi/osgi/OSGiSpreadsheetIT.java @@ -29,7 +29,7 @@ import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import static org.junit.Assert.assertEquals; @@ -48,11 +48,12 @@ public class OSGiSpreadsheetIT extends BaseOSGiTestCase { s.createRow(0).createCell(0).setCellValue("With OSGi"); s.createRow(1).createCell(0).setCellFormula("SUM(A1:B3)"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - wb.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - wb = WorkbookFactory.create(bais); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + wb.write(baos); + try (InputStream bais = baos.toInputStream()) { + wb = WorkbookFactory.create(bais); + } + } assertEquals(1, wb.getNumberOfSheets()); s = wb.getSheet("OSGi"); diff --git a/poi-examples/src/main/java/org/apache/poi/examples/hpsf/WriteAuthorAndTitle.java b/poi-examples/src/main/java/org/apache/poi/examples/hpsf/WriteAuthorAndTitle.java index 94ceaf6c03..71f4d8aa93 100644 --- a/poi-examples/src/main/java/org/apache/poi/examples/hpsf/WriteAuthorAndTitle.java +++ b/poi-examples/src/main/java/org/apache/poi/examples/hpsf/WriteAuthorAndTitle.java @@ -24,7 +24,6 @@ import java.io.InputStream; import java.io.OutputStream; import org.apache.poi.hpsf.HPSFRuntimeException; -import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; @@ -165,7 +164,7 @@ public final class WriteAuthorAndTitle { de.createDocument(event.getName(), is); } - } catch (MarkUnsupportedException | WritingNotSupportedException | IOException | NoPropertySetStreamException ex) { + } catch (WritingNotSupportedException | IOException | NoPropertySetStreamException ex) { // According to the definition of the processPOIFSReaderEvent method we cannot pass checked // exceptions to the caller. throw new HPSFRuntimeException("Could not read file " + event.getPath() + "/" + event.getName(), ex); diff --git a/poi-examples/src/main/java/org/apache/poi/examples/hssf/usermodel/OfficeDrawing.java b/poi-examples/src/main/java/org/apache/poi/examples/hssf/usermodel/OfficeDrawing.java index 4603864d86..2cefd3d87f 100644 --- a/poi-examples/src/main/java/org/apache/poi/examples/hssf/usermodel/OfficeDrawing.java +++ b/poi-examples/src/main/java/org/apache/poi/examples/hssf/usermodel/OfficeDrawing.java @@ -17,11 +17,12 @@ package org.apache.poi.examples.hssf.usermodel; -import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.usermodel.HSSFChildAnchor; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFFont; @@ -188,14 +189,11 @@ public final class OfficeDrawing { } - private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException - { + private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException { int pictureIndex; try (FileInputStream fis = new FileInputStream(path); - ByteArrayOutputStream bos = new ByteArrayOutputStream()) { - int c; - while ((c = fis.read()) != -1) - bos.write(c); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + IOUtils.copy(fis, bos); pictureIndex = wb.addPicture(bos.toByteArray(), Workbook.PICTURE_TYPE_PNG); } return pictureIndex; diff --git a/poi-examples/src/main/java/org/apache/poi/examples/xssf/usermodel/CustomXMLMapping.java b/poi-examples/src/main/java/org/apache/poi/examples/xssf/usermodel/CustomXMLMapping.java index ebc04a4d33..edba46bba3 100644 --- a/poi-examples/src/main/java/org/apache/poi/examples/xssf/usermodel/CustomXMLMapping.java +++ b/poi-examples/src/main/java/org/apache/poi/examples/xssf/usermodel/CustomXMLMapping.java @@ -16,8 +16,9 @@ ==================================================================== */ package org.apache.poi.examples.xssf.usermodel; -import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.extractor.XSSFExportToXml; import org.apache.poi.xssf.usermodel.XSSFMap; @@ -37,9 +38,9 @@ public final class CustomXMLMapping { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); + String xml = os.toString(StandardCharsets.UTF_8); System.out.println(xml); } } diff --git a/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java b/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java index 6863fc9bbe..f21f512284 100644 --- a/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java +++ b/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java @@ -20,9 +20,10 @@ package org.apache.poi.integration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.examples.xssf.eventusermodel.XLSX2CSV; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -33,7 +34,7 @@ import org.junit.jupiter.api.Test; public class TestXLSX2CSV { private PrintStream err; - private final ByteArrayOutputStream errorBytes = new ByteArrayOutputStream(); + private final UnsynchronizedByteArrayOutputStream errorBytes = new UnsynchronizedByteArrayOutputStream(); @BeforeEach public void setUp() { @@ -45,13 +46,13 @@ public class TestXLSX2CSV { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { // restore output-streams again System.setErr(err); // Print out found error if (errorBytes.size() > 0) { - System.err.println("Had stderr: " + errorBytes.toString("UTF-8")); + System.err.println("Had stderr: " + errorBytes.toString(StandardCharsets.UTF_8)); } } @@ -60,7 +61,7 @@ public class TestXLSX2CSV { // returns with some System.err XLSX2CSV.main(new String[0]); - String output = errorBytes.toString("UTF-8"); + String output = errorBytes.toString(StandardCharsets.UTF_8); assertTrue(output.contains("XLSX2CSV <xlsx file>"), "Had: " + output); } @@ -75,7 +76,7 @@ public class TestXLSX2CSV { @Test public void testSampleFile() throws Exception { - final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream outputBytes = new UnsynchronizedByteArrayOutputStream(); PrintStream out = new PrintStream(outputBytes); // The package open is instantaneous, as it should be. @@ -84,17 +85,17 @@ public class TestXLSX2CSV { xlsx2csv.process(); } - String errorOutput = errorBytes.toString("UTF-8"); + String errorOutput = errorBytes.toString(StandardCharsets.UTF_8); assertEquals(errorOutput.length(), 0); - String output = outputBytes.toString("UTF-8"); + String output = outputBytes.toString(StandardCharsets.UTF_8); assertTrue(output.contains("\"Lorem\",111"), "Had: " + output); assertTrue(output.contains(",\"hello, xssf\",,\"hello, xssf\""), "Had: " + output); } @Test public void testMinColumns() throws Exception { - final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream outputBytes = new UnsynchronizedByteArrayOutputStream(); PrintStream out = new PrintStream(outputBytes); // The package open is instantaneous, as it should be. @@ -103,10 +104,10 @@ public class TestXLSX2CSV { xlsx2csv.process(); } - String errorOutput = errorBytes.toString("UTF-8"); + String errorOutput = errorBytes.toString(StandardCharsets.UTF_8); assertEquals(errorOutput.length(), 0); - String output = outputBytes.toString("UTF-8"); + String output = outputBytes.toString(StandardCharsets.UTF_8); assertTrue(output.contains("\"Lorem\",111,,,"), "Had: " + output); assertTrue(output.contains(",\"hello, xssf\",,\"hello, xssf\","), "Had: " + output); } diff --git a/poi-excelant/src/test/java/org/apache/poi/ss/excelant/TestBuildFile.java b/poi-excelant/src/test/java/org/apache/poi/ss/excelant/TestBuildFile.java index 2a2b36b827..df3509cd74 100644 --- a/poi-excelant/src/test/java/org/apache/poi/ss/excelant/TestBuildFile.java +++ b/poi-excelant/src/test/java/org/apache/poi/ss/excelant/TestBuildFile.java @@ -28,7 +28,7 @@ import java.io.File; import java.io.PrintStream; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildListener; import org.apache.tools.ant.Project; diff --git a/poi-integration/src/test/java/org/apache/poi/stress/HPSFFileHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/HPSFFileHandler.java index 088f77ef45..53ca398b5c 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/HPSFFileHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/HPSFFileHandler.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -33,6 +32,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.examples.hpsf.CopyCompare; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; @@ -104,11 +104,11 @@ class HPSFFileHandler extends POIFSFileHandler { public void handleAdditional(File file) throws Exception { assumeFalse(EXCLUDES_HANDLE_ADD.contains(file.getParentFile().getName()+"/"+file.getName())); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); PrintStream psNew = new PrintStream(bos, true, "ISO-8859-1"); CopyCompare.setOut(psNew); CopyCompare.main(new String[]{file.getAbsolutePath(), copyOutput.get().getAbsolutePath()}); - assertEquals("Equal" + NL, bos.toString(StandardCharsets.UTF_8.name())); + assertEquals("Equal" + NL, bos.toString(StandardCharsets.UTF_8)); } diff --git a/poi-integration/src/test/java/org/apache/poi/stress/HSSFFileHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/HSSFFileHandler.java index 1e0348cac5..f8e0de4ff1 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/HSSFFileHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/HSSFFileHandler.java @@ -33,7 +33,7 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.Test; class HSSFFileHandler extends SpreadsheetHandler { diff --git a/poi-integration/src/test/java/org/apache/poi/stress/POIFSFileHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/POIFSFileHandler.java index b92f91f5f9..d492979992 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/POIFSFileHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/POIFSFileHandler.java @@ -18,13 +18,12 @@ package org.apache.poi.stress; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDocument; import org.apache.poi.hpsf.extractor.HPSFPropertiesExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; @@ -58,13 +57,14 @@ class POIFSFileHandler extends AbstractFileHandler { } protected void handlePOIDocument(POIDocument doc) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + doc.write(out); - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - POIFSFileSystem fs = new POIFSFileSystem(in); - handlePOIFSFileSystem(fs); - fs.close(); + try (InputStream in = out.toInputStream(); + POIFSFileSystem fs = new POIFSFileSystem(in)) { + handlePOIFSFileSystem(fs); + } + } } // a test-case to test this locally without executing the full TestAllFiles diff --git a/poi-integration/src/test/java/org/apache/poi/stress/SlideShowHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/SlideShowHandler.java index 9a1defbf21..ec291e1c0b 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/SlideShowHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/SlideShowHandler.java @@ -23,11 +23,10 @@ import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.draw.Drawable; import org.apache.poi.sl.usermodel.GroupShape; import org.apache.poi.sl.usermodel.Notes; @@ -40,7 +39,6 @@ import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.sl.usermodel.TextParagraph; import org.apache.poi.sl.usermodel.TextRun; import org.apache.poi.sl.usermodel.TextShape; -import org.junit.jupiter.api.Assumptions; import org.junit.platform.commons.util.ExceptionUtils; public abstract class SlideShowHandler extends POIFSFileHandler { @@ -51,29 +49,18 @@ public abstract class SlideShowHandler extends POIFSFileHandler { readPictures(ss); // write out the file - ByteArrayOutputStream out = writeToArray(ss); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + ss.write(out); readContent(ss); // read in the written file - try (SlideShow<?, ?> read = SlideShowFactory.create(new ByteArrayInputStream(out.toByteArray()))) { + try (SlideShow<?, ?> read = SlideShowFactory.create(out.toInputStream())) { assertNotNull(read); readContent(read); } } - private ByteArrayOutputStream writeToArray(SlideShow<?,?> ss) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - ss.write(stream); - } finally { - stream.close(); - } - - return stream; - } - - private void readContent(SlideShow<?,?> ss) { for (Slide<?,?> s : ss.getSlides()) { s.getTitle(); diff --git a/poi-integration/src/test/java/org/apache/poi/stress/SpreadsheetHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/SpreadsheetHandler.java index dcee603bf2..341902b4ea 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/SpreadsheetHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/SpreadsheetHandler.java @@ -18,10 +18,9 @@ package org.apache.poi.stress; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ss.extractor.EmbeddedData; import org.apache.poi.ss.extractor.EmbeddedExtractor; import org.apache.poi.ss.usermodel.Cell; @@ -45,10 +44,10 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { readContent(wb); // write once more - ByteArrayOutputStream out = writeToArray(wb); + UnsynchronizedByteArrayOutputStream out = writeToArray(wb); // read in the written file - Workbook read = WorkbookFactory.create(new ByteArrayInputStream(out.toByteArray())); + Workbook read = WorkbookFactory.create(out.toInputStream()); assertNotNull(read); @@ -61,14 +60,9 @@ public abstract class SpreadsheetHandler extends AbstractFileHandler { read.close(); } - private ByteArrayOutputStream writeToArray(Workbook wb) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - wb.write(stream); - } finally { - stream.close(); - } - + private UnsynchronizedByteArrayOutputStream writeToArray(Workbook wb) throws IOException { + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(); + wb.write(stream); return stream; } diff --git a/poi-integration/src/test/java/org/apache/poi/stress/XSSFBFileHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/XSSFBFileHandler.java index 1bc23c49ed..dd25e4148d 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/XSSFBFileHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/XSSFBFileHandler.java @@ -17,7 +17,6 @@ package org.apache.poi.stress; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -40,10 +39,8 @@ class XSSFBFileHandler extends AbstractFileHandler { @Override public void handleFile(InputStream stream, String path) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - IOUtils.copy(stream, out); + byte[] bytes = IOUtils.toByteArray(stream); - final byte[] bytes = out.toByteArray(); try (OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bytes))) { testOne(opcPackage); } diff --git a/poi-integration/src/test/java/org/apache/poi/stress/XSSFFileHandler.java b/poi-integration/src/test/java/org/apache/poi/stress/XSSFFileHandler.java index beb3a8edf8..6f9571564f 100644 --- a/poi-integration/src/test/java/org/apache/poi/stress/XSSFFileHandler.java +++ b/poi-integration/src/test/java/org/apache/poi/stress/XSSFFileHandler.java @@ -16,14 +16,13 @@ ==================================================================== */ package org.apache.poi.stress; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -35,6 +34,8 @@ import java.util.Set; import javax.xml.transform.TransformerException; +import org.apache.commons.io.output.NullPrintStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.examples.ss.ExcelComparator; import org.apache.poi.examples.xssf.eventusermodel.FromHowTo; @@ -50,7 +51,6 @@ import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullPrintStream; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.extractor.XSSFExportToXml; import org.apache.poi.xssf.usermodel.XSSFMap; @@ -70,12 +70,12 @@ class XSSFFileHandler extends SpreadsheetHandler { // make sure the potentially large byte-array is freed up quickly again { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(stream, out); - ByteArrayInputStream bytes = new ByteArrayInputStream(out.toByteArray()); if (pass != null) { - POIFSFileSystem poifs = new POIFSFileSystem(bytes); + POIFSFileSystem poifs = new POIFSFileSystem(out.toInputStream()); EncryptionInfo ei = new EncryptionInfo(poifs); Decryptor dec = ei.getDecryptor(); try { @@ -91,11 +91,9 @@ class XSSFFileHandler extends SpreadsheetHandler { IOUtils.copy(is, out); is.close(); poifs.close(); - bytes = new ByteArrayInputStream(out.toByteArray()); } - checkXSSFReader(OPCPackage.open(bytes)); - bytes.reset(); - wb = new XSSFWorkbook(bytes); + checkXSSFReader(OPCPackage.open(out.toInputStream())); + wb = new XSSFWorkbook(out.toInputStream()); } // use the combined handler for HSSF/XSSF @@ -157,9 +155,7 @@ class XSSFFileHandler extends SpreadsheetHandler { TransformerException { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); + exporter.exportToXML(NULL_OUTPUT_STREAM, true); } } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java index 9c92fb5f3e..70b50e4d63 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java @@ -898,16 +898,12 @@ public abstract class OPCPackage implements RelationshipSource, Closeable { } // Extract the zip entry content to put it in the part content if (content != null) { - try { - OutputStream partOutput = addedPart.getOutputStream(); + try (OutputStream partOutput = addedPart.getOutputStream()) { if (partOutput == null) { return null; } - - partOutput.write(content.toByteArray(), 0, content.size()); - partOutput.close(); - - } catch (IOException ioe) { + content.writeTo(partOutput); + } catch (IOException ignored) { return null; } } else { diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java index 0df7364903..c4ab456fd8 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java @@ -18,11 +18,11 @@ package org.apache.poi.openxml4j.opc.internal; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.OPCPackage; @@ -113,17 +113,15 @@ public final class MemoryPackagePart extends PackagePart { @Override public boolean load(InputStream ios) throws InvalidFormatException { - // Grab the data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + // Grab the data IOUtils.copy(ios, baos); + // Save it + data = baos.toByteArray(); } catch(IOException e) { throw new InvalidFormatException(e.getMessage()); } - // Save it - data = baos.toByteArray(); - // All done return true; } diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java index 5cd07238e3..7fce830721 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java @@ -17,22 +17,23 @@ package org.apache.poi.openxml4j.opc.internal; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; + /** * Build an output stream for MemoryPackagePart. */ public final class MemoryPackagePartOutputStream extends OutputStream { - private MemoryPackagePart _part; + private final MemoryPackagePart _part; - private ByteArrayOutputStream _buff; + private final UnsynchronizedByteArrayOutputStream _buff; public MemoryPackagePartOutputStream(MemoryPackagePart part) { this._part = part; - _buff = new ByteArrayOutputStream(); + _buff = new UnsynchronizedByteArrayOutputStream(); } @Override diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java index 0658a03c6d..d6a625baeb 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java +++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java @@ -202,8 +202,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get the category property. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getCategoryProperty() */ + @Override public Optional<String> getCategoryProperty() { return category; } @@ -211,8 +211,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get content status. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentStatusProperty() */ + @Override public Optional<String> getContentStatusProperty() { return contentStatus; } @@ -220,8 +220,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get content type. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentTypeProperty() */ + @Override public Optional<String> getContentTypeProperty() { return contentType; } @@ -229,8 +229,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get created date. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatedProperty() */ + @Override public Optional<Date> getCreatedProperty() { return created; } @@ -247,8 +247,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get creator. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatorProperty() */ + @Override public Optional<String> getCreatorProperty() { return creator; } @@ -256,8 +256,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get description. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getDescriptionProperty() */ + @Override public Optional<String> getDescriptionProperty() { return description; } @@ -265,8 +265,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get identifier. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getIdentifierProperty() */ + @Override public Optional<String> getIdentifierProperty() { return identifier; } @@ -274,8 +274,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get keywords. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getKeywordsProperty() */ + @Override public Optional<String> getKeywordsProperty() { return keywords; } @@ -283,8 +283,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get the language. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getLanguageProperty() */ + @Override public Optional<String> getLanguageProperty() { return language; } @@ -292,8 +292,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get the author of last modifications. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastModifiedByProperty() */ + @Override public Optional<String> getLastModifiedByProperty() { return lastModifiedBy; } @@ -301,8 +301,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get last printed date. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastPrintedProperty() */ + @Override public Optional<Date> getLastPrintedProperty() { return lastPrinted; } @@ -319,8 +319,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get modified date. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getModifiedProperty() */ + @Override public Optional<Date> getModifiedProperty() { return modified; } @@ -340,8 +340,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get revision. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getRevisionProperty() */ + @Override public Optional<String> getRevisionProperty() { return revision; } @@ -349,8 +349,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get subject. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getSubjectProperty() */ + @Override public Optional<String> getSubjectProperty() { return subject; } @@ -358,8 +358,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get title. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getTitleProperty() */ + @Override public Optional<String> getTitleProperty() { return title; } @@ -367,8 +367,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Get version. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getVersionProperty() */ + @Override public Optional<String> getVersionProperty() { return version; } @@ -376,8 +376,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the category. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.lang.String) */ + @Override public void setCategoryProperty(String category) { this.category = setStringValue(category); } @@ -385,15 +385,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the category. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.util.Optional) */ + @Override public void setCategoryProperty(Optional<String> category) { this.category = category; } /** * Set the content status. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.lang.String) */ + @Override public void setContentStatusProperty(String contentStatus) { this.contentStatus = setStringValue(contentStatus); } @@ -401,15 +401,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the content status. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.util.Optional) */ + @Override public void setContentStatusProperty(Optional<String> contentStatus) { this.contentStatus = contentStatus; } /** * Set the content type. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.lang.String) */ + @Override public void setContentTypeProperty(String contentType) { this.contentType = setStringValue(contentType); } @@ -417,8 +417,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the content type. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.util.Optional) */ + @Override public void setContentTypeProperty(Optional<String> contentType) { this.contentType = contentType; } /** @@ -426,6 +426,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP * * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(java.util.Optional) */ + @Override public void setCreatedProperty(String created) { try { this.created = setDateValue(created); @@ -437,8 +438,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the created date. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(java.util.Optional) */ + @Override public void setCreatedProperty(Optional<Date> created) { if (created.isPresent()) this.created = created; @@ -447,8 +448,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the creator. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.lang.String) */ + @Override public void setCreatorProperty(String creator) { this.creator = setStringValue(creator); } @@ -456,15 +457,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the creator. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.util.Optional) */ + @Override public void setCreatorProperty(Optional<String> creator) { this.creator = creator; } /** * Set the description. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.lang.String) */ + @Override public void setDescriptionProperty(String description) { this.description = setStringValue(description); } @@ -472,15 +473,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set the description. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.util.Optional) */ + @Override public void setDescriptionProperty(Optional<String> description) { this.description = description; } /** * Set identifier. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.lang.String) */ + @Override public void setIdentifierProperty(String identifier) { this.identifier = setStringValue(identifier); } @@ -488,15 +489,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set identifier. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.util.Optional) */ + @Override public void setIdentifierProperty(Optional<String> identifier) { this.identifier = identifier; } /** * Set keywords. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.lang.String) */ + @Override public void setKeywordsProperty(String keywords) { this.keywords = setStringValue(keywords); } @@ -504,15 +505,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set keywords. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.util.Optional) */ + @Override public void setKeywordsProperty(Optional<String> keywords) { this.keywords = keywords; } /** * Set language. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.lang.String) */ + @Override public void setLanguageProperty(String language) { this.language = setStringValue(language); } @@ -520,15 +521,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set language. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.util.Optional) */ + @Override public void setLanguageProperty(Optional<String> language) { this.language = language; } /** * Set last modifications author. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.lang.String) */ + @Override public void setLastModifiedByProperty(String lastModifiedBy) { this.lastModifiedBy = setStringValue(lastModifiedBy); } @@ -536,8 +537,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set last modifications author. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.util.Optional) */ + @Override public void setLastModifiedByProperty(Optional<String> lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } @@ -547,6 +548,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP * * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(java.util.Optional) */ + @Override public void setLastPrintedProperty(String lastPrinted) { try { this.lastPrinted = setDateValue(lastPrinted); @@ -559,8 +561,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set last printed date. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(java.util.Optional) */ + @Override public void setLastPrintedProperty(Optional<Date> lastPrinted) { if (lastPrinted.isPresent()) this.lastPrinted = lastPrinted; @@ -571,6 +573,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP * * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(java.util.Optional) */ + @Override public void setModifiedProperty(String modified) { try { this.modified = setDateValue(modified); @@ -583,8 +586,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set last modification date. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(java.util.Optional) */ + @Override public void setModifiedProperty(Optional<Date> modified) { if (modified.isPresent()) this.modified = modified; @@ -593,23 +596,23 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set revision. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.util.Optional) */ + @Override public void setRevisionProperty(Optional<String> revision) { this.revision = revision; } /** * Set revision. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.lang.String) */ + @Override public void setRevisionProperty(String revision) { this.revision = setStringValue(revision); } /** * Set subject. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.lang.String) */ + @Override public void setSubjectProperty(String subject) { this.subject = setStringValue(subject); } @@ -617,15 +620,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set subject. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.util.Optional) */ + @Override public void setSubjectProperty(Optional<String> subject) { this.subject = subject; } /** * Set title. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.lang.String) */ + @Override public void setTitleProperty(String title) { this.title = setStringValue(title); } @@ -633,15 +636,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set title. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.util.Optional) */ + @Override public void setTitleProperty(Optional<String> title) { this.title = title; } /** * Set version. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.lang.String) */ + @Override public void setVersionProperty(String version) { this.version = setStringValue(version); } @@ -649,12 +652,12 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP /** * Set version. * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.util.Optional) */ + @Override public void setVersionProperty(Optional<String> version) { this.version = version; } /** - * Convert a string value into a Optional<String> + * Convert a string value into a {@code Optional<String>} */ private Optional<String> setStringValue(String s) { if (s == null || s.isEmpty()) { @@ -664,7 +667,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP } /** - * Convert a string value represented a date into a Optional<Date>. + * Convert a string value represented a date into a {@code Optional<Date>} * * @throws InvalidFormatException * Throws if the date format isnot valid. @@ -707,7 +710,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP } /** - * Convert a Optional<Date> into a String. + * Convert a {@code Optional<Date>} into a String. * * @param d * The Date to convert. diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java index f8ad4a33e5..35e0f4924a 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java +++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java @@ -17,7 +17,6 @@ package org.apache.poi.poifs.crypt.dsig; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.GeneralSecurityException; @@ -26,6 +25,7 @@ import java.security.PrivateKey; import javax.crypto.Cipher; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.crypt.ChainingMode; import org.apache.poi.poifs.crypt.CipherAlgorithm; @@ -54,7 +54,7 @@ import org.ietf.jgss.Oid; } md = CryptoFunctions.getMessageDigest(algo); } - + @Override public void write(final int b) throws IOException { md.update((byte)b); @@ -66,7 +66,7 @@ import org.ietf.jgss.Oid; } public byte[] sign() throws IOException, GeneralSecurityException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); bos.write(getHashMagic()); bos.write(md.digest()); @@ -74,7 +74,7 @@ import org.ietf.jgss.Oid; , ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1Padding"); return cipher.doFinal(bos.toByteArray()); } - + static boolean isMSCapi(final PrivateKey key) { return key != null && key.getClass().getName().contains("mscapi"); } @@ -84,7 +84,7 @@ import org.ietf.jgss.Oid; * Each digest method has its own ASN1 header * * @return the ASN1 header bytes for the signatureValue / digestInfo - * + * * @see <a href="https://tools.ietf.org/html/rfc2313#section-10.1.2">Data encoding</a> */ byte[] getHashMagic() { @@ -94,7 +94,7 @@ import org.ietf.jgss.Oid; try { final byte[] oidBytes = new Oid(algo.rsaOid).getDER(); - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); bos.write(0x30); bos.write(algo.hashSize+oidBytes.length+6); bos.write(0x30); @@ -102,7 +102,7 @@ import org.ietf.jgss.Oid; bos.write(oidBytes); bos.write(new byte[] {5,0,4}); bos.write(algo.hashSize); - + return bos.toByteArray(); } catch (GSSException|IOException e) { throw new IllegalStateException(e); diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java index d38088c68c..ff977fa45a 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java +++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java @@ -24,8 +24,6 @@ package org.apache.poi.poifs.crypt.dsig; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -38,6 +36,7 @@ import javax.xml.crypto.URIReference; import javax.xml.crypto.URIReferenceException; import javax.xml.crypto.XMLCryptoContext; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; @@ -60,6 +59,7 @@ public class OOXMLURIDereferencer implements URIDereferencer { baseUriDereferencer = signatureInfo.getSignatureFactory().getURIDereferencer(); } + @Override public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException { if (uriReference == null) { throw new NullPointerException("URIReference cannot be null - call setSignatureInfo(...) before"); @@ -90,12 +90,12 @@ public class OOXMLURIDereferencer implements URIDereferencer { // although xmlsec has an option to ignore line breaks, currently this // only affects .rels files, so we only modify these // http://stackoverflow.com/questions/4728300 - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); for (int ch; (ch = dataStream.read()) != -1; ) { if (ch == 10 || ch == 13) continue; bos.write(ch); } - dataStream = new ByteArrayInputStream(bos.toByteArray()); + dataStream = bos.toInputStream(); } } catch (IOException e) { throw new URIReferenceException("I/O error: " + e.getMessage(), e); diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java index 06067ea531..34fc8d30d1 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java +++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java @@ -32,7 +32,6 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.AttributedCharacterIterator; import java.text.AttributedString; @@ -46,6 +45,7 @@ import com.microsoft.schemas.vml.CTGroup; import com.microsoft.schemas.vml.CTImageData; import com.microsoft.schemas.vml.CTShape; import com.microsoft.schemas.vml.STExt; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.common.usermodel.PictureType; import org.apache.poi.hpsf.ClassID; import org.apache.poi.ooxml.POIXMLException; @@ -290,7 +290,7 @@ public abstract class SignatureLine { xsl.setSuggestedsigneremail(suggestedSignerEmail); } if (setupId == null) { - setupId = new ClassID("{"+ UUID.randomUUID().toString()+"}"); + setupId = new ClassID("{"+ UUID.randomUUID() +"}"); } xsl.setId(setupId.toString()); xsl.setAllowcomments(STTrueFalse.T); @@ -344,7 +344,7 @@ public abstract class SignatureLine { rnd.drawImage(gfx, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight)); gfx.dispose(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); ImageIO.write(bi, "PNG", bos); return bos.toByteArray(); } @@ -429,7 +429,7 @@ public abstract class SignatureLine { gfx.dispose(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); ImageIO.write(bi, "PNG", bos); return bos.toByteArray(); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java index 3b00748156..5a82f4152c 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java +++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java @@ -28,7 +28,6 @@ import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; import static org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet.insertXChild; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.cert.CRLException; @@ -47,6 +46,7 @@ import java.util.UUID; import javax.xml.crypto.MarshalException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.poifs.crypt.dsig.SignatureConfig; @@ -104,8 +104,8 @@ public class XAdESXLSignatureFacet implements SignatureFacet { SignatureConfig signatureConfig = signatureInfo.getSignatureConfig(); - QualifyingPropertiesDocument qualDoc = null; - QualifyingPropertiesType qualProps = null; + QualifyingPropertiesDocument qualDoc; + QualifyingPropertiesType qualProps; // check for XAdES-BES NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties"); @@ -289,7 +289,7 @@ public class XAdESXLSignatureFacet implements SignatureFacet { } public static byte[] getC14nValue(List<Node> nodeList, String c14nAlgoId) { - ByteArrayOutputStream c14nValue = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream c14nValue = new UnsynchronizedByteArrayOutputStream(); try { for (Node node : nodeList) { /* diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java index e0746f60eb..40b05b483d 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java +++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java @@ -24,7 +24,8 @@ package org.apache.poi.poifs.crypt.dsig.services; -import java.io.ByteArrayOutputStream; +import static org.apache.logging.log4j.util.Unbox.box; + import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; @@ -44,6 +45,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.SimpleMessage; @@ -72,8 +74,6 @@ import org.bouncycastle.tsp.TimeStampRequestGenerator; import org.bouncycastle.tsp.TimeStampResponse; import org.bouncycastle.tsp.TimeStampToken; -import static org.apache.logging.log4j.util.Unbox.box; - /** * A TSP time-stamp service implementation. */ @@ -95,7 +95,8 @@ public class TSPTimeStampService implements TimeStampService { } } - @SuppressWarnings({"unchecked","squid:S2647"}) + @Override + @SuppressWarnings({"squid:S2647"}) public byte[] timeStamp(SignatureInfo signatureInfo, byte[] data, RevocationData revocationData) throws Exception { SignatureConfig signatureConfig = signatureInfo.getSignatureConfig(); @@ -124,7 +125,7 @@ public class TSPTimeStampService implements TimeStampService { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(host), (port == -1 ? 80 : port))); } - ByteArrayOutputStream bos; + UnsynchronizedByteArrayOutputStream bos; String contentType; HttpURLConnection huc = (HttpURLConnection)new URL(signatureConfig.getTspUrl()).openConnection(proxy); try { @@ -163,7 +164,7 @@ public class TSPTimeStampService implements TimeStampService { throw new RuntimeException("missing Content-Type header"); } - bos = new ByteArrayOutputStream(); + bos = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(huc.getInputStream(), bos); LOG.atDebug().log(() -> new SimpleMessage("response content: " + HexDump.dump(bos.toByteArray(), 0, 0))); } finally { diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java index e6e72058b8..8dba51f77e 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java @@ -43,7 +43,6 @@ import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.WritableRaster; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.nio.charset.StandardCharsets; @@ -60,6 +59,7 @@ import org.apache.batik.svggen.SVGGeneratorContext; import org.apache.batik.svggen.SVGGraphics2D; import org.apache.batik.svggen.SVGPaintDescriptor; import org.apache.batik.svggen.SVGTexturePaint; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.draw.BitmapImageRenderer; import org.apache.poi.sl.draw.DrawTexturePaint; import org.apache.poi.sl.draw.Drawable; @@ -274,12 +274,12 @@ public class SVGRenderExtension extends DefaultExtensionHandler { null, SVG_VIEW_BOX_ATTRIBUTE, x+" "+ y+" "+ w+" "+h ); - org.apache.poi.sl.usermodel.Shape slShape = fill.getShape(); + org.apache.poi.sl.usermodel.Shape<?,?> slShape = fill.getShape(); // TODO: the rotation handling is incomplete and the scale handling is missing // see DrawTexturePaint on how to do it for AWT if (!fill.isRotatedWithShape() && slShape instanceof SimpleShape) { - double rot = ((SimpleShape)slShape).getRotation(); + double rot = ((SimpleShape<?,?>)slShape).getRotation(); if (rot != 0) { setAttribute(genCtx, patternDef, null, SVG_PATTERN_TRANSFORM_ATTRIBUTE, "rotate(" + genCtx.doubleString(-rot) + ")"); @@ -311,7 +311,7 @@ public class SVGRenderExtension extends DefaultExtensionHandler { } if (imgData == null) { BufferedImage bi = imgRdr.getImage(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { ImageIO.write(bi, "PNG", bos); } catch (IOException e) { diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java index 8ee5017d1f..9b5b9d63dd 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java @@ -19,14 +19,14 @@ package org.apache.poi.xslf.usermodel; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamReader; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.poi.hpsf.ClassID; import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart; import org.apache.poi.ooxml.POIXMLException; @@ -68,7 +68,7 @@ public class XSLFObjectShape extends XSLFGraphicFrame implements ObjectShape<XSL private static final QName[] OLE_OBJ = { new QName(PML_NS, "oleObj") }; private static final QName[] CT_PICTURE = { new QName(PML_NS, "pic") }; - private CTOleObject _oleObject; + private final CTOleObject _oleObject; private XSLFPictureData _data; /*package*/ XSLFObjectShape(CTGraphicalObjectFrame shape, XSLFSheet sheet){ @@ -193,56 +193,45 @@ public class XSLFObjectShape extends XSLFGraphicFrame implements ObjectShape<XSL _oleObject.setProgId(md.getProgId()); _oleObject.setName(md.getObjectName()); - return new XSLFObjectOutputStream(rp.getDocumentPart().getPackagePart(),md); + return new ByteArrayOutputStream() { + @Override + public void close() throws IOException { + addUpdatedData(rp.getDocumentPart().getPackagePart(),md,this); + } + }; } - private static class XSLFObjectOutputStream extends ByteArrayOutputStream { - final PackagePart objectPart; - final ObjectMetaData metaData; - private XSLFObjectOutputStream(final PackagePart objectPart, final ObjectMetaData metaData) { - super(100000); - this.objectPart = objectPart; - this.metaData = metaData; - } - - public void close() throws IOException { - objectPart.clear(); - try (final OutputStream os = objectPart.getOutputStream()) { - final ByteArrayInputStream bis = new ByteArrayInputStream(this.buf, 0, size()); - final FileMagic fm = FileMagic.valueOf(this.buf); + private void addUpdatedData(PackagePart objectPart, ObjectMetaData metaData, ByteArrayOutputStream baos) throws IOException { + objectPart.clear(); + try (InputStream bis = FileMagic.prepareToCheckMagic(baos.toInputStream()); + final OutputStream os = objectPart.getOutputStream()) { + final FileMagic fm = FileMagic.valueOf(bis); - if (fm == FileMagic.OLE2) { - try (final POIFSFileSystem poifs = new POIFSFileSystem(bis)) { - poifs.getRoot().setStorageClsid(metaData.getClassID()); - poifs.writeFilesystem(os); - } - } else if (metaData.getOleEntry() == null) { - // OLE Name hasn't been specified, pass the input through - os.write(this.buf, 0, size()); - } else { - try (final POIFSFileSystem poifs = new POIFSFileSystem()) { - final ClassID clsId = metaData.getClassID(); - if (clsId != null) { - poifs.getRoot().setStorageClsid(clsId); - } - poifs.createDocument(bis, metaData.getOleEntry()); - - Ole10Native.createOleMarkerEntry(poifs); - - poifs.writeFilesystem(os); + if (fm == FileMagic.OLE2) { + try (final POIFSFileSystem poifs = new POIFSFileSystem(bis)) { + poifs.getRoot().setStorageClsid(metaData.getClassID()); + poifs.writeFilesystem(os); + } + } else if (metaData.getOleEntry() == null) { + // OLE Name hasn't been specified, pass the input through + baos.writeTo(os); + } else { + try (final POIFSFileSystem poifs = new POIFSFileSystem()) { + final ClassID clsId = metaData.getClassID(); + if (clsId != null) { + poifs.getRoot().setStorageClsid(clsId); } + poifs.createDocument(bis, metaData.getOleEntry()); + Ole10Native.createOleMarkerEntry(poifs); + poifs.writeFilesystem(os); } } } } - /** - * - * * @param shapeId 1-based shapeId * @param picRel relationship to the picture data in the ooxml package - * @return */ static CTGraphicalObjectFrame prototype(int shapeId, String picRel){ CTGraphicalObjectFrame frame = CTGraphicalObjectFrame.Factory.newInstance(); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java index 9c4fc5902e..21462607d9 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java @@ -25,8 +25,6 @@ import java.awt.Insets; import java.awt.geom.Dimension2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -35,6 +33,7 @@ import javax.imageio.ImageIO; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamReader; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ooxml.util.POIXMLUnits; @@ -127,6 +126,7 @@ public class XSLFPictureShape extends XSLFSimpleShape * Return the data on the (internal) picture. * For an external linked picture, will return null */ + @Override public XSLFPictureData getPictureData() { if(_data == null){ String blipId = getBlipId(); @@ -320,16 +320,16 @@ public class XSLFPictureShape extends XSLFSimpleShape : new Rectangle2D.Double(0,0, Units.pixelToPoints((int)dim.getWidth()), Units.pixelToPoints((int)dim.getHeight())); PictureType pt = (previewType != null) ? previewType : PictureType.PNG; - if (pt != PictureType.JPEG || pt != PictureType.GIF || pt != PictureType.PNG) { + if (pt != PictureType.JPEG && pt != PictureType.GIF && pt != PictureType.PNG) { pt = PictureType.PNG; } BufferedImage thmBI = renderer.getImage(dim); - ByteArrayOutputStream bos = new ByteArrayOutputStream(100000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(100000); // use extension instead of enum name, because of "jpeg" ImageIO.write(thmBI, pt.extension.substring(1), bos); - XSLFPictureData pngPic = sheet.getSlideShow().addPicture(new ByteArrayInputStream(bos.toByteArray()), pt); + XSLFPictureData pngPic = sheet.getSlideShow().addPicture(bos.toInputStream(), pt); XSLFPictureShape shape = sheet.createPicture(pngPic); shape.setAnchor(anc); @@ -375,7 +375,6 @@ public class XSLFPictureShape extends XSLFSimpleShape if(blip.isSetExtLst()) { // TODO: check for SVG copying CTOfficeArtExtensionList extLst = blip.getExtLst(); - //noinspection deprecation for(CTOfficeArtExtension ext : extLst.getExtArray()){ String xpath = "declare namespace a14='"+ MS_DML_NS +"' $this//a14:imgProps/a14:imgLayer"; XmlObject[] obj = ext.selectPath(xpath); diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java index f3dfe26d72..c1cf538c8f 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java @@ -18,7 +18,6 @@ package org.apache.poi.xslf.util; import java.awt.Graphics2D; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -26,14 +25,16 @@ import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; + public class DummyFormat implements OutputFormat { - private final ByteArrayOutputStream bos; + private final UnsynchronizedByteArrayOutputStream bos; private final DummyGraphics2d dummy2d; public DummyFormat() { try { - bos = new ByteArrayOutputStream(); + bos = new UnsynchronizedByteArrayOutputStream(); dummy2d = new DummyGraphics2d(new PrintStream(bos, true, StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); @@ -41,7 +42,7 @@ public class DummyFormat implements OutputFormat { } @Override - public Graphics2D addSlide(double width, double height) throws IOException { + public Graphics2D addSlide(double width, double height) { bos.reset(); return dummy2d; } @@ -55,7 +56,7 @@ public class DummyFormat implements OutputFormat { } @Override - public void writeDocument(MFProxy proxy, File outFile) throws IOException { + public void writeDocument(MFProxy proxy, File outFile) { } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java index 27f053dc85..81fe1f85cc 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java @@ -121,6 +121,7 @@ public final class PPTX2PNG { private PPTX2PNG() { } + @SuppressWarnings("AssignmentToForLoopParameter") private boolean parseCommandLine(String[] args) { if (args.length == 0) { usage(null); @@ -403,6 +404,7 @@ public final class PPTX2PNG { } GenericRecord gr = proxy.getRoot(); try (GenericRecordJsonWriter fw = new GenericRecordJsonWriter(dumpfile) { + @Override protected boolean printBytes(String name, Object o) { return false; } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java index 4cf1ec13a0..6aa3c9f579 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java @@ -20,13 +20,13 @@ package org.apache.poi.xssf.usermodel; import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.xml.namespace.QName; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ooxml.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.xmlbeans.XmlException; @@ -95,7 +95,7 @@ public class XSSFChartSheet extends XSSFSheet { } private static byte[] blankWorksheet(){ - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); try { new XSSFSheet().write(out); } catch (IOException e){ diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java index 16d04085f2..7001c88b5c 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java @@ -17,7 +17,6 @@ package org.apache.poi.xssf.usermodel; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -68,9 +67,6 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData { /** * Prototype with the default structure of a new auto-shape. */ - /** - * Prototype with the default structure of a new auto-shape. - */ protected static CTShape prototype() { final String drawNS = "http://schemas.microsoft.com/office/drawing/2010/main"; @@ -92,7 +88,7 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData { cur.insertNamespace("a14", drawNS); cur.insertAttributeWithValue("spid", "_x0000_s1"); cur.dispose(); - + nv.addNewCNvSpPr(); CTShapeProperties sp = shape.addNewSpPr(); @@ -113,16 +109,16 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData { return prototype; } - - - + + + @Override public String getOLE2ClassName() { return getOleObject().getProgId(); } /** - * @return the CTOleObject associated with the shape + * @return the CTOleObject associated with the shape */ public CTOleObject getOleObject() { if (oleObject == null) { @@ -134,16 +130,14 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData { } return oleObject; } - + @Override public byte[] getObjectData() throws IOException { - InputStream is = getObjectPart().getInputStream(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - IOUtils.copy(is, bos); - is.close(); - return bos.toByteArray(); + try (InputStream is = getObjectPart().getInputStream()) { + return IOUtils.toByteArray(is); + } } - + /** * @return the package part of the object data */ @@ -184,7 +178,7 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData { public String getFileName() { return getObjectPart().getPartName().getName(); } - + protected XSSFSheet getSheet() { return (XSSFSheet)getDrawing().getParent(); } diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java index 45216a8cdd..5255538ef1 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java @@ -21,8 +21,6 @@ import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.setPassword; import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.validatePassword; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -43,6 +41,7 @@ import javax.xml.namespace.QName; import org.apache.commons.collections4.ListValuedMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hpsf.ClassIDPredefined; @@ -485,7 +484,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Su protected static OPCPackage newPackage(XSSFWorkbookType workbookType) { OPCPackage pkg = null; try { - pkg = OPCPackage.create(new ByteArrayOutputStream()); // NOSONAR - we do not want to close this here + pkg = OPCPackage.create(new UnsynchronizedByteArrayOutputStream()); // NOSONAR - we do not want to close this here // Main part PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName()); // Create main part relationship @@ -639,9 +638,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Su } - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { srcSheet.write(out); - try (ByteArrayInputStream bis = new ByteArrayInputStream(out.toByteArray())) { + try (InputStream bis = out.toInputStream()) { clonedSheet.read(bis); } } catch (IOException e){ @@ -2346,12 +2345,12 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Su Ole10Native ole10 = new Ole10Native(label, fileName, command, oleData); - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(oleData.length+500)) { + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(oleData.length+500)) { ole10.writeOut(bos); try (POIFSFileSystem poifs = new POIFSFileSystem()) { DirectoryNode root = poifs.getRoot(); - root.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray())); + root.createDocument(Ole10Native.OLE10_NATIVE, bos.toInputStream()); root.setStorageClsid(ClassIDPredefined.OLE_V1_PACKAGE.getClassID()); // TODO: generate CombObj stream diff --git a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java index fcf58ed692..eeed142563 100644 --- a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java +++ b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java @@ -20,7 +20,6 @@ package org.apache.poi.xwpf.usermodel; import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -36,6 +35,7 @@ import java.util.Map; import javax.xml.namespace.QName; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ooxml.POIXMLDocument; @@ -65,19 +65,37 @@ import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STOnOff1; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocument1; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CommentsDocument; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.DocumentDocument; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.EndnotesDocument; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; /** - * <p>High(ish) level class for working with .docx files.</p> + * High(ish) level class for working with .docx files. * <p> - * <p>This class tries to hide some of the complexity + * This class tries to hide some of the complexity * of the underlying file format, but as it's not a * mature and stable API yet, certain parts of the * XML structure come through. You'll therefore almost * certainly need to refer to the OOXML specifications * from * http://www.ecma-international.org/publications/standards/Ecma-376.htm - * at some point in your use.</p> + * at some point in your use. */ @SuppressWarnings("unused") public class XWPFDocument extends POIXMLDocument implements Document, IBody { @@ -103,9 +121,9 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Keeps track on all id-values used in this document and included parts, like headers, footers, etc. */ - private IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L); + private final IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L); - private FootnoteEndnoteIdManager footnoteIdManager = new FootnoteEndnoteIdManager(this); + private final FootnoteEndnoteIdManager footnoteIdManager = new FootnoteEndnoteIdManager(this); /** * Handles the joy of different headers/footers for different pages @@ -137,7 +155,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { protected static OPCPackage newPackage() { OPCPackage pkg = null; try { - pkg = OPCPackage.create(new ByteArrayOutputStream()); // NOSONAR - we do not want to close this here + pkg = OPCPackage.create(new UnsynchronizedByteArrayOutputStream()); // NOSONAR - we do not want to close this here // Main part PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName()); // Create main part relationship @@ -306,8 +324,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * returns an Iterator with paragraphs and tables - * - * @see IBody#getBodyElements() */ @Override public List<IBodyElement> getBodyElements() { @@ -318,17 +334,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { return bodyElements.iterator(); } - /** - * @see IBody#getParagraphs() - */ @Override public List<XWPFParagraph> getParagraphs() { return Collections.unmodifiableList(paragraphs); } - /** - * @see IBody#getTables() - */ @Override public List<XWPFTable> getTables() { return Collections.unmodifiableList(tables); @@ -341,9 +351,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { return Collections.unmodifiableList(charts); } - /** - * @see IBody#getTableArray(int) - */ @Override public XWPFTable getTableArray(int pos) { if (pos >= 0 && pos < tables.size()) { @@ -755,8 +762,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * verifies that cursor is on the right position - * - * @param cursor */ private boolean isCursorInBody(XmlCursor cursor) { XmlCursor verify = cursor.newCursor(); @@ -818,9 +823,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Gets the index of the relation we're trying to create - * - * @param relation - * @return i */ private int getRelationIndex(XWPFRelation relation) { int i = 1; @@ -843,11 +845,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { paragraphs.add(p); return p; } - - + + /** * Creates an empty comments for the document if one does not already exist - * + * * @return comments */ public XWPFComments createComments() { @@ -953,7 +955,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * remove a BodyElement from bodyElements array list * - * @param pos * @return true if removing was successfully, else return false */ public boolean removeBodyElement(int pos) { @@ -977,9 +978,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * copies content of a paragraph to a existing paragraph in the list paragraphs at position pos - * - * @param paragraph - * @param pos */ public void setParagraph(XWPFParagraph paragraph, int pos) { paragraphs.set(pos, paragraph); @@ -1012,10 +1010,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Create an empty table with a number of rows and cols specified - * - * @param rows - * @param cols - * @return table */ public XWPFTable createTable(int rows, int cols) { XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols); @@ -1045,9 +1039,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Replace content of table in array tables at position pos with a - * - * @param pos - * @param table */ public void setTable(int pos, XWPFTable table) { tables.set(pos, table); @@ -1289,7 +1280,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Validates the existing password * - * @param password * @return true, only if password was set and equals, false otherwise */ public boolean validateProtectionPassword(String password) { @@ -1324,7 +1314,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Check if revision tracking is turned on. * - * @return <code>true</code> if revision tracking is turned on + * @return {@code true} if revision tracking is turned on */ public boolean isTrackRevisions() { return settings.isTrackRevisions(); @@ -1333,7 +1323,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Enable or disable revision tracking. * - * @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off revision tracking + * @param enable {@code true} to turn on revision tracking, {@code false} to turn off revision tracking */ public void setTrackRevisions(boolean enable) { settings.setTrackRevisions(enable); @@ -1394,9 +1384,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * inserts an existing XWPFTable to the arrays bodyElements and tables - * - * @param pos - * @param table */ @Override public void insertTable(int pos, XWPFTable table) { @@ -1506,7 +1493,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get the next free ImageNumber * - * @param format * @return the next free ImageNumber * @throws InvalidFormatException If the format of the picture is not known. */ @@ -1525,7 +1511,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * returns the PictureData by blipID * - * @param blipID * @return XWPFPictureData of a specificID */ public XWPFPictureData getPictureDataByID(String blipID) { @@ -1567,9 +1552,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get a table by its CTTbl-Object * - * @param ctTbl * @return a table by its CTTbl-Object or null - * @see IBody#getTable(CTTbl) */ @Override public XWPFTable getTable(CTTbl ctTbl) { @@ -1591,8 +1574,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * Returns the paragraph that of position pos - * - * @see IBody#getParagraphArray(int) */ @Override public XWPFParagraph getParagraphArray(int pos) { @@ -1606,8 +1587,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * returns the Part, to which the body belongs, which you need for adding relationship to other parts * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell * belongs. - * - * @see IBody#getPart() */ @Override public POIXMLDocumentPart getPart() { @@ -1618,8 +1597,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get the PartType of the body, for example * DOCUMENT, HEADER, FOOTER, FOOTNOTE, - * - * @see IBody#getPartType() */ @Override public BodyType getPartType() { @@ -1628,8 +1605,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { /** * get the TableCell which belongs to the TableCell - * - * @param cell */ @Override public XWPFTableCell getTableCell(CTTc cell) { @@ -1668,8 +1643,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * no need to read MS-Word file and modify charts * * @return This method return object of XWPFChart Object with default height and width - * @throws InvalidFormatException - * @throws IOException * @since POI 4.0.0 */ public XWPFChart createChart() throws InvalidFormatException, IOException { @@ -1683,8 +1656,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * @param width width of chart in document * @param height height of chart in document * @return This method return object of XWPFChart - * @throws InvalidFormatException - * @throws IOException * @since POI 4.0.0 */ public XWPFChart createChart(int width, int height) throws InvalidFormatException, IOException { @@ -1697,8 +1668,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { * @param width in EMU. * @param height in EMU. * @return the new chart. - * @throws InvalidFormatException - * @throws IOException * @since POI 4.1.2 */ public XWPFChart createChart(XWPFRun run, int width, int height) throws InvalidFormatException, IOException { @@ -1729,8 +1698,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { public XWPFFootnote createFootnote() { XWPFFootnotes footnotes = this.createFootnotes(); - XWPFFootnote footnote = footnotes.createFootnote(); - return footnote; + return footnotes.createFootnote(); } /** @@ -1757,8 +1725,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody { public XWPFEndnote createEndnote() { XWPFEndnotes endnotes = this.createEndnotes(); - XWPFEndnote endnote = endnotes.createEndnote(); - return endnote; + return endnotes.createEndnote(); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java index 2104a418a8..ca4d10a135 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java +++ b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java @@ -17,6 +17,7 @@ package org.apache.poi.ooxml; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -25,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.File; @@ -46,7 +46,6 @@ import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullOutputStream; import org.apache.poi.util.TempFile; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xssf.usermodel.XSSFRelation; @@ -142,7 +141,7 @@ public final class TestPOIXMLDocument { // Should not be able to write a document that has been closed doc.close(); - IOException e2 = assertThrows(IOException.class, () -> doc.write(new NullOutputStream()), + IOException e2 = assertThrows(IOException.class, () -> doc.write(NULL_OUTPUT_STREAM), "Should not be able to write a document that has been closed."); assertEquals("Cannot write data, document seems to have been closed already", e2.getMessage()); @@ -292,7 +291,7 @@ public final class TestPOIXMLDocument { XMLSlideShow ppt = new XMLSlideShow(is)) { POIXMLDocumentPart doc = ppt.getSlides().get(12).getRelationById("rId3"); assertNotNull(doc); - assertEquals(POIXMLDocumentPart.class, doc.getClass()); + assertSame(POIXMLDocumentPart.class, doc.getClass()); } } @@ -334,6 +333,7 @@ public final class TestPOIXMLDocument { private static class UncaughtHandler implements UncaughtExceptionHandler { Throwable e; + @Override public synchronized void uncaughtException(Thread t, Throwable e) { this.e = e; } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java index 1c6b942a58..4068a8e80d 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java @@ -25,7 +25,7 @@ import java.io.InputStream; import java.io.IOException; /** - * Centralises logic for finding/opening sample files for ooxml4j unit tests + * Centralises logic for finding/opening sample files for ooxml4j unit tests */ public final class OpenXML4JTestDataSamples { private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance(); @@ -40,19 +40,13 @@ public final class OpenXML4JTestDataSamples { public static String getSampleFileName(String sampleFileName) { return getSampleFile(sampleFileName).getAbsolutePath(); } - + public static File getSampleFile(String sampleFileName) { return _samples.getFile(sampleFileName); } - - public static File getOutputFile(String outputFileName) throws IOException { - String suffix = outputFileName.substring(outputFileName.lastIndexOf('.')); - return TempFile.createTempFile(outputFileName, suffix); - } - - public static InputStream openComplianceSampleStream(String sampleFileName) { - return _samples.openResourceAsStream(sampleFileName); + public static File getOutputFile(String outputFileName) throws IOException { + int idx = outputFileName.lastIndexOf('.'); + return TempFile.createTempFile(outputFileName.substring(0,idx), outputFileName.substring(idx)); } - } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java index 9f297f66c6..9e9997d38f 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java @@ -33,7 +33,6 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -58,6 +57,8 @@ import com.google.common.io.Files; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.output.CountingOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.EncryptedDocumentException; @@ -217,7 +218,7 @@ public final class TestPackage { */ @Test void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try (OPCPackage pkg = OPCPackage.create(baos)) { // Add a core document @@ -675,7 +676,7 @@ public final class TestPackage { @Test void zipBombCreateAndHandle() throws IOException, EncryptedDocumentException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(2500000); try (ZipFile zipFile = ZipHelper.openZipFile(getSampleFile("sample.xlsx")); ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) { @@ -693,21 +694,19 @@ public final class TestPackage { append.putArchiveEntry(eOut); if (!eOut.isDirectory()) { try (InputStream is = zipFile.getInputStream(eIn)) { - if (eOut.getName().equals("[Content_Types].xml")) { - ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); - IOUtils.copy(is, bos2); - long size = bos2.size() - "</Types>".length(); - append.write(bos2.toByteArray(), 0, (int) size); + if ("[Content_Types].xml".equals(eOut.getName())) { + byte[] suffix = "</Types>".getBytes(StandardCharsets.UTF_8); + CountingOutputStream cos = new CountingOutputStream(append); + IOUtils.copy(is, cos, eOut.getSize() - suffix.length); + byte[] spam = new byte[0x7FFF]; Arrays.fill(spam, (byte) ' '); // 0x7FFF0000 is the maximum for 32-bit zips, but less still works - while (size < 0x7FFF00) { - append.write(spam); - size += spam.length; + while (cos.getByteCount() < 0x7FFF00) { + cos.write(spam); } - append.write("</Types>".getBytes(StandardCharsets.UTF_8)); - size += 8; - eOut.setSize(size); + cos.write(suffix); + eOut.setSize(cos.getByteCount()); } else { IOUtils.copy(is, append); } @@ -717,10 +716,7 @@ public final class TestPackage { } } - IOException ex = assertThrows( - IOException.class, - () -> WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray())) - ); + IOException ex = assertThrows(IOException.class, () -> WorkbookFactory.create(bos.toInputStream())); assertTrue(ex.getMessage().contains("Zip bomb detected!")); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java index 317d1009a0..6dbfcf0dc9 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java @@ -17,8 +17,17 @@ package org.apache.poi.openxml4j.opc; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName; +import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; +import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_DOCUMENT; +import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES; +import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.EXTENDED_PROPERTIES; +import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.InputStream; import java.text.ParsePosition; @@ -27,6 +36,7 @@ import java.util.Date; import java.util.Locale; import java.util.Optional; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; @@ -36,9 +46,6 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; -import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; -import static org.junit.jupiter.api.Assertions.*; - public final class TestPackageCoreProperties { /** * Test package core properties getters. @@ -47,7 +54,7 @@ public final class TestPackageCoreProperties { void testGetProperties() throws Exception { // Open the package @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx")); + OPCPackage p = OPCPackage.open(openSampleStream("TestPackageCoreProperiesGetters.docx")); compareProperties(p); p.revert(); } @@ -57,7 +64,7 @@ public final class TestPackageCoreProperties { */ @Test void testSetProperties() throws Exception { - String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx"); + String inputPath = getSampleFileName("TestPackageCoreProperiesSetters.docx"); File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); @@ -75,28 +82,28 @@ public final class TestPackageCoreProperties { //test various date formats props.setCreatedProperty("2007-05-12T08:00:00Z"); - assertEquals(dateToInsert, props.getCreatedProperty().get()); + assertEquals(dateToInsert, props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z - assertEquals(dateToInsert, props.getCreatedProperty().get()); + assertEquals(dateToInsert, props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2007-05-12T08:00:00.123Z");//millis - assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get()); + assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2007-05-12T10:00:00+0200"); - assertEquals(dateToInsert, props.getCreatedProperty().get()); + assertEquals(dateToInsert, props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz - assertEquals(dateToInsert, props.getCreatedProperty().get()); + assertEquals(dateToInsert, props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2007-05-12T06:00:00-0200"); - assertEquals(dateToInsert, props.getCreatedProperty().get()); + assertEquals(dateToInsert, props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2015-07-27"); - assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().get()); + assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().orElse(null)); props.setCreatedProperty("2007-05-12T10:00:00.123+0200"); - assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get()); + assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().orElse(null)); props.setCategoryProperty("MyCategory"); props.setContentStatusProperty("MyContentStatus"); @@ -122,7 +129,7 @@ public final class TestPackageCoreProperties { OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); compareProperties(p2); p2.revert(); - outputFile.delete(); + assertTrue(outputFile.delete()); } private void compareProperties(OPCPackage p) throws InvalidFormatException { @@ -132,22 +139,22 @@ public final class TestPackageCoreProperties { // Gets the core properties PackageProperties props = p.getPackageProperties(); - assertEquals("MyCategory", props.getCategoryProperty().get()); - assertEquals("MyContentStatus", props.getContentStatusProperty().get()); - assertEquals("MyContentType", props.getContentTypeProperty().get()); - assertEquals(expectedDate, props.getCreatedProperty().get()); - assertEquals("MyCreator", props.getCreatorProperty().get()); - assertEquals("MyDescription", props.getDescriptionProperty().get()); - assertEquals("MyIdentifier", props.getIdentifierProperty().get()); - assertEquals("MyKeywords", props.getKeywordsProperty().get()); - assertEquals("MyLanguage", props.getLanguageProperty().get()); - assertEquals("Julien Chable", props.getLastModifiedByProperty().get()); - assertEquals(expectedDate, props.getLastPrintedProperty().get()); - assertEquals(expectedDate, props.getModifiedProperty().get()); - assertEquals("2", props.getRevisionProperty().get()); - assertEquals("MySubject", props.getSubjectProperty().get()); - assertEquals("MyTitle", props.getTitleProperty().get()); - assertEquals("2", props.getVersionProperty().get()); + assertEquals("MyCategory", props.getCategoryProperty().orElse(null)); + assertEquals("MyContentStatus", props.getContentStatusProperty().orElse(null)); + assertEquals("MyContentType", props.getContentTypeProperty().orElse(null)); + assertEquals(expectedDate, props.getCreatedProperty().orElse(null)); + assertEquals("MyCreator", props.getCreatorProperty().orElse(null)); + assertEquals("MyDescription", props.getDescriptionProperty().orElse(null)); + assertEquals("MyIdentifier", props.getIdentifierProperty().orElse(null)); + assertEquals("MyKeywords", props.getKeywordsProperty().orElse(null)); + assertEquals("MyLanguage", props.getLanguageProperty().orElse(null)); + assertEquals("Julien Chable", props.getLastModifiedByProperty().orElse(null)); + assertEquals(expectedDate, props.getLastPrintedProperty().orElse(null)); + assertEquals(expectedDate, props.getModifiedProperty().orElse(null)); + assertEquals("2", props.getRevisionProperty().orElse(null)); + assertEquals("MySubject", props.getSubjectProperty().orElse(null)); + assertEquals("MyTitle", props.getTitleProperty().orElse(null)); + assertEquals("2", props.getVersionProperty().orElse(null)); } @Test @@ -157,90 +164,92 @@ public final class TestPackageCoreProperties { String strDate = "2007-05-12T08:00:00Z"; Date date = df.parse(strDate); - OPCPackage pkg = new ZipPackage(); - PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); - - // created - assertEquals("", props.getCreatedPropertyString()); - assertFalse(props.getCreatedProperty().isPresent()); - props.setCreatedProperty((String)null); - assertEquals("", props.getCreatedPropertyString()); - assertFalse(props.getCreatedProperty().isPresent()); - props.setCreatedProperty(Optional.empty()); - assertEquals("", props.getCreatedPropertyString()); - assertFalse(props.getCreatedProperty().isPresent()); - props.setCreatedProperty(Optional.of(date)); - assertEquals(strDate, props.getCreatedPropertyString()); - assertEquals(date, props.getCreatedProperty().get()); - props.setCreatedProperty(strDate); - assertEquals(strDate, props.getCreatedPropertyString()); - assertEquals(date, props.getCreatedProperty().get()); - - // lastPrinted - assertEquals("", props.getLastPrintedPropertyString()); - assertFalse(props.getLastPrintedProperty().isPresent()); - props.setLastPrintedProperty((String)null); - assertEquals("", props.getLastPrintedPropertyString()); - assertFalse(props.getLastPrintedProperty().isPresent()); - props.setLastPrintedProperty(Optional.empty()); - assertEquals("", props.getLastPrintedPropertyString()); - assertFalse(props.getLastPrintedProperty().isPresent()); - props.setLastPrintedProperty(Optional.of(date)); - assertEquals(strDate, props.getLastPrintedPropertyString()); - assertEquals(date, props.getLastPrintedProperty().get()); - props.setLastPrintedProperty(strDate); - assertEquals(strDate, props.getLastPrintedPropertyString()); - assertEquals(date, props.getLastPrintedProperty().get()); - - // modified - assertFalse(props.getModifiedProperty().isPresent()); - props.setModifiedProperty((String)null); - assertFalse(props.getModifiedProperty().isPresent()); - props.setModifiedProperty(Optional.empty()); - assertFalse(props.getModifiedProperty().isPresent()); - props.setModifiedProperty(Optional.of(date)); - assertEquals(strDate, props.getModifiedPropertyString()); - assertEquals(date, props.getModifiedProperty().get()); - props.setModifiedProperty(strDate); - assertEquals(strDate, props.getModifiedPropertyString()); - assertEquals(date, props.getModifiedProperty().get()); - - // Tidy - pkg.close(); + try (OPCPackage pkg = new ZipPackage()) { + PackagePropertiesPart props = (PackagePropertiesPart) pkg.getPackageProperties(); + + // created + assertEquals("", props.getCreatedPropertyString()); + assertFalse(props.getCreatedProperty().isPresent()); + props.setCreatedProperty((String) null); + assertEquals("", props.getCreatedPropertyString()); + assertFalse(props.getCreatedProperty().isPresent()); + props.setCreatedProperty(Optional.empty()); + assertEquals("", props.getCreatedPropertyString()); + assertFalse(props.getCreatedProperty().isPresent()); + props.setCreatedProperty(Optional.of(date)); + assertEquals(strDate, props.getCreatedPropertyString()); + assertEquals(date, props.getCreatedProperty().get()); + props.setCreatedProperty(strDate); + assertEquals(strDate, props.getCreatedPropertyString()); + assertEquals(date, props.getCreatedProperty().get()); + + // lastPrinted + assertEquals("", props.getLastPrintedPropertyString()); + assertFalse(props.getLastPrintedProperty().isPresent()); + props.setLastPrintedProperty((String) null); + assertEquals("", props.getLastPrintedPropertyString()); + assertFalse(props.getLastPrintedProperty().isPresent()); + props.setLastPrintedProperty(Optional.empty()); + assertEquals("", props.getLastPrintedPropertyString()); + assertFalse(props.getLastPrintedProperty().isPresent()); + props.setLastPrintedProperty(Optional.of(date)); + assertEquals(strDate, props.getLastPrintedPropertyString()); + assertEquals(date, props.getLastPrintedProperty().get()); + props.setLastPrintedProperty(strDate); + assertEquals(strDate, props.getLastPrintedPropertyString()); + assertEquals(date, props.getLastPrintedProperty().get()); + + // modified + assertFalse(props.getModifiedProperty().isPresent()); + props.setModifiedProperty((String) null); + assertFalse(props.getModifiedProperty().isPresent()); + props.setModifiedProperty(Optional.empty()); + assertFalse(props.getModifiedProperty().isPresent()); + props.setModifiedProperty(Optional.of(date)); + assertEquals(strDate, props.getModifiedPropertyString()); + assertEquals(date, props.getModifiedProperty().get()); + props.setModifiedProperty(strDate); + assertEquals(strDate, props.getModifiedPropertyString()); + assertEquals(date, props.getModifiedProperty().get()); + } } @Test void testGetPropertiesLO() throws Exception { + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); // Open the package - OPCPackage pkg1 = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("51444.xlsx")); - PackageProperties props1 = pkg1.getPackageProperties(); - assertFalse(props1.getTitleProperty().isPresent()); - props1.setTitleProperty("Bug 51444 fixed"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - pkg1.save(out); - out.close(); - pkg1.close(); - - OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray())); - PackageProperties props2 = pkg2.getPackageProperties(); - props2.setTitleProperty("Bug 51444 fixed"); - pkg2.close(); + try (OPCPackage pkg1 = OPCPackage.open(openSampleStream("51444.xlsx"))) { + PackageProperties props1 = pkg1.getPackageProperties(); + assertFalse(props1.getTitleProperty().isPresent()); + props1.setTitleProperty("Bug 51444 fixed"); + pkg1.save(out); + } + + try (OPCPackage pkg2 = OPCPackage.open(out.toInputStream())) { + PackageProperties props2 = pkg2.getPackageProperties(); + props2.setTitleProperty("Bug 51444 fixed"); + } } @Test void testEntitiesInCoreProps_56164() throws Exception { - try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is)) { + try (InputStream is = openSampleStream("CorePropertiesHasEntities.ooxml"); + OPCPackage p = OPCPackage.open(is)) { // Should have 3 root relationships boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; for (PackageRelationship pr : p.getRelationships()) { - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) - foundDocRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) - foundCorePropRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) - foundExtPropRel = true; + switch (pr.getRelationshipType()) { + case CORE_DOCUMENT: + foundDocRel = true; + break; + case CORE_PROPERTIES: + foundCorePropRel = true; + break; + case EXTENDED_PROPERTIES: + foundExtPropRel = true; + break; + } } assertTrue(foundDocRel, "Core Doc Relationship not found in " + p.getRelationships()); assertTrue(foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships()); @@ -257,67 +266,68 @@ public final class TestPackageCoreProperties { @Test void testListOfCustomProperties() throws Exception { File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm"); - OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); + try (OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ); + XSSFWorkbook wb = new XSSFWorkbook(pkg)) { - assertNotNull(wb.getProperties()); - assertNotNull(wb.getProperties().getCustomProperties()); + assertNotNull(wb.getProperties()); + assertNotNull(wb.getProperties().getCustomProperties()); - for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) { - assertNotNull(prop); + for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) { + assertNotNull(prop); + } } - - wb.close(); - pkg.close(); } @Test void testAlternateCorePropertyTimezones() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); - is.close(); - // We need predictable dates for testing! SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - // Check text properties first - assertEquals("Lorem Ipsum", props.getTitleProperty().get()); - assertEquals("Apache POI", props.getCreatorProperty().get()); - - // Created at has a +3 timezone and milliseconds - // 2006-10-13T18:06:00.123+03:00 - // = 2006-10-13T15:06:00.123+00:00 - assertEquals("2006-10-13T15:06:00Z", props.getCreatedPropertyString()); - assertEquals("2006-10-13T15:06:00.123Z", df.format(props.getCreatedProperty().get())); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx"); + OPCPackage pkg1 = OPCPackage.open(is)) { + PackagePropertiesPart props1 = (PackagePropertiesPart) pkg1.getPackageProperties(); - // Modified at has a -13 timezone but no milliseconds - // 2007-06-20T07:59:00-13:00 - // = 2007-06-20T20:59:00-13:00 - assertEquals("2007-06-20T20:59:00Z", props.getModifiedPropertyString()); - assertEquals("2007-06-20T20:59:00.000Z", df.format(props.getModifiedProperty().get())); + // Check text properties first + assertEquals("Lorem Ipsum", props1.getTitleProperty().orElse(null)); + assertEquals("Apache POI", props1.getCreatorProperty().orElse(null)); + // Created at has a +3 timezone and milliseconds + // 2006-10-13T18:06:00.123+03:00 + // = 2006-10-13T15:06:00.123+00:00 + assertEquals("2006-10-13T15:06:00Z", props1.getCreatedPropertyString()); + assertEquals("2006-10-13T15:06:00.123Z", df.format(props1.getCreatedProperty().orElse(null))); - // Ensure we can change them with other timezones and still read back OK - props.setCreatedProperty("2007-06-20T20:57:00+13:00"); - props.setModifiedProperty("2007-06-20T20:59:00.123-13:00"); + // Modified at has a -13 timezone but no milliseconds + // 2007-06-20T07:59:00-13:00 + // = 2007-06-20T20:59:00-13:00 + assertEquals("2007-06-20T20:59:00Z", props1.getModifiedPropertyString()); + assertEquals("2007-06-20T20:59:00.000Z", df.format(props1.getModifiedProperty().orElse(null))); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray())); - // Check text properties first - should be unchanged - assertEquals("Lorem Ipsum", props.getTitleProperty().get()); - assertEquals("Apache POI", props.getCreatorProperty().get()); + // Ensure we can change them with other timezones and still read back OK + props1.setCreatedProperty("2007-06-20T20:57:00+13:00"); + props1.setModifiedProperty("2007-06-20T20:59:00.123-13:00"); - // Check the updated times - // 2007-06-20T20:57:00+13:00 - // = 2007-06-20T07:57:00Z - assertEquals("2007-06-20T07:57:00.000Z", df.format(props.getCreatedProperty().get())); - - // 2007-06-20T20:59:00.123-13:00 - // = 2007-06-21T09:59:00.123Z - assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().get())); + pkg1.save(baos); + } + try (OPCPackage pkg2 = OPCPackage.open(baos.toInputStream())) { + PackagePropertiesPart props2 = (PackagePropertiesPart) pkg2.getPackageProperties(); + + // Check text properties first - should be unchanged + assertEquals("Lorem Ipsum", props2.getTitleProperty().orElse(null)); + assertEquals("Apache POI", props2.getCreatorProperty().orElse(null)); + + // Check the updated times + // 2007-06-20T20:57:00+13:00 + // = 2007-06-20T07:57:00Z + assertEquals("2007-06-20T07:57:00.000Z", df.format(props2.getCreatedProperty().orElse(null))); + + // 2007-06-20T20:59:00.123-13:00 + // = 2007-06-21T09:59:00.123Z + // CoreProperties are stored as xs:dateTime -> no milliseconds are saved! + assertEquals("2007-06-21T09:59:00.000Z", df.format(props2.getModifiedProperty().orElse(null))); + } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java index d80c88ae12..d6b81c9a54 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java @@ -24,12 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URI; import java.util.regex.Pattern; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; @@ -198,18 +197,16 @@ class TestRelationships { // Write out and re-load - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); pkg.save(baos); // use revert to not re-write the input file pkg.revert(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); + pkg = OPCPackage.open(baos.toInputStream()); // Check again - sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); + sheet = pkg.getPart(PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); @@ -228,7 +225,7 @@ class TestRelationships { @Test void testCreateRelationsFromScratch() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); OPCPackage pkg = OPCPackage.create(baos); PackagePart partA = @@ -255,8 +252,7 @@ class TestRelationships { // Save, and re-load pkg.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); + pkg = OPCPackage.open(baos.toInputStream()); partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); partB = pkg.getPart(PackagingURIHelper.createPartName("/partB")); @@ -297,20 +293,17 @@ class TestRelationships { @Test void testTargetWithSpecialChars() throws Exception{ - OPCPackage pkg; - String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx"); - pkg = OPCPackage.open(filepath); + OPCPackage pkg = OPCPackage.open(filepath); assert_50154(pkg); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); pkg.save(baos); // use revert to not re-write the input file pkg.revert(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); + pkg = OPCPackage.open(baos.toInputStream()); assert_50154(pkg); } @@ -359,7 +352,7 @@ class TestRelationships { @Test void testSelfRelations_bug51187() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); PackageRelationship rel1; try (OPCPackage pkg = OPCPackage.create(baos)) { @@ -374,8 +367,7 @@ class TestRelationships { // Save, and re-load } - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - try (OPCPackage pkg = OPCPackage.open(bais)) { + try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) { PackagePart partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); @@ -406,11 +398,10 @@ class TestRelationships { assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString()); assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); pkg1.save(out); - out.close(); - try (OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()))) { + try (OPCPackage pkg2 = OPCPackage.open(out.toInputStream())) { sheetRels = pkg2.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships(); assertEquals(3, sheetRels.size()); rId1 = sheetRels.getRelationshipByID("rId1"); diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java index 598630546b..9b21bb7db0 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -33,6 +32,7 @@ import java.util.TreeMap; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.IOUtils; import org.junit.jupiter.api.Assertions; import org.xmlunit.builder.DiffBuilder; @@ -52,15 +52,15 @@ public final class ZipFileAssert { } private static void equals( - TreeMap<String, ByteArrayOutputStream> file1, - TreeMap<String, ByteArrayOutputStream> file2) { + TreeMap<String, UnsynchronizedByteArrayOutputStream> file1, + TreeMap<String, UnsynchronizedByteArrayOutputStream> file2) { Set<String> listFile1 = file1.keySet(); Assertions.assertEquals(listFile1.size(), file2.keySet().size(), "not the same number of files in zip:"); for (String fileName : listFile1) { // extract the contents for both - ByteArrayOutputStream contain1 = file1.get(fileName); - ByteArrayOutputStream contain2 = file2.get(fileName); + UnsynchronizedByteArrayOutputStream contain1 = file1.get(fileName); + UnsynchronizedByteArrayOutputStream contain2 = file2.get(fileName); assertNotNull(contain2, fileName + " not found in 2nd zip"); // no need to check for contain1. The key come from it @@ -84,11 +84,11 @@ public final class ZipFileAssert { } } - private static TreeMap<String, ByteArrayOutputStream> decompress( + private static TreeMap<String, UnsynchronizedByteArrayOutputStream> decompress( File filename) throws IOException { // store the zip content in memory // let s assume it is not Go ;-) - TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>(); + TreeMap<String, UnsynchronizedByteArrayOutputStream> zipContent = new TreeMap<>(); try ( /* Open file to decompress */ @@ -106,7 +106,7 @@ public final class ZipFileAssert { while ((entree = zis.getNextEntry()) != null) { /* Create a array for the current entry */ - ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream byteArray = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(zis, byteArray); zipContent.put(entree.getName(), byteArray); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java index 3ebd4041a3..b079f00bf3 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java @@ -17,7 +17,8 @@ package org.apache.poi.openxml4j.opc.compliance; -import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openComplianceSampleStream; +import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getOutputFile; +import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile; import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -26,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -35,7 +34,7 @@ import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; -import org.apache.poi.POIDataSamples; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidOperationException; import org.apache.poi.openxml4j.opc.ContentTypes; @@ -44,7 +43,6 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.openxml4j.opc.TargetMode; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; import org.junit.jupiter.api.Test; /** @@ -81,13 +79,13 @@ public final class TestOPCComplianceCoreProperties { @Test void testCorePropertiesPart() throws IOException { - try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { + try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { assertDoesNotThrow(() -> OPCPackage.open(is).close()); } } private static String extractInvalidFormatMessage(String sampleNameSuffix) throws IOException { - try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) { + try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) { InvalidFormatException e = assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is).revert(), "expected OPC compliance exception was not thrown"); return e.getMessage(); @@ -137,7 +135,7 @@ public final class TestOPCComplianceCoreProperties { */ @Test void testOnlyOneCorePropertiesPart_AddRelationship() throws IOException, InvalidFormatException { - try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { + try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) { OPCPackage pkg = OPCPackage.open(is); URI partUri = createURI("/docProps/core2.xml"); InvalidOperationException e = assertThrows(InvalidOperationException.class, () -> @@ -155,7 +153,7 @@ public final class TestOPCComplianceCoreProperties { @Test void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException, IOException { String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"; - try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { + try (OPCPackage pkg = OPCPackage.open(getSampleFile(sampleFileName).getPath())) { URI partUri = createURI("/docProps/core2.xml"); InvalidOperationException e = assertThrows(InvalidOperationException.class, () -> @@ -218,9 +216,9 @@ public final class TestOPCComplianceCoreProperties { @Test void testNoCoreProperties_saveNew() throws Exception { String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); - try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { + try (OPCPackage pkg = OPCPackage.open(getSampleFile(sampleFileName).getPath())) { // Verify it has empty properties assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); assertNotNull(pkg.getPackageProperties()); @@ -232,7 +230,7 @@ public final class TestOPCComplianceCoreProperties { pkg.revert(); } - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) { + try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) { // An Empty Properties part has been added in the save/load assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); assertNotNull(pkg.getPackageProperties()); @@ -241,14 +239,14 @@ public final class TestOPCComplianceCoreProperties { } // Open a new copy of it - try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) { + try (OPCPackage pkg = OPCPackage.open(getSampleFile(sampleFileName).getPath())) { // Save and re-load, without having touched the properties yet baos.reset(); pkg.save(baos); pkg.revert(); } - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) { + try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) { // Check that this too added empty properties without error assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); assertNotNull(pkg.getPackageProperties()); @@ -266,9 +264,9 @@ public final class TestOPCComplianceCoreProperties { String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; // Copy this into a temp file, so we can play with it - File tmp = TempFile.createTempFile("poi-test", ".opc"); + File tmp = getOutputFile("poi-test.opc"); try (FileOutputStream out = new FileOutputStream(tmp); - InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName)) { + InputStream in = openSampleStream(sampleFileName)) { IOUtils.copy(in, out); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java index aab917ec63..1fe70833c9 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java @@ -23,12 +23,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; -import org.apache.poi.ooxml.util.POIXMLUnits; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -40,11 +39,9 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFPicture; import org.apache.poi.xssf.usermodel.XSSFPictureData; @@ -53,8 +50,6 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; public final class TestContentTypeManager { @@ -137,7 +132,7 @@ public final class TestContentTypeManager { } protected byte[] toByteArray(Workbook wb) { - try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + try (UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream()) { wb.write(os); return os.toByteArray(); } catch (IOException e) { diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java index 3b9b03aed4..40345a029a 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java @@ -17,16 +17,17 @@ package org.apache.poi.openxml4j.opc.internal.marshallers; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.exceptions.OpenXML4JException; import org.apache.poi.openxml4j.opc.PackagePartName; import org.apache.poi.openxml4j.opc.PackagingURIHelper; @@ -38,7 +39,7 @@ class TestZipPackagePropertiesMarshaller { private final PartMarshaller marshaller = new ZipPackagePropertiesMarshaller(); private boolean marshall() throws OpenXML4JException { - return marshall(new ZipArchiveOutputStream(new ByteArrayOutputStream())); + return marshall(new ZipArchiveOutputStream(new UnsynchronizedByteArrayOutputStream())); } private boolean marshall(OutputStream zos) throws OpenXML4JException { @@ -50,8 +51,7 @@ class TestZipPackagePropertiesMarshaller { @Test void nonZipOutputStream() { - OutputStream notAZipOutputStream = new ByteArrayOutputStream(0); - assertThrows(IllegalArgumentException.class, () -> marshall(notAZipOutputStream)); + assertThrows(IllegalArgumentException.class, () -> marshall(NULL_OUTPUT_STREAM)); } @Test @@ -61,7 +61,7 @@ class TestZipPackagePropertiesMarshaller { @Test void ioException() { - ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()) { + ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new UnsynchronizedByteArrayOutputStream()) { @Override public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException { throw new IOException("TestException"); diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java index 52516d0c68..afd498aa12 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java @@ -32,7 +32,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.BufferedReader; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -77,6 +76,7 @@ import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.dom.DOMSignContext; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -160,6 +160,8 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.w3.x2000.x09.xmldsig.ReferenceType; import org.w3.x2000.x09.xmldsig.SignatureDocument; import org.w3c.dom.Document; @@ -210,36 +212,36 @@ class TestSignatureInfo { @Test void bug61182() throws Exception { final String pfxInput = - "H4sIAAAAAAAAAFXTfzzTeRwH8P2uGRmG6hKSmJh9a2HsuPy60VnHCEU6v86sieZH2Jr2qFl+s+ZHJ5tfUcfKb4uho/OjiFq1qTv5ceFyp0PqEK"+ - "fH4+66++Pz+Dwer9fj8f7r9cRzEd4QMBTPRWxDIM14ZN47NfAWsJgL34Bx4at4Lvwdngvd9b8KqgbjQpGbMXzzgRGovytVFTBEzIXU47kQCd4U"+ - "ofJPvHl8JwyTjRS55hbKoor3UJLDE1i/PcPKCBAIDATjQlKiK67XjVYdcnkZgD2txroiAUb8W9dtn57DvTsbM+3wIsdocXDEN7TdPKgaSl+tU1"+ - "xq9oqiB5yMaZCPho8uUEbFU9U6u3N7lEMLTJGeA0RfX+5FMRrpXPFrbrlJ8uNUCE2H247P28Ckyfqlsy32yeKg/HTbH5JpqUDNw2B32+SaiRw7"+ - "ofRMePUpaAoK7KYgmd5ZIc0rLLYjJBfOWCb28xlrGhbpJvdToFdqt5PXVjEz5YOJ6g7W0fskuKW9/iZP0yLEVpR9XkkHmb6tfpcE8YwCdWNCan"+ - "LvAsco25JdF1j2/FLAMVU79HdOex07main90dy40511OZtTGZ+TdVd3lKZ7D3clEg9hLESHwSNnZ6239X4yLM4xYSElQ/hqSbwdmiozYG9PhF2"+ - "Zf0XaZnxzTK0Iot+rJ3kYoxWTLE8DR9leV62Ywbtlg4mapYOxb3lT7fQ1x4EQ44flh2oFWSPLR8LMbsc6jzJsV6OZ3TrODjHEdw9W+8OD32vd8"+ - "XQ6iCaIHcrSOn6qS0TKLr786234eeSAhvAQbEsVn7vrvc/487Be/O2e/+5Y5zRq2zAtz6pfcNyraJNDqMW1inNkgJ3t3VESbZ3pNzyl3KHILs0"+ - "51dY6msDYSlWhw40TglXxj9rw95O6gFWIuN012W/vhS50jpKXcao4gc1aLaXtJXxirbRkpZ/0e7a0pD6TDa7+GxEdEEML3VGo9udD5YUKhU3y7"+ - "SzWAgN6WIEIglq7LilvCjqIVLIfg8CvVGL9f5iSsCDf5hef4vMxbyvcjINuy06gZu+iPYOWNxjfrwKGYzoqqotK2aywgYVrPMh0JovfkDuN95n"+ - "MdVlYHbN1Mnn4TxAwuv+u3AkBlDZvRUUCwoDMUGxeMNPhTaAgWl60xhhBgCBaEMgAACReMAav7n3x598IDYJ9GxGXRAwaPOT/kfO/1AgPqLQkp"+ - "MiIVaHthnUS4v2y32e2BjdMPyIImUTBW3cV3R5tjVQm0MOm+D2C5+bBW9vHLjLR4lun4toQiY3Ls/v4bES/OJ4EmpZk5xhL9i5ClofYZNEsxFn"+ - "An/q821Tg+Cq9Er4XYGQe8ogjjLJ2b7dUsJ3auFQFNUJF7Ke7yUL2EeYYxl6vz5l4q5u8704mRbFts1E1eWMp6WIy91GPrsVlRGvtuNERfrjfE"+ - "YtzUI3Flcv65zJUbUBEzUnTS0fEYso2XyToAl8kb251mUY2o2lJzv5dp/1htmcjeeP2MjxC+3S45ljx7jd52Pv9XAat+ryiauFOF7YgztkoWWD"+ - "h62tplPH1bzDV+d0NLdaE5AfVJ09HuUYTFS+iggtvT5Euyk+unj4N2XvzW91n+GNjtgWfKOHmkinUPvYRh70Jv+wlPJrVaT8mL7GxJLqDC9jbv"+ - "Gznoiae6es+wQejnk3XjU366MrK/zXxngBYj9J6NnXc9mMiTFLX8WqQ8iTelTAFs2NJzPoDzrBUz4JFIEOa6Dja6dULc68g1jFDTeEHZyra7RZ"+ - "2ElqGDEqcNRo3SNX6feMy9EF1GOyZK0Sa87KwjKw8aM68dpsIYjfLcTXaZ6atg0BKfMnl6axeUGEaIFSP7rzj9wjzumRbG3jgUVp2lX5AK/tsO"+ - "7R4TQX/9/H6RiN34c9KldmPZZGANXzzTajZS9mR2OSvlJ+F4AgSko4htrMAKFTBu51/5SWNsO1vlRaaG48ZRJ+8PzuHQMdvS36gNpRPi7jhF1S"+ - "H3B2ycI4y0VURv6SrqJNUY/X645ZFJQ+eBO+ptG7o8axf1dcqh2beiQk+GRTeZ37LVeUlaeo9vl1/+8tyBfyT2v5lFC5E19WdKIyCuZe7r99Px"+ - "D/Od4Qj0TA92+DQnbCQTCMy/wwse9O4gsEebkkpPIP5GBV3Q0YBsj75XE0uSFQ1tCZSW8bNa9MUJZ/nPBfExohHlgGAAA="; + "H4sIAAAAAAAAAFXTfzzTeRwH8P2uGRmG6hKSmJh9a2HsuPy60VnHCEU6v86sieZH2Jr2qFl+s+ZHJ5tfUcfKb4uho/OjiFq1qTv5ceFyp0PqEK"+ + "fH4+66++Pz+Dwer9fj8f7r9cRzEd4QMBTPRWxDIM14ZN47NfAWsJgL34Bx4at4Lvwdngvd9b8KqgbjQpGbMXzzgRGovytVFTBEzIXU47kQCd4U"+ + "ofJPvHl8JwyTjRS55hbKoor3UJLDE1i/PcPKCBAIDATjQlKiK67XjVYdcnkZgD2txroiAUb8W9dtn57DvTsbM+3wIsdocXDEN7TdPKgaSl+tU1"+ + "xq9oqiB5yMaZCPho8uUEbFU9U6u3N7lEMLTJGeA0RfX+5FMRrpXPFrbrlJ8uNUCE2H247P28Ckyfqlsy32yeKg/HTbH5JpqUDNw2B32+SaiRw7"+ + "ofRMePUpaAoK7KYgmd5ZIc0rLLYjJBfOWCb28xlrGhbpJvdToFdqt5PXVjEz5YOJ6g7W0fskuKW9/iZP0yLEVpR9XkkHmb6tfpcE8YwCdWNCan"+ + "LvAsco25JdF1j2/FLAMVU79HdOex07main90dy40511OZtTGZ+TdVd3lKZ7D3clEg9hLESHwSNnZ6239X4yLM4xYSElQ/hqSbwdmiozYG9PhF2"+ + "Zf0XaZnxzTK0Iot+rJ3kYoxWTLE8DR9leV62Ywbtlg4mapYOxb3lT7fQ1x4EQ44flh2oFWSPLR8LMbsc6jzJsV6OZ3TrODjHEdw9W+8OD32vd8"+ + "XQ6iCaIHcrSOn6qS0TKLr786234eeSAhvAQbEsVn7vrvc/487Be/O2e/+5Y5zRq2zAtz6pfcNyraJNDqMW1inNkgJ3t3VESbZ3pNzyl3KHILs0"+ + "51dY6msDYSlWhw40TglXxj9rw95O6gFWIuN012W/vhS50jpKXcao4gc1aLaXtJXxirbRkpZ/0e7a0pD6TDa7+GxEdEEML3VGo9udD5YUKhU3y7"+ + "SzWAgN6WIEIglq7LilvCjqIVLIfg8CvVGL9f5iSsCDf5hef4vMxbyvcjINuy06gZu+iPYOWNxjfrwKGYzoqqotK2aywgYVrPMh0JovfkDuN95n"+ + "MdVlYHbN1Mnn4TxAwuv+u3AkBlDZvRUUCwoDMUGxeMNPhTaAgWl60xhhBgCBaEMgAACReMAav7n3x598IDYJ9GxGXRAwaPOT/kfO/1AgPqLQkp"+ + "MiIVaHthnUS4v2y32e2BjdMPyIImUTBW3cV3R5tjVQm0MOm+D2C5+bBW9vHLjLR4lun4toQiY3Ls/v4bES/OJ4EmpZk5xhL9i5ClofYZNEsxFn"+ + "An/q821Tg+Cq9Er4XYGQe8ogjjLJ2b7dUsJ3auFQFNUJF7Ke7yUL2EeYYxl6vz5l4q5u8704mRbFts1E1eWMp6WIy91GPrsVlRGvtuNERfrjfE"+ + "YtzUI3Flcv65zJUbUBEzUnTS0fEYso2XyToAl8kb251mUY2o2lJzv5dp/1htmcjeeP2MjxC+3S45ljx7jd52Pv9XAat+ryiauFOF7YgztkoWWD"+ + "h62tplPH1bzDV+d0NLdaE5AfVJ09HuUYTFS+iggtvT5Euyk+unj4N2XvzW91n+GNjtgWfKOHmkinUPvYRh70Jv+wlPJrVaT8mL7GxJLqDC9jbv"+ + "Gznoiae6es+wQejnk3XjU366MrK/zXxngBYj9J6NnXc9mMiTFLX8WqQ8iTelTAFs2NJzPoDzrBUz4JFIEOa6Dja6dULc68g1jFDTeEHZyra7RZ"+ + "2ElqGDEqcNRo3SNX6feMy9EF1GOyZK0Sa87KwjKw8aM68dpsIYjfLcTXaZ6atg0BKfMnl6axeUGEaIFSP7rzj9wjzumRbG3jgUVp2lX5AK/tsO"+ + "7R4TQX/9/H6RiN34c9KldmPZZGANXzzTajZS9mR2OSvlJ+F4AgSko4htrMAKFTBu51/5SWNsO1vlRaaG48ZRJ+8PzuHQMdvS36gNpRPi7jhF1S"+ + "H3B2ycI4y0VURv6SrqJNUY/X645ZFJQ+eBO+ptG7o8axf1dcqh2beiQk+GRTeZ37LVeUlaeo9vl1/+8tyBfyT2v5lFC5E19WdKIyCuZe7r99Px"+ + "D/Od4Qj0TA92+DQnbCQTCMy/wwse9O4gsEebkkpPIP5GBV3Q0YBsj75XE0uSFQ1tCZSW8bNa9MUJZ/nPBfExohHlgGAAA="; // Unix final String unixSignExp = - "QkqTFQZjXagjRAoOWKpAGa8AR0rKqkSfBtfSWqtjBmTgyjarn+t2POHkpySIpheHAbg+90GKSH88ACMtPHbG7q" + - "FL4gtgAD9Kjew6j16j0IRBwy145UlPrSLFMfF7YF7UlU1k1LBkIlRJ6Fv4MAJl6XspuzZOZIUmHZrWrdxycUQ="; + "QkqTFQZjXagjRAoOWKpAGa8AR0rKqkSfBtfSWqtjBmTgyjarn+t2POHkpySIpheHAbg+90GKSH88ACMtPHbG7q" + + "FL4gtgAD9Kjew6j16j0IRBwy145UlPrSLFMfF7YF7UlU1k1LBkIlRJ6Fv4MAJl6XspuzZOZIUmHZrWrdxycUQ="; // Windows final String winSignExp = - "GmAlL7+bT1r3FsMHJOp3pKg8betblYieZTjhMIrPZPRBbSzjO7KsYRGNtr0aOE3qr8xzyYJN6/8QdF5X7pUEUc" + - "2m8ctrm7s5o2vZTkAqk9ENJGDjBPXX7TnuVOiVeL1cJdtjHC2QpjtRwkFR+B54G6b1OXLOFuQpP3vqR3+/XXE="; + "GmAlL7+bT1r3FsMHJOp3pKg8betblYieZTjhMIrPZPRBbSzjO7KsYRGNtr0aOE3qr8xzyYJN6/8QdF5X7pUEUc" + + "2m8ctrm7s5o2vZTkAqk9ENJGDjBPXX7TnuVOiVeL1cJdtjHC2QpjtRwkFR+B54G6b1OXLOFuQpP3vqR3+/XXE="; // Mac final String macSignExp = @@ -259,13 +261,13 @@ class TestSignatureInfo { SignatureInfo si = new SignatureInfo(); si.setSignatureConfig(signatureConfig); - ByteArrayOutputStream bos = new ByteArrayOutputStream(100000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(100000); try (XSSFWorkbook wb1 = new XSSFWorkbook()) { wb1.createSheet().createRow(1).createCell(1).setCellValue("Test"); wb1.write(bos); } - try (OPCPackage pkg1 = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) { + try (OPCPackage pkg1 = OPCPackage.open(bos.toInputStream())) { si.setOpcPackage(pkg1); si.confirmSignature(); assertTrue(si.verifySignature()); @@ -273,7 +275,7 @@ class TestSignatureInfo { pkg1.save(bos); } - try (XSSFWorkbook wb2 = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { + try (XSSFWorkbook wb2 = new XSSFWorkbook(bos.toInputStream())) { assertEquals("Test", wb2.getSheetAt(0).getRow(1).getCell(1).getStringCellValue()); OPCPackage pkg2 = wb2.getPackage(); si.setOpcPackage(pkg2); @@ -306,71 +308,65 @@ class TestSignatureInfo { } } - @Test - void getSignerUnsigned() throws Exception { - String[] testFiles = { - "hello-world-unsigned.docx", - "hello-world-unsigned.pptx", - "hello-world-unsigned.xlsx", - "hello-world-office-2010-technical-preview-unsigned.docx" - }; - - for (String testFile : testFiles) { - List<X509Certificate> result = new ArrayList<>(); - try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } + @ParameterizedTest + @ValueSource(strings = { + "hello-world-unsigned.docx", + "hello-world-unsigned.pptx", + "hello-world-unsigned.xlsx", + "hello-world-office-2010-technical-preview-unsigned.docx" + }) + void getSignerUnsigned(String testFile) throws Exception { + List<X509Certificate> result = new ArrayList<>(); + try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { + SignatureConfig sic = new SignatureConfig(); + SignatureInfo si = new SignatureInfo(); + si.setOpcPackage(pkg); + si.setSignatureConfig(sic); + for (SignaturePart sp : si.getSignatureParts()) { + if (sp.validate()) { + result.add(sp.getSigner()); } - pkg.revert(); } - assertNotNull(result); - assertTrue(result.isEmpty()); + pkg.revert(); } + assertNotNull(result); + assertTrue(result.isEmpty()); } - @Test - void getSigner() throws Exception { - String[] testFiles = { - "hyperlink-example-signed.docx", - "hello-world-signed.docx", - "hello-world-signed.pptx", - "hello-world-signed.xlsx", - "hello-world-office-2010-technical-preview.docx", - "ms-office-2010-signed.docx", - "ms-office-2010-signed.pptx", - "ms-office-2010-signed.xlsx", - "Office2010-SP1-XAdES-X-L.docx", - "signed.docx" - }; - - for (String testFile : testFiles) { - try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { - SignatureConfig sic = new SignatureConfig(); - SignatureInfo si = new SignatureInfo(); - si.setOpcPackage(pkg); - si.setSignatureConfig(sic); - List<X509Certificate> result = new ArrayList<>(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } + @ParameterizedTest + @ValueSource(strings = { + "hyperlink-example-signed.docx", + "hello-world-signed.docx", + "hello-world-signed.pptx", + "hello-world-signed.xlsx", + "hello-world-office-2010-technical-preview.docx", + "ms-office-2010-signed.docx", + "ms-office-2010-signed.pptx", + "ms-office-2010-signed.xlsx", + "Office2010-SP1-XAdES-X-L.docx", + "signed.docx" + }) + void getSigner(String testFile) throws Exception { + try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) { + SignatureConfig sic = new SignatureConfig(); + SignatureInfo si = new SignatureInfo(); + si.setOpcPackage(pkg); + si.setSignatureConfig(sic); + List<X509Certificate> result = new ArrayList<>(); + for (SignaturePart sp : si.getSignatureParts()) { + if (sp.validate()) { + result.add(sp.getSigner()); } + } - assertNotNull(result); - assertEquals(1, result.size(), "test-file: " + testFile); - X509Certificate signer = result.get(0); - LOG.atDebug().log("signer: {}", signer.getSubjectX500Principal()); + assertNotNull(result); + assertEquals(1, result.size(), "test-file: " + testFile); + X509Certificate signer = result.get(0); + LOG.atDebug().log("signer: {}", signer.getSubjectX500Principal()); - boolean b = si.verifySignature(); - assertTrue(b, "test-file: " + testFile); - pkg.revert(); - } + boolean b = si.verifySignature(); + assertTrue(b, "test-file: " + testFile); + pkg.revert(); } } @@ -474,7 +470,7 @@ class TestSignatureInfo { void testSignEnvelopingDocument() throws Exception { String testFile = "hello-world-unsigned.xlsx"; File sigCopy = testdata.getFile(testFile); - ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(50000); final String execTimestr; @@ -613,7 +609,7 @@ class TestSignatureInfo { pkg.save(bos); } - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) { + try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) { SignatureConfig signatureConfig = new SignatureConfig(); signatureConfig.setUpdateConfigOnValidate(true); @@ -752,7 +748,7 @@ class TestSignatureInfo { void bug65214() throws Exception { initKeyPair(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (XWPFDocument doc = new XWPFDocument()) { XWPFHyperlinkRun r = doc.createParagraph().createHyperlinkRun("http://poi.apache.org"); r.setText("Hyperlink"); @@ -765,7 +761,7 @@ class TestSignatureInfo { signatureConfig.setKey(keyPair.getPrivate()); signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); signatureConfig.setDigestAlgo(HashAlgorithm.sha256); - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) { + try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) { SignatureInfo si = new SignatureInfo(); si.setOpcPackage(pkg); si.setSignatureConfig(signatureConfig); @@ -776,7 +772,7 @@ class TestSignatureInfo { assumeTrue(e.getMessage().startsWith("Export Restrictions")); } - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) { + try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) { SignatureInfo si = new SignatureInfo(); si.setOpcPackage(pkg); si.setSignatureConfig(signatureConfig); @@ -793,10 +789,10 @@ class TestSignatureInfo { try (SXSSFWorkbook wb1 = new SXSSFWorkbook((XSSFWorkbook)WorkbookFactory.create(tpl), 10)) { wb1.setCompressTempFiles(true); wb1.removeSheetAt(0); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); wb1.write(os); - try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(os.toByteArray()))) { + try (OPCPackage pkg = OPCPackage.open(os.toInputStream())) { initKeyPair(); SignatureConfig signatureConfig = new SignatureConfig(); signatureConfig.setKey(keyPair.getPrivate()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java index 14e6debbf4..27930ce1d0 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java @@ -20,8 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; @@ -30,6 +28,7 @@ import java.util.stream.Stream; import javax.crypto.Cipher; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.poifs.crypt.ChainingMode; import org.apache.poi.poifs.crypt.CipherAlgorithm; @@ -79,7 +78,7 @@ class TestAgileEncryptionParameters { int maxKeyLen = Cipher.getMaxAllowedKeyLength(ca.jceId); assumeTrue(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files"); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); POIFSFileSystem fsEnc = new POIFSFileSystem(); EncryptionInfo infoEnc = new EncryptionInfo(EncryptionMode.agile, ca, ha, -1, -1, cm); @@ -92,7 +91,7 @@ class TestAgileEncryptionParameters { fsEnc.writeFilesystem(bos); fsEnc.close(); - POIFSFileSystem fsDec = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); + POIFSFileSystem fsDec = new POIFSFileSystem(bos.toInputStream()); EncryptionInfo infoDec = new EncryptionInfo(fsDec); Decryptor dec = infoDec.getDecryptor(); boolean passed = dec.verifyPassword("foobaa"); diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java index fed15e2f3c..4be8a9b674 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java @@ -22,7 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -34,6 +33,7 @@ import javax.crypto.Cipher; import org.apache.commons.codec.binary.Base64; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.poifs.crypt.CryptoFunctions; import org.apache.poi.poifs.crypt.Decryptor; @@ -142,7 +142,7 @@ class TestDecryptor { Decryptor d = Decryptor.getInstance(info); d.verifyPassword("pwd123"); - final ByteArrayOutputStream bos = new ByteArrayOutputStream(10000); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(10000); try (final ZipArchiveInputStream zis = new ZipArchiveInputStream(d.getDataStream(fs))) { int[] sizes = { 3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910 }; for (int size : sizes) { diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java index ed2ee87e02..4cd6e0e1fd 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java @@ -16,6 +16,7 @@ ==================================================================== */ package org.apache.poi.poifs.crypt.tests; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -24,8 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -39,6 +38,7 @@ import java.util.Random; import javax.crypto.Cipher; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.openxml4j.opc.ContentTypes; import org.apache.poi.openxml4j.opc.OPCPackage; @@ -59,7 +59,6 @@ import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.TempFilePOIFSFileSystem; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullOutputStream; import org.apache.poi.util.TempFile; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; @@ -78,7 +77,7 @@ class TestEncryptor { payloadExpected = IOUtils.toByteArray(is); } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (POIFSFileSystem fs = new POIFSFileSystem()) { EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); Encryptor enc = ei.getEncryptor(); @@ -92,7 +91,7 @@ class TestEncryptor { } final byte[] payloadActual; - try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { + try (POIFSFileSystem fs = new POIFSFileSystem(bos.toInputStream())) { EncryptionInfo ei = new EncryptionInfo(fs); Decryptor dec = ei.getDecryptor(); boolean b = dec.verifyPassword(password); @@ -115,7 +114,7 @@ class TestEncryptor { payloadExpected = IOUtils.toByteArray(is); } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (POIFSFileSystem fs = new TempFilePOIFSFileSystem()) { EncryptionInfo ei = new EncryptionInfo(EncryptionMode.agile); Encryptor enc = ei.getEncryptor(); @@ -129,7 +128,7 @@ class TestEncryptor { } final byte[] payloadActual; - try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { + try (POIFSFileSystem fs = new POIFSFileSystem(bos.toInputStream())) { EncryptionInfo ei = new EncryptionInfo(fs); Decryptor dec = ei.getDecryptor(); boolean b = dec.verifyPassword(password); @@ -202,7 +201,7 @@ class TestEncryptor { Encryptor e = Encryptor.getInstance(infoActual); e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (POIFSFileSystem fs = new POIFSFileSystem()) { try (OutputStream os = e.getDataStream(fs)) { os.write(payloadExpected); @@ -213,7 +212,7 @@ class TestEncryptor { final EncryptionInfo infoActual2; final byte[] payloadActual, encPackActual; final long decPackLenActual; - try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { + try (POIFSFileSystem nfs = new POIFSFileSystem(bos.toInputStream())) { infoActual2 = new EncryptionInfo(nfs.getRoot()); Decryptor decActual = Decryptor.getInstance(infoActual2); boolean passed = decActual.verifyPassword(pass); @@ -289,7 +288,7 @@ class TestEncryptor { // now we use a newly generated salt/verifier and check // if the file content is still the same - final byte[] encBytes; + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(50000); try (POIFSFileSystem fs = new POIFSFileSystem()) { final EncryptionInfo infoActual2 = new EncryptionInfo( @@ -308,13 +307,11 @@ class TestEncryptor { os.write(payloadExpected); } - final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); fs.writeFilesystem(bos); - encBytes = bos.toByteArray(); } final byte[] payloadActual; - try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) { + try (POIFSFileSystem nfs = new POIFSFileSystem(bos.toInputStream())) { final EncryptionInfo ei = new EncryptionInfo(nfs); Decryptor d2 = Decryptor.getInstance(ei); assertTrue(d2.verifyPassword(pass), "Unable to process: document is encrypted"); @@ -336,7 +333,7 @@ class TestEncryptor { @Test void encryptPackageWithoutCoreProperties() throws Exception { // Open our file without core properties - final byte[] encBytes; + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try (InputStream is = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("OPCCompliance_NoCoreProperties.xlsx"); OPCPackage pkg = OPCPackage.open(is)) { @@ -358,14 +355,12 @@ class TestEncryptor { } // Save the resulting OLE2 document, and re-open it - ByteArrayOutputStream baos = new ByteArrayOutputStream(); fs.writeFilesystem(baos); - encBytes = baos.toByteArray(); } } - try (POIFSFileSystem inpFS = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) { + try (POIFSFileSystem inpFS = new POIFSFileSystem(baos.toInputStream())) { // Check we can decrypt it EncryptionInfo info = new EncryptionInfo(inpFS); Decryptor d = Decryptor.getInstance(info); @@ -539,10 +534,10 @@ class TestEncryptor { os.write(zipInput); } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); fsNew.writeFilesystem(bos); - try (POIFSFileSystem fsReload = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) { + try (POIFSFileSystem fsReload = new POIFSFileSystem(bos.toInputStream())) { infoReload = new EncryptionInfo(fsReload); try (InputStream epReload = fsReload.getRoot().createDocumentInputStream("EncryptedPackage")) { epNewBytes = IOUtils.toByteArray(epReload, 9400); @@ -633,9 +628,8 @@ class TestEncryptor { assertTrue(passOk); try (InputStream is = dec.getDataStream(poifs); - DigestInputStream dis = new DigestInputStream(is, md); - NullOutputStream nos = new NullOutputStream()) { - IOUtils.copy(dis, nos); + DigestInputStream dis = new DigestInputStream(is, md)) { + IOUtils.copy(dis, NULL_OUTPUT_STREAM); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java index bf5aebb590..6f4f27c486 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java @@ -26,28 +26,20 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.stream.Stream; -import org.apache.poi.hssf.model.WorkbookRecordList; -import org.apache.poi.hssf.record.FilePassRecord; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; import org.apache.poi.extractor.ExtractorFactory; import org.apache.poi.extractor.POITextExtractor; -import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionHeader; import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; import org.apache.poi.poifs.storage.RawDataUtil; import org.junit.jupiter.api.Test; @@ -110,14 +102,13 @@ class TestHxxFEncryption { private void newPassword(String newPass, POIDataSamples sampleDir, String file, String password, String expected) throws IOException { File f = sampleDir.getFile(file); Biff8EncryptionKey.setCurrentUserPassword(password); - try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) { + try (POITextExtractor te1 = ExtractorFactory.createExtractor(f); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { Biff8EncryptionKey.setCurrentUserPassword(newPass); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (POIDocument doc = (POIDocument) te1.getDocument()) { doc.write(bos); } - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - try (POITextExtractor te2 = ExtractorFactory.createExtractor(bis)) { + try (POITextExtractor te2 = ExtractorFactory.createExtractor(bos.toInputStream())) { String actual = te2.getText().trim(); assertEquals(expected, actual); } @@ -131,9 +122,9 @@ class TestHxxFEncryption { @MethodSource("data") void changeEncryption(POIDataSamples sampleDir, String file, String password, String expected) throws IOException { File f = sampleDir.getFile(file); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); Biff8EncryptionKey.setCurrentUserPassword(password); - try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) { + try (POITextExtractor te1 = ExtractorFactory.createExtractor(f); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { // first remove encryption Biff8EncryptionKey.setCurrentUserPassword(null); try (POIDocument doc = (POIDocument) te1.getDocument()) { @@ -141,7 +132,7 @@ class TestHxxFEncryption { } // then use default setting, which is cryptoapi String newPass = "newPass"; - try (POITextExtractor te2 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()))) { + try (POITextExtractor te2 = ExtractorFactory.createExtractor(bos.toInputStream())) { Biff8EncryptionKey.setCurrentUserPassword(newPass); try (POIDocument doc = (POIDocument) te2.getDocument()) { bos.reset(); @@ -149,7 +140,7 @@ class TestHxxFEncryption { } } // and finally update cryptoapi setting - try (POITextExtractor te3 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray())); + try (POITextExtractor te3 = ExtractorFactory.createExtractor(bos.toInputStream()); POIDocument doc = (POIDocument) te3.getDocument()) { // need to cache data (i.e. read all data) before changing the key size Class<?> clazz = doc.getClass(); @@ -167,7 +158,7 @@ class TestHxxFEncryption { doc.write(bos); } // check the setting - try (POITextExtractor te4 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray())); + try (POITextExtractor te4 = ExtractorFactory.createExtractor(bos.toInputStream()); POIDocument doc = (POIDocument) te4.getDocument()) { EncryptionInfo ei = doc.getEncryptionInfo(); assertNotNull(ei); @@ -181,7 +172,7 @@ class TestHxxFEncryption { @Test public void changeEncryptionMode() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(10_000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(10_000); try (HSSFWorkbook wb = new HSSFWorkbook()) { wb.createSheet().createRow(1).createCell(1).setCellValue("Test"); @@ -189,7 +180,7 @@ class TestHxxFEncryption { wb.write(bos); } - try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { + try (HSSFWorkbook wb = new HSSFWorkbook(bos.toInputStream())) { assertEquals(EncryptionMode.cryptoAPI, wb.getEncryptionMode()); wb.setEncryptionMode(EncryptionMode.binaryRC4); Biff8EncryptionKey.setCurrentUserPassword("test2"); @@ -197,7 +188,7 @@ class TestHxxFEncryption { wb.write(bos); } - try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { + try (HSSFWorkbook wb = new HSSFWorkbook(bos.toInputStream())) { assertEquals(EncryptionMode.binaryRC4, wb.getEncryptionMode()); wb.setEncryptionMode(null); bos.reset(); @@ -206,7 +197,7 @@ class TestHxxFEncryption { assertNull(Biff8EncryptionKey.getCurrentUserPassword()); - try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { + try (HSSFWorkbook wb = new HSSFWorkbook(bos.toInputStream())) { assertNull(wb.getEncryptionMode()); wb.setEncryptionMode(null); assertEquals("Test", wb.getSheetAt(0).getRow(1).getCell(1).getStringCellValue()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java index bda636d2ad..8352e0061c 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java +++ b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java @@ -29,8 +29,6 @@ import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -39,6 +37,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.stream.Stream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -114,7 +113,7 @@ class TestOleShape { @ParameterizedTest @MethodSource("data") void embedData(Api api, ObjectMetaData.Application app) throws IOException, ReflectiveOperationException { - final ByteArrayInputStream pptBytes; + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(50000); try (SlideShow<?,?> ppt = createSlideShow(api)) { final PictureData picData = ppt.addPicture(pictureFile, PictureType.EMF); final Slide<?,?> slide = ppt.createSlide(); @@ -123,11 +122,9 @@ class TestOleShape { try (OutputStream os = oleShape.updateObjectData(app, null)) { fillOleData(app, os); } - final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); ppt.write(bos); - pptBytes = new ByteArrayInputStream(bos.toByteArray()); } - try (SlideShow<?,?> ppt = SlideShowFactory.create(pptBytes)) { + try (SlideShow<?,?> ppt = SlideShowFactory.create(bos.toInputStream())) { final ObjectShape<?,?> oleShape = (ObjectShape<?,?>)ppt.getSlides().get(0).getShapes().get(0); try (InputStream bis = oleShape.readObjectData()) { validateOleData(app, bis); diff --git a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java index eb066e4688..06c358a459 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java +++ b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java @@ -24,11 +24,10 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; @@ -56,10 +55,10 @@ class TestSlide { ppt1.createSlide().setHidden(true); ppt1.createSlide(); - try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { ppt1.write(bos); - try (InputStream is = new ByteArrayInputStream(bos.toByteArray()); + try (InputStream is = bos.toInputStream(); SlideShow<?, ?> ppt2 = SlideShowFactory.create(is)) { Boolean[] hiddenState = ppt2.getSlides().stream().map(Slide::isHidden).toArray(Boolean[]::new); diff --git a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java index cedb11eed0..ccd6d86aa5 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java +++ b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java @@ -29,11 +29,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; @@ -42,6 +40,8 @@ import org.apache.poi.sl.usermodel.TableShape; import org.apache.poi.sl.usermodel.TextShape.TextDirection; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class TestTable { @@ -51,26 +51,23 @@ class TestTable { // Test of table dimensions of same slideshow saved as ppt/x // to check if both return similar (points) value - SlideShow<?,?> ppt = openSampleSlideshow("table_test.ppt"); - TableShape<?,?> ts = (TableShape<?,?>)ppt.getSlides().get(0).getShapes().get(0); - - SlideShow<?,?> pptx = openSampleSlideshow("table_test.pptx"); - TableShape<?,?> tsx = (TableShape<?,?>)pptx.getSlides().get(0).getShapes().get(0); - - // assume table shape should be equal to itself - confirmTableShapeEqual(ts, ts); - confirmTableShapeEqual(tsx, tsx); - - // assert ppt and pptx versions of the same table have the same shape - confirmTableShapeEqual(ts, tsx); - - // change row height and validate again - tsx.setRowHeight(1, 50); - ts.setRowHeight(1, 50); - confirmTableShapeEqual(ts, tsx); - - pptx.close(); - ppt.close(); + try (SlideShow<?,?> ppt = openSampleSlideshow("table_test.ppt"); + SlideShow<?,?> pptx = openSampleSlideshow("table_test.pptx")) { + TableShape<?, ?> ts = (TableShape<?, ?>) ppt.getSlides().get(0).getShapes().get(0); + TableShape<?, ?> tsx = (TableShape<?, ?>) pptx.getSlides().get(0).getShapes().get(0); + + // assume table shape should be equal to itself + confirmTableShapeEqual(ts, ts); + confirmTableShapeEqual(tsx, tsx); + + // assert ppt and pptx versions of the same table have the same shape + confirmTableShapeEqual(ts, tsx); + + // change row height and validate again + tsx.setRowHeight(1, 50); + ts.setRowHeight(1, 50); + confirmTableShapeEqual(ts, tsx); + } } private void confirmTableShapeEqual(TableShape<?,?> tableA, TableShape<?,?> tableB) { @@ -95,16 +92,16 @@ class TestTable { @Test void directionHSLF() throws IOException { assumeFalse(xslfOnly()); - SlideShow<?,?> ppt1 = SlideShowFactory.create(false); - testTextDirection(ppt1); - ppt1.close(); + try (SlideShow<?,?> ppt1 = SlideShowFactory.create(false)) { + testTextDirection(ppt1); + } } @Test void directionXSLF() throws IOException { - SlideShow<?,?> ppt1 = new XMLSlideShow(); - testTextDirection(ppt1); - ppt1.close(); + try (SlideShow<?,?> ppt1 = new XMLSlideShow()) { + testTextDirection(ppt1); + } } private void testTextDirection(SlideShow<?,?> ppt1) throws IOException { @@ -128,27 +125,26 @@ class TestTable { } } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); ppt1.write(bos); - ppt1.close(); - InputStream is = new ByteArrayInputStream(bos.toByteArray()); - SlideShow<?,?> ppt2 = SlideShowFactory.create(is); - TableShape<?,?> tbl2 = (TableShape<?,?>)ppt2.getSlides().get(0).getShapes().get(0); + try (SlideShow<?,?> ppt2 = SlideShowFactory.create(bos.toInputStream())) { + TableShape<?, ?> tbl2 = (TableShape<?, ?>) ppt2.getSlides().get(0).getShapes().get(0); - col = 0; - for (TextDirection td : tds) { - TableCell<?,?> c = tbl2.getCell(0, col++); - assertEquals(td, c.getTextDirection()); + col = 0; + for (TextDirection td : tds) { + TableCell<?, ?> c = tbl2.getCell(0, col++); + assertEquals(td, c.getTextDirection()); + } } - ppt2.close(); } - @Test - void tableSpan() throws IOException { - String[] files = (xslfOnly()) ? new String[]{"bug60993.pptx"} : new String[]{"bug60993.pptx", "bug60993.ppt"}; - for (String f : files) { - SlideShow<?,?> ppt = openSampleSlideshow(f); + @ParameterizedTest + @ValueSource(strings = {"bug60993.pptx", "bug60993.ppt"}) + void tableSpan(String file) throws IOException { + assumeFalse(file.endsWith("ppt") && xslfOnly()); + + try (SlideShow<?,?> ppt = openSampleSlideshow(file)) { Slide<?,?> slide = ppt.getSlides().get(0); TableShape<?,?> ts = (TableShape<?,?>)slide.getShapes().get(0); int cols = ts.getNumberOfColumns(); @@ -157,11 +153,11 @@ class TestTable { for (int c=0; c<cols; c++) { TableCell<?,?> tc = ts.getCell(r, c); int rc = r*10+c; - String msg = f+" (r"+r+",c"+c+")"; + String msg = file+" (r"+r+",c"+c+")"; switch (rc) { case 22: case 51: - if (f.endsWith("ppt")) { + if (file.endsWith("ppt")) { assertNull(tc, msg); } else { assertNotNull(tc, msg); @@ -189,7 +185,6 @@ class TestTable { } } } - ppt.close(); } } }
\ No newline at end of file diff --git a/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java b/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java index 001ea8ebce..4c085df879 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java +++ b/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; @@ -35,6 +34,7 @@ import java.util.List; import java.util.Locale; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.ClassIDPredefined; import org.apache.poi.hssf.HSSFTestDataSamples; @@ -121,9 +121,9 @@ class TestEmbedOLEPackage { try (POIFSFileSystem scratchFS = new POIFSFileSystem(); POIFSFileSystem ole1FS = new POIFSFileSystem(new ByteArrayInputStream(oleShapes.get(0).getObjectData()))) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); scratch.writeOut(bos); - scratchFS.createDocument(new ByteArrayInputStream(bos.toByteArray()), Ole10Native.OLE10_NATIVE); + scratchFS.createDocument(bos.toInputStream(), Ole10Native.OLE10_NATIVE); scratchFS.getRoot().setStorageClsid(ClassIDPredefined.OLE_V1_PACKAGE.getClassID()); assertTrue(EntryUtils.areDirectoriesIdentical(ole1FS.getRoot(), scratchFS.getRoot())); } @@ -220,7 +220,7 @@ class TestEmbedOLEPackage { sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200)); sh1.setFillColor(java.awt.Color.red); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); ppt.write(bos); ppt.close(); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java index 08250192ac..5b239a8ad6 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java @@ -20,6 +20,7 @@ import static org.apache.poi.POITestCase.assertContains; import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_HREF; import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_LABEL; import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument; +import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -32,7 +33,6 @@ import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.Color; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -76,13 +76,15 @@ import org.apache.poi.sl.usermodel.TextRun; import org.apache.poi.sl.usermodel.TextShape; import org.apache.poi.sl.usermodel.VerticalAlignment; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.xslf.usermodel.*; import org.apache.poi.xslf.util.DummyGraphics2d; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.ThrowingSupplier; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; @@ -121,89 +123,87 @@ class TestXSLFBugs { @Test void bug62736() throws Exception { - XMLSlideShow ss1 = openSampleDocument("bug62736.pptx"); - - assertEquals(1, ss1.getSlides().size()); + try (XMLSlideShow ss1 = openSampleDocument("bug62736.pptx")) { + assertEquals(1, ss1.getSlides().size()); - XSLFSlide slide0 = ss1.getSlides().get(0); + XSLFSlide slide0 = ss1.getSlides().get(0); - assertEquals(slide0.getShapes().size(), 4); + assertEquals(slide0.getShapes().size(), 4); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertRelation(slide0, "/ppt/media/image1.png", "rId2"); - assertEquals(slide0.getRelations().size(), 2); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); + assertRelation(slide0, "/ppt/media/image1.png", "rId2"); + assertEquals(slide0.getRelations().size(), 2); - List<XSLFPictureShape> pictures = new ArrayList<>(); - for (XSLFShape shape : slide0.getShapes()) { - if (shape instanceof XSLFPictureShape) { - pictures.add((XSLFPictureShape) shape); + List<XSLFPictureShape> pictures = new ArrayList<>(); + for (XSLFShape shape : slide0.getShapes()) { + if (shape instanceof XSLFPictureShape) { + pictures.add((XSLFPictureShape) shape); + } } - } - assertEquals(pictures.size(), 2); - assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); - assertEquals(pictures.get(1).getPictureData().getFileName(), "image1.png"); - // blipId is rId2 of both pictures + assertEquals(pictures.size(), 2); + assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); + assertEquals(pictures.get(1).getPictureData().getFileName(), "image1.png"); + // blipId is rId2 of both pictures - // remove just the first picture - slide0.removeShape(pictures.get(0)); + // remove just the first picture + slide0.removeShape(pictures.get(0)); - assertEquals(slide0.getShapes().size(), 3); + assertEquals(slide0.getShapes().size(), 3); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - // the bug is that the following relation is gone - assertRelation(slide0, "/ppt/media/image1.png", "rId2"); - assertEquals(slide0.getRelations().size(), 2); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); + // the bug is that the following relation is gone + assertRelation(slide0, "/ppt/media/image1.png", "rId2"); + assertEquals(slide0.getRelations().size(), 2); - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); - ss1.close(); - assertEquals(1, ss2.getSlides().size()); + // Save and re-load + try (XMLSlideShow ss2 = writeOutAndReadBack(ss1)) { + assertEquals(1, ss2.getSlides().size()); - slide0 = ss2.getSlides().get(0); + slide0 = ss2.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertRelation(slide0, "/ppt/media/image1.png", "rId2"); - assertEquals(slide0.getRelations().size(), 2); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); + assertRelation(slide0, "/ppt/media/image1.png", "rId2"); + assertEquals(slide0.getRelations().size(), 2); - pictures.clear(); - for (XSLFShape shape : slide0.getShapes()) { - if (shape instanceof XSLFPictureShape) { - pictures.add((XSLFPictureShape) shape); - } - } + pictures.clear(); + for (XSLFShape shape : slide0.getShapes()) { + if (shape instanceof XSLFPictureShape) { + pictures.add((XSLFPictureShape) shape); + } + } - assertEquals(pictures.size(), 1); - assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); + assertEquals(pictures.size(), 1); + assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); - slide0.removeShape(pictures.get(0)); + slide0.removeShape(pictures.get(0)); - assertEquals(slide0.getShapes().size(), 2); + assertEquals(slide0.getShapes().size(), 2); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertNull(slide0.getRelationById("rId2")); - assertEquals(slide0.getRelations().size(), 1); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); + assertNull(slide0.getRelationById("rId2")); + assertEquals(slide0.getRelations().size(), 1); - // Save and re-load - XMLSlideShow ss3 = XSLFTestDataSamples.writeOutAndReadBack(ss2); - ss2.close(); - assertEquals(1, ss3.getSlides().size()); + // Save and re-load + try (XMLSlideShow ss3 = writeOutAndReadBack(ss2)) { + assertEquals(1, ss3.getSlides().size()); - slide0 = ss3.getSlides().get(0); + slide0 = ss3.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertEquals(slide0.getShapes().size(), 2); - ss3.close(); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); + assertEquals(slide0.getShapes().size(), 2); + } + } + } } @Test void bug61589() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (XMLSlideShow src = new XMLSlideShow(); XMLSlideShow dest = new XMLSlideShow()) { XSLFSlide slide = src.createSlide(); @@ -229,71 +229,65 @@ class TestXSLFBugs { dest.createSlide().importContent(slide); dest.createSlide().importContent(slide2); - dest.write(bos); + try (XMLSlideShow ppt3 = writeOutAndReadBack(dest)) { + XSLFSlide slide3 = ppt3.getSlides().get(0); + XSLFTextBox shape3 = (XSLFTextBox) slide3.getShapes().get(0); + XSLFTextParagraph p3 = shape3.getTextParagraphs().get(1); + XSLFHyperlink h1 = p3.getTextRuns().get(0).getHyperlink(); + assertNotNull(h1); + assertEquals("https://poi.apache.org", h1.getAddress()); + XSLFHyperlink h2 = p3.getTextRuns().get(2).getHyperlink(); + assertNotNull(h2); + // relative url will be resolved to an absolute url, therefore this doesn't equals to "slide2.xml" + assertEquals("/ppt/slides/slide2.xml", h2.getAddress()); + RelationPart sldRef = slide3.getRelationPartById(h2.getXmlObject().getId()); + assertTrue(sldRef.getDocumentPart() instanceof XSLFSlide); + } } - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { - XSLFSlide slide = ppt.getSlides().get(0); - XSLFTextBox shape = (XSLFTextBox) slide.getShapes().get(0); - XSLFTextParagraph p = shape.getTextParagraphs().get(1); - XSLFHyperlink h1 = p.getTextRuns().get(0).getHyperlink(); - assertNotNull(h1); - assertEquals("https://poi.apache.org", h1.getAddress()); - XSLFHyperlink h2 = p.getTextRuns().get(2).getHyperlink(); - assertNotNull(h2); - // relative url will be resolved to an absolute url, therefore this doesn't equals to "slide2.xml" - assertEquals("/ppt/slides/slide2.xml", h2.getAddress()); - RelationPart sldRef = slide.getRelationPartById(h2.getXmlObject().getId()); - assertTrue(sldRef.getDocumentPart() instanceof XSLFSlide); - } } @Test void bug62587() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (XMLSlideShow ppt = new XMLSlideShow()) { - Slide<?, ?> slide = ppt.createSlide(); - XSLFPictureData pd = ppt.addPicture(slTests.getFile("wrench.emf"), PictureType.EMF); - PictureShape<?, ?> ps = slide.createPicture(pd); - ps.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); - ppt.write(bos); - } - Object[][] pics = { {"santa.wmf", PictureType.WMF, XSLFRelation.IMAGE_WMF}, {"tomcat.png", PictureType.PNG, XSLFRelation.IMAGE_PNG}, {"clock.jpg", PictureType.JPEG, XSLFRelation.IMAGE_JPEG} }; - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { - XSLFSlide s1 = ppt.getSlides().get(0); - - for (Object[] p : pics) { - XSLFSlide s2 = ppt.createSlide(); - s2.importContent(s1); - - XSLFPictureData pd = ppt.addPicture(slTests.getFile((String) p[0]), (PictureType) p[1]); - XSLFPictureShape ps = (XSLFPictureShape) s2.getShapes().get(0); - Rectangle2D anchor = ps.getAnchor(); - s2.removeShape(ps); - ps = s2.createPicture(pd); - ps.setAnchor(anchor); - } - - bos.reset(); - ppt.write(bos); - } + try (XMLSlideShow ppt1 = new XMLSlideShow()) { + Slide<?, ?> slide = ppt1.createSlide(); + XSLFPictureData pd1 = ppt1.addPicture(slTests.getFile("wrench.emf"), PictureType.EMF); + PictureShape<?, ?> ps1 = slide.createPicture(pd1); + ps1.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); + + try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + XSLFSlide s1 = ppt2.getSlides().get(0); + + for (Object[] p : pics) { + XSLFSlide s2 = ppt2.createSlide(); + s2.importContent(s1); + + XSLFPictureData pd2 = ppt2.addPicture(slTests.getFile((String) p[0]), (PictureType) p[1]); + XSLFPictureShape ps2 = (XSLFPictureShape) s2.getShapes().get(0); + Rectangle2D anchor2 = ps2.getAnchor(); + s2.removeShape(ps2); + ps2 = s2.createPicture(pd2); + ps2.setAnchor(anchor2); + } - try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) { - for (XSLFSlide sl : ppt.getSlides()) { - List<RelationPart> rels = sl.getRelationParts(); - assertEquals(2, rels.size()); - RelationPart rel0 = rels.get(0); - assertEquals("rId1", rel0.getRelationship().getId()); - assertEquals(XSLFRelation.SLIDE_LAYOUT.getRelation(), rel0.getRelationship().getRelationshipType()); - RelationPart rel1 = rels.get(1); - assertEquals("rId2", rel1.getRelationship().getId()); - assertEquals(XSLFRelation.IMAGES.getRelation(), rel1.getRelationship().getRelationshipType()); + try (XMLSlideShow ppt3 = writeOutAndReadBack(ppt2)) { + for (XSLFSlide sl : ppt3.getSlides()) { + List<RelationPart> rels = sl.getRelationParts(); + assertEquals(2, rels.size()); + RelationPart rel0 = rels.get(0); + assertEquals("rId1", rel0.getRelationship().getId()); + assertEquals(XSLFRelation.SLIDE_LAYOUT.getRelation(), rel0.getRelationship().getRelationshipType()); + RelationPart rel1 = rels.get(1); + assertEquals("rId2", rel1.getRelationship().getId()); + assertEquals(XSLFRelation.IMAGES.getRelation(), rel1.getRelationship().getRelationshipType()); + } + } } } } @@ -301,78 +295,73 @@ class TestXSLFBugs { @Test void bug60499() throws IOException, InvalidFormatException { - InputStream is = slTests.openResourceAsStream("bug60499.pptx"); - byte[] buf = IOUtils.toByteArray(is); - is.close(); - PackagePartName ppn = PackagingURIHelper.createPartName("/ppt/media/image1.png"); - XMLSlideShow ppt1 = new XMLSlideShow(new ByteArrayInputStream(buf)); - XSLFSlide slide1 = ppt1.getSlides().get(0); - - Optional<XSLFShape> shapeToDelete1 = - slide1.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).findFirst(); - - assertTrue(shapeToDelete1.isPresent()); - slide1.removeShape(shapeToDelete1.get()); - assertTrue(slide1.getRelationParts().stream() - .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId()))); - - assertNotNull(ppt1.getPackage().getPart(ppn)); - ppt1.close(); - - XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(buf)); - XSLFSlide slide2 = ppt2.getSlides().get(0); - - Optional<XSLFShape> shapeToDelete2 = - slide2.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).skip(1).findFirst(); - assertTrue(shapeToDelete2.isPresent()); - slide2.removeShape(shapeToDelete2.get()); - assertTrue(slide2.getRelationParts().stream() - .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId()))); - assertNotNull(ppt2.getPackage().getPart(ppn)); - ppt2.close(); - - XMLSlideShow ppt3 = new XMLSlideShow(new ByteArrayInputStream(buf)); - XSLFSlide slide3 = ppt3.getSlides().get(0); - slide3.getShapes().stream() - .filter(s -> s instanceof XSLFPictureShape) - .collect(Collectors.toList()) - .forEach(slide3::removeShape); - assertNull(ppt3.getPackage().getPart(ppn)); - ppt3.close(); + try (XMLSlideShow ppt1 = openSampleDocument("bug60499.pptx")) { + XSLFSlide slide1 = ppt1.getSlides().get(0); + + Optional<XSLFShape> shapeToDelete1 = + slide1.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).findFirst(); + + assertTrue(shapeToDelete1.isPresent()); + slide1.removeShape(shapeToDelete1.get()); + assertTrue(slide1.getRelationParts().stream() + .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId()))); + + assertNotNull(ppt1.getPackage().getPart(ppn)); + } + + try (XMLSlideShow ppt2 = openSampleDocument("bug60499.pptx")) { + XSLFSlide slide2 = ppt2.getSlides().get(0); + Optional<XSLFShape> shapeToDelete2 = + slide2.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).skip(1).findFirst(); + assertTrue(shapeToDelete2.isPresent()); + slide2.removeShape(shapeToDelete2.get()); + assertTrue(slide2.getRelationParts().stream() + .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId()))); + assertNotNull(ppt2.getPackage().getPart(ppn)); + } + + try (XMLSlideShow ppt3 = openSampleDocument("bug60499.pptx")) { + XSLFSlide slide3 = ppt3.getSlides().get(0); + slide3.getShapes().stream() + .filter(s -> s instanceof XSLFPictureShape) + .collect(Collectors.toList()) + .forEach(slide3::removeShape); + assertNull(ppt3.getPackage().getPart(ppn)); + } } @Test void bug51187() throws Exception { - XMLSlideShow ss1 = openSampleDocument("51187.pptx"); - - assertEquals(1, ss1.getSlides().size()); - - // Check the relations on it - // Note - rId3 is a self reference - XSLFSlide slide0 = ss1.getSlides().get(0); - - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); - ss1.close(); - assertEquals(1, ss2.getSlides().size()); - - slide0 = ss2.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - // TODO Fix this - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - - ss2.close(); + try (XMLSlideShow ss1 = openSampleDocument("51187.pptx")) { + + assertEquals(1, ss1.getSlides().size()); + + // Check the relations on it + // Note - rId3 is a self reference + XSLFSlide slide0 = ss1.getSlides().get(0); + + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); + assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); + assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); + assertRelation(slide0, "/ppt/media/image1.png", "rId4"); + + // Save and re-load + try (XMLSlideShow ss2 = writeOutAndReadBack(ss1)) { + assertEquals(1, ss2.getSlides().size()); + + slide0 = ss2.getSlides().get(0); + assertRelation(slide0, "/ppt/slides/slide1.xml", null); + assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); + assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); + // TODO Fix this + assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); + assertRelation(slide0, "/ppt/media/image1.png", "rId4"); + + } + } } private static void assertRelation(XSLFSlide slide, String exp, String rId) { @@ -386,41 +375,40 @@ class TestXSLFBugs { */ @Test void tika705() throws Exception { - XMLSlideShow ss = openSampleDocument("with_japanese.pptx"); - - // Should have one slide - assertEquals(1, ss.getSlides().size()); - XSLFSlide slide = ss.getSlides().get(0); - - // Check the relations from this - Collection<RelationPart> rels = slide.getRelationParts(); - - // Should have 6 relations: - // 1 external hyperlink (skipped from list) - // 4 internal hyperlinks - // 1 slide layout - assertEquals(5, rels.size()); - int layouts = 0; - int hyperlinks = 0; - for (RelationPart p : rels) { - if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - hyperlinks++; - } else if (p.getDocumentPart() instanceof XSLFSlideLayout) { - layouts++; + try (XMLSlideShow ss = openSampleDocument("with_japanese.pptx")) { + // Should have one slide + assertEquals(1, ss.getSlides().size()); + XSLFSlide slide = ss.getSlides().get(0); + + // Check the relations from this + Collection<RelationPart> rels = slide.getRelationParts(); + + // Should have 6 relations: + // 1 external hyperlink (skipped from list) + // 4 internal hyperlinks + // 1 slide layout + assertEquals(5, rels.size()); + int layouts = 0; + int hyperlinks = 0; + for (RelationPart p : rels) { + if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { + hyperlinks++; + } else if (p.getDocumentPart() instanceof XSLFSlideLayout) { + layouts++; + } } - } - assertEquals(1, layouts); - assertEquals(4, hyperlinks); - - // Hyperlinks should all be to #_ftn1 or #ftnref1 - for (RelationPart p : rels) { - if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - URI target = p.getRelationship().getTargetURI(); - String frag = target.getFragment(); - assertTrue(frag.equals("_ftn1") || frag.equals("_ftnref1"), "Invalid target " + frag + " on " + target); + assertEquals(1, layouts); + assertEquals(4, hyperlinks); + + // Hyperlinks should all be to #_ftn1 or #ftnref1 + for (RelationPart p : rels) { + if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { + URI target = p.getRelationship().getTargetURI(); + String frag = target.getFragment(); + assertTrue(frag.equals("_ftn1") || frag.equals("_ftnref1"), "Invalid target " + frag + " on " + target); + } } } - ss.close(); } /** @@ -459,34 +447,34 @@ class TestXSLFBugs { */ @Test void bug56812() throws Exception { - XMLSlideShow ppt = openSampleDocument("56812.pptx"); - - int internalPictures = 0; - int externalPictures = 0; - for (XSLFSlide slide : ppt.getSlides()) { - for (XSLFShape shape : slide.getShapes()) { - assertNotNull(shape); - - if (shape instanceof XSLFPictureShape) { - XSLFPictureShape picture = (XSLFPictureShape) shape; - if (picture.isExternalLinkedPicture()) { - externalPictures++; - - assertNotNull(picture.getPictureLink()); - } else { - internalPictures++; - - XSLFPictureData data = picture.getPictureData(); - assertNotNull(data); - assertNotNull(data.getFileName()); + try (XMLSlideShow ppt = openSampleDocument("56812.pptx")) { + + int internalPictures = 0; + int externalPictures = 0; + for (XSLFSlide slide : ppt.getSlides()) { + for (XSLFShape shape : slide.getShapes()) { + assertNotNull(shape); + + if (shape instanceof XSLFPictureShape) { + XSLFPictureShape picture = (XSLFPictureShape) shape; + if (picture.isExternalLinkedPicture()) { + externalPictures++; + + assertNotNull(picture.getPictureLink()); + } else { + internalPictures++; + + XSLFPictureData data = picture.getPictureData(); + assertNotNull(data); + assertNotNull(data.getFileName()); + } } } } - } - assertEquals(2, internalPictures); - assertEquals(1, externalPictures); - ppt.close(); + assertEquals(2, internalPictures); + assertEquals(1, externalPictures); + } } private String getSlideText(XMLSlideShow ppt, XSLFSlide slide) throws IOException { @@ -502,29 +490,29 @@ class TestXSLFBugs { @Test void bug57250() throws Exception { - XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1", "Slide2"}) { - ss.createSlide().createTextBox().setText(s); - } - validateSlides(ss, false, "Slide1", "Slide2"); + try (XMLSlideShow ss = new XMLSlideShow()) { + for (String s : new String[]{"Slide1", "Slide2"}) { + ss.createSlide().createTextBox().setText(s); + } + validateSlides(ss, false, "Slide1", "Slide2"); - XSLFSlide slide = ss.createSlide(); - slide.createTextBox().setText("New slide"); - validateSlides(ss, true, "Slide1", "Slide2", "New slide"); + XSLFSlide slide = ss.createSlide(); + slide.createTextBox().setText("New slide"); + validateSlides(ss, true, "Slide1", "Slide2", "New slide"); - // Move backward - ss.setSlideOrder(slide, 0); - validateSlides(ss, true, "New slide", "Slide1", "Slide2"); + // Move backward + ss.setSlideOrder(slide, 0); + validateSlides(ss, true, "New slide", "Slide1", "Slide2"); - // Move forward - ss.setSlideOrder(slide, 1); - validateSlides(ss, true, "Slide1", "New slide", "Slide2"); + // Move forward + ss.setSlideOrder(slide, 1); + validateSlides(ss, true, "Slide1", "New slide", "Slide2"); - // Move to end - ss.setSlideOrder(slide, 0); - ss.setSlideOrder(slide, 2); - validateSlides(ss, true, "Slide1", "Slide2", "New slide"); - ss.close(); + // Move to end + ss.setSlideOrder(slide, 0); + ss.setSlideOrder(slide, 2); + validateSlides(ss, true, "Slide1", "Slide2", "New slide"); + } } /** @@ -533,89 +521,88 @@ class TestXSLFBugs { */ @Test void test57552() throws Exception { - XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1", "Slide2"}) { - ss.createSlide().createTextBox().setText(s); - } + try (XMLSlideShow ss = new XMLSlideShow()) { + for (String s : new String[]{"Slide1", "Slide2"}) { + ss.createSlide().createTextBox().setText(s); + } - // Slide starts with just layout relation - XSLFSlide slide = ss.getSlides().get(0); - assertEquals(0, ss.getPictureData().size()); - assertEquals(1, slide.getShapes().size()); + // Slide starts with just layout relation + XSLFSlide slide = ss.getSlides().get(0); + assertEquals(0, ss.getPictureData().size()); + assertEquals(1, slide.getShapes().size()); - assertEquals(1, slide.getRelations().size()); + assertEquals(1, slide.getRelations().size()); - final XSLFRelation expected = XSLFRelation.SLIDE_LAYOUT; - final POIXMLDocumentPart relation = slide.getRelations().get(0); + final XSLFRelation expected = XSLFRelation.SLIDE_LAYOUT; + final POIXMLDocumentPart relation = slide.getRelations().get(0); - assertEquals(expected.getContentType(), relation.getPackagePart().getContentType()); - assertEquals(expected.getFileName(expected.getFileNameIndex(relation)), relation.getPackagePart().getPartName().getName()); + assertEquals(expected.getContentType(), relation.getPackagePart().getContentType()); + assertEquals(expected.getFileName(expected.getFileNameIndex(relation)), relation.getPackagePart().getPartName().getName()); - // Some dummy pictures - byte[][] pics = new byte[15][3]; - for (int i = 0; i < pics.length; i++) { - Arrays.fill(pics[i], (byte) i); - } - - // Add a few pictures - addPictures(ss, slide, pics, 0, 10); + // Some dummy pictures + byte[][] pics = new byte[15][3]; + for (int i = 0; i < pics.length; i++) { + Arrays.fill(pics[i], (byte) i); + } - // Re-fetch the pictures and check - for (int i = 0; i < 10; i++) { - XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - } + // Add a few pictures + addPictures(ss, slide, pics, 0, 10); - // Add past 10 - addPictures(ss, slide, pics, 10, 15); + // Re-fetch the pictures and check + for (int i = 0; i < 10; i++) { + XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1); + assertNotNull(shape.getPictureData()); + assertArrayEquals(pics[i], shape.getPictureData().getData()); + } - // Check all pictures - for (int i = 0; i < 15; i++) { - XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - } + // Add past 10 + addPictures(ss, slide, pics, 10, 15); - // Add a duplicate, check the right one is picked - XSLFPictureData data = ss.addPicture(pics[3], PictureType.JPEG); - assertEquals(3, data.getIndex()); - assertEquals(15, ss.getPictureData().size()); + // Check all pictures + for (int i = 0; i < 15; i++) { + XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1); + assertNotNull(shape.getPictureData()); + assertArrayEquals(pics[i], shape.getPictureData().getData()); + } - XSLFPictureShape shape = slide.createPicture(data); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[3], shape.getPictureData().getData()); - assertEquals(17, slide.getShapes().size()); + // Add a duplicate, check the right one is picked + XSLFPictureData data = ss.addPicture(pics[3], PictureType.JPEG); + assertEquals(3, data.getIndex()); + assertEquals(15, ss.getPictureData().size()); + XSLFPictureShape shape = slide.createPicture(data); + assertNotNull(shape.getPictureData()); + assertArrayEquals(pics[3], shape.getPictureData().getData()); + assertEquals(17, slide.getShapes().size()); - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss); - slide = ss2.getSlides().get(0); - // Check the 15 individual ones added - for (int i = 0; i < 15; i++) { - shape = (XSLFPictureShape) slide.getShapes().get(i + 1); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[i], shape.getPictureData().getData()); - } + // Save and re-load + try (XMLSlideShow ss2 = writeOutAndReadBack(ss)) { + slide = ss2.getSlides().get(0); - // Check the duplicate - shape = (XSLFPictureShape) slide.getShapes().get(16); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[3], shape.getPictureData().getData()); + // Check the 15 individual ones added + for (int i = 0; i < 15; i++) { + shape = (XSLFPictureShape) slide.getShapes().get(i + 1); + assertNotNull(shape.getPictureData()); + assertArrayEquals(pics[i], shape.getPictureData().getData()); + } - // Add another duplicate - data = ss2.addPicture(pics[5], PictureType.JPEG); - assertEquals(5, data.getIndex()); - assertEquals(15, ss2.getPictureData().size()); + // Check the duplicate + shape = (XSLFPictureShape) slide.getShapes().get(16); + assertNotNull(shape.getPictureData()); + assertArrayEquals(pics[3], shape.getPictureData().getData()); - shape = slide.createPicture(data); - assertNotNull(shape.getPictureData()); - assertArrayEquals(pics[5], shape.getPictureData().getData()); - assertEquals(18, slide.getShapes().size()); + // Add another duplicate + data = ss2.addPicture(pics[5], PictureType.JPEG); + assertEquals(5, data.getIndex()); + assertEquals(15, ss2.getPictureData().size()); - ss2.close(); - ss.close(); + shape = slide.createPicture(data); + assertNotNull(shape.getPictureData()); + assertArrayEquals(pics[5], shape.getPictureData().getData()); + assertEquals(18, slide.getShapes().size()); + } + } } private void addPictures(XMLSlideShow ss, XSLFSlide slide, byte[][] pics, int start, int end) { @@ -633,9 +620,9 @@ class TestXSLFBugs { private void validateSlides(XMLSlideShow ss, boolean saveAndReload, String... slideTexts) throws IOException { if (saveAndReload) { - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss); - validateSlides(ss, slideTexts); - ss2.close(); + try (XMLSlideShow ss2 = writeOutAndReadBack(ss)) { + validateSlides(ss2, slideTexts); + } } else { validateSlides(ss, slideTexts); } @@ -652,69 +639,57 @@ class TestXSLFBugs { @Test void bug58205() throws IOException { - XMLSlideShow ss = openSampleDocument("themes.pptx"); - - int i = 1; - for (XSLFSlideMaster sm : ss.getSlideMasters()) { - assertEquals("rId" + (i++), ss.getRelationId(sm)); + try (XMLSlideShow ss = openSampleDocument("themes.pptx")) { + int i = 1; + for (XSLFSlideMaster sm : ss.getSlideMasters()) { + assertEquals("rId" + (i++), ss.getRelationId(sm)); + } } - - ss.close(); } - @Test - void bug55791a() throws IOException { - XMLSlideShow ppt = openSampleDocument("45541_Footer.pptx"); - removeAndCreateSlide(ppt); - ppt.close(); - } - - @Test - void bug55791b() throws IOException { - XMLSlideShow ppt = openSampleDocument("SampleShow.pptx"); - removeAndCreateSlide(ppt); - ppt.close(); - } - - private void removeAndCreateSlide(XMLSlideShow ppt) { - assertTrue(ppt.getSlides().size() > 1); - ppt.removeSlide(1); - assertNotNull(ppt.createSlide()); + @ParameterizedTest + @ValueSource(strings = {"45541_Footer.pptx", "SampleShow.pptx"}) + void bug55791(String fileName) throws IOException { + try (XMLSlideShow ppt = openSampleDocument(fileName)) { + assertTrue(ppt.getSlides().size() > 1); + ppt.removeSlide(1); + assertNotNull(ppt.createSlide()); + } } @Test void blibFillAlternateContent() throws IOException { - XMLSlideShow ppt = openSampleDocument("2411-Performance_Up.pptx"); - XSLFPictureShape ps = (XSLFPictureShape) ppt.getSlides().get(4).getShapes().get(0); - assertNotNull(ps.getPictureData()); - ppt.close(); + try (XMLSlideShow ppt = openSampleDocument("2411-Performance_Up.pptx")) { + XSLFPictureShape ps = (XSLFPictureShape) ppt.getSlides().get(4).getShapes().get(0); + assertNotNull(ps.getPictureData()); + } } @Test void bug59434() throws IOException { String url1 = "https://poi.apache.org/changes.html"; String url2 = "https://poi.apache.org/faq.html"; - XMLSlideShow ppt1 = new XMLSlideShow(); - PictureData pd1 = ppt1.addPicture(slTests.readFile("tomcat.png"), PictureType.PNG); - PictureData pd2 = ppt1.addPicture(slTests.readFile("santa.wmf"), PictureType.WMF); - XSLFSlide slide = ppt1.createSlide(); - XSLFPictureShape ps1 = slide.createPicture(pd1); - ps1.setAnchor(new Rectangle2D.Double(20, 20, 100, 100)); - XSLFHyperlink hl1 = ps1.createHyperlink(); - hl1.linkToUrl(url1); - XSLFPictureShape ps2 = slide.createPicture(pd2); - ps2.setAnchor(new Rectangle2D.Double(120, 120, 100, 100)); - XSLFHyperlink hl2 = ps2.createHyperlink(); - hl2.linkToUrl(url2); - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - slide = ppt2.getSlides().get(0); - ps1 = (XSLFPictureShape) slide.getShapes().get(0); - ps2 = (XSLFPictureShape) slide.getShapes().get(1); - assertEquals(url1, ps1.getHyperlink().getAddress()); - assertEquals(url2, ps2.getHyperlink().getAddress()); - - ppt2.close(); + try (XMLSlideShow ppt1 = new XMLSlideShow()) { + PictureData pd1 = ppt1.addPicture(slTests.readFile("tomcat.png"), PictureType.PNG); + PictureData pd2 = ppt1.addPicture(slTests.readFile("santa.wmf"), PictureType.WMF); + XSLFSlide slide = ppt1.createSlide(); + XSLFPictureShape ps1 = slide.createPicture(pd1); + ps1.setAnchor(new Rectangle2D.Double(20, 20, 100, 100)); + XSLFHyperlink hl1 = ps1.createHyperlink(); + hl1.linkToUrl(url1); + XSLFPictureShape ps2 = slide.createPicture(pd2); + ps2.setAnchor(new Rectangle2D.Double(120, 120, 100, 100)); + XSLFHyperlink hl2 = ps2.createHyperlink(); + hl2.linkToUrl(url2); + + try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + ps1 = (XSLFPictureShape) slide.getShapes().get(0); + ps2 = (XSLFPictureShape) slide.getShapes().get(1); + assertEquals(url1, ps1.getHyperlink().getAddress()); + assertEquals(url2, ps2.getHyperlink().getAddress()); + } + } } @Test @@ -723,27 +698,27 @@ class TestXSLFBugs { Color lineColor = new Color(25.3f / 255f, 1f, 0f, 0.4f); Color textColor = new Color(1f, 1f, 0f, 0.6f); - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide sl = ppt1.createSlide(); - XSLFAutoShape as = sl.createAutoShape(); - as.setShapeType(ShapeType.STAR_10); - as.setAnchor(new Rectangle2D.Double(100, 100, 300, 300)); - as.setFillColor(fillColor); - as.setLineColor(lineColor); - as.setText("Alpha"); - as.setVerticalAlignment(VerticalAlignment.MIDDLE); - as.setHorizontalCentered(true); - XSLFTextRun tr = as.getTextParagraphs().get(0).getTextRuns().get(0); - tr.setFontSize(32d); - tr.setFontColor(textColor); - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - sl = ppt2.getSlides().get(0); - as = (XSLFAutoShape) sl.getShapes().get(0); - checkColor(fillColor, as.getFillStyle().getPaint()); - checkColor(lineColor, as.getStrokeStyle().getPaint()); - checkColor(textColor, as.getTextParagraphs().get(0).getTextRuns().get(0).getFontColor()); - ppt2.close(); + try (XMLSlideShow ppt1 = new XMLSlideShow()) { + XSLFSlide sl = ppt1.createSlide(); + XSLFAutoShape as = sl.createAutoShape(); + as.setShapeType(ShapeType.STAR_10); + as.setAnchor(new Rectangle2D.Double(100, 100, 300, 300)); + as.setFillColor(fillColor); + as.setLineColor(lineColor); + as.setText("Alpha"); + as.setVerticalAlignment(VerticalAlignment.MIDDLE); + as.setHorizontalCentered(true); + XSLFTextRun tr = as.getTextParagraphs().get(0).getTextRuns().get(0); + tr.setFontSize(32d); + tr.setFontColor(textColor); + try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + sl = ppt2.getSlides().get(0); + as = (XSLFAutoShape) sl.getShapes().get(0); + checkColor(fillColor, as.getFillStyle().getPaint()); + checkColor(lineColor, as.getStrokeStyle().getPaint()); + checkColor(textColor, as.getTextParagraphs().get(0).getTextRuns().get(0).getFontColor()); + } + } } private static void checkColor(Color expected, PaintStyle actualStyle) { @@ -757,64 +732,60 @@ class TestXSLFBugs { @Test void bug55714() throws IOException { - XMLSlideShow srcPptx = openSampleDocument("pptx2svg.pptx"); - XMLSlideShow newPptx = new XMLSlideShow(); - XSLFSlide srcSlide = srcPptx.getSlides().get(0); - XSLFSlide newSlide = newPptx.createSlide(); - - XSLFSlideLayout srcSlideLayout = srcSlide.getSlideLayout(); - XSLFSlideLayout newSlideLayout = newSlide.getSlideLayout(); - newSlideLayout.importContent(srcSlideLayout); - - XSLFSlideMaster srcSlideMaster = srcSlide.getSlideMaster(); - XSLFSlideMaster newSlideMaster = newSlide.getSlideMaster(); - newSlideMaster.importContent(srcSlideMaster); - - newSlide.importContent(srcSlide); - XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(newPptx); - - PaintStyle ps = rwPptx.getSlides().get(0).getBackground().getFillStyle().getPaint(); - assertTrue(ps instanceof TexturePaint); - - rwPptx.close(); - newPptx.close(); - srcPptx.close(); + try (XMLSlideShow srcPptx = openSampleDocument("pptx2svg.pptx"); + XMLSlideShow newPptx = new XMLSlideShow()) { + XSLFSlide srcSlide = srcPptx.getSlides().get(0); + XSLFSlide newSlide = newPptx.createSlide(); + + XSLFSlideLayout srcSlideLayout = srcSlide.getSlideLayout(); + XSLFSlideLayout newSlideLayout = newSlide.getSlideLayout(); + newSlideLayout.importContent(srcSlideLayout); + + XSLFSlideMaster srcSlideMaster = srcSlide.getSlideMaster(); + XSLFSlideMaster newSlideMaster = newSlide.getSlideMaster(); + newSlideMaster.importContent(srcSlideMaster); + + newSlide.importContent(srcSlide); + try (XMLSlideShow rwPptx = writeOutAndReadBack(newPptx)) { + PaintStyle ps = rwPptx.getSlides().get(0).getBackground().getFillStyle().getPaint(); + assertTrue(ps instanceof TexturePaint); + } + } } @Test void bug59273() throws IOException { - XMLSlideShow ppt = openSampleDocument("bug59273.potx"); - ppt.getPackage().replaceContentType( - XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType(), - XSLFRelation.MAIN.getContentType() - ); - - XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(ppt); - OPCPackage pkg = rwPptx.getPackage(); - int size = pkg.getPartsByContentType(XSLFRelation.MAIN.getContentType()).size(); - assertEquals(1, size); - size = pkg.getPartsByContentType(XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType()).size(); - assertEquals(0, size); - - rwPptx.close(); - ppt.close(); + try (XMLSlideShow ppt = openSampleDocument("bug59273.potx")) { + ppt.getPackage().replaceContentType( + XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType(), + XSLFRelation.MAIN.getContentType() + ); + + try (XMLSlideShow rwPptx = writeOutAndReadBack(ppt)) { + OPCPackage pkg = rwPptx.getPackage(); + int size = pkg.getPartsByContentType(XSLFRelation.MAIN.getContentType()).size(); + assertEquals(1, size); + size = pkg.getPartsByContentType(XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType()).size(); + assertEquals(0, size); + } + } } @Test void bug60373() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide sl = ppt.createSlide(); - XSLFTable t = sl.createTable(); - XSLFTableRow r = t.addRow(); - bug60373_addCell(r); - bug60373_addCell(r); - r = t.addRow(); - XSLFTableCell c = bug60373_addCell(r); - // call getTextHeight, when table is not fully populated - double th = c.getTextHeight(); - assertTrue(th > 10); - ppt.close(); + try (XMLSlideShow ppt = new XMLSlideShow()) { + XSLFSlide sl = ppt.createSlide(); + XSLFTable t = sl.createTable(); + XSLFTableRow r = t.addRow(); + bug60373_addCell(r); + bug60373_addCell(r); + r = t.addRow(); + XSLFTableCell c = bug60373_addCell(r); + // call getTextHeight, when table is not fully populated + double th = c.getTextHeight(); + assertTrue(th > 10); + } } private static XSLFTableCell bug60373_addCell(XSLFTableRow r) { @@ -834,42 +805,39 @@ class TestXSLFBugs { @Test void bug60662() throws IOException { - XMLSlideShow src = new XMLSlideShow(); - XSLFSlide sl = src.createSlide(); - XSLFGroupShape gs = sl.createGroup(); - gs.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); - gs.setInteriorAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - XSLFAutoShape as = gs.createAutoShape(); - as.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - as.setShapeType(ShapeType.STAR_24); - as.setFillColor(Color.YELLOW); - CTShape csh = (CTShape) as.getXmlObject(); - CTOuterShadowEffect shadow = csh.getSpPr().addNewEffectLst().addNewOuterShdw(); - shadow.setDir(270000); - shadow.setDist(100000); - shadow.addNewSrgbClr().setVal(new byte[]{0x00, (byte) 0xFF, 0x00}); - - XMLSlideShow dst = new XMLSlideShow(); - XSLFSlide sl2 = dst.createSlide(); - sl2.importContent(sl); - XSLFGroupShape gs2 = (XSLFGroupShape) sl2.getShapes().get(0); - XSLFAutoShape as2 = (XSLFAutoShape) gs2.getShapes().get(0); - CTShape csh2 = (CTShape) as2.getXmlObject(); - assertTrue(csh2.getSpPr().isSetEffectLst()); - - dst.close(); - src.close(); + try (XMLSlideShow src = new XMLSlideShow(); + XMLSlideShow dst = new XMLSlideShow()) { + XSLFSlide sl = src.createSlide(); + XSLFGroupShape gs = sl.createGroup(); + gs.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); + gs.setInteriorAnchor(new Rectangle2D.Double(0, 0, 100, 100)); + XSLFAutoShape as = gs.createAutoShape(); + as.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); + as.setShapeType(ShapeType.STAR_24); + as.setFillColor(Color.YELLOW); + CTShape csh = (CTShape) as.getXmlObject(); + CTOuterShadowEffect shadow = csh.getSpPr().addNewEffectLst().addNewOuterShdw(); + shadow.setDir(270000); + shadow.setDist(100000); + shadow.addNewSrgbClr().setVal(new byte[]{0x00, (byte) 0xFF, 0x00}); + + XSLFSlide sl2 = dst.createSlide(); + sl2.importContent(sl); + XSLFGroupShape gs2 = (XSLFGroupShape) sl2.getShapes().get(0); + XSLFAutoShape as2 = (XSLFAutoShape) gs2.getShapes().get(0); + CTShape csh2 = (CTShape) as2.getXmlObject(); + assertTrue(csh2.getSpPr().isSetEffectLst()); + } } @Test void test60810() throws IOException { - XMLSlideShow ppt = openSampleDocument("60810.pptx"); - for (XSLFSlide slide : ppt.getSlides()) { - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); + try (XMLSlideShow ppt = openSampleDocument("60810.pptx")) { + for (XSLFSlide slide : ppt.getSlides()) { + XSLFNotes notesSlide = ppt.getNotesSlide(slide); + assertNotNull(notesSlide); + } } - - ppt.close(); } @Test @@ -886,7 +854,7 @@ class TestXSLFBugs { try (XMLSlideShow ppt = openSampleDocument("61515.pptx")) { ppt.removeSlide(0); assertEquals(1, ppt.createSlide().getRelations().size()); - try (XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { + try (XMLSlideShow saved = writeOutAndReadBack(ppt)) { assertEquals(1, saved.getSlides().size()); XSLFSlide slide = saved.getSlides().get(0); assertEquals(1, slide.getRelations().size()); @@ -897,7 +865,7 @@ class TestXSLFBugs { @Test void testAptia() throws IOException { try (XMLSlideShow ppt = openSampleDocument("aptia.pptx"); - XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { + XMLSlideShow saved = writeOutAndReadBack(ppt)) { assertEquals(ppt.getSlides().size(), saved.getSlides().size()); } } @@ -906,7 +874,7 @@ class TestXSLFBugs { @Test void testDivinoRevelado() throws IOException { try (XMLSlideShow ppt = openSampleDocument("Divino_Revelado.pptx"); - XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) { + XMLSlideShow saved = writeOutAndReadBack(ppt)) { assertEquals(ppt.getSlides().size(), saved.getSlides().size()); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java index d902c12714..897fcd1d27 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java @@ -16,54 +16,32 @@ ==================================================================== */ package org.apache.poi.xslf; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xslf.usermodel.XMLSlideShow; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - public class XSLFTestDataSamples { public static XMLSlideShow openSampleDocument(String sampleName) { - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream(sampleName); - try { + try (InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream(sampleName)) { return new XMLSlideShow(OPCPackage.open(is)); } catch (Exception e) { throw new RuntimeException(e); - } finally { - try { - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } } } public static XMLSlideShow writeOutAndReadBack(XMLSlideShow doc) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - try { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) { doc.write(baos); + try (InputStream bais = baos.toInputStream()) { + return new XMLSlideShow(bais); + } } catch (IOException e) { throw new RuntimeException(e); } - - InputStream bais; - bais = new ByteArrayInputStream(baos.toByteArray()); - try { - return new XMLSlideShow(OPCPackage.open(bais)); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - baos.close(); - bais.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java index 520f62fb04..295767a75c 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java @@ -16,14 +16,14 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; +import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument; +import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.poi.openxml4j.opc.OPCPackage; @@ -69,133 +69,119 @@ class TestXMLSlideShow extends BaseTestSlideShow<XSLFShape, XSLFTextParagraph> { @Test void testOpen() throws Exception { // With the finalised uri, should be fine - XMLSlideShow xml = new XMLSlideShow(pack); - // Check the core - assertNotNull(xml.getCTPresentation()); + try (XMLSlideShow xml = new XMLSlideShow(pack)) { + // Check the core + assertNotNull(xml.getCTPresentation()); - // Check it has some slides - assertFalse(xml.getSlides().isEmpty()); - assertFalse(xml.getSlideMasters().isEmpty()); - - xml.close(); + // Check it has some slides + assertFalse(xml.getSlides().isEmpty()); + assertFalse(xml.getSlideMasters().isEmpty()); + } } - @SuppressWarnings("deprecation") @Test void testSlideBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); + try (XMLSlideShow xml = new XMLSlideShow(pack)) { - // Should have 1 master - assertEquals(1, xml.getSlideMasters().size()); + // Should have 1 master + assertEquals(1, xml.getSlideMasters().size()); - // Should have two sheets - assertEquals(2, xml.getSlides().size()); + // Should have two sheets + assertEquals(2, xml.getSlides().size()); - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray(); + // Check they're as expected + CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray(); - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); + assertEquals(256, slides[0].getId()); + assertEquals(257, slides[1].getId()); + assertEquals("rId2", slides[0].getId2()); + assertEquals("rId3", slides[1].getId2()); - // Now get those objects - assertNotNull(xml.getSlides().get(0)); - assertNotNull(xml.getSlides().get(1)); + // Now get those objects + assertNotNull(xml.getSlides().get(0)); + assertNotNull(xml.getSlides().get(1)); - // And check they have notes as expected - assertNotNull(xml.getSlides().get(0).getNotes()); - assertNotNull(xml.getSlides().get(1).getNotes()); + // And check they have notes as expected + assertNotNull(xml.getSlides().get(0).getNotes()); + assertNotNull(xml.getSlides().get(1).getNotes()); - // Next up look for the slide master - CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray(); + // Next up look for the slide master + CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray(); - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMasters().get(0)); + // see SlideAtom.USES_MASTER_SLIDE_ID + assertEquals(0x80000000L, masters[0].getId()); + assertEquals("rId1", masters[0].getId2()); + assertNotNull(xml.getSlideMasters().get(0)); - // Finally look for the notes master - CTNotesMasterIdListEntry notesMaster = - xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId(); - assertNotNull(notesMaster); + // Finally look for the notes master + CTNotesMasterIdListEntry notesMaster = + xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId(); + assertNotNull(notesMaster); - assertNotNull(xml.getNotesMaster()); - - xml.close(); + assertNotNull(xml.getNotesMaster()); + } } @Test void testMetadataBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); + try (XMLSlideShow xml = new XMLSlideShow(pack)) { - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); + assertNotNull(xml.getProperties().getCoreProperties()); + assertNotNull(xml.getProperties().getExtendedProperties()); - assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); + assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); + assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); + assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - assertNull(xml.getProperties().getCoreProperties().getTitle()); - assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); - - xml.close(); + assertNull(xml.getProperties().getCoreProperties().getTitle()); + assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); + } } @Test void testComments() throws Exception { // Default sample file has none - XMLSlideShow xml = new XMLSlideShow(pack); - - assertNull(xml.getCommentAuthors()); + try (XMLSlideShow xml = new XMLSlideShow(pack)) { + assertNull(xml.getCommentAuthors()); - for (XSLFSlide slide : xml.getSlides()) { - assertTrue(slide.getComments().isEmpty()); + for (XSLFSlide slide : xml.getSlides()) { + assertTrue(slide.getComments().isEmpty()); + } } // Try another with comments - XMLSlideShow xmlComments = new XMLSlideShow(slTests.openResourceAsStream("45545_Comment.pptx")); - - // Has one author - assertNotNull(xmlComments.getCommentAuthors()); - assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray()); - assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName()); - - // First two slides have comments - int i = -1; - for (XSLFSlide slide : xmlComments.getSlides()) { - i++; - - if (i == 0) { - assertNotNull(slide.getCommentsPart()); - assertEquals(1, slide.getCommentsPart().getNumberOfComments()); - assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText()); - assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); - } else if (i == 1) { - assertNotNull(slide.getComments()); - assertEquals(1, slide.getCommentsPart().getNumberOfComments()); - assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText()); - assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); - } else { - assertNull(slide.getCommentsPart()); - assertTrue(slide.getComments().isEmpty()); + try (XMLSlideShow xmlComments = openSampleDocument("45545_Comment.pptx")) { + + // Has one author + assertNotNull(xmlComments.getCommentAuthors()); + assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray()); + assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName()); + + // First two slides have comments + int i = -1; + for (XSLFSlide slide : xmlComments.getSlides()) { + i++; + + if (i == 0) { + assertNotNull(slide.getCommentsPart()); + assertEquals(1, slide.getCommentsPart().getNumberOfComments()); + assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText()); + assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); + } else if (i == 1) { + assertNotNull(slide.getComments()); + assertEquals(1, slide.getCommentsPart().getNumberOfComments()); + assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText()); + assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId()); + } else { + assertNull(slide.getCommentsPart()); + assertTrue(slide.getComments().isEmpty()); + } } } - - xmlComments.close(); - xml.close(); } @Override public XMLSlideShow reopen(SlideShow<XSLFShape, XSLFTextParagraph> show) throws IOException { - BufAccessBAOS bos = new BufAccessBAOS(); - show.write(bos); - return new XMLSlideShow(new ByteArrayInputStream(bos.getBuf())); - } - - private static class BufAccessBAOS extends ByteArrayOutputStream { - byte[] getBuf() { - return buf; - } + return writeOutAndReadBack((XMLSlideShow) show); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java index 02640c0efe..78ae286f7e 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java @@ -21,12 +21,10 @@ import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERT import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Rectangle; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.util.List; import javax.xml.namespace.QName; diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java index 0df21b2720..37fb3318be 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java @@ -16,6 +16,8 @@ ==================================================================== */ package org.apache.poi.xslf.usermodel; +import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument; +import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -25,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -41,7 +41,6 @@ import org.apache.poi.POIDataSamples; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; -import org.apache.poi.xslf.XSLFTestDataSamples; import org.apache.poi.xslf.util.PPTX2PNG; import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; @@ -51,245 +50,240 @@ class TestXSLFPictureShape { @Test void testCreate() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - assertEquals(0, ppt1.getPictureData().size()); - byte[] data1 = new byte[100]; - for(int i = 0;i < 100;i++) { data1[i] = (byte)i; } - XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); - assertEquals(0, pdata1.getIndex()); - assertEquals(1, ppt1.getPictureData().size()); - - XSLFSlide slide = ppt1.createSlide(); - XSLFPictureShape shape1 = slide.createPicture(pdata1); - assertNotNull(shape1.getPictureData()); - assertArrayEquals(data1, shape1.getPictureData().getData()); - - byte[] data2 = new byte[200]; - for(int i = 0;i < 200;i++) { data2[i] = (byte)i; } - XSLFPictureData pdata2 = ppt1.addPicture(data2, PictureType.PNG); - XSLFPictureShape shape2 = slide.createPicture(pdata2); - assertNotNull(shape2.getPictureData()); - assertEquals(1, pdata2.getIndex()); - assertEquals(2, ppt1.getPictureData().size()); - assertArrayEquals(data2, shape2.getPictureData().getData()); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - List<XSLFPictureData> pics = ppt2.getPictureData(); - assertEquals(2, pics.size()); - assertArrayEquals(data1, pics.get(0).getData()); - assertArrayEquals(data2, pics.get(1).getData()); - - List<XSLFShape> shapes = ppt2.getSlides().get(0).getShapes(); - assertArrayEquals(data1, ((XSLFPictureShape) shapes.get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((XSLFPictureShape) shapes.get(1)).getPictureData().getData()); - ppt2.close(); + try (XMLSlideShow ppt1 = new XMLSlideShow()) { + assertEquals(0, ppt1.getPictureData().size()); + byte[] data1 = new byte[100]; + for (int i = 0; i < 100; i++) { + data1[i] = (byte) i; + } + XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); + assertEquals(0, pdata1.getIndex()); + assertEquals(1, ppt1.getPictureData().size()); + + XSLFSlide slide = ppt1.createSlide(); + XSLFPictureShape shape1 = slide.createPicture(pdata1); + assertNotNull(shape1.getPictureData()); + assertArrayEquals(data1, shape1.getPictureData().getData()); + + byte[] data2 = new byte[200]; + for (int i = 0; i < 200; i++) { + data2[i] = (byte) i; + } + XSLFPictureData pdata2 = ppt1.addPicture(data2, PictureType.PNG); + XSLFPictureShape shape2 = slide.createPicture(pdata2); + assertNotNull(shape2.getPictureData()); + assertEquals(1, pdata2.getIndex()); + assertEquals(2, ppt1.getPictureData().size()); + assertArrayEquals(data2, shape2.getPictureData().getData()); + + try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + List<XSLFPictureData> pics = ppt2.getPictureData(); + assertEquals(2, pics.size()); + assertArrayEquals(data1, pics.get(0).getData()); + assertArrayEquals(data2, pics.get(1).getData()); + + List<XSLFShape> shapes = ppt2.getSlides().get(0).getShapes(); + assertArrayEquals(data1, ((XSLFPictureShape) shapes.get(0)).getPictureData().getData()); + assertArrayEquals(data2, ((XSLFPictureShape) shapes.get(1)).getPictureData().getData()); + } + } } @Test void testCreateMultiplePictures() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide1 = ppt1.createSlide(); - XSLFGroupShape group1 = slide1.createGroup(); - - - int pictureIndex = 0; - // first add 20 images to the slide - for (int i = 0; i < 20; i++, pictureIndex++) { - byte[] data = new byte[]{(byte)pictureIndex}; - XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); - assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 - XSLFPictureShape picture = slide1.createPicture(elementData); - // POI saves images as image1.png, image2.png, etc. - String fileName = "image" + (elementData.getIndex()+1) + ".png"; - assertEquals(fileName, picture.getPictureData().getFileName()); - assertArrayEquals(data, picture.getPictureData().getData()); - } - - // and then add next 20 images to a group - for (int i = 0; i < 20; i++, pictureIndex++) { - byte[] data = new byte[]{(byte)pictureIndex}; - XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); - XSLFPictureShape picture = group1.createPicture(elementData); - // POI saves images as image1.png, image2.png, etc. - assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 - String fileName = "image" + (pictureIndex + 1) + ".png"; - assertEquals(fileName, picture.getPictureData().getFileName()); - assertArrayEquals(data, picture.getPictureData().getData()); - } + try (XMLSlideShow ppt1 = new XMLSlideShow()) { + XSLFSlide slide1 = ppt1.createSlide(); + XSLFGroupShape group1 = slide1.createGroup(); + + + int pictureIndex = 0; + // first add 20 images to the slide + for (int i = 0; i < 20; i++, pictureIndex++) { + byte[] data = new byte[]{(byte) pictureIndex}; + XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); + assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 + XSLFPictureShape picture = slide1.createPicture(elementData); + // POI saves images as image1.png, image2.png, etc. + String fileName = "image" + (elementData.getIndex() + 1) + ".png"; + assertEquals(fileName, picture.getPictureData().getFileName()); + assertArrayEquals(data, picture.getPictureData().getData()); + } - // serialize, read back and check that all images are there + // and then add next 20 images to a group + for (int i = 0; i < 20; i++, pictureIndex++) { + byte[] data = new byte[]{(byte) pictureIndex}; + XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); + XSLFPictureShape picture = group1.createPicture(elementData); + // POI saves images as image1.png, image2.png, etc. + assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 + String fileName = "image" + (pictureIndex + 1) + ".png"; + assertEquals(fileName, picture.getPictureData().getFileName()); + assertArrayEquals(data, picture.getPictureData().getData()); + } - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - // pictures keyed by file name - Map<String, XSLFPictureData> pics = new HashMap<>(); - for(XSLFPictureData p : ppt2.getPictureData()){ - pics.put(p.getFileName(), p); - } - assertEquals(40, pics.size()); - for (int i = 0; i < 40; i++) { - byte[] data1 = new byte[]{(byte)i}; - String fileName = "image" + (i + 1) + ".png"; - XSLFPictureData data = pics.get(fileName); - assertNotNull(data); - assertEquals(fileName, data.getFileName()); - assertArrayEquals(data1, data.getData()); + // serialize, read back and check that all images are there + + try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // pictures keyed by file name + Map<String, XSLFPictureData> pics = new HashMap<>(); + for (XSLFPictureData p : ppt2.getPictureData()) { + pics.put(p.getFileName(), p); + } + assertEquals(40, pics.size()); + for (int i = 0; i < 40; i++) { + byte[] data1 = new byte[]{(byte) i}; + String fileName = "image" + (i + 1) + ".png"; + XSLFPictureData data = pics.get(fileName); + assertNotNull(data); + assertEquals(fileName, data.getFileName()); + assertArrayEquals(data1, data.getData()); + } + } } - ppt2.close(); } @Test void testImageCaching() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - byte[] img1 = new byte[]{1,2,3}; - byte[] img2 = new byte[]{3,4,5}; - XSLFPictureData pdata1 = ppt.addPicture(img1, PictureType.PNG); - assertEquals(0, pdata1.getIndex()); - assertEquals(0, ppt.addPicture(img1, PictureType.PNG).getIndex()); - - XSLFPictureData idx2 = ppt.addPicture(img2, PictureType.PNG); - assertEquals(1, idx2.getIndex()); - assertEquals(1, ppt.addPicture(img2, PictureType.PNG).getIndex()); - - XSLFSlide slide1 = ppt.createSlide(); - assertNotNull(slide1); - XSLFSlide slide2 = ppt.createSlide(); - assertNotNull(slide2); - - ppt.close(); + try (XMLSlideShow ppt = new XMLSlideShow()) { + byte[] img1 = new byte[]{1, 2, 3}; + byte[] img2 = new byte[]{3, 4, 5}; + XSLFPictureData pdata1 = ppt.addPicture(img1, PictureType.PNG); + assertEquals(0, pdata1.getIndex()); + assertEquals(0, ppt.addPicture(img1, PictureType.PNG).getIndex()); + + XSLFPictureData idx2 = ppt.addPicture(img2, PictureType.PNG); + assertEquals(1, idx2.getIndex()); + assertEquals(1, ppt.addPicture(img2, PictureType.PNG).getIndex()); + + XSLFSlide slide1 = ppt.createSlide(); + assertNotNull(slide1); + XSLFSlide slide2 = ppt.createSlide(); + assertNotNull(slide2); + } } @Test void testMerge() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - byte[] data1 = new byte[100]; - XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); + try (XMLSlideShow ppt1 = new XMLSlideShow()) { + byte[] data1 = new byte[100]; + XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); - XSLFSlide slide1 = ppt1.createSlide(); - XSLFPictureShape shape1 = slide1.createPicture(pdata1); - CTPicture ctPic1 = (CTPicture)shape1.getXmlObject(); - ctPic1.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); + XSLFSlide slide1 = ppt1.createSlide(); + XSLFPictureShape shape1 = slide1.createPicture(pdata1); + CTPicture ctPic1 = (CTPicture) shape1.getXmlObject(); + ctPic1.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); - XSLFPictureShape shape2 = slide1.createPicture(pdata1); - CTPicture ctPic2 = (CTPicture)shape2.getXmlObject(); - ctPic2.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); + XSLFPictureShape shape2 = slide1.createPicture(pdata1); + CTPicture ctPic2 = (CTPicture) shape2.getXmlObject(); + ctPic2.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); - differentShapeName(shape1, shape2); + differentShapeName(shape1, shape2); - XSLFGroupShape group = slide1.createGroup(); - XSLFTextBox tb1 = group.createTextBox(); - XSLFTextBox tb2 = group.createTextBox(); + XSLFGroupShape group = slide1.createGroup(); + XSLFTextBox tb1 = group.createTextBox(); + XSLFTextBox tb2 = group.createTextBox(); - assertNotEquals("We should have different names now, but had: " + tb1.getShapeName() + " for both", tb1.getShapeName(), tb2.getShapeName()); + differentShapeName(tb1, tb2); - XMLSlideShow pptCopy = new XMLSlideShow(); + try (XMLSlideShow pptCopy = new XMLSlideShow()) { + XSLFSlide slideCopy = pptCopy.createSlide().importContent(slide1); + XSLFPictureShape shapeCopy1 = (XSLFPictureShape) slideCopy.getShapes().get(0); - XSLFSlide slideCopy = pptCopy.createSlide().importContent(slide1); - XSLFPictureShape shapeCopy1 = (XSLFPictureShape)slideCopy.getShapes().get(0); + assertArrayEquals(data1, shapeCopy1.getPictureData().getData()); + assertEquals(shape1.getShapeName(), shapeCopy1.getShapeName()); - assertArrayEquals(data1, shapeCopy1.getPictureData().getData()); - assertEquals(shape1.getShapeName(), shapeCopy1.getShapeName()); + CTPicture ctPicCopy1 = (CTPicture) shapeCopy1.getXmlObject(); + assertFalse(ctPicCopy1.getNvPicPr().getNvPr().isSetCustDataLst()); - CTPicture ctPicCopy1 = (CTPicture)shapeCopy1.getXmlObject(); - assertFalse(ctPicCopy1.getNvPicPr().getNvPr().isSetCustDataLst()); + XSLFPictureShape shapeCopy2 = (XSLFPictureShape) slideCopy.getShapes().get(1); - XSLFPictureShape shapeCopy2 = (XSLFPictureShape)slideCopy.getShapes().get(1); + assertArrayEquals(data1, shapeCopy2.getPictureData().getData()); + assertEquals(shape2.getShapeName(), shapeCopy2.getShapeName()); - assertArrayEquals(data1, shapeCopy2.getPictureData().getData()); - assertEquals(shape2.getShapeName(), shapeCopy2.getShapeName()); + CTPicture ctPicCopy2 = (CTPicture) shapeCopy2.getXmlObject(); + assertFalse(ctPicCopy2.getNvPicPr().getNvPr().isSetCustDataLst()); - CTPicture ctPicCopy2 = (CTPicture)shapeCopy2.getXmlObject(); - assertFalse(ctPicCopy2.getNvPicPr().getNvPr().isSetCustDataLst()); + differentShapeName(shapeCopy1, shapeCopy2); - differentShapeName(shapeCopy1, shapeCopy2); + XSLFGroupShape groupCopy = (XSLFGroupShape) slideCopy.getShapes().get(2); + XSLFTextBox tbCopy1 = (XSLFTextBox) groupCopy.getShapes().get(0); + XSLFTextBox tbCopy2 = (XSLFTextBox) groupCopy.getShapes().get(1); - XSLFGroupShape groupCopy = (XSLFGroupShape) slideCopy.getShapes().get(2); - XSLFTextBox tbCopy1 = (XSLFTextBox) groupCopy.getShapes().get(0); - XSLFTextBox tbCopy2 = (XSLFTextBox) groupCopy.getShapes().get(1); + assertEquals(group.getShapeName(), groupCopy.getShapeName()); + assertEquals(tb1.getShapeName(), tbCopy1.getShapeName()); + assertEquals(tb2.getShapeName(), tbCopy2.getShapeName()); - assertEquals(group.getShapeName(), groupCopy.getShapeName()); - assertEquals(tb1.getShapeName(), tbCopy1.getShapeName()); - assertEquals(tb2.getShapeName(), tbCopy2.getShapeName()); - - differentShapeName(tb1, tb2); - - ppt1.close(); - pptCopy.close(); + differentShapeName(tb1, tb2); + } + } } private void differentShapeName(XSLFShape shape1, XSLFShape shape2) { - assertNotEquals("We should have different names now, but had: " + shape1.getShapeName() + " for both", shape1.getShapeName(), shape2.getShapeName()); + assertNotEquals(shape1.getShapeName(), shape2.getShapeName(), + "We should have different names now, but had: " + shape1.getShapeName() + " for both"); } @Test void bug58663() throws IOException { - InputStream is = _slTests.openResourceAsStream("shapes.pptx"); - XMLSlideShow ppt = new XMLSlideShow(is); - is.close(); - - XSLFSlide slide = ppt.getSlides().get(0); - XSLFPictureShape ps = (XSLFPictureShape)slide.getShapes().get(3); - slide.removeShape(ps); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt.write(bos); - ppt.close(); + try (XMLSlideShow ppt = openSampleDocument("shapes.pptx")) { + XSLFSlide slide = ppt.getSlides().get(0); + XSLFPictureShape ps = (XSLFPictureShape) slide.getShapes().get(3); + slide.removeShape(ps); - XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray())); - assertTrue(ppt2.getPictureData().isEmpty()); - ppt2.close(); + try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt)) { + assertTrue(ppt2.getPictureData().isEmpty()); + } + } } @Test void testTiffImageBug59742() throws Exception { - XMLSlideShow slideShow = new XMLSlideShow(); - final InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif"); - final byte[] pictureData = IOUtils.toByteArray(tiffStream); - IOUtils.closeQuietly(tiffStream); - - XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF); - assertEquals("image/tiff", pic.getContentType()); - assertEquals("image1.tiff", pic.getFileName()); + try (XMLSlideShow slideShow = new XMLSlideShow(); + InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif")) { + final byte[] pictureData = IOUtils.toByteArray(tiffStream); - slideShow.close(); + XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF); + assertEquals("image/tiff", pic.getContentType()); + assertEquals("image1.tiff", pic.getFileName()); + } } @Test void renderSvgImage() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); + try (XMLSlideShow ppt = new XMLSlideShow()) { + XSLFSlide slide = ppt.createSlide(); - try { - XSLFPictureData svgPic = ppt.addPicture(POIDataSamples.getDocumentInstance().getFile("../project-header.svg"), PictureType.SVG); - XSLFPictureShape shape = XSLFPictureShape.addSvgImage(slide, svgPic, PictureType.JPEG, null); + try { + XSLFPictureData svgPic = ppt.addPicture(POIDataSamples.getDocumentInstance().getFile("../project-header.svg"), PictureType.SVG); + XSLFPictureShape shape = XSLFPictureShape.addSvgImage(slide, svgPic, PictureType.JPEG, null); - Rectangle2D anchor = shape.getAnchor(); - anchor.setRect(100, 100, anchor.getWidth(), anchor.getHeight()); - shape.setAnchor(anchor); + Rectangle2D anchor = shape.getAnchor(); + anchor.setRect(100, 100, anchor.getWidth(), anchor.getHeight()); + shape.setAnchor(anchor); - assertNotNull(shape.getSvgImage()); + assertNotNull(shape.getSvgImage()); - final File tmpFile = TempFile.createTempFile("svgtest", ".pptx"); - System.out.println(tmpFile); - try (FileOutputStream fos = new FileOutputStream(tmpFile)) { - ppt.write(fos); - } + final File tmpFile = TempFile.createTempFile("svgtest", ".pptx"); + System.out.println(tmpFile); + try (FileOutputStream fos = new FileOutputStream(tmpFile)) { + ppt.write(fos); + } - String[] args = { + String[] args = { "-format", "png", // png,gif,jpg or null for test "-slide", "-1", // -1 for all "-outdir", tmpFile.getParentFile().getCanonicalPath(), "-quiet", tmpFile.getAbsolutePath() - }; - PPTX2PNG.main(args); - } catch (IIOException ignore) { - // Ignore all ImageIO related exceptions like "Can't create output stream!" - // which fail often in maven builds because of missing/wrong temp directory - } catch (NoClassDefFoundError ignore) { - assumeFalse(true, "Batik doesn't work on th module-path"); + }; + PPTX2PNG.main(args); + } catch (IIOException ignored) { + // Ignore all ImageIO related exceptions like "Can't create output stream!" + // which fail often in maven builds because of missing/wrong temp directory + } catch (NoClassDefFoundError ignored) { + assumeFalse(true, "Batik doesn't work on th module-path"); + } } } }
\ No newline at end of file diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java index 56c5efda1f..c35db12765 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java @@ -19,6 +19,12 @@ package org.apache.poi.xssf; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; + +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.SpreadsheetVersion; @@ -31,13 +37,6 @@ import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - public final class DeferredSXSSFITestDataProvider implements ITestDataProvider { public static final DeferredSXSSFITestDataProvider instance = new DeferredSXSSFITestDataProvider(); @@ -69,16 +68,14 @@ public final class DeferredSXSSFITestDataProvider implements ITestDataProvider { throw new IllegalArgumentException("Expected an instance of XSSFWorkbook"); } - XSSFWorkbook result; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { wb.write(baos); - InputStream is = new ByteArrayInputStream(baos.toByteArray()); - result = new XSSFWorkbook(is); + try (InputStream is = baos.toInputStream()) { + return new XSSFWorkbook(is); + } } catch (IOException e) { throw new RuntimeException(e); } - return result; } @Override @@ -87,7 +84,7 @@ public final class DeferredSXSSFITestDataProvider implements ITestDataProvider { instances.add(wb); return wb; } - + //************ SXSSF-specific methods ***************// @Override public DeferredSXSSFWorkbook createWorkbook(int rowAccessWindowSize) { @@ -95,13 +92,13 @@ public final class DeferredSXSSFITestDataProvider implements ITestDataProvider { instances.add(wb); return wb; } - + @Override public void trackAllColumnsForAutosizing(Sheet sheet) { ((DeferredSXSSFSheet)sheet).trackAllColumnsForAutoSizing(); } //************ End SXSSF-specific methods ***************// - + @Override public FormulaEvaluator createFormulaEvaluator(Workbook wb) { return new XSSFFormulaEvaluator(((DeferredSXSSFWorkbook) wb).getXSSFWorkbook()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java index 744b02beb0..8c722151ee 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java @@ -19,13 +19,12 @@ package org.apache.poi.xssf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.SpreadsheetVersion; @@ -68,16 +67,14 @@ public final class SXSSFITestDataProvider implements ITestDataProvider { throw new IllegalArgumentException("Expected an instance of SXSSFWorkbook"); } - XSSFWorkbook result; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { wb.write(baos); - InputStream is = new ByteArrayInputStream(baos.toByteArray()); - result = new XSSFWorkbook(is); + try (InputStream is = baos.toInputStream()) { + return new XSSFWorkbook(is); + } } catch (IOException e) { throw new RuntimeException(e); } - return result; } @Override diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java index bb9859998c..3b35c52ac9 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java @@ -21,13 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ooxml.POIXMLException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; @@ -72,7 +72,7 @@ public class TestXSSFMemoryLeak { // not freed until we free up the Cell itself //verifier.addObject(ctCell); - try (OutputStream out = new ByteArrayOutputStream(8192)) { + try (OutputStream out = new UnsynchronizedByteArrayOutputStream(8192)) { wb.write(out); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java index 6beb153bd2..3a0ed9d4c3 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java @@ -17,14 +17,13 @@ package org.apache.poi.xssf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.ss.usermodel.Workbook; @@ -62,8 +61,8 @@ public class XSSFTestDataSamples { } /** - * Write out workbook <code>wb</code> to {@link #TEST_OUTPUT_DIR}/testName.xlsx - * (or create a temporary file if <code>TEST_OUTPUT_DIR</code> is not defined). + * Write out workbook {@code wb} to {@link #TEST_OUTPUT_DIR}/testName.xlsx + * (or create a temporary file if {@code TEST_OUTPUT_DIR} is not defined). * * @param wb the workbook to write * @param testName a fragment of the filename @@ -93,7 +92,7 @@ public class XSSFTestDataSamples { final File file; if (testOutputDir != null) { // In case user provided testName with a file extension, don't repeat the file extension a second time - final String testNameWithExtension = testName.endsWith(".xlsx") ? testName : testName + ".xlsx"; + final String testNameWithExtension = (testName.endsWith(".xlsx") || testName.endsWith(".xlsxm")) ? testName : testName + ".xlsx"; // FIXME: may want to defer to the TempFile with a persistent file creation strategy to the test output dir // This would add the random value in the middle of the filename so that test runs wouldn't overwrite files file = new File(testOutputDir, testNameWithExtension); @@ -110,14 +109,14 @@ public class XSSFTestDataSamples { } /** - * Write out workbook <code>wb</code> to a memory buffer + * Write out workbook {@code wb} to a memory buffer * * @param wb the workbook to write * @return the memory buffer * @throws IOException If writing the file fails */ - public static <R extends Workbook> ByteArrayOutputStream writeOut(R wb) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(8192); + public static <R extends Workbook> UnsynchronizedByteArrayOutputStream writeOut(R wb) throws IOException { + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(8192); wb.write(out); return out; } @@ -130,10 +129,10 @@ public class XSSFTestDataSamples { * Make sure there are no references to any objects in the workbook * so that garbage collection may free the workbook. * - * After calling this method, null the reference to <code>wb</code>, + * After calling this method, null the reference to {@code wb}, * then call {@link #readBack(File)} or {@link #readBackAndDelete(File)} to re-read the file. * - * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream + * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a UnsynchronizedByteArrayOutputStream/ByteArrayInputStream * to avoid creating a temporary file. However, this may complicate the calling * code to avoid having the workbook, BAOS, and BAIS open at the same time. * @@ -156,15 +155,15 @@ public class XSSFTestDataSamples { /** - * Write out workbook <code>wb</code> to a memory buffer, + * Write out workbook {@code wb} to a memory buffer, * then close the workbook * * @param wb the workbook to write * @return the memory buffer * @throws RuntimeException If writing the file fails */ - public static <R extends Workbook> ByteArrayOutputStream writeOutAndClose(R wb) throws IOException { - ByteArrayOutputStream out = writeOut(wb); + public static <R extends Workbook> UnsynchronizedByteArrayOutputStream writeOutAndClose(R wb) throws IOException { + UnsynchronizedByteArrayOutputStream out = writeOut(wb); // Do not close the workbook if there was a problem writing the workbook wb.close(); return out; @@ -211,8 +210,8 @@ public class XSSFTestDataSamples { * @return the read back workbook * @throws IOException If reading the file fails */ - public static XSSFWorkbook readBack(ByteArrayOutputStream out) throws IOException { - try (InputStream is = new ByteArrayInputStream(out.toByteArray())) { + public static XSSFWorkbook readBack(UnsynchronizedByteArrayOutputStream out) throws IOException { + try (InputStream is = out.toInputStream()) { out.close(); return new XSSFWorkbook(is); } @@ -226,12 +225,12 @@ public class XSSFTestDataSamples { * Workbook wb = new XSSFWorkbook(); * String testName = "example"; * - * <code> + * {@code * File file = writeOutAndClose(wb, testName); * // clear all references that would prevent the workbook from getting garbage collected * wb = null; * Workbook wbBack = readBackAndDelete(file); - * </code> + * } * * @param wb the workbook to write out * @return the read back workbook diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java index e85998cb12..5672564fd0 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collection; @@ -34,6 +33,7 @@ import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ooxml.POIXMLDocumentPart; import org.apache.poi.ooxml.util.DocumentHelper; import org.apache.poi.ss.usermodel.Cell; @@ -66,7 +66,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(1); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xml = os.toString("UTF-8"); @@ -114,7 +114,7 @@ public final class TestXSSFExportToXML { XSSFMap map = mapInfo.getXSSFMapById(1); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xml = os.toString("UTF-8"); @@ -187,7 +187,7 @@ public final class TestXSSFExportToXML { assertNotNull(map); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xml = os.toString("UTF-8"); @@ -223,7 +223,7 @@ public final class TestXSSFExportToXML { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); } } @@ -246,7 +246,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -290,7 +290,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -325,7 +325,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -364,7 +364,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -390,7 +390,7 @@ public final class TestXSSFExportToXML { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -468,7 +468,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -546,7 +546,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -577,7 +577,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, false); String xmlData = os.toString("UTF-8"); @@ -609,7 +609,7 @@ public final class TestXSSFExportToXML { assertNotNull(map, "XSSFMap is null"); XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, true); String xmlData = os.toString("UTF-8"); @@ -635,7 +635,7 @@ public final class TestXSSFExportToXML { for (XSSFMap map : mappings) { XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(os, false); assertNotNull(os.toString("UTF-8")); } @@ -647,9 +647,9 @@ public final class TestXSSFExportToXML { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61281.xlsx")) { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); exporter.exportToXML(bos, true); - assertNotNull(DocumentHelper.readDocument(new ByteArrayInputStream(bos.toByteArray()))); + assertNotNull(DocumentHelper.readDocument(bos.toInputStream())); String exportedXml = bos.toString("UTF-8"); assertEquals("<Test><Test>1</Test></Test>", exportedXml.replaceAll("\\s+", "")); } @@ -661,7 +661,7 @@ public final class TestXSSFExportToXML { try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("xxe_in_schema.xlsx")) { for (XSSFMap map : wb.getCustomXMLMappings()) { XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); assertThrows(SAXParseException.class, () -> exporter.exportToXML(bos, true)); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java index e065b26adb..17c4eec074 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java @@ -19,6 +19,7 @@ package org.apache.poi.xssf.streaming; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.POITestCase.assertEndsWith; import static org.apache.poi.POITestCase.assertStartsWith; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -29,14 +30,13 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -48,7 +48,6 @@ import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.NullOutputStream; import org.apache.poi.xssf.SXSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.SharedStringsTable; @@ -74,7 +73,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Override @Test protected void cloneSheet() throws IOException { - RuntimeException e = assertThrows(RuntimeException.class, () -> super.cloneSheet()); + RuntimeException e = assertThrows(RuntimeException.class, super::cloneSheet); assertEquals("Not Implemented", e.getMessage()); } @@ -84,7 +83,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Override @Test protected void sheetClone() { - RuntimeException e = assertThrows(RuntimeException.class, () -> super.sheetClone()); + RuntimeException e = assertThrows(RuntimeException.class, super::sheetClone); assertEquals("Not Implemented", e.getMessage()); } @@ -407,8 +406,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { private static void saveTwice(Workbook wb) throws Exception { for (int i = 0; i < 2; i++) { - try (NullOutputStream out = new NullOutputStream()) { - wb.write(out); + try { + wb.write(NULL_OUTPUT_STREAM); } catch (Exception e) { throw new Exception("ERROR: failed on " + (i + 1) + "th time calling " + wb.getClass().getName() @@ -471,7 +470,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { } } - assertDoesNotThrow(() -> swb.write(new NullOutputStream())); + assertDoesNotThrow(() -> swb.write(NULL_OUTPUT_STREAM)); swb.dispose(); } } @@ -489,7 +488,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { File input = XSSFTestDataSamples.getSampleFile("sample.xlsx"); try (OPCPackage pkg = OPCPackage.open(input, PackageAccess.READ)) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (XSSFWorkbook xssf = new XSSFWorkbook(pkg)) { try (SXSSFWorkbook wb = new SXSSFWorkbook(xssf, 2)) { Sheet s = wb.createSheet(sheetName); @@ -506,7 +505,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { } } - try (XSSFWorkbook xssf = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { + try (XSSFWorkbook xssf = new XSSFWorkbook(bos.toInputStream())) { Sheet s = xssf.getSheet(sheetName); assertEquals(10, s.getLastRowNum()); assertTrue(s.getRow(0).getCell(0).getBooleanCellValue()); @@ -518,20 +517,17 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook { @Test void test56557() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56557.xlsx"); - - // Using streaming XSSFWorkbook makes the output file invalid - wb = new SXSSFWorkbook(((XSSFWorkbook) wb)); - - // Should not throw POIXMLException: java.io.IOException: Unable to parse xml bean when reading back - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56557.xlsx"); + // Using streaming XSSFWorkbook makes the output file invalid + Workbook wb2 = new SXSSFWorkbook(wb); + // Should not throw POIXMLException: java.io.IOException: Unable to parse xml bean when reading back + Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb2) + ) { + assertNotNull(wbBack); + } } + @Disabled("not implemented") void changeSheetNameWithSharedFormulas() { - /* not implemented */ } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java index b1fa40fe69..d5afe8ea15 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java @@ -20,12 +20,11 @@ package org.apache.poi.xssf.streaming; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -33,6 +32,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.util.ZipEntrySource; @@ -58,38 +58,40 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource { // write an unencrypted workbook to disk, but any temporary files are encrypted @Test void customZipEntrySource() throws IOException { - SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - ByteArrayOutputStream os = new ByteArrayOutputStream(8192); - workbook.write(os); - workbook.close(); - workbook.dispose(); - XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(os.toByteArray())); - XSSFSheet xs1 = xwb.getSheetAt(0); - assertEquals(sheetName, xs1.getSheetName()); - XSSFRow xr1 = xs1.getRow(1); - XSSFCell xc1 = xr1.getCell(1); - assertEquals(cellValue, xc1.getStringCellValue()); - xwb.close(); + UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(8192); + try (SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource()) { + SXSSFSheet sheet1 = workbook.createSheet(sheetName); + SXSSFRow row1 = sheet1.createRow(1); + SXSSFCell cell1 = row1.createCell(1); + cell1.setCellValue(cellValue); + workbook.write(os); + workbook.close(); + workbook.dispose(); + } + try (XSSFWorkbook xwb = new XSSFWorkbook(os.toInputStream())) { + XSSFSheet xs1 = xwb.getSheetAt(0); + assertEquals(sheetName, xs1.getSheetName()); + XSSFRow xr1 = xs1.getRow(1); + XSSFCell xc1 = xr1.getCell(1); + assertEquals(cellValue, xc1.getStringCellValue()); + } } // write an encrypted workbook to disk, and encrypt any temporary files as well @Test void customZipEntrySourceForWriteAndRead() throws IOException, InvalidFormatException { - SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); EncryptedTempData tempData = new EncryptedTempData(); - try (OutputStream os = tempData.getOutputStream()) { - workbook.write(os); + try (SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource()) { + SXSSFSheet sheet1 = workbook.createSheet(sheetName); + SXSSFRow row1 = sheet1.createRow(1); + SXSSFCell cell1 = row1.createCell(1); + cell1.setCellValue(cellValue); + try (OutputStream os = tempData.getOutputStream()) { + workbook.write(os); + } + workbook.close(); + workbook.dispose(); } - workbook.close(); - workbook.dispose(); try (InputStream is = tempData.getInputStream(); ZipEntrySource zipEntrySource = AesZipFileZipEntrySource.createZipEntrySource(is)) { tempData.dispose(); @@ -111,8 +113,7 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource { SXSSFRow row1 = sheet1.createRow(1); SXSSFCell cell1 = row1.createCell(1); cell1.setCellValue(cellValue); - ByteArrayOutputStream os = new ByteArrayOutputStream(8192); - workbook.write(os); + workbook.write(NULL_OUTPUT_STREAM); workbook.close(); List<File> tempFiles = workbook.getTempFiles(); assertEquals(1, tempFiles.size()); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java index 679c3c60bf..0b307277f5 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java @@ -17,6 +17,7 @@ package org.apache.poi.xssf.usermodel; +import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -24,13 +25,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ss.formula.OperationEvaluationContext; import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.ValueEval; @@ -242,7 +243,7 @@ public final class TestUnfixedBugs { checkRows57423(testSheet); - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); + Workbook wbBack = writeOutAndReadBack(wb); /* XSSFTestDataSamples.writeOut(wb, "bug 57423 for manual review"); */ wb.close(); @@ -277,12 +278,8 @@ public final class TestUnfixedBugs { checkRow57423(testSheet, 17, "17"); checkRow57423(testSheet, 18, "18"); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - ((XSSFSheet)testSheet).write(stream); - } finally { - stream.close(); - } + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(); + ((XSSFSheet)testSheet).write(stream); // verify that the resulting XML has the rows in correct order as required by Excel String xml = new String(stream.toByteArray(), StandardCharsets.UTF_8); @@ -310,27 +307,21 @@ public final class TestUnfixedBugs { @Test void bug57423_shiftRowsByLargeOffset() throws IOException { - try ( - XSSFWorkbook wb = new XSSFWorkbook() - //OutputStream out = new FileOutputStream("/tmp/57423." + wb.getClass().getName() + ".xlsx")); - ) { + try (XSSFWorkbook wb = new XSSFWorkbook()) { Sheet sh = wb.createSheet(); sh.createRow(0).createCell(0).setCellValue("a"); sh.createRow(1).createCell(0).setCellValue("b"); sh.createRow(2).createCell(0).setCellValue("c"); sh.shiftRows(0, 1, 3); - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - assertThatRowsInAscendingOrder(wb); - assertThatRowsInAscendingOrder(wbBack); - - //wbBack.write(out); - // Excel reports that the workbook is corrupt because the rows are not in ascending order - // LibreOffice doesn't complain when rows are not in ascending order - - wbBack.close(); + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { + assertThatRowsInAscendingOrder(wb); + assertThatRowsInAscendingOrder(wbBack); + //wbBack.write(out); + // Excel reports that the workbook is corrupt because the rows are not in ascending order + // LibreOffice doesn't complain when rows are not in ascending order + } fail("Excel reports that the workbook is corrupt, LibreOffice can read it"); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java index d0d97e91de..508362e820 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java @@ -19,20 +19,20 @@ package org.apache.poi.xssf.usermodel; import static java.time.Duration.between; import static java.time.Instant.now; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.logging.log4j.util.Unbox.box; import static org.apache.poi.extractor.ExtractorFactory.OOXML_PACKAGE; import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive; +import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; +import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeFalse; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; @@ -47,6 +47,7 @@ import java.util.TreeMap; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.POIDataSamples; @@ -99,7 +100,7 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellUtil; import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NullOutputStream; +import org.apache.commons.io.output.NullOutputStream; import org.apache.poi.util.TempFile; import org.apache.poi.util.XMLHelper; import org.apache.poi.xssf.SXSSFITestDataProvider; @@ -115,6 +116,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; @@ -140,7 +142,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug45430() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("45430.xlsx")) { assertFalse(wb.isMacroEnabled()); assertEquals(3, wb.getNumberOfNames()); @@ -160,7 +162,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertEquals("SheetC", wb.getName("SheetCA1").getSheetName()); // Save and re-load, still there - try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (XSSFWorkbook nwb = writeOutAndReadBack(wb)) { assertEquals(3, nwb.getNumberOfNames()); assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula()); } @@ -172,79 +174,74 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug45431() throws IOException, InvalidFormatException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm"); - OPCPackage pkg1 = wb1.getPackage(); - assertTrue(wb1.isMacroEnabled()); + try (XSSFWorkbook wb1 = openSampleWorkbook("45431.xlsm"); + OPCPackage pkg1 = wb1.getPackage()) { + assertTrue(wb1.isMacroEnabled()); - // Check the various macro related bits can be found - PackagePart vba = pkg1.getPart( + // Check the various macro related bits can be found + PackagePart vba = pkg1.getPart( PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - // And the drawing bit - PackagePart drw = pkg1.getPart( + ); + assertNotNull(vba); + // And the drawing bit + PackagePart drw = pkg1.getPart( PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - - // Save and re-open, both still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - pkg1.close(); - wb1.close(); - - OPCPackage pkg2 = wb2.getPackage(); - assertTrue(wb2.isMacroEnabled()); - - vba = pkg2.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - drw = pkg2.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - // And again, just to be sure - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - pkg2.close(); - wb2.close(); - OPCPackage pkg3 = wb3.getPackage(); - assertTrue(wb3.isMacroEnabled()); - - vba = pkg3.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - drw = pkg3.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - pkg3.close(); - wb3.close(); + ); + assertNotNull(drw); + + + // Save and re-open, both still there + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1); + OPCPackage pkg2 = wb2.getPackage()) { + assertTrue(wb2.isMacroEnabled()); + + vba = pkg2.getPart( + PackagingURIHelper.createPartName("/xl/vbaProject.bin") + ); + assertNotNull(vba); + drw = pkg2.getPart( + PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") + ); + assertNotNull(drw); + + // And again, just to be sure + try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2); + OPCPackage pkg3 = wb3.getPackage()) { + assertTrue(wb3.isMacroEnabled()); + + vba = pkg3.getPart( + PackagingURIHelper.createPartName("/xl/vbaProject.bin") + ); + assertNotNull(vba); + drw = pkg3.getPart( + PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") + ); + assertNotNull(drw); + } + } + } } @Test void bug47504() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx"); - assertEquals(1, wb1.getNumberOfSheets()); - XSSFSheet sh = wb1.getSheetAt(0); - XSSFDrawing drawing = sh.createDrawingPatriarch(); - List<RelationPart> rels = drawing.getRelationParts(); - assertEquals(1, rels.size()); - assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); - - // And again, just to be sure - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(1, wb2.getNumberOfSheets()); - sh = wb2.getSheetAt(0); - drawing = sh.createDrawingPatriarch(); - rels = drawing.getRelationParts(); - assertEquals(1, rels.size()); - assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); - wb2.close(); + try (XSSFWorkbook wb1 = openSampleWorkbook("47504.xlsx")) { + assertEquals(1, wb1.getNumberOfSheets()); + XSSFSheet sh = wb1.getSheetAt(0); + XSSFDrawing drawing = sh.createDrawingPatriarch(); + List<RelationPart> rels = drawing.getRelationParts(); + assertEquals(1, rels.size()); + assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); + + // And again, just to be sure + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + assertEquals(1, wb2.getNumberOfSheets()); + sh = wb2.getSheetAt(0); + drawing = sh.createDrawingPatriarch(); + rels = drawing.getRelationParts(); + assertEquals(1, rels.size()); + assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); + } + } } /** @@ -255,7 +252,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49020() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("BrNotClosed.xlsx")) { assertNotNull(wb); } } @@ -265,7 +262,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49325() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("49325.xlsx")) { CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet(); assertNotNull(sh.getPhoneticPr()); } @@ -277,7 +274,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug48923() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("48923.xlsx")) { assertEquals(4, wb.getNumberOfNames()); Name b1 = wb.getName("NameB1"); @@ -321,7 +318,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug48539() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("48539.xlsx")) { assertEquals(3, wb.getNumberOfSheets()); assertEquals(0, wb.getNumberOfNames()); @@ -358,7 +355,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug48779() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("48779.xlsx")) { XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); XSSFCellStyle cs = cell.getCellStyle(); @@ -396,7 +393,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug47490() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("GeneralFormatTests.xlsx")) { Sheet s = wb.getSheetAt(1); Row r; DataFormatter df = new DataFormatter(); @@ -434,7 +431,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49609() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("49609.xlsx")) { assertEquals("FAM", wb.getSheetName(0)); assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); } @@ -443,7 +440,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug49783() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx")) { + try (Workbook wb = openSampleWorkbook("49783.xlsx")) { Sheet sheet = wb.getSheetAt(0); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); Cell cell; @@ -476,78 +473,77 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49941() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet s = wb1.createSheet(); - XSSFRow r = s.createRow(0); - XSSFCell c = r.createCell(0); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet s = wb1.createSheet(); + XSSFRow r = s.createRow(0); + XSSFCell c = r.createCell(0); - // First without fonts - c.setCellValue( + // First without fonts + c.setCellValue( new XSSFRichTextString(" with spaces ") - ); - assertEquals(" with spaces ", c.getRichStringCellValue().toString()); - assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray()); - assertTrue(c.getRichStringCellValue().getCTRst().isSetT()); - // Should have the preserve set - assertEquals( + ); + assertEquals(" with spaces ", c.getRichStringCellValue().toString()); + assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray()); + assertTrue(c.getRichStringCellValue().getCTRst().isSetT()); + // Should have the preserve set + assertEquals( 1, c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength() - ); - assertEquals( + ); + assertEquals( "preserve", c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue() - ); - - // Save and check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertEquals(" with spaces ", c.getRichStringCellValue().toString()); - assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray()); - assertTrue(c.getRichStringCellValue().getCTRst().isSetT()); - - // Change the string - c.setCellValue( - new XSSFRichTextString("hello world") - ); - assertEquals("hello world", c.getRichStringCellValue().toString()); - // Won't have preserve - assertEquals( - 0, - c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength() - ); - - // Apply a font - XSSFFont f = wb2.createFont(); - f.setBold(true); - c.getRichStringCellValue().applyFont(0, 5, f); - assertEquals("hello world", c.getRichStringCellValue().toString()); - // Does need preserving on the 2nd part - assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray()); - assertEquals( - 0, - c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength() - ); - assertEquals( - 1, - c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength() - ); - assertEquals( - "preserve", - c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue() - ); - - // Save and check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); + ); - s = wb3.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertEquals("hello world", c.getRichStringCellValue().toString()); - wb3.close(); + // Save and check + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + s = wb2.getSheetAt(0); + r = s.getRow(0); + c = r.getCell(0); + assertEquals(" with spaces ", c.getRichStringCellValue().toString()); + assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray()); + assertTrue(c.getRichStringCellValue().getCTRst().isSetT()); + + // Change the string + c.setCellValue( + new XSSFRichTextString("hello world") + ); + assertEquals("hello world", c.getRichStringCellValue().toString()); + // Won't have preserve + assertEquals( + 0, + c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength() + ); + + // Apply a font + XSSFFont f = wb2.createFont(); + f.setBold(true); + c.getRichStringCellValue().applyFont(0, 5, f); + assertEquals("hello world", c.getRichStringCellValue().toString()); + // Does need preserving on the 2nd part + assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray()); + assertEquals( + 0, + c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength() + ); + assertEquals( + 1, + c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength() + ); + assertEquals( + "preserve", + c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue() + ); + + // Save and check + try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { + s = wb3.getSheetAt(0); + r = s.getRow(0); + c = r.getCell(0); + assertEquals("hello world", c.getRichStringCellValue().toString()); + } + } + } } /** @@ -555,25 +551,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49940() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("styles.xlsx")) { assertEquals(3, wb.getNumberOfSheets()); assertEquals(10, wb.getStylesSource().getNumCellStyles()); - ByteArrayOutputStream b1 = new ByteArrayOutputStream(); - ByteArrayOutputStream b2 = new ByteArrayOutputStream(); - ByteArrayOutputStream b3 = new ByteArrayOutputStream(); - wb.write(b1); - wb.write(b2); - wb.write(b3); - - for (byte[] data : new byte[][]{ - b1.toByteArray(), b2.toByteArray(), b3.toByteArray() - }) { - ByteArrayInputStream bais = new ByteArrayInputStream(data); - XSSFWorkbook wb2 = new XSSFWorkbook(bais); - assertEquals(3, wb2.getNumberOfSheets()); - assertEquals(10, wb2.getStylesSource().getNumCellStyles()); - wb2.close(); + for (int i=0; i<3; i++) { + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb)) { + assertEquals(3, wb2.getNumberOfSheets()); + assertEquals(10, wb2.getStylesSource().getNumCellStyles()); + } } } } @@ -584,11 +570,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49966() throws IOException { - try (XSSFWorkbook wb1 = XSSFTestDataSamples - .openSampleWorkbook("shared_formulas.xlsx")) { + try (XSSFWorkbook wb1 = openSampleWorkbook("shared_formulas.xlsx")) { XSSFSheet sheet = wb1.getSheetAt(0); - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); // CalcChain has lots of entries CalculationChain cc = wb1.getCalculationChain(); @@ -601,7 +586,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR()); assertEquals(40, cc.getCTCalcChain().sizeOfCArray()); - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); // Try various ways of changing the formulas // If it stays a formula, chain entry should remain @@ -609,25 +594,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay sheet.getRow(2).getCell(0).setCellFormula(null); // go sheet.getRow(3).getCell(0).setCellFormula("14"); // stay - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); sheet.getRow(4).getCell(0).setBlank(); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); validateCells(sheet); sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go validateCells(sheet); - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); sheet.getRow(6).getCell(0).setBlank(); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); sheet.getRow(7).getCell(0).setCellValue((String) null); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + writeOutAndReadBack(wb1).close(); // Save and check - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { wb1.close(); assertEquals(35, cc.getCTCalcChain().sizeOfCArray()); @@ -641,8 +626,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug49966Row() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("shared_formulas.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("shared_formulas.xlsx")) { XSSFSheet sheet = wb.getSheetAt(0); validateCells(sheet); @@ -660,7 +644,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug49156() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx")) { + try (Workbook wb = openSampleWorkbook("49156.xlsx")) { FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); Sheet sheet = wb.getSheetAt(0); @@ -680,7 +664,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50440And51875() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx")) { + try (Workbook wb = openSampleWorkbook("NewlineInFormulas.xlsx")) { Sheet s = wb.getSheetAt(0); Cell c = s.getRow(0).getCell(0); @@ -706,58 +690,55 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50795() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - XSSFRow row = sheet.getRow(0); - - XSSFCell cellWith = row.getCell(0); - XSSFCell cellWithoutComment = row.getCell(1); - - assertNotNull(cellWith.getCellComment()); - assertNull(cellWithoutComment.getCellComment()); - - String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment"; - XSSFComment comment = cellWith.getCellComment(); - assertEquals(exp, comment.getString().getString()); + try (XSSFWorkbook wb1 = openSampleWorkbook("50795.xlsx")) { + XSSFSheet sheet = wb1.getSheetAt(0); + XSSFRow row = sheet.getRow(0); + XSSFCell cellWith = row.getCell(0); + XSSFCell cellWithoutComment = row.getCell(1); - // Check we can write it out and read it back as-is - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); + assertNotNull(cellWith.getCellComment()); + assertNull(cellWithoutComment.getCellComment()); - sheet = wb2.getSheetAt(0); - row = sheet.getRow(0); - cellWith = row.getCell(0); - cellWithoutComment = row.getCell(1); + String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment"; + XSSFComment comment = cellWith.getCellComment(); + assertEquals(exp, comment.getString().getString()); - // Double check things are as expected - assertNotNull(cellWith.getCellComment()); - assertNull(cellWithoutComment.getCellComment()); - comment = cellWith.getCellComment(); - assertEquals(exp, comment.getString().getString()); + // Check we can write it out and read it back as-is + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + row = sheet.getRow(0); + cellWith = row.getCell(0); + cellWithoutComment = row.getCell(1); - // Move the comment - cellWithoutComment.setCellComment(comment); + // Double check things are as expected + assertNotNull(cellWith.getCellComment()); + assertNull(cellWithoutComment.getCellComment()); + comment = cellWith.getCellComment(); + assertEquals(exp, comment.getString().getString()); - // Write out and re-check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); + // Move the comment + cellWithoutComment.setCellComment(comment); - sheet = wb3.getSheetAt(0); - row = sheet.getRow(0); - // Ensure it swapped over - cellWith = row.getCell(0); - cellWithoutComment = row.getCell(1); - assertNull(cellWith.getCellComment()); - assertNotNull(cellWithoutComment.getCellComment()); + // Write out and re-check + try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { + sheet = wb3.getSheetAt(0); + row = sheet.getRow(0); - comment = cellWithoutComment.getCellComment(); - assertEquals(exp, comment.getString().getString()); + // Ensure it swapped over + cellWith = row.getCell(0); + cellWithoutComment = row.getCell(1); + assertNull(cellWith.getCellComment()); + assertNotNull(cellWithoutComment.getCellComment()); - wb3.close(); + comment = cellWithoutComment.getCellComment(); + assertEquals(exp, comment.getString().getString()); + } + } + } } /** @@ -768,7 +749,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50299() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) { + try (Workbook wb = openSampleWorkbook("50299.xlsx")) { // Check all the colours for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) { @@ -799,7 +780,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50786() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("50786-indexed_colours.xlsx")) { XSSFSheet s = wb.getSheetAt(0); XSSFRow r = s.getRow(2); @@ -822,7 +803,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50846() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("50846-border_colours.xlsx")) { XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row = sheet.getRow(0); @@ -852,7 +833,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50784() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("50784-font_theme_colours.xlsx")) { XSSFSheet s = wb.getSheetAt(0); XSSFRow r = s.getRow(0); @@ -886,69 +867,65 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { String text = "Use \n with word wrap on to create a new line.\n" + "This line finishes with two trailing spaces. "; - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet(); - Font font1 = wb1.createFont(); - font1.setColor((short) 20); - Font font2 = wb1.createFont(); - font2.setColor(Font.COLOR_RED); - Font font3 = wb1.getFontAt(0); + Font font1 = wb1.createFont(); + font1.setColor((short) 20); + Font font2 = wb1.createFont(); + font2.setColor(Font.COLOR_RED); + Font font3 = wb1.getFontAt(0); - XSSFRow row = sheet.createRow(2); - XSSFCell cell = row.createCell(2); + XSSFRow row = sheet.createRow(2); + XSSFCell cell = row.createCell(2); - XSSFRichTextString richTextString = + XSSFRichTextString richTextString = wb1.getCreationHelper().createRichTextString(text); - // Check the text has the newline - assertEquals(text, richTextString.getString()); - - // Apply the font - richTextString.applyFont(font3); - richTextString.applyFont(0, 3, font1); - cell.setCellValue(richTextString); + // Check the text has the newline + assertEquals(text, richTextString.getString()); - // To enable newlines you need set a cell styles with wrap=true - CellStyle cs = wb1.createCellStyle(); - cs.setWrapText(true); - cell.setCellStyle(cs); + // Apply the font + richTextString.applyFont(font3); + richTextString.applyFont(0, 3, font1); + cell.setCellValue(richTextString); - // Check the text has the - assertEquals(text, cell.getStringCellValue()); + // To enable newlines you need set a cell styles with wrap=true + CellStyle cs = wb1.createCellStyle(); + cs.setWrapText(true); + cell.setCellStyle(cs); - // Save the file and re-read it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - row = sheet.getRow(2); - cell = row.getCell(2); - assertEquals(text, cell.getStringCellValue()); + // Check the text has the + assertEquals(text, cell.getStringCellValue()); - // Now add a 2nd, and check again - int fontAt = text.indexOf('\n', 6); - cell.getRichStringCellValue().applyFont(10, fontAt + 1, font2); - assertEquals(text, cell.getStringCellValue()); + // Save the file and re-read it + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + row = sheet.getRow(2); + cell = row.getCell(2); + assertEquals(text, cell.getStringCellValue()); - assertEquals(4, cell.getRichStringCellValue().numFormattingRuns()); - assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT()); + // Now add a 2nd, and check again + int fontAt = text.indexOf('\n', 6); + cell.getRichStringCellValue().applyFont(10, fontAt + 1, font2); + assertEquals(text, cell.getStringCellValue()); - String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT(); - assertEquals("line.\n", r3.substring(r3.length() - 6)); + assertEquals(4, cell.getRichStringCellValue().numFormattingRuns()); + assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT()); - // Save and re-check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); + String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT(); + assertEquals("line.\n", r3.substring(r3.length() - 6)); - sheet = wb3.getSheetAt(0); - row = sheet.getRow(2); - cell = row.getCell(2); - assertEquals(text, cell.getStringCellValue()); - wb3.close(); + // Save and re-check + try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { - // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx"); - // wb.write(out); - // out.close(); + sheet = wb3.getSheetAt(0); + row = sheet.getRow(2); + cell = row.getCell(2); + assertEquals(text, cell.getStringCellValue()); + } + } + } } /** @@ -956,119 +933,118 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug50867() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx"); - assertEquals(3, wb1.getNumberOfSheets()); - - XSSFSheet s1 = wb1.getSheetAt(0); - XSSFSheet s2 = wb1.getSheetAt(1); - XSSFSheet s3 = wb1.getSheetAt(2); - assertEquals(1, s1.getTables().size()); - assertEquals(0, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - - XSSFTable t = s1.getTables().get(0); - assertEquals("Tabella1", t.getName()); - assertEquals("Tabella1", t.getDisplayName()); - assertEquals("A1:C3", t.getCTTable().getRef()); - - // Add a sheet and re-order - XSSFSheet s4 = wb1.createSheet("NewSheet"); - wb1.setSheetOrder(s4.getSheetName(), 0); - - // Check on tables - assertEquals(1, s1.getTables().size()); - assertEquals(0, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - // Refetch to get the new order - s1 = wb1.getSheetAt(0); - s2 = wb1.getSheetAt(1); - s3 = wb1.getSheetAt(2); - s4 = wb1.getSheetAt(3); - assertEquals(0, s1.getTables().size()); - assertEquals(1, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - s1 = wb2.getSheetAt(0); - s2 = wb2.getSheetAt(1); - s3 = wb2.getSheetAt(2); - s4 = wb2.getSheetAt(3); - assertEquals(0, s1.getTables().size()); - assertEquals(1, s2.getTables().size()); - assertEquals(0, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - t = s2.getTables().get(0); - assertEquals("Tabella1", t.getName()); - assertEquals("Tabella1", t.getDisplayName()); - assertEquals("A1:C3", t.getCTTable().getRef()); - - - // Add some more tables, and check - t = s2.createTable(null); - t.setName("New 2"); - t.setDisplayName("New 2"); - t = s3.createTable(null); - t.setName("New 3"); - t.setDisplayName("New 3"); - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - s1 = wb3.getSheetAt(0); - s2 = wb3.getSheetAt(1); - s3 = wb3.getSheetAt(2); - s4 = wb3.getSheetAt(3); - assertEquals(0, s1.getTables().size()); - assertEquals(2, s2.getTables().size()); - assertEquals(1, s3.getTables().size()); - assertEquals(0, s4.getTables().size()); - - t = s2.getTables().get(0); - assertEquals("Tabella1", t.getName()); - assertEquals("Tabella1", t.getDisplayName()); - assertEquals("A1:C3", t.getCTTable().getRef()); - - t = s2.getTables().get(1); - assertEquals("New 2", t.getName()); - assertEquals("New 2", t.getDisplayName()); - - t = s3.getTables().get(0); - assertEquals("New 3", t.getName()); - assertEquals("New 3", t.getDisplayName()); - - // Check the relationships - assertEquals(0, s1.getRelations().size()); - assertEquals(3, s2.getRelations().size()); - assertEquals(1, s3.getRelations().size()); - assertEquals(0, s4.getRelations().size()); - - assertEquals( - XSSFRelation.PRINTER_SETTINGS.getContentType(), - s2.getRelations().get(0).getPackagePart().getContentType() - ); - assertEquals( - XSSFRelation.TABLE.getContentType(), - s2.getRelations().get(1).getPackagePart().getContentType() - ); - assertEquals( - XSSFRelation.TABLE.getContentType(), - s2.getRelations().get(2).getPackagePart().getContentType() - ); - assertEquals( - XSSFRelation.TABLE.getContentType(), - s3.getRelations().get(0).getPackagePart().getContentType() - ); - assertEquals( - "/xl/tables/table3.xml", - s3.getRelations().get(0).getPackagePart().getPartName().toString() - ); - wb3.close(); + try (XSSFWorkbook wb1 = openSampleWorkbook("50867_with_table.xlsx")) { + assertEquals(3, wb1.getNumberOfSheets()); + + XSSFSheet s1 = wb1.getSheetAt(0); + XSSFSheet s2 = wb1.getSheetAt(1); + XSSFSheet s3 = wb1.getSheetAt(2); + assertEquals(1, s1.getTables().size()); + assertEquals(0, s2.getTables().size()); + assertEquals(0, s3.getTables().size()); + + XSSFTable t = s1.getTables().get(0); + assertEquals("Tabella1", t.getName()); + assertEquals("Tabella1", t.getDisplayName()); + assertEquals("A1:C3", t.getCTTable().getRef()); + + // Add a sheet and re-order + XSSFSheet s4 = wb1.createSheet("NewSheet"); + wb1.setSheetOrder(s4.getSheetName(), 0); + + // Check on tables + assertEquals(1, s1.getTables().size()); + assertEquals(0, s2.getTables().size()); + assertEquals(0, s3.getTables().size()); + assertEquals(0, s4.getTables().size()); + + // Refetch to get the new order + s1 = wb1.getSheetAt(0); + s2 = wb1.getSheetAt(1); + s3 = wb1.getSheetAt(2); + s4 = wb1.getSheetAt(3); + assertEquals(0, s1.getTables().size()); + assertEquals(1, s2.getTables().size()); + assertEquals(0, s3.getTables().size()); + assertEquals(0, s4.getTables().size()); + + // Save and re-load + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + s1 = wb2.getSheetAt(0); + s2 = wb2.getSheetAt(1); + s3 = wb2.getSheetAt(2); + s4 = wb2.getSheetAt(3); + assertEquals(0, s1.getTables().size()); + assertEquals(1, s2.getTables().size()); + assertEquals(0, s3.getTables().size()); + assertEquals(0, s4.getTables().size()); + + t = s2.getTables().get(0); + assertEquals("Tabella1", t.getName()); + assertEquals("Tabella1", t.getDisplayName()); + assertEquals("A1:C3", t.getCTTable().getRef()); + + + // Add some more tables, and check + t = s2.createTable(null); + t.setName("New 2"); + t.setDisplayName("New 2"); + t = s3.createTable(null); + t.setName("New 3"); + t.setDisplayName("New 3"); + + try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { + s1 = wb3.getSheetAt(0); + s2 = wb3.getSheetAt(1); + s3 = wb3.getSheetAt(2); + s4 = wb3.getSheetAt(3); + assertEquals(0, s1.getTables().size()); + assertEquals(2, s2.getTables().size()); + assertEquals(1, s3.getTables().size()); + assertEquals(0, s4.getTables().size()); + + t = s2.getTables().get(0); + assertEquals("Tabella1", t.getName()); + assertEquals("Tabella1", t.getDisplayName()); + assertEquals("A1:C3", t.getCTTable().getRef()); + + t = s2.getTables().get(1); + assertEquals("New 2", t.getName()); + assertEquals("New 2", t.getDisplayName()); + + t = s3.getTables().get(0); + assertEquals("New 3", t.getName()); + assertEquals("New 3", t.getDisplayName()); + + // Check the relationships + assertEquals(0, s1.getRelations().size()); + assertEquals(3, s2.getRelations().size()); + assertEquals(1, s3.getRelations().size()); + assertEquals(0, s4.getRelations().size()); + + assertEquals( + XSSFRelation.PRINTER_SETTINGS.getContentType(), + s2.getRelations().get(0).getPackagePart().getContentType() + ); + assertEquals( + XSSFRelation.TABLE.getContentType(), + s2.getRelations().get(1).getPackagePart().getContentType() + ); + assertEquals( + XSSFRelation.TABLE.getContentType(), + s2.getRelations().get(2).getPackagePart().getContentType() + ); + assertEquals( + XSSFRelation.TABLE.getContentType(), + s3.getRelations().get(0).getPackagePart().getContentType() + ); + assertEquals( + "/xl/tables/table3.xml", + s3.getRelations().get(0).getPackagePart().getPartName().toString() + ); + } + } + } } /** @@ -1077,45 +1053,43 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug49253() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFWorkbook wb2 = new XSSFWorkbook(); - CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3"); - - // No print settings before repeating - XSSFSheet s1 = wb1.createSheet(); - assertFalse(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); - s1.setRepeatingColumns(cra); - s1.setRepeatingRows(cra); + try (XSSFWorkbook wb1 = new XSSFWorkbook(); + XSSFWorkbook wb2 = new XSSFWorkbook()) { + CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3"); - assertTrue(s1.getCTWorksheet().isSetPageSetup()); - assertTrue(s1.getCTWorksheet().isSetPageMargins()); + // No print settings before repeating + XSSFSheet s1 = wb1.createSheet(); + assertFalse(s1.getCTWorksheet().isSetPageSetup()); + assertTrue(s1.getCTWorksheet().isSetPageMargins()); + s1.setRepeatingColumns(cra); + s1.setRepeatingRows(cra); - PrintSetup ps1 = s1.getPrintSetup(); - assertFalse(ps1.getValidSettings()); - assertFalse(ps1.getLandscape()); + assertTrue(s1.getCTWorksheet().isSetPageSetup()); + assertTrue(s1.getCTWorksheet().isSetPageMargins()); + PrintSetup ps1 = s1.getPrintSetup(); + assertFalse(ps1.getValidSettings()); + assertFalse(ps1.getLandscape()); - // Had valid print settings before repeating - XSSFSheet s2 = wb2.createSheet(); - PrintSetup ps2 = s2.getPrintSetup(); - assertTrue(s2.getCTWorksheet().isSetPageSetup()); - assertTrue(s2.getCTWorksheet().isSetPageMargins()); - ps2.setLandscape(false); - assertTrue(ps2.getValidSettings()); - assertFalse(ps2.getLandscape()); - s2.setRepeatingColumns(cra); - s2.setRepeatingRows(cra); + // Had valid print settings before repeating + XSSFSheet s2 = wb2.createSheet(); + PrintSetup ps2 = s2.getPrintSetup(); + assertTrue(s2.getCTWorksheet().isSetPageSetup()); + assertTrue(s2.getCTWorksheet().isSetPageMargins()); - ps2 = s2.getPrintSetup(); - assertTrue(s2.getCTWorksheet().isSetPageSetup()); - assertTrue(s2.getCTWorksheet().isSetPageMargins()); - assertTrue(ps2.getValidSettings()); - assertFalse(ps2.getLandscape()); + ps2.setLandscape(false); + assertTrue(ps2.getValidSettings()); + assertFalse(ps2.getLandscape()); + s2.setRepeatingColumns(cra); + s2.setRepeatingRows(cra); - wb1.close(); - wb2.close(); + ps2 = s2.getPrintSetup(); + assertTrue(s2.getCTWorksheet().isSetPageSetup()); + assertTrue(s2.getCTWorksheet().isSetPageMargins()); + assertTrue(ps2.getValidSettings()); + assertFalse(ps2.getLandscape()); + } } /** @@ -1123,77 +1097,77 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug51037() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s = wb.createSheet(); - - CellStyle defaultStyle = wb.getCellStyleAt((short) 0); - assertEquals(0, defaultStyle.getIndex()); - - CellStyle blueStyle = wb.createCellStyle(); - blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex()); - blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(1, blueStyle.getIndex()); - - CellStyle pinkStyle = wb.createCellStyle(); - pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); - pinkStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(2, pinkStyle.getIndex()); - - // Starts empty - assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); - CTCols cols = s.getCTWorksheet().getColsArray(0); - assertEquals(0, cols.sizeOfColArray()); - - // Add some rows and columns - XSSFRow r1 = s.createRow(0); - XSSFRow r2 = s.createRow(1); - r1.createCell(0); - r1.createCell(2); - r2.createCell(0); - r2.createCell(3); - - // Check no style is there - assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); - assertEquals(0, cols.sizeOfColArray()); - - assertEquals(defaultStyle, s.getColumnStyle(0)); - assertEquals(defaultStyle, s.getColumnStyle(2)); - assertEquals(defaultStyle, s.getColumnStyle(3)); - - - // Apply the styles - s.setDefaultColumnStyle(0, pinkStyle); - s.setDefaultColumnStyle(3, blueStyle); - - // Check - assertEquals(pinkStyle, s.getColumnStyle(0)); - assertEquals(defaultStyle, s.getColumnStyle(2)); - assertEquals(blueStyle, s.getColumnStyle(3)); - - assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); - assertEquals(2, cols.sizeOfColArray()); - - assertEquals(1, cols.getColArray(0).getMin()); - assertEquals(1, cols.getColArray(0).getMax()); - assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle()); - - assertEquals(4, cols.getColArray(1).getMin()); - assertEquals(4, cols.getColArray(1).getMax()); - assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle()); - - - // Save, re-load and re-check - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - s = wbBack.getSheetAt(0); - defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex()); - blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex()); - pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex()); - - assertEquals(pinkStyle, s.getColumnStyle(0)); - assertEquals(defaultStyle, s.getColumnStyle(2)); - assertEquals(blueStyle, s.getColumnStyle(3)); - wbBack.close(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet s = wb.createSheet(); + + CellStyle defaultStyle = wb.getCellStyleAt((short) 0); + assertEquals(0, defaultStyle.getIndex()); + + CellStyle blueStyle = wb.createCellStyle(); + blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex()); + blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + assertEquals(1, blueStyle.getIndex()); + + CellStyle pinkStyle = wb.createCellStyle(); + pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); + pinkStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + assertEquals(2, pinkStyle.getIndex()); + + // Starts empty + assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); + CTCols cols = s.getCTWorksheet().getColsArray(0); + assertEquals(0, cols.sizeOfColArray()); + + // Add some rows and columns + XSSFRow r1 = s.createRow(0); + XSSFRow r2 = s.createRow(1); + r1.createCell(0); + r1.createCell(2); + r2.createCell(0); + r2.createCell(3); + + // Check no style is there + assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); + assertEquals(0, cols.sizeOfColArray()); + + assertEquals(defaultStyle, s.getColumnStyle(0)); + assertEquals(defaultStyle, s.getColumnStyle(2)); + assertEquals(defaultStyle, s.getColumnStyle(3)); + + + // Apply the styles + s.setDefaultColumnStyle(0, pinkStyle); + s.setDefaultColumnStyle(3, blueStyle); + + // Check + assertEquals(pinkStyle, s.getColumnStyle(0)); + assertEquals(defaultStyle, s.getColumnStyle(2)); + assertEquals(blueStyle, s.getColumnStyle(3)); + + assertEquals(1, s.getCTWorksheet().sizeOfColsArray()); + assertEquals(2, cols.sizeOfColArray()); + + assertEquals(1, cols.getColArray(0).getMin()); + assertEquals(1, cols.getColArray(0).getMax()); + assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle()); + + assertEquals(4, cols.getColArray(1).getMin()); + assertEquals(4, cols.getColArray(1).getMax()); + assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle()); + + + // Save, re-load and re-check + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { + s = wbBack.getSheetAt(0); + defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex()); + blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex()); + pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex()); + + assertEquals(pinkStyle, s.getColumnStyle(0)); + assertEquals(defaultStyle, s.getColumnStyle(2)); + assertEquals(blueStyle, s.getColumnStyle(3)); + } + } } /** @@ -1203,9 +1177,9 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug46662() throws IOException { for (int i=0; i<2; i++) { - try (XSSFWorkbook wb1 = (i == 0) ? new XSSFWorkbook() : XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { + try (XSSFWorkbook wb1 = (i == 0) ? new XSSFWorkbook() : openSampleWorkbook("sample.xlsx")) { for (int j=0; j<3; j++) { - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { assertEquals(wb1.getNumberOfSheets(), wb2.getNumberOfSheets()); } } @@ -1220,7 +1194,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug51222() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("51222.xlsx")) { XSSFSheet s = wb.getSheetAt(0); XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0); @@ -1260,7 +1234,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug51470() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("51470.xlsx")) { XSSFSheet sh0 = wb.getSheetAt(0); XSSFSheet sh1 = wb.cloneSheet(0); List<RelationPart> rels0 = sh0.getRelationParts(); @@ -1286,64 +1260,64 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug51850() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx"); - XSSFSheet sh1 = wb1.getSheetAt(0); - XSSFSheet sh2 = wb1.getSheetAt(1); + try (XSSFWorkbook wb1 = openSampleWorkbook("51850.xlsx")) { + XSSFSheet sh1 = wb1.getSheetAt(0); + XSSFSheet sh2 = wb1.getSheetAt(1); - // Sheet 2 has comments - assertNotNull(sh2.getCommentsTable(false)); - assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); + // Sheet 2 has comments + assertNotNull(sh2.getCommentsTable(false)); + assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); - // Sheet 1 doesn't (yet) - assertNull(sh1.getCommentsTable(false)); + // Sheet 1 doesn't (yet) + assertNull(sh1.getCommentsTable(false)); - // Try to add comments to Sheet 1 - CreationHelper factory = wb1.getCreationHelper(); - Drawing<?> drawing = sh1.createDrawingPatriarch(); + // Try to add comments to Sheet 1 + CreationHelper factory = wb1.getCreationHelper(); + Drawing<?> drawing = sh1.createDrawingPatriarch(); - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(0); - anchor.setCol2(4); - anchor.setRow1(0); - anchor.setRow2(1); + ClientAnchor anchor = factory.createClientAnchor(); + anchor.setCol1(0); + anchor.setCol2(4); + anchor.setRow1(0); + anchor.setRow2(1); - Comment comment1 = drawing.createCellComment(anchor); - comment1.setString( + Comment comment1 = drawing.createCellComment(anchor); + comment1.setString( factory.createRichTextString("I like this cell. It's my favourite.")); - comment1.setAuthor("Bob T. Fish"); - - anchor = factory.createClientAnchor(); - anchor.setCol1(0); - anchor.setCol2(4); - anchor.setRow1(1); - anchor.setRow2(1); - Comment comment2 = drawing.createCellComment(anchor); - comment2.setString( + comment1.setAuthor("Bob T. Fish"); + + anchor = factory.createClientAnchor(); + anchor.setCol1(0); + anchor.setCol2(4); + anchor.setRow1(1); + anchor.setRow2(1); + Comment comment2 = drawing.createCellComment(anchor); + comment2.setString( factory.createRichTextString("This is much less fun...")); - comment2.setAuthor("Bob T. Fish"); + comment2.setAuthor("Bob T. Fish"); - Cell c1 = sh1.getRow(0).createCell(4); - c1.setCellValue(2.3); - c1.setCellComment(comment1); + Cell c1 = sh1.getRow(0).createCell(4); + c1.setCellValue(2.3); + c1.setCellComment(comment1); - Cell c2 = sh1.getRow(0).createCell(5); - c2.setCellValue(2.1); - c2.setCellComment(comment2); + Cell c2 = sh1.getRow(0).createCell(5); + c2.setCellValue(2.1); + c2.setCellComment(comment2); - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh1 = wb2.getSheetAt(0); - sh2 = wb2.getSheetAt(1); + // Save and re-load + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + sh1 = wb2.getSheetAt(0); + sh2 = wb2.getSheetAt(1); - // Check the comments - assertNotNull(sh2.getCommentsTable(false)); - assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); + // Check the comments + assertNotNull(sh2.getCommentsTable(false)); + assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); - assertNotNull(sh1.getCommentsTable(false)); - assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments()); - wb2.close(); + assertNotNull(sh1.getCommentsTable(false)); + assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments()); + } + } } /** @@ -1351,7 +1325,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug51963() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("51963.xlsx")) { Sheet sheet = wb.getSheetAt(0); assertEquals("Abc,1", sheet.getSheetName()); @@ -1372,7 +1346,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug48703() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("48703.xlsx")) { XSSFSheet sheet = wb.getSheetAt(0); // Contains two forms, one with a range and one a list @@ -1402,7 +1376,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug51710() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx")) { + try (Workbook wb = openSampleWorkbook("51710.xlsx")) { final String[] columns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}; final int rowMax = 500; // bug triggers on row index 59 @@ -1434,7 +1408,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug5301() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx")) { + try (Workbook wb = openSampleWorkbook("53101.xlsx")) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); // A1: SUM(B1: IZ1) @@ -1455,7 +1429,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug54436() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx")) { + try (Workbook wb = openSampleWorkbook("54436.xlsx")) { if (!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")) { Function func = (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA; @@ -1507,7 +1481,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug53282() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx")) { + try (Workbook wb = openSampleWorkbook("53282b.xlsx")) { Cell c = wb.getSheetAt(0).getRow(1).getCell(0); assertEquals("#@_#", c.getStringCellValue()); assertEquals("http://invalid.uri", c.getHyperlink().getAddress()); @@ -1521,11 +1495,11 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug56278() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx")) { + try (Workbook wb = openSampleWorkbook("56278.xlsx")) { assertEquals(0, wb.getSheetIndex("Market Rates")); // Save and re-check - Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); + Workbook nwb = writeOutAndReadBack(wb); assertEquals(0, nwb.getSheetIndex("Market Rates")); nwb.close(); } @@ -1533,7 +1507,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug56315() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("56315.xlsx")) { Cell c = wb.getSheetAt(0).getRow(1).getCell(0); CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c); double rounded = cv.getNumberValue(); @@ -1558,7 +1532,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { Thread.sleep(10); } - ByteArrayOutputStream bos = new ByteArrayOutputStream(8096); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(8096); wb.write(bos); byte[] firstSave = bos.toByteArray(); bos.reset(); @@ -1578,17 +1552,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { void bug54034() throws IOException { TimeZone tz = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx")) { - Sheet sheet = wb.getSheet("Sheet1"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(2); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - DataFormatter fmt = new DataFormatter(); - assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); - assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); - } + try (Workbook wb = openSampleWorkbook("54034.xlsx")) { + Sheet sheet = wb.getSheet("Sheet1"); + Row row = sheet.getRow(1); + Cell cell = row.getCell(2); + assertTrue(DateUtil.isCellDateFormatted(cell)); + + DataFormatter fmt = new DataFormatter(); + assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); + assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); } finally { LocaleUtil.setUserTimeZone(tz); } @@ -1597,7 +1569,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void testBug53798XLSX() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); bug53798Work(wb, xlsOutput); } @@ -1606,7 +1578,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Disabled("Shifting rows is not yet implemented in SXSSFSheet") @Test void testBug53798XLSXStream() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); SXSSFWorkbook wb2 = new SXSSFWorkbook(wb); bug53798Work(wb2, xlsOutput); @@ -1616,10 +1588,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void testBug53798XLS() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xls"); - bug53798Work(wb, xlsOutput); - wb.close(); + try (Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls")) { + File xlsOutput = TempFile.createTempFile("testBug53798", ".xls"); + bug53798Work(wb, xlsOutput); + } } /** @@ -1627,7 +1599,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void testBug56420SumIfNPE() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("56420.xlsx")) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); @@ -1689,7 +1661,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug56702() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("56702.xlsx")) { Sheet sheet = wb.getSheetAt(0); @@ -1718,7 +1690,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug56737() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx")) { + try (Workbook wb = openSampleWorkbook("56737.xlsx")) { // Check the named range definitions Name nSheetScope = wb.getName("NR_To_A1"); @@ -1787,38 +1759,32 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - @Test - void testBug56688_1() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx"); - checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */ - excel.close(); - } - - @Test - void testBug56688_2() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx"); - checkValue(excel, "#VALUE!"); - excel.close(); - } + @ParameterizedTest + @CsvSource({ + /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */ + "56688_1.xlsx, -1.0", + "56688_2.xlsx, #VALUE!", + "56688_3.xlsx, #VALUE!", + "56688_4.xlsx, date" + }) + void testBug56688(String fileName, String expect) throws IOException { + if ("date".equals(expect)) { + Calendar calendar = LocaleUtil.getLocaleCalendar(); + calendar.add(Calendar.MONTH, 2); + double excelDate = DateUtil.getExcelDate(calendar.getTime()); + NumberEval eval = new NumberEval(Math.floor(excelDate)); + expect = eval.getStringValue() + ".0"; + } - @Test - void testBug56688_3() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx"); - checkValue(excel, "#VALUE!"); - excel.close(); - } + try (XSSFWorkbook excel = openSampleWorkbook(fileName)) { + XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel); + evaluator.evaluateAll(); - @Test - void testBug56688_4() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx"); - - Calendar calendar = LocaleUtil.getLocaleCalendar(); - calendar.add(Calendar.MONTH, 2); - double excelDate = DateUtil.getExcelDate(calendar.getTime()); - NumberEval eval = new NumberEval(Math.floor(excelDate)); - checkValue(excel, eval.getStringValue() + ".0"); + XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1); + CellValue value = evaluator.evaluate(cell); - excel.close(); + assertEquals(expect, value.formatAsString()); + } } /** @@ -1827,33 +1793,33 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void testBug56527() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFCreationHelper creationHelper = wb.getCreationHelper(); - XSSFHyperlink hyperlink; - - // Try with a cell reference - hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); - sheet.addHyperlink(hyperlink); - hyperlink.setAddress("http://myurl"); - hyperlink.setCellReference("B4"); - assertEquals(3, hyperlink.getFirstRow()); - assertEquals(1, hyperlink.getFirstColumn()); - assertEquals(3, hyperlink.getLastRow()); - assertEquals(1, hyperlink.getLastColumn()); - - // Try with explicit rows / columns - hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); - sheet.addHyperlink(hyperlink); - hyperlink.setAddress("http://myurl"); - hyperlink.setFirstRow(5); - hyperlink.setFirstColumn(3); - - assertEquals(5, hyperlink.getFirstRow()); - assertEquals(3, hyperlink.getFirstColumn()); - assertEquals(5, hyperlink.getLastRow()); - assertEquals(3, hyperlink.getLastColumn()); - wb.close(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFCreationHelper creationHelper = wb.getCreationHelper(); + XSSFHyperlink hyperlink; + + // Try with a cell reference + hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); + sheet.addHyperlink(hyperlink); + hyperlink.setAddress("http://myurl"); + hyperlink.setCellReference("B4"); + assertEquals(3, hyperlink.getFirstRow()); + assertEquals(1, hyperlink.getFirstColumn()); + assertEquals(3, hyperlink.getLastRow()); + assertEquals(1, hyperlink.getLastColumn()); + + // Try with explicit rows / columns + hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); + sheet.addHyperlink(hyperlink); + hyperlink.setAddress("http://myurl"); + hyperlink.setFirstRow(5); + hyperlink.setFirstColumn(3); + + assertEquals(5, hyperlink.getFirstRow()); + assertEquals(3, hyperlink.getFirstColumn()); + assertEquals(5, hyperlink.getLastRow()); + assertEquals(3, hyperlink.getLastColumn()); + } } /** @@ -1862,7 +1828,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug56502() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx")) { + try (Workbook wb = openSampleWorkbook("56502.xlsx")) { Sheet sheet = wb.getSheetAt(0); Cell cFunc = sheet.getRow(3).getCell(0); @@ -1900,7 +1866,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { "Should fail as too much expansion occurs"); // Check we can still parse valid files after all that - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { + try (Workbook wb = openSampleWorkbook("sample.xlsx")) { assertEquals(3, wb.getNumberOfSheets()); } } @@ -1936,7 +1902,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug57176() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("57176.xlsx")) { CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames(); List<CTDefinedName> definedNameList = definedNames.getDefinedNameList(); for (CTDefinedName defName : definedNameList) { @@ -1967,19 +1933,9 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertThrows(XLSBUnsupportedException.class, () -> WorkbookFactory.create(xlsbFile), ".xlsb files not supported"); } - private void checkValue(XSSFWorkbook excel, String expect) { - XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel); - evaluator.evaluateAll(); - - XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1); - CellValue value = evaluator.evaluate(cell); - - assertEquals(expect, value.formatAsString()); - } - @Test void testBug57196() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx")) { + try (Workbook wb = openSampleWorkbook("57196.xlsx")) { Sheet sheet = wb.getSheet("Feuil1"); Row mod = sheet.getRow(1); mod.getCell(1).setCellValue(3); @@ -1992,30 +1948,30 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test57196_Detail() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)"); - XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet("Sheet1"); + XSSFRow row = sheet.createRow(0); + XSSFCell cell = row.createCell(0); + cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)"); + XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); + CellValue cv = fe.evaluate(cell); - assertNotNull(cv); - wb.close(); + assertNotNull(cv); + } } @Test void test57196_Detail2() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellFormula("DEC2HEX(O2+D2)"); - XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet("Sheet1"); + XSSFRow row = sheet.createRow(0); + XSSFCell cell = row.createCell(0); + cell.setCellFormula("DEC2HEX(O2+D2)"); + XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); + CellValue cv = fe.evaluate(cell); - assertNotNull(cv); - wb.close(); + assertNotNull(cv); + } } @ParameterizedTest @@ -2081,7 +2037,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { // Try to write-out and read again, should only work // in read-write mode, not read-only mode - try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { if (access == PackageAccess.READ) { fail("Shouln't be able to write from read-only mode"); } @@ -2110,7 +2066,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug57535() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx")) { + try (Workbook wb = openSampleWorkbook("57535.xlsx")) { FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); evaluator.clearAllCachedResultValues(); @@ -2130,13 +2086,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test57165() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("57171_57163_57165.xlsx")) { removeAllSheetsBut(3, wb); // Throws exception here assertDoesNotThrow(() -> wb.cloneSheet(0)); wb.setSheetName(1, "New Sheet"); - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { assertNotNull(wbBack.getSheet("New Sheet")); } } @@ -2144,13 +2100,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test57165_create() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("57171_57163_57165.xlsx")) { removeAllSheetsBut(3, wb); // Throws exception here assertDoesNotThrow(() -> wb.createSheet("newsheet")); wb.setSheetName(1, "New Sheet"); - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { assertNotNull(wbBack.getSheet("New Sheet")); } } @@ -2235,7 +2191,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test56467() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx")) { + try (Workbook wb = openSampleWorkbook("picture.xlsx")) { Sheet orig = wb.getSheetAt(0); assertNotNull(orig); @@ -2258,12 +2214,12 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test @Disabled("XMLBeans namespace mis-match on ooxml-strict files") void test57699() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("sample.strict.xlsx")) { assertEquals(3, wb.getNumberOfSheets()); // TODO Check sheet contents // TODO Check formula evaluation - try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { assertEquals(3, wbBack.getNumberOfSheets()); // TODO Re-check sheet contents // TODO Re-check formula evaluation @@ -2273,13 +2229,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void testBug56295_MergeXlslsWithStyles() throws IOException { - XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx"); - XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0); - XSSFRow srcRow = sheet.getRow(0); - XSSFCell oldCell = srcRow.getCell(0); - XSSFCellStyle cellStyle = oldCell.getCellStyle(); + try (XSSFWorkbook xlsToAppendWorkbook = openSampleWorkbook("56295.xlsx"); + XSSFWorkbook targetWorkbook = new XSSFWorkbook()) { + XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0); + XSSFRow srcRow = sheet.getRow(0); + XSSFCell oldCell = srcRow.getCell(0); + XSSFCellStyle cellStyle = oldCell.getCellStyle(); - checkStyle(cellStyle); + checkStyle(cellStyle); // StylesTable table = xlsToAppendWorkbook.getStylesSource(); // List<XSSFCellFill> fills = table.getFills(); @@ -2287,33 +2244,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { // for(XSSFCellFill fill : fills) { // System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor()); // } - xlsToAppendWorkbook.close(); - - XSSFWorkbook targetWorkbook = new XSSFWorkbook(); - XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName()); - XSSFRow destRow = newSheet.createRow(0); - XSSFCell newCell = destRow.createCell(0); - - //newCell.getCellStyle().cloneStyleFrom(cellStyle); - CellStyle newCellStyle = targetWorkbook.createCellStyle(); - newCellStyle.cloneStyleFrom(cellStyle); - newCell.setCellStyle(newCellStyle); - checkStyle(newCell.getCellStyle()); - newCell.setCellValue(oldCell.getStringCellValue()); - -// OutputStream os = new FileOutputStream("output.xlsm"); -// try { -// targetWorkbook.write(os); -// } finally { -// os.close(); -// } + xlsToAppendWorkbook.close(); + + XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName()); + XSSFRow destRow = newSheet.createRow(0); + XSSFCell newCell = destRow.createCell(0); - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook); - XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle(); - checkStyle(styleBack); + //newCell.getCellStyle().cloneStyleFrom(cellStyle); + CellStyle newCellStyle = targetWorkbook.createCellStyle(); + newCellStyle.cloneStyleFrom(cellStyle); + newCell.setCellStyle(newCellStyle); + checkStyle(newCell.getCellStyle()); + newCell.setCellValue(oldCell.getStringCellValue()); - targetWorkbook.close(); - wbBack.close(); + try (XSSFWorkbook wbBack = writeOutAndReadBack(targetWorkbook)) { + XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle(); + checkStyle(styleBack); + + } + } } /** @@ -2323,27 +2272,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void testBug57826() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx"); - - assertTrue(workbook.getNumberOfSheets() >= 1, "no sheets in workbook"); - XSSFSheet sheet = workbook.getSheetAt(0); + try (XSSFWorkbook workbook = openSampleWorkbook("57826.xlsx")) { + assertTrue(workbook.getNumberOfSheets() >= 1, "no sheets in workbook"); + XSSFSheet sheet = workbook.getSheetAt(0); - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - assertNotNull(drawing); + XSSFDrawing drawing = sheet.getDrawingPatriarch(); + assertNotNull(drawing); - List<XSSFShape> shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); + List<XSSFShape> shapes = drawing.getShapes(); + assertEquals(1, shapes.size()); + assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - XSSFSimpleShape shape = (XSSFSimpleShape) shapes.get(0); + XSSFSimpleShape shape = (XSSFSimpleShape) shapes.get(0); - // Used to throw a NPE - String text = shape.getText(); + // Used to throw a NPE + String text = shape.getText(); - // No bulleting info included - assertEquals("test ok", text); - - workbook.close(); + // No bulleting info included + assertEquals("test ok", text); + } } private void checkStyle(XSSFCellStyle cellStyle) { @@ -2363,20 +2310,19 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug57642() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s = wb.createSheet("TestSheet"); - XSSFCell c = s.createRow(0).createCell(0); - c.setCellFormula("ISERROR(TestSheet!A1)"); - c = s.createRow(1).createCell(1); - c.setCellFormula("ISERROR(B2)"); - - wb.setSheetName(0, "CSN"); - c = s.getRow(0).getCell(0); - assertEquals("ISERROR(CSN!A1)", c.getCellFormula()); - c = s.getRow(1).getCell(1); - assertEquals("ISERROR(B2)", c.getCellFormula()); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet s = wb.createSheet("TestSheet"); + XSSFCell c = s.createRow(0).createCell(0); + c.setCellFormula("ISERROR(TestSheet!A1)"); + c = s.createRow(1).createCell(1); + c.setCellFormula("ISERROR(B2)"); - wb.close(); + wb.setSheetName(0, "CSN"); + c = s.getRow(0).getCell(0); + assertEquals("ISERROR(CSN!A1)", c.getCellFormula()); + c = s.getRow(1).getCell(1); + assertEquals("ISERROR(B2)", c.getCellFormula()); + } } /** @@ -2386,47 +2332,42 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void bug57880() throws IOException { int numStyles = 33000; - XSSFWorkbook wb = new XSSFWorkbook(); - for (int i = 1; i < numStyles; i++) { - // Create a style and use it - XSSFCellStyle style = wb.createCellStyle(); - assertEquals(i, style.getUIndex()); - } - assertEquals(numStyles, wb.getNumCellStyles()); + File file; + try (XSSFWorkbook wb = new XSSFWorkbook()) { + for (int i = 1; i < numStyles; i++) { + // Create a style and use it + XSSFCellStyle style = wb.createCellStyle(); + assertEquals(i, style.getUIndex()); + } + assertEquals(numStyles, wb.getNumCellStyles()); - // avoid OOM in Gump run - File file = XSSFTestDataSamples.writeOutAndClose(wb, "bug57880"); - //noinspection UnusedAssignment - wb = null; - // Garbage collection may happen here + // avoid OOM in Gump run + file = XSSFTestDataSamples.writeOutAndClose(wb, "bug57880"); + } // avoid zip bomb detection double ratio = ZipSecureFile.getMinInflateRatio(); ZipSecureFile.setMinInflateRatio(0.00005); - wb = XSSFTestDataSamples.readBackAndDelete(file); - ZipSecureFile.setMinInflateRatio(ratio); - - //Assume identical cell styles aren't consolidated - //If XSSFWorkbooks ever implicitly optimize/consolidate cell styles (such as when the workbook is written to disk) - //then this unit test should be updated - assertEquals(numStyles, wb.getNumCellStyles()); - for (int i = 1; i < numStyles; i++) { - XSSFCellStyle style = wb.getCellStyleAt(i); - assertNotNull(style); - assertEquals(i, style.getUIndex()); + try (XSSFWorkbook wb = XSSFTestDataSamples.readBackAndDelete(file)) { + ZipSecureFile.setMinInflateRatio(ratio); + + //Assume identical cell styles aren't consolidated + //If XSSFWorkbooks ever implicitly optimize/consolidate cell styles (such as when the workbook is written to disk) + //then this unit test should be updated + assertEquals(numStyles, wb.getNumCellStyles()); + for (int i = 1; i < numStyles; i++) { + XSSFCellStyle style = wb.getCellStyleAt(i); + assertNotNull(style); + assertEquals(i, style.getUIndex()); + } } - wb.close(); } - @Test - void test56574() throws IOException { - runTest56574(false); - runTest56574(true); - } - - private void runTest56574(boolean createRow) throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx")) { + @ParameterizedTest + @ValueSource(booleans = { false, true}) + void test56574(boolean createRow) throws IOException { + try (XSSFWorkbook wb = openSampleWorkbook("56574.xlsx")) { Sheet sheet = wb.getSheet("Func"); assertNotNull(sheet); @@ -2475,14 +2416,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { CalculationChain chain = wb.getCalculationChain(); checkCellsAreGone(chain); - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - Sheet sheetBack = wbBack.getSheet("Func"); - assertNotNull(sheetBack); - - chain = wbBack.getCalculationChain(); - checkCellsAreGone(chain); + try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) { + Sheet sheetBack = wbBack.getSheet("Func"); + assertNotNull(sheetBack); - wbBack.close(); + chain = wbBack.getCalculationChain(); + checkCellsAreGone(chain); + } } } @@ -2502,14 +2442,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void bug57181() throws IOException { - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm")) { + try (XSSFWorkbook wb = openSampleWorkbook("57181.xlsm")) { assertEquals(9, wb.getNumberOfSheets()); } } @Test void bug52111() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx")) { + try (Workbook wb = openSampleWorkbook("Intersection-52111-xssf.xlsx")) { Sheet s = wb.getSheetAt(0); assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0"); @@ -2519,7 +2459,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test48962() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx")) { + try (Workbook wb = openSampleWorkbook("48962.xlsx")) { Sheet sh = wb.getSheetAt(0); Row row = sh.getRow(1); Cell cell = row.getCell(0); @@ -2544,7 +2484,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test50755_workday_formula_example() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx")) { + try (Workbook wb = openSampleWorkbook("50755_workday_formula_example.xlsx")) { Sheet sheet = wb.getSheet("Sheet1"); for (Row aRow : sheet) { Cell cell = aRow.getCell(1); @@ -2559,25 +2499,17 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - @Test - void test51626() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51626.xlsx"); - assertNotNull(wb); - wb.close(); - - InputStream stream = HSSFTestDataSamples.openSampleFileStream("51626.xlsx"); - wb = WorkbookFactory.create(stream); - stream.close(); - wb.close(); - - wb = XSSFTestDataSamples.openSampleWorkbook("51626_contact.xlsx"); - assertNotNull(wb); - wb.close(); + @ParameterizedTest + @ValueSource(strings = { "51626.xlsx", "51626_contact.xlsx"}) + void test51626(String fileName) throws IOException { + try (Workbook wb = openSampleWorkbook(fileName)) { + assertNotNull(wb); + } - stream = HSSFTestDataSamples.openSampleFileStream("51626_contact.xlsx"); - wb = WorkbookFactory.create(stream); - stream.close(); - wb.close(); + try (InputStream stream = HSSFTestDataSamples.openSampleFileStream(fileName); + Workbook wb = WorkbookFactory.create(stream)) { + assertNotNull(wb); + } } @Disabled("this test is only for manual verification, as we can't test if the cell is visible in Excel") @@ -2599,7 +2531,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test53105() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx")) { + try (Workbook wb = openSampleWorkbook("53105.xlsx")) { assertNotNull(wb); @@ -2616,7 +2548,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test58315() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx")) { + try (Workbook wb = openSampleWorkbook("58315.xlsx")) { Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); assertNotNull(cell); StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue()); @@ -2635,7 +2567,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test55406() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) { + try (Workbook wb = openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) { Sheet sheet = wb.getSheetAt(0); Cell cellA1 = sheet.getRow(0).getCell(0); Cell cellA2 = sheet.getRow(1).getCell(0); @@ -2662,45 +2594,43 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test51998() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51998.xlsx"); + try (Workbook wb = openSampleWorkbook("51998.xlsx")) { + Set<String> sheetNames = new HashSet<>(); - Set<String> sheetNames = new HashSet<>(); + for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { + sheetNames.add(wb.getSheetName(sheetNum)); + } - for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { - sheetNames.add(wb.getSheetName(sheetNum)); - } + for (String sheetName : sheetNames) { + int sheetIndex = wb.getSheetIndex(sheetName); - for (String sheetName : sheetNames) { - int sheetIndex = wb.getSheetIndex(sheetName); + wb.removeSheetAt(sheetIndex); - wb.removeSheetAt(sheetIndex); + Sheet newSheet = wb.createSheet(); + //Sheet newSheet = wb.createSheet(sheetName); + int newSheetIndex = wb.getSheetIndex(newSheet); + wb.setSheetName(newSheetIndex, sheetName); + wb.setSheetOrder(sheetName, sheetIndex); + } - Sheet newSheet = wb.createSheet(); - //Sheet newSheet = wb.createSheet(sheetName); - int newSheetIndex = wb.getSheetIndex(newSheet); - wb.setSheetName(newSheetIndex, sheetName); - wb.setSheetOrder(sheetName, sheetIndex); + try (Workbook wbBack = writeOutAndReadBack(wb)) { + assertNotNull(wbBack); + } } - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertNotNull(wbBack); - wbBack.close(); } @Test void test58731() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx")) { + Object[][] bookData = { + {"Head First Java", "Kathy Serria", 79}, + {"Effective Java", "Joshua Bloch", 36}, + {"Clean Code", "Robert martin", 42}, + {"Thinking in Java", "Bruce Eckel", 35}, + }; + + try (Workbook wb = openSampleWorkbook("58731.xlsx")) { Sheet sheet = wb.createSheet("Java Books"); - Object[][] bookData = { - {"Head First Java", "Kathy Serria", 79}, - {"Effective Java", "Joshua Bloch", 36}, - {"Clean Code", "Robert martin", 42}, - {"Thinking in Java", "Bruce Eckel", 35}, - }; - int rowCount = 0; for (Object[] aBook : bookData) { Row row = sheet.createRow(rowCount++); @@ -2716,7 +2646,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - try (Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (Workbook wb2 = writeOutAndReadBack(wb)) { sheet = wb2.getSheet("Java Books"); assertNotNull(sheet.getRow(0)); assertNotNull(sheet.getRow(0).getCell(0)); @@ -2733,14 +2663,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void test58760() throws IOException { - Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("58760.xlsx"); - assertEquals(1, wb1.getNumberOfSheets()); - assertEquals("Sheet1", wb1.getSheetName(0)); - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(1, wb2.getNumberOfSheets()); - assertEquals("Sheet1", wb2.getSheetName(0)); - wb2.close(); - wb1.close(); + try (Workbook wb1 = openSampleWorkbook("58760.xlsx")) { + assertEquals(1, wb1.getNumberOfSheets()); + assertEquals("Sheet1", wb1.getSheetName(0)); + try (Workbook wb2 = writeOutAndReadBack(wb1)) { + assertEquals(1, wb2.getNumberOfSheets()); + assertEquals("Sheet1", wb2.getSheetName(0)); + } + } } @Test @@ -2755,7 +2685,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { DataFormatter formatter = new DataFormatter(true); - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("57236.xlsx")) { for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { Sheet sheet = wb.getSheetAt(sheetNum); for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum(); rowNum++) { @@ -2771,41 +2701,27 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - /** - * helper function for {@link #test58043()} - * Side-effects: closes the provided workbook! - * - * @param workbook the workbook to save for manual checking - * @param outputFile the output file location to save the workbook to - */ - private void saveRotatedTextExample(Workbook workbook, File outputFile) throws IOException { - Sheet sheet = workbook.createSheet(); - Row row = sheet.createRow((short) 0); - - Cell cell = row.createCell(0); - - cell.setCellValue("Unsuccessful rotated text."); - - CellStyle style = workbook.createCellStyle(); - style.setRotation((short) -90); - - cell.setCellStyle(style); + @ParameterizedTest() + @CsvSource({ "false, rotated.xls", "true, rotated.xlsx" }) + @Disabled("Creates files for checking results manually, actual values are tested in Test*CellStyle") + void test58043(boolean xssf, String fileName) throws IOException { + try (Workbook wb = WorkbookFactory.create(xssf)) { + Sheet sheet = wb.createSheet(); + Row row = sheet.createRow((short) 0); + Cell cell = row.createCell(0); + cell.setCellValue("Unsuccessful rotated text."); - OutputStream fos = new FileOutputStream(outputFile); - workbook.write(fos); - fos.close(); - workbook.close(); - } + CellStyle style = wb.createCellStyle(); + style.setRotation((short) -90); + cell.setCellStyle(style); - @Disabled("Creates files for checking results manually, actual values are tested in Test*CellStyle") - void test58043() throws IOException { - saveRotatedTextExample(new HSSFWorkbook(), TempFile.createTempFile("rotated", ".xls")); - saveRotatedTextExample(new XSSFWorkbook(), TempFile.createTempFile("rotated", ".xlsx")); + XSSFTestDataSamples.writeOut(wb, fileName); + } } @Test void test59132() throws IOException { - try (Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("59132.xlsx")) { + try (Workbook workbook = openSampleWorkbook("59132.xlsx")) { Sheet worksheet = workbook.getSheet("sheet1"); // B3 @@ -2848,51 +2764,51 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Disabled("bug 59442") @Test void testSetRGBBackgroundColor() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFCell cell = workbook.createSheet().createRow(0).createCell(0); - - XSSFColor color = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors()); - XSSFCellStyle style = workbook.createCellStyle(); - style.setFillForegroundColor(color); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cell.setCellStyle(style); - - // Everything is fine at this point, cell is red - XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor(); - assertNull(actual); - actual = cell.getCellStyle().getFillForegroundColorColor(); - assertNotNull(actual); - assertEquals(color.getARGBHex(), actual.getARGBHex()); - - Map<String, Object> properties = new HashMap<>(); - properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - CellUtil.setCellStyleProperties(cell, properties); - - // Now the cell is all black - actual = cell.getCellStyle().getFillBackgroundColorColor(); - assertNotNull(actual); - assertNull(actual.getARGBHex()); - actual = cell.getCellStyle().getFillForegroundColorColor(); - assertNotNull(actual); - assertEquals(color.getARGBHex(), actual.getARGBHex()); - - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(workbook); - workbook.close(); - XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0); - XSSFColor ncolor = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors()); - - // Now the cell is all black - XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor(); - assertNotNull(nactual); - assertEquals(ncolor.getARGBHex(), nactual.getARGBHex()); - - nwb.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFCell cell = workbook.createSheet().createRow(0).createCell(0); + + XSSFColor color = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors()); + XSSFCellStyle style = workbook.createCellStyle(); + style.setFillForegroundColor(color); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + cell.setCellStyle(style); + + // Everything is fine at this point, cell is red + XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor(); + assertNull(actual); + actual = cell.getCellStyle().getFillForegroundColorColor(); + assertNotNull(actual); + assertEquals(color.getARGBHex(), actual.getARGBHex()); + + Map<String, Object> properties = new HashMap<>(); + properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN); + CellUtil.setCellStyleProperties(cell, properties); + + // Now the cell is all black + actual = cell.getCellStyle().getFillBackgroundColorColor(); + assertNotNull(actual); + assertNull(actual.getARGBHex()); + actual = cell.getCellStyle().getFillForegroundColorColor(); + assertNotNull(actual); + assertEquals(color.getARGBHex(), actual.getARGBHex()); + + try (XSSFWorkbook nwb = writeOutAndReadBack(workbook)) { + XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0); + XSSFColor ncolor = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors()); + + // Now the cell is all black + XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor(); + assertNotNull(nactual); + assertEquals(ncolor.getARGBHex(), nactual.getARGBHex()); + + } + } } @Disabled("currently fails on POI 3.15 beta 2") @Test void test55273() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx")) { + try (Workbook wb = openSampleWorkbook("ExcelTables.xlsx")) { Sheet sheet = wb.getSheet("ExcelTable"); Name name = wb.getName("TableAsRangeName"); @@ -2910,7 +2826,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test57523() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx")) { + try (Workbook wb = openSampleWorkbook("57523.xlsx")) { Sheet sheet = wb.getSheet("Attribute Master"); Row row = sheet.getRow(15); @@ -2930,7 +2846,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void noRowNumbers59746() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx")) { + try (Workbook wb = openSampleWorkbook("59746_NoRowNums.xlsx")) { Sheet sheet = wb.getSheetAt(0); assertTrue(sheet.getLastRowNum() > 20, "Last row num: " + sheet.getLastRowNum()); assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue()); @@ -2944,7 +2860,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void testWorkdayFunction() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx")) { + try (XSSFWorkbook workbook = openSampleWorkbook("59106.xlsx")) { XSSFSheet sheet = workbook.getSheet("Test"); Row row = sheet.getRow(1); Cell cell = row.getCell(0); @@ -3003,7 +2919,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test void drawingNumbersAlreadyTaken_60255() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx")) { + try (Workbook wb = openSampleWorkbook("60255_extra_drawingparts.xlsx")) { assertEquals(4, wb.getNumberOfSheets()); // Sheet 3 starts with a drawing @@ -3023,7 +2939,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertNotNull(sheet.getDrawingPatriarch()); // Save and check - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); + Workbook wbBack = writeOutAndReadBack(wb); assertEquals(5, wbBack.getNumberOfSheets()); // Sheets 3 and 5 now @@ -3042,52 +2958,50 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test53611() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("blabla"); - - //0 1 2 3 4 5 6 7 - //A B C D E F G H - row = sheet.createRow(4); - cell = row.createCell(7); - cell.setCellValue("blabla"); + try (Workbook wb = new XSSFWorkbook()) { + Sheet sheet = wb.createSheet("test"); + Row row = sheet.createRow(1); + Cell cell = row.createCell(1); + cell.setCellValue("blabla"); - // we currently only populate the dimension during writing out - // to avoid having to iterate all rows/cells in each add/remove of a row or cell - wb.write(new NullOutputStream()); + //0 1 2 3 4 5 6 7 + //A B C D E F G H + row = sheet.createRow(4); + cell = row.createCell(7); + cell.setCellValue("blabla"); - assertEquals("B2:H5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef()); + // we currently only populate the dimension during writing out + // to avoid having to iterate all rows/cells in each add/remove of a row or cell + wb.write(NULL_OUTPUT_STREAM); - wb.close(); + assertEquals("B2:H5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef()); + } } @Test void test61798() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("blabla"); - - row = sheet.createRow(4); - // Allowable column range for EXCEL2007 is (0..16383) or ('A'..'XDF') - cell = row.createCell(16383); - cell.setCellValue("blabla"); + try (Workbook wb = new XSSFWorkbook()) { + Sheet sheet = wb.createSheet("test"); + Row row = sheet.createRow(1); + Cell cell = row.createCell(1); + cell.setCellValue("blabla"); - // we currently only populate the dimension during writing out - // to avoid having to iterate all rows/cells in each add/remove of a row or cell - wb.write(new NullOutputStream()); + row = sheet.createRow(4); + // Allowable column range for EXCEL2007 is (0..16383) or ('A'..'XDF') + cell = row.createCell(16383); + cell.setCellValue("blabla"); - assertEquals("B2:XFD5", ((XSSFSheet)sheet).getCTWorksheet().getDimension().getRef()); + // we currently only populate the dimension during writing out + // to avoid having to iterate all rows/cells in each add/remove of a row or cell + wb.write(NULL_OUTPUT_STREAM); - wb.close(); + assertEquals("B2:XFD5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef()); + } } @Test void bug61063() throws Exception { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61063.xlsx")) { + try (Workbook wb = openSampleWorkbook("61063.xlsx")) { FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); Sheet s = wb.getSheetAt(0); @@ -3107,59 +3021,59 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { final String initialFormula = "A1"; final String expectedFormula = "#REF!"; // from ms excel - XSSFWorkbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet1"); - sheet.createRow(0).createCell(0).setCellValue(1); // A1 = 1 - - { - Cell c3 = sheet.createRow(2).createCell(2); - c3.setCellFormula(initialFormula); // C3 = =A1 - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cellValue = evaluator.evaluate(c3); - assertEquals(1, cellValue.getNumberValue(), 0.0001); - } + try (XSSFWorkbook wb = new XSSFWorkbook()) { + Sheet sheet = wb.createSheet("sheet1"); + sheet.createRow(0).createCell(0).setCellValue(1); // A1 = 1 + + { + Cell c3 = sheet.createRow(2).createCell(2); + c3.setCellFormula(initialFormula); // C3 = =A1 + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + CellValue cellValue = evaluator.evaluate(c3); + assertEquals(1, cellValue.getNumberValue(), 0.0001); + } - { - FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/ + { + FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/ , -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1] - formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] - String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A - //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); - assertEquals(expectedFormula, shiftedFmla, - "On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF"); - } + XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); + Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1] + formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] + String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A + //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); + assertEquals(expectedFormula, shiftedFmla, + "On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF"); + } - { - FormulaShifter formulaShifter = FormulaShifter.createForRowShift(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/ + { + FormulaShifter formulaShifter = FormulaShifter.createForRowShift(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/ , -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1] - formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] - String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A - //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); - assertEquals(initialFormula, shiftedFmla, - "On move we expect the formula to stay the same, thus expecting the initial formula A1 here"); - } + XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); + Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1] + formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A] + String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A + //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla)); + assertEquals(initialFormula, shiftedFmla, + "On move we expect the formula to stay the same, thus expecting the initial formula A1 here"); + } - sheet.shiftRows(2, 2, -1); - { - Cell c2 = sheet.getRow(1).getCell(2); - assertNotNull(c2, "cell C2 needs to exist now"); - assertEquals(CellType.FORMULA, c2.getCellType()); - assertEquals(initialFormula, c2.getCellFormula()); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cellValue = evaluator.evaluate(c2); - assertEquals(1, cellValue.getNumberValue(), 0.0001); - } + sheet.shiftRows(2, 2, -1); + { + Cell c2 = sheet.getRow(1).getCell(2); + assertNotNull(c2, "cell C2 needs to exist now"); + assertEquals(CellType.FORMULA, c2.getCellType()); + assertEquals(initialFormula, c2.getCellFormula()); + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + CellValue cellValue = evaluator.evaluate(c2); + assertEquals(1, cellValue.getNumberValue(), 0.0001); + } - wb.close(); + } } @Test void test61652() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61652.xlsx")) { + try (Workbook wb = openSampleWorkbook("61652.xlsx")) { Sheet sheet = wb.getSheet("IRPPCalc"); Row row = sheet.getRow(11); Cell cell = row.getCell(18); @@ -3240,52 +3154,41 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } } - @Test - void test61905xlsx() throws IOException { - try (Workbook wb = new XSSFWorkbook()) { - checkActiveSheet(wb, XSSFITestDataProvider.instance); - } - } - - @Test - void test61905xls() throws IOException { - try (Workbook wb = new HSSFWorkbook()) { - checkActiveSheet(wb, HSSFITestDataProvider.instance); + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void test61905(boolean xssf) throws IOException { + ITestDataProvider instance = xssf ? XSSFITestDataProvider.instance : HSSFITestDataProvider.instance; + try (Workbook wb = instance.createWorkbook()) { + Sheet sheet = wb.createSheet("new sheet"); + sheet.setActiveCell(new CellAddress("E11")); + assertEquals("E11", sheet.getActiveCell().formatAsString()); + + try (Workbook wbBack = instance.writeOutAndReadBack(wb)) { + sheet = wbBack.getSheetAt(0); + assertEquals("E11", sheet.getActiveCell().formatAsString()); + } } } - private void checkActiveSheet(Workbook wb, ITestDataProvider instance) throws IOException { - Sheet sheet = wb.createSheet("new sheet"); - sheet.setActiveCell(new CellAddress("E11")); - assertEquals("E11", sheet.getActiveCell().formatAsString()); - - Workbook wbBack = instance.writeOutAndReadBack(wb); - sheet = wbBack.getSheetAt(0); - assertEquals("E11", sheet.getActiveCell().formatAsString()); - wbBack.close(); - } - @Test void testBug54084Unicode() throws IOException { // sample XLSX with the same text-contents as the text-file above - try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("54084 - Greek - beyond BMP.xlsx")) { + try (XSSFWorkbook wb = openSampleWorkbook("54084 - Greek - beyond BMP.xlsx")) { verifyBug54084Unicode(wb); //XSSFTestDataSamples.writeOut(wb, "bug 54084 for manual review"); // now write the file and read it back in - XSSFWorkbook wbWritten = XSSFTestDataSamples.writeOutAndReadBack(wb); - verifyBug54084Unicode(wbWritten); + try (XSSFWorkbook wbWritten = writeOutAndReadBack(wb)) { + verifyBug54084Unicode(wbWritten); + } // finally also write it out via the streaming interface and verify that we still can read it back in - SXSSFWorkbook swb = new SXSSFWorkbook(wb); - Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); - verifyBug54084Unicode(wbStreamingWritten); - - wbWritten.close(); - swb.close(); - wbStreamingWritten.close(); + try (SXSSFWorkbook swb = new SXSSFWorkbook(wb); + Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb)) { + verifyBug54084Unicode(wbStreamingWritten); + } } } @@ -3309,29 +3212,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { void bug63371() throws IOException { try (XSSFWorkbook wb = new XSSFWorkbook()) { XSSFSheet sheet = wb.createSheet(); - CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2); assertEquals(0, sheet.addMergedRegion(region)); - //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index)); - - final List<CellRangeAddress> ranges = sheet.getMergedRegions(); - final int numMergedRegions = sheet.getNumMergedRegions(); - final CTWorksheet ctSheet = sheet.getCTWorksheet(); - final CTMergeCells ctMergeCells = ctSheet.getMergeCells(); - final List<CTMergeCell> ctMergeCellList = ctMergeCells.getMergeCellList(); - final long ctMergeCellCount = ctMergeCells.getCount(); - final int ctMergeCellListSize = ctMergeCellList.size(); - - /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region")); - System.out.println(String.format("ranges.size=%d", ranges.size())); - System.out.println(String.format("numMergedRegions=%d", numMergedRegions)); - System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); - System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/ - assertEquals(1, ranges.size()); - assertEquals(1, numMergedRegions); - assertEquals(1, ctMergeCellCount); - assertEquals(1, ctMergeCellListSize); + final CTMergeCells ctMergeCells = sheet.getCTWorksheet().getMergeCells(); + + assertEquals(1, sheet.getMergedRegions().size()); + assertEquals(1, sheet.getNumMergedRegions()); + assertEquals(1, ctMergeCells.getCount()); + assertEquals(1, ctMergeCells.getMergeCellList().size()); } } @@ -3343,7 +3232,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2); assertEquals(0, sheet.addMergedRegion(region)); - //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index)); List<CellRangeAddress> ranges = sheet.getMergedRegions(); int numMergedRegions = sheet.getNumMergedRegions(); @@ -3353,12 +3241,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { long ctMergeCellCount = ctMergeCells.getCount(); int ctMergeCellListSize = ctMergeCellList.size(); - /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region")); - System.out.println(String.format("ranges.size=%d", ranges.size())); - System.out.println(String.format("numMergedRegions=%d", numMergedRegions)); - System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); - System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize)); */ - assertEquals(1, ranges.size()); assertEquals(1, numMergedRegions); assertEquals(1, ctMergeCellCount); @@ -3366,7 +3248,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { CellRangeAddress region2 = new CellRangeAddress(1, 2, 4, 6); assertEquals(1, sheet.addMergedRegion(region2)); - //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index)); ranges = sheet.getMergedRegions(); numMergedRegions = sheet.getNumMergedRegions(); @@ -3376,12 +3257,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { ctMergeCellCount = ctMergeCells.getCount(); ctMergeCellListSize = ctMergeCellList.size(); - /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding second region")); - System.out.println(String.format("ranges.size=%d", ranges.size())); - System.out.println(String.format("numMergedRegions=%d", numMergedRegions)); - System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); - System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/ - assertEquals(2, ranges.size()); assertEquals(2, numMergedRegions); assertEquals(2, ctMergeCellCount); @@ -3420,7 +3295,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test58896WithFile() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58896.xlsx")) { + try (Workbook wb = openSampleWorkbook("58896.xlsx")) { Sheet sheet = wb.getSheetAt(0); Instant start = now(); @@ -3455,7 +3330,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { assertNull(((XSSFCell) cell).getCTCell().getV(), "Element 'v' should not be set for formulas unless the value was calculated"); - try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (Workbook wbBack = writeOutAndReadBack(wb)) { Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(0); assertNull(((XSSFCell) cellBack).getCTCell().getV(), "Element 'v' should not be set for formulas unless the value was calculated"); @@ -3484,7 +3359,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { row.createCell(1).setCellValue(5); row.createCell(2).setCellFormula("A1+B1"); - try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + try (Workbook wbBack = writeOutAndReadBack(wb)) { Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(2); assertNull(((XSSFCell) cellBack).getCTCell().getV(), @@ -3533,7 +3408,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void testBug64508() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64508.xlsx")) { + try (Workbook wb = openSampleWorkbook("64508.xlsx")) { int activeSheet = wb.getActiveSheetIndex(); Sheet sheet1 = wb.getSheetAt(activeSheet); Row row = sheet1.getRow(1); @@ -3547,7 +3422,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void testBug64667() throws IOException { //test that an NPE isn't thrown on opening - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64667.xlsx")) { + try (Workbook wb = openSampleWorkbook("64667.xlsx")) { int activeSheet = wb.getActiveSheetIndex(); assertEquals(0, activeSheet); assertNotNull(wb.getSheetAt(activeSheet)); @@ -3602,32 +3477,33 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } @Test - void test64986() { - XSSFWorkbook w = new XSSFWorkbook(); - XSSFSheet s = w.createSheet(); - XSSFRow r = s.createRow(0); - XSSFCell c = r.createCell(0); - c.setCellFormula("MATCH(\"VAL\",B1:B11,)"); + void test64986() throws IOException { + try (XSSFWorkbook w = new XSSFWorkbook()) { + XSSFSheet s = w.createSheet(); + XSSFRow r = s.createRow(0); + XSSFCell c = r.createCell(0); + c.setCellFormula("MATCH(\"VAL\",B1:B11,)"); - FormulaEvaluator evaluator = w.getCreationHelper().createFormulaEvaluator(); - CellValue value = evaluator.evaluate(c); - assertEquals(CellType.ERROR, value.getCellType()); - assertEquals(ErrorEval.NA.getErrorCode(), value.getErrorValue()); + FormulaEvaluator evaluator = w.getCreationHelper().createFormulaEvaluator(); + CellValue value = evaluator.evaluate(c); + assertEquals(CellType.ERROR, value.getCellType()); + assertEquals(ErrorEval.NA.getErrorCode(), value.getErrorValue()); - // put a value in place so the match should find something - Cell val = r.createCell(1); - val.setCellValue("VAL"); + // put a value in place so the match should find something + Cell val = r.createCell(1); + val.setCellValue("VAL"); - // clear and check that now we find a match - evaluator.clearAllCachedResultValues(); - value = evaluator.evaluate(c); - assertEquals(CellType.NUMERIC, value.getCellType()); - assertEquals(1, value.getNumberValue(), 0.01); + // clear and check that now we find a match + evaluator.clearAllCachedResultValues(); + value = evaluator.evaluate(c); + assertEquals(CellType.NUMERIC, value.getCellType()); + assertEquals(1, value.getNumberValue(), 0.01); + } } @Test void test64750() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64750.xlsx")) { + try (Workbook wb = openSampleWorkbook("64750.xlsx")) { Sheet sheet = wb.getSheet("Sheet1"); assertEquals(1, sheet.getDataValidations().size()); } @@ -3635,7 +3511,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test void test64450() throws IOException { - try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64450.xlsx")) { + try (Workbook wb = openSampleWorkbook("64450.xlsx")) { assertNotNull(wb); } } @@ -3664,10 +3540,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { cellLeft.setCellValue("L"); cellLeft.setCellStyle(styleLeft); - /*try (OutputStream out = new FileOutputStream("/tmp/64494.xlsx")) { - wb.write(out); - }*/ - assertEquals(HorizontalAlignment.RIGHT, cellRight.getCellStyle().getAlignment()); assertEquals(HorizontalAlignment.LEFT, cellLeft.getCellStyle().getAlignment()); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java index b544f916ac..064d2d83c1 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java @@ -20,6 +20,7 @@ package org.apache.poi.xssf.usermodel; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import java.io.IOException; import java.util.List; @@ -41,6 +42,7 @@ public final class TestXSSFPicture extends BaseTestPicture { super(XSSFITestDataProvider.instance); } + @Override protected Picture getPictureShape(Drawing<?> pat, int picIdx) { return (Picture)((XSSFDrawing)pat).getShapes().get(picIdx); } @@ -73,7 +75,7 @@ public final class TestXSSFPicture extends BaseTestPicture { CTTwoCellAnchor ctShapeHolder = drawing.getCTDrawing().getTwoCellAnchorArray(0); // STEditAs.ABSOLUTE corresponds to ClientAnchor.DONT_MOVE_AND_RESIZE - assertEquals(STEditAs.ABSOLUTE, ctShapeHolder.getEditAs()); + assertSame(STEditAs.ABSOLUTE, ctShapeHolder.getEditAs()); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java index 3bd3012ef5..4ee8a83d3c 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java @@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; @@ -45,6 +44,7 @@ import com.microsoft.schemas.vml.CTShapetype; import com.microsoft.schemas.vml.STExt; import com.microsoft.schemas.vml.STStrokeJoinStyle; import com.microsoft.schemas.vml.impl.CTShapetypeImpl; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; @@ -62,8 +62,8 @@ class TestXSSFVMLDrawing { assertEquals(2, items.size()); assertTrue(items.get(0) instanceof CTShapeLayout); CTShapeLayout layout = (CTShapeLayout)items.get(0); - assertEquals(STExt.EDIT, layout.getExt()); - assertEquals(STExt.EDIT, layout.getIdmap().getExt()); + assertSame(STExt.EDIT, layout.getExt()); + assertSame(STExt.EDIT, layout.getIdmap().getExt()); assertEquals("1", layout.getIdmap().getData()); assertTrue(items.get(1) instanceof CTShapetype); @@ -72,8 +72,8 @@ class TestXSSFVMLDrawing { assertEquals(202.0f, type.getSpt(), 0); assertEquals("m,l,21600r21600,l21600,xe", type.getPath2()); assertEquals("_x0000_t202", type.getId()); - assertEquals(STTrueFalse.T, type.getPathArray(0).getGradientshapeok()); - assertEquals(STConnectType.RECT, type.getPathArray(0).getConnecttype()); + assertSame(STTrueFalse.T, type.getPathArray(0).getGradientshapeok()); + assertSame(STConnectType.RECT, type.getPathArray(0).getConnecttype()); CTShape shape = vml.newCommentShape(); items = vml.getItems(); @@ -82,16 +82,16 @@ class TestXSSFVMLDrawing { assertEquals("#_x0000_t202", shape.getType()); assertEquals("position:absolute; visibility:hidden", shape.getStyle()); assertEquals("#ffffe1", shape.getFillcolor()); - assertEquals(STInsetMode.AUTO, shape.getInsetmode()); + assertSame(STInsetMode.AUTO, shape.getInsetmode()); assertEquals("#ffffe1", shape.getFillArray(0).getColor()); CTShadow shadow = shape.getShadowArray(0); - assertEquals(STTrueFalse.T, shadow.getOn()); + assertSame(STTrueFalse.T, shadow.getOn()); assertEquals("black", shadow.getColor()); - assertEquals(STTrueFalse.T, shadow.getObscured()); - assertEquals(STConnectType.NONE, shape.getPathArray(0).getConnecttype()); + assertSame(STTrueFalse.T, shadow.getObscured()); + assertSame(STConnectType.NONE, shape.getPathArray(0).getConnecttype()); assertEquals("mso-direction-alt:auto", shape.getTextboxArray(0).getStyle()); CTClientData cldata = shape.getClientDataArray(0); - assertEquals(STObjectType.NOTE, cldata.getObjectType()); + assertSame(STObjectType.NOTE, cldata.getObjectType()); assertEquals(1, cldata.sizeOfMoveWithCellsArray()); assertEquals(1, cldata.sizeOfSizeWithCellsArray()); assertEquals("1, 15, 0, 2, 3, 15, 3, 16", cldata.getAnchorArray(0)); @@ -103,11 +103,11 @@ class TestXSSFVMLDrawing { assertEquals("[True]", cldata.getVisibleList().toString()); //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); vml.write(out); XSSFVMLDrawing vml2 = new XSSFVMLDrawing(); - vml2.read(new ByteArrayInputStream(out.toByteArray())); + vml2.read(out.toInputStream()); List<XmlObject> items2 = vml2.getItems(); assertEquals(3, items2.size()); assertTrue(items2.get(0) instanceof CTShapeLayout); @@ -208,6 +208,6 @@ class TestXSSFVMLDrawing { XmlObject xst = objs.get(0); assertTrue(xst instanceof CTShapetypeImpl); CTShapetype st = (CTShapetype)xst; - assertEquals(STStrokeJoinStyle.MITER, st.getStrokeArray(0).getJoinstyle()); + assertSame(STStrokeJoinStyle.MITER, st.getStrokeArray(0).getJoinstyle()); } }
\ No newline at end of file diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java index 78563bc32e..ef17baa8e7 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java @@ -17,6 +17,11 @@ package org.apache.poi.xssf.usermodel; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; +import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleFileStream; +import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; +import static org.apache.poi.xssf.XSSFTestDataSamples.writeOut; +import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -27,12 +32,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Iterator; @@ -72,7 +75,6 @@ import org.apache.poi.util.TempFile; import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData; import org.apache.poi.xddf.usermodel.chart.XDDFChartData; import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.model.StylesTable; import org.junit.jupiter.api.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; @@ -92,94 +94,87 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { */ @Test void saveLoadNew() throws IOException, InvalidFormatException { - XSSFWorkbook wb1 = new XSSFWorkbook(); + File file; + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { - //check that the default date system is set to 1900 - CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr(); - assertNotNull(pr); - assertTrue(pr.isSetDate1904()); - assertFalse(pr.getDate1904(), "XSSF must use the 1900 date system"); + //check that the default date system is set to 1900 + CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr(); + assertNotNull(pr); + assertTrue(pr.isSetDate1904()); + assertFalse(pr.getDate1904(), "XSSF must use the 1900 date system"); - Sheet sheet1 = wb1.createSheet("sheet1"); - Sheet sheet2 = wb1.createSheet("sheet2"); - wb1.createSheet("sheet3"); + Sheet sheet1 = wb1.createSheet("sheet1"); + Sheet sheet2 = wb1.createSheet("sheet2"); + wb1.createSheet("sheet3"); - RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world"); + RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world"); - sheet1.createRow(0).createCell((short)0).setCellValue(1.2); - sheet1.createRow(1).createCell((short)0).setCellValue(rts); - sheet2.createRow(0); + sheet1.createRow(0).createCell((short) 0).setCellValue(1.2); + sheet1.createRow(1).createCell((short) 0).setCellValue(rts); + sheet2.createRow(0); - assertEquals(0, wb1.getSheetAt(0).getFirstRowNum()); - assertEquals(1, wb1.getSheetAt(0).getLastRowNum()); - assertEquals(0, wb1.getSheetAt(1).getFirstRowNum()); - assertEquals(0, wb1.getSheetAt(1).getLastRowNum()); - assertEquals(-1, wb1.getSheetAt(2).getFirstRowNum()); - assertEquals(-1, wb1.getSheetAt(2).getLastRowNum()); + assertEquals(0, wb1.getSheetAt(0).getFirstRowNum()); + assertEquals(1, wb1.getSheetAt(0).getLastRowNum()); + assertEquals(0, wb1.getSheetAt(1).getFirstRowNum()); + assertEquals(0, wb1.getSheetAt(1).getLastRowNum()); + assertEquals(-1, wb1.getSheetAt(2).getFirstRowNum()); + assertEquals(-1, wb1.getSheetAt(2).getLastRowNum()); - File file = TempFile.createTempFile("poi-", ".xlsx"); - OutputStream out = new FileOutputStream(file); - wb1.write(out); - out.close(); + file = writeOut(wb1, "poi-.xlsx"); + } // Check the package contains what we'd expect it to - OPCPackage pkg = OPCPackage.open(file.toString()); - PackagePart wbRelPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels")); - assertNotNull(wbRelPart); - assertTrue(wbRelPart.isRelationshipPart()); - assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType()); - - PackagePart wbPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - // Links to the three sheets, shared strings and styles - assertTrue(wbPart.hasRelationships()); - assertEquals(5, wbPart.getRelationships().size()); - wb1.close(); - - // Load back the XSSFWorkbook - @SuppressWarnings("resource") - XSSFWorkbook wb2 = new XSSFWorkbook(pkg); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - assertNotNull(wb2.getSharedStringSource()); - assertNotNull(wb2.getStylesSource()); - - assertEquals(0, wb2.getSheetAt(0).getFirstRowNum()); - assertEquals(1, wb2.getSheetAt(0).getLastRowNum()); - assertEquals(0, wb2.getSheetAt(1).getFirstRowNum()); - assertEquals(0, wb2.getSheetAt(1).getLastRowNum()); - assertEquals(-1, wb2.getSheetAt(2).getFirstRowNum()); - assertEquals(-1, wb2.getSheetAt(2).getLastRowNum()); - - sheet1 = wb2.getSheetAt(0); - assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001); - assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString()); - - pkg.close(); + try (OPCPackage pkg = OPCPackage.open(file.toString())) { + PackagePart wbRelPart = + pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels")); + assertNotNull(wbRelPart); + assertTrue(wbRelPart.isRelationshipPart()); + assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType()); + + PackagePart wbPart = + pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); + // Links to the three sheets, shared strings and styles + assertTrue(wbPart.hasRelationships()); + assertEquals(5, wbPart.getRelationships().size()); + + // Load back the XSSFWorkbook + try (XSSFWorkbook wb2 = new XSSFWorkbook(pkg)) { + assertEquals(3, wb2.getNumberOfSheets()); + assertNotNull(wb2.getSheetAt(0)); + assertNotNull(wb2.getSheetAt(1)); + assertNotNull(wb2.getSheetAt(2)); + + assertNotNull(wb2.getSharedStringSource()); + assertNotNull(wb2.getStylesSource()); + + assertEquals(0, wb2.getSheetAt(0).getFirstRowNum()); + assertEquals(1, wb2.getSheetAt(0).getLastRowNum()); + assertEquals(0, wb2.getSheetAt(1).getFirstRowNum()); + assertEquals(0, wb2.getSheetAt(1).getLastRowNum()); + assertEquals(-1, wb2.getSheetAt(2).getFirstRowNum()); + assertEquals(-1, wb2.getSheetAt(2).getLastRowNum()); + + Sheet sheet1 = wb2.getSheetAt(0); + assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001); + assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString()); + } + } } @Test void existing() throws Exception { + try (XSSFWorkbook workbook = openSampleWorkbook("Formatting.xlsx"); + OPCPackage pkg = OPCPackage.open(openSampleFileStream("Formatting.xlsx"))) { + assertNotNull(workbook.getSharedStringSource()); + assertNotNull(workbook.getStylesSource()); - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertNotNull(workbook.getSharedStringSource()); - assertNotNull(workbook.getStylesSource()); - - // And check a few low level bits too - OPCPackage pkg = OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx")); - PackagePart wbPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - - // Links to the three sheets, shared, styles and themes - assertTrue(wbPart.hasRelationships()); - assertEquals(6, wbPart.getRelationships().size()); + // And check a few low level bits too + PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - pkg.close(); - workbook.close(); + // Links to the three sheets, shared, styles and themes + assertTrue(wbPart.hasRelationships()); + assertEquals(6, wbPart.getRelationships().size()); + } } @Test @@ -230,7 +225,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test void loadSave() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); + XSSFWorkbook workbook = openSampleWorkbook("Formatting.xlsx"); assertEquals(3, workbook.getNumberOfSheets()); assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); assertNotNull(workbook.getSharedStringSource()); @@ -238,7 +233,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { // Write out, and check // Load up again, check all still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); + XSSFWorkbook wb2 = writeOutAndReadBack(workbook); assertEquals(3, wb2.getNumberOfSheets()); assertNotNull(wb2.getSheetAt(0)); assertNotNull(wb2.getSheetAt(1)); @@ -257,43 +252,41 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test void styles() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - - StylesTable ss = wb1.getStylesSource(); - assertNotNull(ss); - StylesTable st = ss; - - // Has 8 number formats - assertEquals(8, st.getNumDataFormats()); - // Has 2 fonts - assertEquals(2, st.getFonts().size()); - // Has 2 fills - assertEquals(2, st.getFills().size()); - // Has 1 border - assertEquals(1, st.getBorders().size()); - - // Add two more styles - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, + try (XSSFWorkbook wb1 = openSampleWorkbook("Formatting.xlsx")) { + StylesTable ss = wb1.getStylesSource(); + assertNotNull(ss); + StylesTable st = ss; + + // Has 8 number formats + assertEquals(8, st.getNumDataFormats()); + // Has 2 fonts + assertEquals(2, st.getFonts().size()); + // Has 2 fills + assertEquals(2, st.getFills().size()); + // Has 1 border + assertEquals(1, st.getBorders().size()); + + // Add two more styles + assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, st.putNumberFormat("testFORMAT")); - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, + assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, st.putNumberFormat("testFORMAT")); - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9, + assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9, st.putNumberFormat("testFORMAT2")); - assertEquals(10, st.getNumDataFormats()); - + assertEquals(10, st.getNumDataFormats()); - // Save, load back in again, and check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - ss = wb2.getStylesSource(); - assertNotNull(ss); + // Save, load back in again, and check + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + ss = wb2.getStylesSource(); + assertNotNull(ss); - assertEquals(10, st.getNumDataFormats()); - assertEquals(2, st.getFonts().size()); - assertEquals(2, st.getFills().size()); - assertEquals(1, st.getBorders().size()); - wb2.close(); + assertEquals(10, st.getNumDataFormats()); + assertEquals(2, st.getFonts().size()); + assertEquals(2, st.getFills().size()); + assertEquals(1, st.getBorders().size()); + } + } } @Test @@ -305,7 +298,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertEquals(2, sheetId); //test file with gaps in the sheetId sequence - try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) { + try (XSSFWorkbook wbBack = openSampleWorkbook("47089.xlsm")) { int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId(); sheetId = (int) wbBack.createSheet().sheet.getSheetId(); assertEquals(lastSheetId + 1, sheetId); @@ -328,15 +321,15 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertNotNull(opcProps); opcProps.setTitleProperty("Testing Bugzilla #47460"); - assertEquals("Apache POI", opcProps.getCreatorProperty().get()); + assertEquals("Apache POI", opcProps.getCreatorProperty().orElse("")); opcProps.setCreatorProperty("poi-dev@poi.apache.org"); - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties(); - assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().get()); - assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().get()); - wbBack.close(); + try (XSSFWorkbook wbBack = writeOutAndReadBack(workbook)) { + assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); + opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties(); + assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().orElse("")); + assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().orElse("")); + } } } @@ -346,36 +339,36 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { */ @Test void bug47668() throws Exception { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("47668.xlsx"); - List<XSSFPictureData> allPictures = workbook.getAllPictures(); - assertEquals(1, allPictures.size()); + try (XSSFWorkbook workbook = openSampleWorkbook("47668.xlsx")) { + List<XSSFPictureData> allPictures = workbook.getAllPictures(); + assertEquals(1, allPictures.size()); - PackagePartName imagePartName = PackagingURIHelper + PackagePartName imagePartName = PackagingURIHelper .createPartName("/xl/media/image1.jpeg"); - PackagePart imagePart = workbook.getPackage().getPart(imagePartName); - assertNotNull(imagePart); + PackagePart imagePart = workbook.getPackage().getPart(imagePartName); + assertNotNull(imagePart); - for (XSSFPictureData pictureData : allPictures) { - PackagePart picturePart = pictureData.getPackagePart(); - assertSame(imagePart, picturePart); - } + for (XSSFPictureData pictureData : allPictures) { + PackagePart picturePart = pictureData.getPackagePart(); + assertSame(imagePart, picturePart); + } - XSSFSheet sheet0 = workbook.getSheetAt(0); - XSSFDrawing drawing0 = sheet0.createDrawingPatriarch(); - XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0); - byte[] data0 = pictureData0.getData(); - CRC32 crc0 = new CRC32(); - crc0.update(data0); - - XSSFSheet sheet1 = workbook.getSheetAt(1); - XSSFDrawing drawing1 = sheet1.createDrawingPatriarch(); - XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0); - byte[] data1 = pictureData1.getData(); - CRC32 crc1 = new CRC32(); - crc1.update(data1); - - assertEquals(crc0.getValue(), crc1.getValue()); - workbook.close(); + XSSFSheet sheet0 = workbook.getSheetAt(0); + XSSFDrawing drawing0 = sheet0.createDrawingPatriarch(); + XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0); + byte[] data0 = pictureData0.getData(); + CRC32 crc0 = new CRC32(); + crc0.update(data0); + + XSSFSheet sheet1 = workbook.getSheetAt(1); + XSSFDrawing drawing1 = sheet1.createDrawingPatriarch(); + XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0); + byte[] data1 = pictureData1.getData(); + CRC32 crc1 = new CRC32(); + crc1.update(data1); + + assertEquals(crc0.getValue(), crc1.getValue()); + } } /** @@ -384,27 +377,26 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @SuppressWarnings("deprecation") @Test void bug47737() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx"); - assertEquals(2, wb.getNumberOfNames()); - assertNotNull(wb.getCalculationChain()); - - XSSFName nm0 = wb.getNameAt(0); - assertTrue(nm0.getCTName().isSetLocalSheetId()); - assertEquals(0, nm0.getCTName().getLocalSheetId()); - - XSSFName nm1 = wb.getNameAt(1); - assertTrue(nm1.getCTName().isSetLocalSheetId()); - assertEquals(1, nm1.getCTName().getLocalSheetId()); - - wb.removeSheetAt(0); - assertEquals(1, wb.getNumberOfNames()); - XSSFName nm2 = wb.getNameAt(0); - assertTrue(nm2.getCTName().isSetLocalSheetId()); - assertEquals(0, nm2.getCTName().getLocalSheetId()); - //calculation chain is removed as well - assertNull(wb.getCalculationChain()); - wb.close(); - + try (XSSFWorkbook wb = openSampleWorkbook("47737.xlsx")) { + assertEquals(2, wb.getNumberOfNames()); + assertNotNull(wb.getCalculationChain()); + + XSSFName nm0 = wb.getNameAt(0); + assertTrue(nm0.getCTName().isSetLocalSheetId()); + assertEquals(0, nm0.getCTName().getLocalSheetId()); + + XSSFName nm1 = wb.getNameAt(1); + assertTrue(nm1.getCTName().isSetLocalSheetId()); + assertEquals(1, nm1.getCTName().getLocalSheetId()); + + wb.removeSheetAt(0); + assertEquals(1, wb.getNumberOfNames()); + XSSFName nm2 = wb.getNameAt(0); + assertTrue(nm2.getCTName().isSetLocalSheetId()); + assertEquals(0, nm2.getCTName().getLocalSheetId()); + //calculation chain is removed as well + assertNull(wb.getCalculationChain()); + } } /** @@ -412,28 +404,28 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { */ @Test void bug47813() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx"); - assertEquals(3, wb1.getNumberOfSheets()); - assertNotNull(wb1.getCalculationChain()); - - assertEquals("Numbers", wb1.getSheetName(0)); - //the second sheet is of type 'chartsheet' - assertEquals("Chart", wb1.getSheetName(1)); - assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet); - assertEquals("SomeJunk", wb1.getSheetName(2)); - - wb1.removeSheetAt(2); - assertEquals(2, wb1.getNumberOfSheets()); - assertNull(wb1.getCalculationChain()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(2, wb2.getNumberOfSheets()); - assertNull(wb2.getCalculationChain()); - - assertEquals("Numbers", wb2.getSheetName(0)); - assertEquals("Chart", wb2.getSheetName(1)); - wb2.close(); - wb1.close(); + try (XSSFWorkbook wb1 = openSampleWorkbook("47813.xlsx")) { + assertEquals(3, wb1.getNumberOfSheets()); + assertNotNull(wb1.getCalculationChain()); + + assertEquals("Numbers", wb1.getSheetName(0)); + //the second sheet is of type 'chartsheet' + assertEquals("Chart", wb1.getSheetName(1)); + assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet); + assertEquals("SomeJunk", wb1.getSheetName(2)); + + wb1.removeSheetAt(2); + assertEquals(2, wb1.getNumberOfSheets()); + assertNull(wb1.getCalculationChain()); + + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + assertEquals(2, wb2.getNumberOfSheets()); + assertNull(wb2.getCalculationChain()); + + assertEquals("Numbers", wb2.getSheetName(0)); + assertEquals("Chart", wb2.getSheetName(1)); + } + } } /** @@ -461,14 +453,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertNull(wb1.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist"); // Save and reload - try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + try (XSSFWorkbook nwb = writeOutAndReadBack(wb1)) { assertEquals(2, nwb.getNumCellStyles()); nwb.getCellStyleAt((short) 0); nwb.getCellStyleAt((short) 1); assertNull(nwb.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist"); // Now with an existing file - try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { + try (XSSFWorkbook wb2 = openSampleWorkbook("sample.xlsx")) { assertEquals(3, wb2.getNumCellStyles()); wb2.getCellStyleAt((short) 0); wb2.getCellStyleAt((short) 1); @@ -501,7 +493,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { // calcMode="manual" is unset when forceFormulaRecalculation=true calcPr.setCalcMode(STCalcMode.MANUAL); wb.setForceFormulaRecalculation(true); - assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); + assertSame(STCalcMode.AUTO, calcPr.getCalcMode()); assertTrue(wb.getForceFormulaRecalculation()); wb.setForceFormulaRecalculation(false); @@ -514,26 +506,22 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test void columnWidthPOI52233() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("hello world"); - - sheet = workbook.createSheet(); - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + XSSFRow row = sheet.createRow(0); + XSSFCell cell = row.createCell(0); + cell.setCellValue("hello world"); - sheet.groupColumn((short) 4, (short) 5); + sheet = workbook.createSheet(); + sheet.setColumnWidth(4, 5000); + sheet.setColumnWidth(5, 5000); - accessWorkbook(workbook); + sheet.groupColumn((short) 4, (short) 5); - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - workbook.write(stream); + accessWorkbook(workbook); + workbook.write(NULL_OUTPUT_STREAM); + accessWorkbook(workbook); } - - accessWorkbook(workbook); - workbook.close(); } private void accessWorkbook(XSSFWorkbook workbook) { @@ -546,136 +534,128 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test void bug48495() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx"); + try (Workbook wb = openSampleWorkbook("48495.xlsx")) { + assertSheetOrder(wb, "Sheet1"); + + Sheet sheet = wb.getSheetAt(0); + sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false); + Row newRow = sheet.getRow(2); + if (newRow == null) { + newRow = sheet.createRow(2); + } + newRow.createCell(0).setCellValue(" Another Header"); + wb.cloneSheet(0); - assertSheetOrder(wb, "Sheet1"); + assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); - Sheet sheet = wb.getSheetAt(0); - sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false); - Row newRow = sheet.getRow(2); - if (newRow == null) { - newRow = sheet.createRow(2); + try (Workbook read = writeOutAndReadBack(wb)) { + assertNotNull(read); + assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); + } } - newRow.createCell(0).setCellValue(" Another Header"); - wb.cloneSheet(0); - - assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); - - // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx"); -// try { -// wb.write(fileOut); -// } finally { -// fileOut.close(); -// } - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(read); - assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); - read.close(); - wb.close(); } @Test void bug47090a() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet2", "Sheet1"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet1"); - read.close(); - workbook.close(); + try (Workbook workbook = openSampleWorkbook("47090.xlsx")) { + assertSheetOrder(workbook, "Sheet1", "Sheet2"); + workbook.removeSheetAt(0); + assertSheetOrder(workbook, "Sheet2"); + workbook.createSheet(); + assertSheetOrder(workbook, "Sheet2", "Sheet1"); + try (Workbook read = writeOutAndReadBack(workbook)) { + assertSheetOrder(read, "Sheet2", "Sheet1"); + } + } } @Test void bug47090b() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(1); - assertSheetOrder(workbook, "Sheet1"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet1", "Sheet0"); - read.close(); - workbook.close(); + try (Workbook workbook = openSampleWorkbook("47090.xlsx")) { + assertSheetOrder(workbook, "Sheet1", "Sheet2"); + workbook.removeSheetAt(1); + assertSheetOrder(workbook, "Sheet1"); + workbook.createSheet(); + assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! + try (Workbook read = writeOutAndReadBack(workbook)) { + assertSheetOrder(read, "Sheet1", "Sheet0"); + } + } } @Test void bug47090c() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2"); - workbook.cloneSheet(0); - assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); - read.close(); - workbook.close(); + try (Workbook workbook = openSampleWorkbook("47090.xlsx")) { + assertSheetOrder(workbook, "Sheet1", "Sheet2"); + workbook.removeSheetAt(0); + assertSheetOrder(workbook, "Sheet2"); + workbook.cloneSheet(0); + assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); + try (Workbook read = writeOutAndReadBack(workbook)) { + assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); + } + } } @Test void bug47090d() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2", "Sheet0"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); - read.close(); - workbook.close(); + try (Workbook workbook = openSampleWorkbook("47090.xlsx")) { + assertSheetOrder(workbook, "Sheet1", "Sheet2"); + workbook.createSheet(); + assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); + workbook.removeSheetAt(0); + assertSheetOrder(workbook, "Sheet2", "Sheet0"); + workbook.createSheet(); + assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); + try (Workbook read = writeOutAndReadBack(workbook)) { + assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); + } + } } @Test void bug51158() throws IOException { // create a workbook - final XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("Test Sheet"); - XSSFRow row = sheet.createRow(2); - XSSFCell cell = row.createCell(3); - cell.setCellValue("test1"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("Test Sheet"); + XSSFRow row = sheet.createRow(2); + XSSFCell cell = row.createCell(3); + cell.setCellValue("test1"); - //XSSFCreationHelper helper = workbook.getCreationHelper(); - //cell.setHyperlink(helper.createHyperlink(0)); + //XSSFCreationHelper helper = workbook.getCreationHelper(); + //cell.setHyperlink(helper.createHyperlink(0)); - XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); - assertNotNull(comment); - comment.setString("some comment"); + XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); + assertNotNull(comment); + comment.setString("some comment"); // CellStyle cs = workbook.createCellStyle(); // cs.setShrinkToFit(false); // row.createCell(0).setCellStyle(cs); - // write the first excel file - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertNotNull(wb2); - sheet = wb2.getSheetAt(0); - row = sheet.getRow(2); - assertEquals("test1", row.getCell(3).getStringCellValue()); - assertNull(row.getCell(4)); - - // add a new cell to the sheet - cell = row.createCell(4); - cell.setCellValue("test2"); - - // write the second excel file - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb3); - sheet = wb3.getSheetAt(0); - row = sheet.getRow(2); - - assertEquals("test1", row.getCell(3).getStringCellValue()); - assertEquals("test2", row.getCell(4).getStringCellValue()); - wb3.close(); - wb2.close(); - wb1.close(); + // write the first excel file + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + assertNotNull(wb2); + sheet = wb2.getSheetAt(0); + row = sheet.getRow(2); + assertEquals("test1", row.getCell(3).getStringCellValue()); + assertNull(row.getCell(4)); + + // add a new cell to the sheet + cell = row.createCell(4); + cell.setCellValue("test2"); + + // write the second excel file + try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) { + assertNotNull(wb3); + sheet = wb3.getSheetAt(0); + row = sheet.getRow(2); + + assertEquals("test1", row.getCell(3).getStringCellValue()); + assertEquals("test2", row.getCell(4).getStringCellValue()); + } + } + } } @Test @@ -704,20 +684,20 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { @Test void bug60509() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60509.xlsx"); - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3"); - int sheetIndex = wb.getSheetIndex("Sheet1"); - wb.setSheetName(sheetIndex, "Sheet1-Renamed"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(read); - assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3"); - XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed"); - XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries(0); - assertTrue(series instanceof XDDFBarChartData.Series, "should be a bar chart data series"); - String formula = series.getCategoryData().getFormula(); - assertTrue(formula.startsWith("'Sheet1-Renamed'!"), "should contain new sheet name"); - read.close(); - wb.close(); + try (XSSFWorkbook wb = openSampleWorkbook("60509.xlsx")) { + assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3"); + int sheetIndex = wb.getSheetIndex("Sheet1"); + wb.setSheetName(sheetIndex, "Sheet1-Renamed"); + try (Workbook read = writeOutAndReadBack(wb)) { + assertNotNull(read); + assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3"); + XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed"); + XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries(0); + assertTrue(series instanceof XDDFBarChartData.Series, "should be a bar chart data series"); + String formula = series.getCategoryData().getFormula(); + assertTrue(formula.startsWith("'Sheet1-Renamed'!"), "should contain new sheet name"); + } + } } private static final int INDEX_NOT_FOUND = -1; @@ -850,15 +830,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertEquals(idx2, wb.getFirstVisibleTab()); assertEquals(idx3, wb.getActiveSheetIndex()); - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - sheet2 = wbBack.getSheetAt(idx2); - assertNotNull(sheet2); - sheet3 = wbBack.getSheetAt(idx3); - assertNotNull(sheet3); - assertEquals(idx2, wb.getFirstVisibleTab()); - assertEquals(idx3, wb.getActiveSheetIndex()); - wbBack.close(); + try (Workbook wbBack = writeOutAndReadBack(wb)) { + sheet2 = wbBack.getSheetAt(idx2); + assertNotNull(sheet2); + sheet3 = wbBack.getSheetAt(idx3); + assertNotNull(sheet3); + assertEquals(idx2, wb.getFirstVisibleTab()); + assertEquals(idx3, wb.getActiveSheetIndex()); + } } } @@ -873,42 +852,39 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { allBytes[i] = (byte) (i - 128); } - XSSFWorkbook wb1 = new XSSFWorkbook(); - wb1.createSheet(); - wb1.setVBAProject(new ByteArrayInputStream(allBytes)); - file = TempFile.createTempFile("poi-", ".xlsm"); - OutputStream out = new FileOutputStream(file); - wb1.write(out); - out.close(); - wb1.close(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + wb1.createSheet(); + wb1.setVBAProject(new ByteArrayInputStream(allBytes)); + file = writeOut(wb1, "ooi-.xlsm"); + } // Check the package contains what we'd expect it to - OPCPackage pkg = OPCPackage.open(file.toString()); - PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - assertTrue(wbPart.hasRelationships()); - final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation()); - assertEquals(1, relationships.size()); - PackageRelationship relationship = relationships.getRelationship(0); - assertNotNull(relationship); - assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationship.getTargetURI().toString()); - PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName())); - assertNotNull(vbaPart); - assertFalse(vbaPart.isRelationshipPart()); - assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType()); - final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream()); - assertArrayEquals(allBytes, fromFile); - - // Load back the XSSFWorkbook just to check nothing explodes - @SuppressWarnings("resource") - XSSFWorkbook wb2 = new XSSFWorkbook(pkg); - assertEquals(1, wb2.getNumberOfSheets()); - assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType()); - pkg.close(); + try (OPCPackage pkg = OPCPackage.open(file.toString())) { + PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); + assertTrue(wbPart.hasRelationships()); + final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation()); + assertEquals(1, relationships.size()); + PackageRelationship relationship = relationships.getRelationship(0); + assertNotNull(relationship); + assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationship.getTargetURI().toString()); + PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName())); + assertNotNull(vbaPart); + assertFalse(vbaPart.isRelationshipPart()); + assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType()); + final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream()); + assertArrayEquals(allBytes, fromFile); + + // Load back the XSSFWorkbook just to check nothing explodes + try (XSSFWorkbook wb2 = new XSSFWorkbook(pkg)) { + assertEquals(1, wb2.getNumberOfSheets()); + assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType()); + } + } } @Test void testBug54399() throws IOException { - try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54399.xlsx")) { + try (XSSFWorkbook workbook = openSampleWorkbook("54399.xlsx")) { for (int i = 0; i < workbook.getNumberOfSheets(); i++) { String name = "SheetRenamed" + (i + 1); @@ -920,14 +896,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { } /** - * Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30 - * and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator + * {@code Iterator<XSSFSheet> XSSFWorkbook.iterator} was committed in r700472 on 2008-09-30 + * and has been replaced with {@code Iterator<Sheet> XSSFWorkbook.iterator} * * In order to make code for looping over sheets in workbooks standard, regardless * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously - * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator - * have been replaced with Iterator<Sheet> {@link Sheet#iterator} and - * Iterator<Sheet> {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook + * available {@code Iterator<XSSFSheet> iterator} and {@code Iterator<XSSFSheet> sheetIterator} + * have been replaced with {@code Iterator<Sheet>} {@link Sheet#iterator} and + * {@code Iterator<Sheet>} {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook * similar to iterating over rows in a sheet and cells in a row. * * Note: this breaks backwards compatibility! Existing codebases will need to @@ -1054,7 +1030,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { assertThrows(IOException.class, () -> { try { - XSSFTestDataSamples.writeOutAndReadBack(wb); + writeOutAndReadBack(wb); } catch (RuntimeException e) { throw e.getCause(); } @@ -1067,7 +1043,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook { */ @Test void getTable() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); + XSSFWorkbook wb = openSampleWorkbook("WithTable.xlsx"); XSSFTable table1 = wb.getTable("Tabella1"); assertNotNull(table1, "Tabella1 was not found in workbook"); assertEquals("Tabella1", table1.getName(), "Table name"); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java index 77a7e8be08..ec2b4cc5e6 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java @@ -20,10 +20,10 @@ package org.apache.poi.xssf.util; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.IOUtils; import org.apache.poi.util.ReplacingInputStream; import org.junit.jupiter.api.Test; @@ -68,23 +68,20 @@ public final class TestEvilUnclosedBRFixingInputStream { // Vary the buffer size, so that we can end up with the br in the // overflow or only part in the buffer for(int i=5; i<orig.length; i++) { - EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean going = true; - while(going) { - byte[] b = new byte[i]; - int r = inp.read(b); - if(r > 0) { + try (EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig); + UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream()) { + for (;;) { + byte[] b = new byte[i]; + int r = inp.read(b); + if (r <= 0) { + break; + } bout.write(b, 0, r); - } else { - going = false; } - } - byte[] result = bout.toByteArray(); - assertArrayEquals(fixed, result); - inp.close(); + byte[] result = bout.toByteArray(); + assertArrayEquals(fixed, result); + } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java index b24d0bf46c..e38b5b1e2d 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java @@ -16,11 +16,10 @@ ==================================================================== */ package org.apache.poi.xwpf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils; import org.apache.poi.xwpf.usermodel.XWPFDocument; @@ -33,10 +32,9 @@ public class XWPFTestDataSamples { } public static XWPFDocument writeOutAndReadBack(XWPFDocument doc) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096); doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new XWPFDocument(bais); + return new XWPFDocument(baos.toInputStream()); } public static byte[] getImage(String filename) throws IOException { diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java index 39673c3bba..0b74bfa5f1 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java @@ -19,9 +19,9 @@ package org.apache.poi.xwpf.usermodel; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.xwpf.XWPFTestDataSamples; import org.junit.jupiter.api.Test; @@ -58,14 +58,14 @@ class TestChangeTracking { r1.setText("Lorem ipsum dolor sit amet."); doc.setTrackRevisions(true); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + doc.write(out); - ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray()); - XWPFDocument document = new XWPFDocument(inputStream); - inputStream.close(); - - assertTrue(document.isTrackRevisions()); + try (InputStream inputStream = out.toInputStream()) { + XWPFDocument document = new XWPFDocument(inputStream); + assertTrue(document.isTrackRevisions()); + } + } } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java index 2974c879dc..10c8fca9e7 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java @@ -16,6 +16,7 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; +import static org.apache.poi.xwpf.XWPFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -23,8 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.List; @@ -170,15 +169,11 @@ class TestXWPFBugs { @Test void test59378() throws IOException { try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("59378.docx")) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); - out.close(); - - try (XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()))) { + try (XWPFDocument doc2 = writeOutAndReadBack(doc)) { assertNotNull(doc2); } - try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) { + try (XWPFDocument docBack = writeOutAndReadBack(doc)) { assertNotNull(docBack); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java index 856fcd9be3..dc614470ea 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java @@ -16,15 +16,17 @@ ==================================================================== */ package org.apache.poi.xwpf.usermodel; +import static org.apache.poi.xwpf.XWPFTestDataSamples.openSampleDocument; +import static org.apache.poi.xwpf.XWPFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.List; @@ -296,7 +298,7 @@ class TestXWPFRun { */ @Test void testExisting() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); + XWPFDocument doc = openSampleDocument("TestDocument.docx"); XWPFParagraph p; XWPFRun run; @@ -430,7 +432,7 @@ class TestXWPFRun { @Test void testPictureInHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); + XWPFDocument sampleDoc = openSampleDocument("headerPic.docx"); XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); XWPFHeader header = policy.getDefaultHeader(); @@ -486,7 +488,7 @@ class TestXWPFRun { @Test void testAddPicture() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); + XWPFDocument doc = openSampleDocument("TestDocument.docx"); XWPFParagraph p = doc.getParagraphArray(2); XWPFRun r = p.getRuns().get(0); @@ -498,7 +500,7 @@ class TestXWPFRun { assertEquals(1, doc.getAllPictures().size()); assertEquals(1, r.getEmbeddedPictures().size()); - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); + XWPFDocument docBack = writeOutAndReadBack(doc); XWPFParagraph pBack = docBack.getParagraphArray(2); XWPFRun rBack = pBack.getRuns().get(0); @@ -513,39 +515,39 @@ class TestXWPFRun { */ @Test void testAddPictureInHeader() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFParagraph p = hdr.createParagraph(); - XWPFRun r = p.createRun(); + try (XWPFDocument doc = openSampleDocument("TestDocument.docx")) { + XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); + XWPFParagraph p = hdr.createParagraph(); + XWPFRun r = p.createRun(); - assertEquals(0, hdr.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); + assertEquals(0, hdr.getAllPictures().size()); + assertEquals(0, r.getEmbeddedPictures().size()); - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); + r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - assertEquals(1, hdr.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); + assertEquals(1, hdr.getAllPictures().size()); + assertEquals(1, r.getEmbeddedPictures().size()); - XWPFPicture pic = r.getEmbeddedPictures().get(0); - CTPicture ctPic = pic.getCTPicture(); - CTBlipFillProperties ctBlipFill = ctPic.getBlipFill(); + XWPFPicture pic = r.getEmbeddedPictures().get(0); + CTPicture ctPic = pic.getCTPicture(); + CTBlipFillProperties ctBlipFill = ctPic.getBlipFill(); - assertNotNull(ctBlipFill); + assertNotNull(ctBlipFill); - CTBlip ctBlip = ctBlipFill.getBlip(); + CTBlip ctBlip = ctBlipFill.getBlip(); - assertNotNull(ctBlip); - assertEquals("rId1", ctBlip.getEmbed()); + assertNotNull(ctBlip); + assertEquals("rId1", ctBlip.getEmbed()); - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFHeader hdrBack = docBack.getHeaderArray(0); - XWPFParagraph pBack = hdrBack.getParagraphArray(0); - XWPFRun rBack = pBack.getRuns().get(0); + try (XWPFDocument docBack = writeOutAndReadBack(doc)) { + XWPFHeader hdrBack = docBack.getHeaderArray(0); + XWPFParagraph pBack = hdrBack.getParagraphArray(0); + XWPFRun rBack = pBack.getRuns().get(0); - assertEquals(1, hdrBack.getAllPictures().size()); - assertEquals(1, rBack.getEmbeddedPictures().size()); - docBack.close(); - doc.close(); + assertEquals(1, hdrBack.getAllPictures().size()); + assertEquals(1, rBack.getEmbeddedPictures().size()); + } + } } /** @@ -554,7 +556,7 @@ class TestXWPFRun { */ @Test void testSetFontFamily_52288() throws IOException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx")) { + try (XWPFDocument doc = openSampleDocument("52288.docx")) { doc.getParagraphs().stream() .flatMap(p -> p.getRuns().stream()) .filter(p -> p != null && p.getText(0) != null) @@ -565,157 +567,148 @@ class TestXWPFRun { @Test void testBug55476() throws IOException, InvalidFormatException { byte[] image = XWPFTestDataSamples.getImage("abstract1.jpg"); - XWPFDocument document = new XWPFDocument(); + try (XWPFDocument document = new XWPFDocument()) { - document.createParagraph().createRun().addPicture( + document.createParagraph().createRun().addPicture( new ByteArrayInputStream(image), Document.PICTURE_TYPE_JPEG, "test.jpg", Units.toEMU(300), Units.toEMU(100)); - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(document); - List<XWPFPicture> pictures = docBack.getParagraphArray(0).getRuns().get(0).getEmbeddedPictures(); - assertEquals(1, pictures.size()); - docBack.close(); - - /*OutputStream stream = new FileOutputStream("c:\\temp\\55476.docx"); - try { - document.write(stream); - } finally { - stream.close(); - }*/ - - document.close(); + try (XWPFDocument docBack = writeOutAndReadBack(document)) { + List<XWPFPicture> pictures = docBack.getParagraphArray(0).getRuns().get(0).getEmbeddedPictures(); + assertEquals(1, pictures.size()); + } + } } @Test void testBug58922() throws IOException { - XWPFDocument document = new XWPFDocument(); - - final XWPFRun run = document.createParagraph().createRun(); + try (XWPFDocument document = new XWPFDocument()) { + final XWPFRun run = document.createParagraph().createRun(); - assertEquals(-1, run.getFontSize()); - run.setFontSize(10); - assertEquals(10, run.getFontSize()); + assertEquals(-1, run.getFontSize()); - run.setFontSize(Short.MAX_VALUE-1); - assertEquals(Short.MAX_VALUE-1, run.getFontSize()); + run.setFontSize(10); + assertEquals(10, run.getFontSize()); - run.setFontSize(Short.MAX_VALUE); - assertEquals(Short.MAX_VALUE, run.getFontSize()); + run.setFontSize(Short.MAX_VALUE - 1); + assertEquals(Short.MAX_VALUE - 1, run.getFontSize()); - run.setFontSize(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getFontSize()); + run.setFontSize(Short.MAX_VALUE); + assertEquals(Short.MAX_VALUE, run.getFontSize()); - run.setFontSize(Integer.MAX_VALUE-1); - assertEquals(Integer.MAX_VALUE-1, run.getFontSize()); + run.setFontSize(Short.MAX_VALUE + 1); + assertEquals(Short.MAX_VALUE + 1, run.getFontSize()); - run.setFontSize(Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, run.getFontSize()); + run.setFontSize(Integer.MAX_VALUE - 1); + assertEquals(Integer.MAX_VALUE - 1, run.getFontSize()); - run.setFontSize(-1); - assertEquals(-1, run.getFontSize()); + run.setFontSize(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, run.getFontSize()); + run.setFontSize(-1); + assertEquals(-1, run.getFontSize()); - assertEquals(-1, run.getTextPosition()); - run.setTextPosition(10); - assertEquals(10, run.getTextPosition()); + assertEquals(-1, run.getTextPosition()); - run.setTextPosition(Short.MAX_VALUE-1); - assertEquals(Short.MAX_VALUE-1, run.getTextPosition()); + run.setTextPosition(10); + assertEquals(10, run.getTextPosition()); - run.setTextPosition(Short.MAX_VALUE); - assertEquals(Short.MAX_VALUE, run.getTextPosition()); + run.setTextPosition(Short.MAX_VALUE - 1); + assertEquals(Short.MAX_VALUE - 1, run.getTextPosition()); - run.setTextPosition(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getTextPosition()); + run.setTextPosition(Short.MAX_VALUE); + assertEquals(Short.MAX_VALUE, run.getTextPosition()); - run.setTextPosition(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getTextPosition()); + run.setTextPosition(Short.MAX_VALUE + 1); + assertEquals(Short.MAX_VALUE + 1, run.getTextPosition()); - run.setTextPosition(Integer.MAX_VALUE-1); - assertEquals(Integer.MAX_VALUE-1, run.getTextPosition()); + run.setTextPosition(Short.MAX_VALUE + 1); + assertEquals(Short.MAX_VALUE + 1, run.getTextPosition()); - run.setTextPosition(Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, run.getTextPosition()); + run.setTextPosition(Integer.MAX_VALUE - 1); + assertEquals(Integer.MAX_VALUE - 1, run.getTextPosition()); - run.setTextPosition(-1); - assertEquals(-1, run.getTextPosition()); + run.setTextPosition(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, run.getTextPosition()); - document.close(); + run.setTextPosition(-1); + assertEquals(-1, run.getTextPosition()); + } } @Test - void testSetters() { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - - // at least trigger some of the setters to ensure classes are included in - // the poi-ooxml-lite - run.setBold(true); - run.setCapitalized(true); - run.setCharacterSpacing(2); - assertEquals(2, run.getCharacterSpacing()); - run.setColor("000000"); - run.setDoubleStrikethrough(true); - run.setEmbossed(true); - run.setFontFamily("Calibri"); - assertEquals("Calibri", run.getFontFamily()); - run.setFontSize(10); - assertEquals(10, run.getFontSize()); - run.setImprinted(true); - run.setItalic(true); + void testSetters() throws IOException { + try (XWPFDocument document = new XWPFDocument()) { + final XWPFRun run = document.createParagraph().createRun(); + + // at least trigger some of the setters to ensure classes are included in + // the poi-ooxml-lite + run.setBold(true); + run.setCapitalized(true); + run.setCharacterSpacing(2); + assertEquals(2, run.getCharacterSpacing()); + run.setColor("000000"); + run.setDoubleStrikethrough(true); + run.setEmbossed(true); + run.setFontFamily("Calibri"); + assertEquals("Calibri", run.getFontFamily()); + run.setFontSize(10); + assertEquals(10, run.getFontSize()); + run.setImprinted(true); + run.setItalic(true); + } } @Test void testSetGetTextScale() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertEquals(100, run.getTextScale()); - run.setTextScale(200); - assertEquals(200, run.getTextScale()); - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + final XWPFRun run = document.createParagraph().createRun(); + assertEquals(100, run.getTextScale()); + run.setTextScale(200); + assertEquals(200, run.getTextScale()); + } } @Test void testSetGetTextHighlightColor() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertEquals(STHighlightColor.NONE, run.getTextHightlightColor()); - assertFalse(run.isHighlighted()); - run.setTextHighlightColor("darkGreen"); // See 17.18.40 ST_HighlightColor (Text Highlight Colors) - assertEquals(STHighlightColor.DARK_GREEN, run.getTextHightlightColor()); - assertTrue(run.isHighlighted()); - run.setTextHighlightColor("none"); - assertFalse(run.isHighlighted()); - - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + final XWPFRun run = document.createParagraph().createRun(); + assertSame(STHighlightColor.NONE, run.getTextHightlightColor()); + assertFalse(run.isHighlighted()); + run.setTextHighlightColor("darkGreen"); // See 17.18.40 ST_HighlightColor (Text Highlight Colors) + assertSame(STHighlightColor.DARK_GREEN, run.getTextHightlightColor()); + assertTrue(run.isHighlighted()); + run.setTextHighlightColor("none"); + assertFalse(run.isHighlighted()); + } } @Test void testSetGetVanish() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertFalse(run.isVanish()); - run.setVanish(true); - assertTrue(run.isVanish()); - run.setVanish(false); - assertFalse(run.isVanish()); - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + final XWPFRun run = document.createParagraph().createRun(); + assertFalse(run.isVanish()); + run.setVanish(true); + assertTrue(run.isVanish()); + run.setVanish(false); + assertFalse(run.isVanish()); + } } @Test void testSetGetVerticalAlignment() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals(STVerticalAlignRun.BASELINE, run.getVerticalAlignment()); - // Reset to a fresh run so we test case of run not having vertical alignment at all - run = document.createParagraph().createRun(); - run.setVerticalAlignment("subscript"); - assertEquals(STVerticalAlignRun.SUBSCRIPT, run.getVerticalAlignment()); - run.setVerticalAlignment("superscript"); - assertEquals(STVerticalAlignRun.SUPERSCRIPT, run.getVerticalAlignment()); - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + XWPFRun run = document.createParagraph().createRun(); + assertSame(STVerticalAlignRun.BASELINE, run.getVerticalAlignment()); + // Reset to a fresh run so we test case of run not having vertical alignment at all + run = document.createParagraph().createRun(); + run.setVerticalAlignment("subscript"); + assertSame(STVerticalAlignRun.SUBSCRIPT, run.getVerticalAlignment()); + run.setVerticalAlignment("superscript"); + assertSame(STVerticalAlignRun.SUPERSCRIPT, run.getVerticalAlignment()); + } } @Test @@ -726,82 +719,81 @@ class TestXWPFRun { XWPFRun run = new XWPFRun(ctRun, irb); run.setSubscript(VerticalAlign.BASELINE); - assertEquals(STVerticalAlignRun.BASELINE, rpr.getVertAlignArray(0).getVal()); + assertSame(STVerticalAlignRun.BASELINE, rpr.getVertAlignArray(0).getVal()); } @Test void testSetGetEmphasisMark() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals(STEm.NONE, run.getEmphasisMark()); - // Reset to a fresh run so we test case of run not having property at all - run = document.createParagraph().createRun(); - run.setEmphasisMark("dot"); - assertEquals(STEm.DOT, run.getEmphasisMark()); - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + XWPFRun run = document.createParagraph().createRun(); + assertSame(STEm.NONE, run.getEmphasisMark()); + // Reset to a fresh run so we test case of run not having property at all + run = document.createParagraph().createRun(); + run.setEmphasisMark("dot"); + assertSame(STEm.DOT, run.getEmphasisMark()); + } } @Test void testSetGetUnderlineColor() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals("auto", run.getUnderlineColor()); - // Reset to a fresh run so we test case of run not having property at all - run = document.createParagraph().createRun(); - String colorRgb = "C0F1a2"; - run.setUnderlineColor(colorRgb); - assertEquals(colorRgb.toUpperCase(LocaleUtil.getUserLocale()), run.getUnderlineColor()); - run.setUnderlineColor("auto"); - assertEquals("auto", run.getUnderlineColor()); - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + XWPFRun run = document.createParagraph().createRun(); + assertEquals("auto", run.getUnderlineColor()); + // Reset to a fresh run so we test case of run not having property at all + run = document.createParagraph().createRun(); + String colorRgb = "C0F1a2"; + run.setUnderlineColor(colorRgb); + assertEquals(colorRgb.toUpperCase(LocaleUtil.getUserLocale()), run.getUnderlineColor()); + run.setUnderlineColor("auto"); + assertEquals("auto", run.getUnderlineColor()); + } } @Test void testSetGetUnderlineThemeColor() throws IOException { - XWPFDocument document = new XWPFDocument(); - XWPFRun run = document.createParagraph().createRun(); - assertEquals(STThemeColor.NONE, run.getUnderlineThemeColor()); - // Reset to a fresh run so we test case of run not having property at all - run = document.createParagraph().createRun(); - String colorName = "accent4"; - run.setUnderlineThemeColor(colorName); - assertEquals(STThemeColor.Enum.forString(colorName), run.getUnderlineThemeColor()); - run.setUnderlineThemeColor("none"); - assertEquals(STThemeColor.NONE, run.getUnderlineThemeColor()); - document.close(); + try (XWPFDocument document = new XWPFDocument()) { + XWPFRun run = document.createParagraph().createRun(); + assertSame(STThemeColor.NONE, run.getUnderlineThemeColor()); + // Reset to a fresh run so we test case of run not having property at all + run = document.createParagraph().createRun(); + String colorName = "accent4"; + run.setUnderlineThemeColor(colorName); + assertSame(STThemeColor.Enum.forString(colorName), run.getUnderlineThemeColor()); + run.setUnderlineThemeColor("none"); + assertSame(STThemeColor.NONE, run.getUnderlineThemeColor()); + } } @Test void testSetStyleId() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - final XWPFRun run = document.createParagraph().createRun(); - - String styleId = "bolditalic"; - run.setStyle(styleId); - String candStyleId = run.getCTR().getRPr().getRStyleArray(0).getVal(); - assertNotNull( candStyleId, "Expected to find a run style ID" ); - assertEquals(styleId, candStyleId); + try (XWPFDocument document = openSampleDocument("SampleDoc.docx")) { + final XWPFRun run = document.createParagraph().createRun(); - assertEquals(styleId, run.getStyle()); + String styleId = "bolditalic"; + run.setStyle(styleId); + String candStyleId = run.getCTR().getRPr().getRStyleArray(0).getVal(); + assertNotNull(candStyleId, "Expected to find a run style ID"); + assertEquals(styleId, candStyleId); - document.close(); + assertEquals(styleId, run.getStyle()); + } } @Test void testGetEmptyStyle() throws IOException { - XWPFDocument document = new XWPFDocument(); - final XWPFRun run = document.createParagraph().createRun(); - assertEquals("", run.getStyle()); + try (XWPFDocument document = new XWPFDocument()) { + final XWPFRun run = document.createParagraph().createRun(); + assertEquals("", run.getStyle()); - run.getCTR().addNewRPr(); - assertEquals("", run.getStyle()); - document.close(); + run.getCTR().addNewRPr(); + assertEquals("", run.getStyle()); + } } @Test void testGetDepthWidth() throws IOException, InvalidFormatException { - try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) { + try (XWPFDocument doc = openSampleDocument("TestDocument.docx")) { XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); XWPFParagraph p = hdr.createParagraph(); XWPFRun r = p.createRun(); @@ -827,35 +819,28 @@ class TestXWPFRun { " The quick brown fox", "\t\tjumped over the lazy dog" }; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try (XWPFDocument doc = new XWPFDocument();) { + try (XWPFDocument doc1 = new XWPFDocument()) { for(String s : text) { - XWPFParagraph p1 = doc.createParagraph(); + XWPFParagraph p1 = doc1.createParagraph(); XWPFRun r1 = p1.createRun(); r1.setText(s); } - doc.write(bos); - bos.flush(); - } - - try ( - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - XWPFDocument doc = new XWPFDocument(bis) - ) { - List<XWPFParagraph> paragraphs = doc.getParagraphs(); - assertEquals(2, paragraphs.size()); - for (int i = 0; i < text.length; i++) { - XWPFParagraph p1 = paragraphs.get(i); - String expected = text[i]; - assertEquals(expected, p1.getText()); - CTP ctp = p1.getCTP(); - CTR ctr = ctp.getRArray(0); - CTText ctText = ctr.getTArray(0); - // if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set - // <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> - boolean isWhitespace = Character.isWhitespace(expected.charAt(0)); - assertEquals(isWhitespace, ctText.isSetSpace()); + try (XWPFDocument doc2 = writeOutAndReadBack(doc1)) { + List<XWPFParagraph> paragraphs = doc2.getParagraphs(); + assertEquals(2, paragraphs.size()); + for (int i = 0; i < text.length; i++) { + XWPFParagraph p1 = paragraphs.get(i); + String expected = text[i]; + assertEquals(expected, p1.getText()); + CTP ctp = p1.getCTP(); + CTR ctr = ctp.getRArray(0); + CTText ctText = ctr.getTArray(0); + // if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set + // <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> + boolean isWhitespace = Character.isWhitespace(expected.charAt(0)); + assertEquals(isWhitespace, ctText.isSetSpace()); + } } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java b/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java index 9879eee028..5e70f033a2 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.hdgf; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LZWDecompresser; /** @@ -53,7 +53,7 @@ public class HDGFLZW extends LZWDecompresser { * @throws IOException when the InputStream can't be read */ public byte[] compress(InputStream src) throws IOException { - ByteArrayOutputStream res = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream res = new UnsynchronizedByteArrayOutputStream(); compress(src,res); return res.toByteArray(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java index 803fb98855..f1b668e3f0 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java @@ -26,8 +26,6 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -36,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hemf.draw.HemfDrawProperties; import org.apache.poi.hemf.draw.HemfGraphics; import org.apache.poi.hwmf.draw.HwmfGraphics; @@ -793,14 +792,14 @@ public final class HemfFill { return (long)undefinedSpace1 + bitmap.init(leis, dibSize); } - final ByteArrayOutputStream bos = new ByteArrayOutputStream(cbBmi+cbBits); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(cbBmi+cbBits); final long cbBmiSrcAct = IOUtils.copy(leis, bos, cbBmi); assert (cbBmiSrcAct == cbBmi); leis.skipFully(undefinedSpace2); final long cbBitsSrcAct = IOUtils.copy(leis, bos, cbBits); assert (cbBitsSrcAct == cbBits); - final LittleEndianInputStream leisDib = new LittleEndianInputStream(new ByteArrayInputStream(bos.toByteArray())); + final LittleEndianInputStream leisDib = new LittleEndianInputStream(bos.toInputStream()); final int dibSizeAct = bitmap.init(leisDib, dibSize); assert (dibSizeAct <= dibSize); return (long)undefinedSpace1 + cbBmi + undefinedSpace2 + cbBits; diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java index 71ade3fdb3..9739635c21 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java @@ -27,7 +27,6 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; @@ -41,6 +40,7 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.common.usermodel.GenericRecord; import org.apache.poi.hemf.draw.HemfDrawProperties; import org.apache.poi.hemf.draw.HemfGraphics; @@ -399,7 +399,7 @@ public class HemfPlusBrush { } public byte[] getRawData(List<? extends EmfPlusObjectData> continuedObjectData) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { bos.write(getBrushBytes()); if (continuedObjectData != null) { @@ -473,6 +473,7 @@ public class HemfPlusBrush { public static class EmfPlusHatchBrushData implements EmfPlusBrushData { private EmfPlusHatchStyle style; private Color foreColor, backColor; + @Override public long init(LittleEndianInputStream leis, long dataSize) { style = EmfPlusHatchStyle.valueOf(leis.readInt()); foreColor = readARGB(leis.readInt()); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java index 840b752f37..1ea137dc1a 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java @@ -23,7 +23,6 @@ import java.awt.Color; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashMap; @@ -33,6 +32,7 @@ import java.util.function.Supplier; import javax.imageio.ImageIO; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hemf.draw.HemfDrawProperties; import org.apache.poi.hemf.draw.HemfGraphics; import org.apache.poi.hemf.record.emfplus.HemfPlusHeader.EmfPlusGraphicsVersion; @@ -445,7 +445,7 @@ public class HemfPlusImage { } public byte[] getRawData(List<? extends EmfPlusObjectData> continuedObjectData) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { bos.write(getImageData()); if (continuedObjectData != null) { @@ -607,6 +607,7 @@ public class HemfPlusImage { return size + 5*LittleEndianConsts.INT_SIZE; } + @Override public EmfPlusGraphicsVersion getGraphicsVersion() { return graphicsVersion; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java index 1b02478861..f94c05a598 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java @@ -18,7 +18,6 @@ package org.apache.poi.hemf.usermodel; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; @@ -27,6 +26,7 @@ import java.util.NoSuchElementException; import javax.imageio.ImageIO; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hemf.record.emf.HemfComment; import org.apache.poi.hemf.record.emf.HemfComment.EmfComment; import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataFormat; @@ -273,7 +273,7 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> { private void compressGDIBitmap(EmfPlusImage img, HwmfEmbedded emb, HwmfEmbeddedType et) { BufferedImage bi = img.readGDIImage(emb.getRawData()); try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); // use HwmfEmbeddedType literal for conversion ImageIO.write(bi, et.toString(), bos); emb.setData(bos.toByteArray()); @@ -298,7 +298,7 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> { int totalSize = epo.getTotalObjectSize(); IOUtils.safelyAllocateCheck(totalSize, MAX_RECORD_LENGTH); - ByteArrayOutputStream bos = new ByteArrayOutputStream(epo.getTotalObjectSize()); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(epo.getTotalObjectSize()); try { for (;;) { bos.write(img.getImageData()); @@ -315,8 +315,8 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> { return emb; } } - } catch (IOException e) { - // ByteArrayOutputStream doesn't throw IOException + } catch (IOException ignored) { + // UnsynchronizedByteArrayOutputStream doesn't throw IOException return null; } finally { emb.setData(bos.toByteArray()); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java b/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java index c3e2ab0c38..46988b9ec0 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java @@ -70,6 +70,7 @@ public final class CompressedRTF extends LZWDecompresser { * if you need to know how much of the result is * real. (Padding may be up to 7 bytes). */ + @Override public void decompress(InputStream src, OutputStream res) throws IOException { // Validate the header on the front of the RTF compressedSize = LittleEndian.readInt(src); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java index e6bf60da16..ec8d2b2fec 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java @@ -19,11 +19,11 @@ package org.apache.poi.hslf.blip; import java.awt.Dimension; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.hslf.exceptions.HSLFException; @@ -41,7 +41,7 @@ public final class EMF extends Metafile { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link EMF}. This API led to detached {@link EMF} instances (See Bugzilla + * EMF. This API led to detached EMF instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -64,23 +64,19 @@ public final class EMF extends Metafile { @Override public byte[] getData(){ - try { - byte[] rawdata = getRawData(); + byte[] rawdata = getRawData(); + Header header = new Header(); + header.read(rawdata, CHECKSUM_SIZE); + + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + InputStream is = new ByteArrayInputStream(rawdata); + InflaterInputStream inflater = new InflaterInputStream(is)) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - InputStream is = new ByteArrayInputStream( rawdata ); - Header header = new Header(); - header.read(rawdata, CHECKSUM_SIZE); long len = IOUtils.skipFully(is,header.getSize() + (long)CHECKSUM_SIZE); assert(len == header.getSize() + CHECKSUM_SIZE); - InflaterInputStream inflater = new InflaterInputStream( is ); - byte[] chunk = new byte[4096]; - int count; - while ((count = inflater.read(chunk)) >=0 ) { - out.write(chunk,0,count); - } - inflater.close(); + IOUtils.copy(inflater, out); + return out.toByteArray(); } catch (IOException e){ throw new HSLFException(e); @@ -129,13 +125,15 @@ public final class EMF extends Metafile { * * @return EMF signature ({@code 0x3D40} or {@code 0x3D50}) */ + @Override public int getSignature(){ return (getUIDInstanceCount() == 1 ? 0x3D40 : 0x3D50); } - + /** * Sets the EMF signature - either {@code 0x3D40} or {@code 0x3D50} */ + @Override public void setSignature(int signature) { switch (signature) { case 0x3D40: @@ -146,6 +144,6 @@ public final class EMF extends Metafile { break; default: throw new IllegalArgumentException(signature+" is not a valid instance/signature value for EMF"); - } + } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java index ea855d460e..ca0b01556e 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java @@ -20,11 +20,11 @@ package org.apache.poi.hslf.blip; import java.awt.Dimension; import java.awt.Rectangle; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.DeflaterOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.hslf.usermodel.HSLFPictureData; @@ -44,7 +44,7 @@ public abstract class Metafile extends HSLFPictureData { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link Metafile}. This API led to detached {@link Metafile} instances (See Bugzilla + * Metafile. This API led to detached Metafile instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -70,7 +70,7 @@ public abstract class Metafile extends HSLFPictureData { */ public static class Header{ private static final int RECORD_LENGTH = 34; - + /** * size of the original file */ @@ -105,7 +105,7 @@ public abstract class Metafile extends HSLFPictureData { @SuppressWarnings("resource") LittleEndianInputStream leis = new LittleEndianInputStream( new ByteArrayInputStream(data, offset, RECORD_LENGTH)); - + wmfsize = leis.readInt(); int left = leis.readInt(); @@ -126,7 +126,7 @@ public abstract class Metafile extends HSLFPictureData { public void write(OutputStream out) throws IOException { @SuppressWarnings("resource") LittleEndianOutputStream leos = new LittleEndianOutputStream(out); - + //hmf leos.writeInt(wmfsize); //left @@ -140,8 +140,8 @@ public abstract class Metafile extends HSLFPictureData { //inch leos.writeInt(size.width); //inch - leos.writeInt(size.height); - leos.writeInt(zipsize); + leos.writeInt(size.height); + leos.writeInt(zipsize); leos.writeByte(compression); leos.writeByte(filter); } @@ -187,15 +187,15 @@ public abstract class Metafile extends HSLFPictureData { public int getSize(){ return 34; } - + public int getWmfSize() { return wmfsize; } - + protected void setWmfSize(int wmfSize) { this.wmfsize = wmfSize; } - + protected void setZipSize(int zipSize) { this.zipsize = zipSize; } @@ -203,25 +203,25 @@ public abstract class Metafile extends HSLFPictureData { public Rectangle getBounds() { return (Rectangle)bounds.clone(); } - + protected void setBounds(Rectangle bounds) { this.bounds.setBounds(bounds); } - + protected void setDimension(Dimension size) { this.size.setSize(size); } } protected static byte[] compress(byte[] bytes, int offset, int length) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); try (DeflaterOutputStream deflater = new DeflaterOutputStream(out)) { deflater.write(bytes, offset, length); - } catch (IOException e) { + } catch (IOException ignored) { // IOException won't get thrown by the DeflaterOutputStream in this configuration because: - // 1. ByteArrayOutputStream doesn't throw an IOException during writes. + // 1. UnsynchronizedByteArrayOutputStream doesn't throw an IOException during writes. // 2. The DeflaterOutputStream is not finished until we're done writing. - throw new AssertionError("Won't happen", e); + throw new AssertionError("Won't happen", ignored); } return out.toByteArray(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java index a6c2765ec7..dc1e93cc67 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java @@ -17,13 +17,15 @@ package org.apache.poi.hslf.blip; +import static org.apache.logging.log4j.util.Unbox.box; + import java.awt.Dimension; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherBSERecord; @@ -36,8 +38,6 @@ import org.apache.poi.util.Internal; import org.apache.poi.util.Removal; import org.apache.poi.util.Units; -import static org.apache.logging.log4j.util.Unbox.box; - /** * Represents Macintosh PICT picture data. */ @@ -46,7 +46,7 @@ public final class PICT extends Metafile { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link PICT}. This API led to detached {@link PICT} instances (See Bugzilla + * PICT. This API led to detached PICT instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -72,7 +72,7 @@ public final class PICT extends Metafile { byte[] rawdata = getRawData(); try { byte[] macheader = new byte[512]; - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); out.write(macheader); int pos = CHECKSUM_SIZE*getUIDInstanceCount(); byte[] pict = read(rawdata, pos); @@ -93,7 +93,7 @@ public final class PICT extends Metafile { throw new EOFException(); } byte[] chunk = new byte[4096]; - ByteArrayOutputStream out = new ByteArrayOutputStream(header.getWmfSize()); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(header.getWmfSize()); try (InflaterInputStream inflater = new InflaterInputStream(bis)) { int count; while ((count = inflater.read(chunk)) >= 0) { @@ -163,6 +163,7 @@ public final class PICT extends Metafile { * * @return PICT signature ({@code 0x5420} or {@code 0x5430}) */ + @Override public int getSignature(){ return (getUIDInstanceCount() == 1 ? 0x5420 : 0x5430); } @@ -170,6 +171,7 @@ public final class PICT extends Metafile { /** * Sets the PICT signature - either {@code 0x5420} or {@code 0x5430} */ + @Override public void setSignature(int signature) { switch (signature) { case 0x5420: diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java index 55b74bdb6f..6a039510c6 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java @@ -19,11 +19,11 @@ package org.apache.poi.hslf.blip; import java.awt.Dimension; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.hslf.exceptions.HSLFException; @@ -41,7 +41,7 @@ public final class WMF extends Metafile { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link WMF}. This API led to detached {@link WMF} instances (See Bugzilla + * WMF. This API led to detached WMF instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -67,7 +67,6 @@ public final class WMF extends Metafile { try { byte[] rawdata = getRawData(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream is = new ByteArrayInputStream( rawdata ); Header header = new Header(); header.read(rawdata, CHECKSUM_SIZE*getUIDInstanceCount()); @@ -76,15 +75,12 @@ public final class WMF extends Metafile { assert(skipped == skipLen); ImageHeaderWMF aldus = new ImageHeaderWMF(header.getBounds()); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); aldus.write(out); - InflaterInputStream inflater = new InflaterInputStream( is ); - byte[] chunk = new byte[4096]; - int count; - while ((count = inflater.read(chunk)) >=0 ) { - out.write(chunk,0,count); + try (InflaterInputStream inflater = new InflaterInputStream( is )) { + IOUtils.copy(inflater, out); } - inflater.close(); return out.toByteArray(); } catch (IOException e){ throw new HSLFException(e); @@ -133,6 +129,7 @@ public final class WMF extends Metafile { /** * WMF signature is either {@code 0x2160} or {@code 0x2170} */ + @Override public int getSignature(){ return (getUIDInstanceCount() == 1 ? 0x2160 : 0x2170); } @@ -140,6 +137,7 @@ public final class WMF extends Metafile { /** * Sets the WMF signature - either {@code 0x2160} or {@code 0x2170} */ + @Override public void setSignature(int signature) { switch (signature) { case 0x2160: diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java index 4e431976a3..b15d37c987 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -28,6 +27,7 @@ import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.record.RecordTypes; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.poifs.filesystem.DirectoryNode; @@ -41,19 +41,15 @@ import org.apache.poi.util.LittleEndianConsts; */ public final class PPTXMLDump { - - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 1_000_000; - private static final int HEADER_SIZE = 8; //size of the record header private static final int PICT_HEADER_SIZE = 25; //size of the picture header private static final String PICTURES_ENTRY = "Pictures"; private static final String CR = System.getProperty("line.separator"); private Writer out; - private byte[] docstream; - private byte[] pictstream; - private boolean hexHeader = true; + private final byte[] docstream; + private final byte[] pictstream; + private final boolean hexHeader = true; public PPTXMLDump(File ppt) throws IOException { try (POIFSFileSystem fs = new POIFSFileSystem(ppt, true)) { @@ -68,8 +64,8 @@ public final class PPTXMLDump { if (!dn.hasEntry(entry)) { return null; } - try (InputStream is = dn.createDocumentInputStream(entry)) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (InputStream is = dn.createDocumentInputStream(entry); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { IOUtils.copy(is, bos); return bos.toByteArray(); } @@ -77,7 +73,7 @@ public final class PPTXMLDump { /** * Dump the structure of the supplied PPT file into XML - * @param outWriter <code>Writer</code> to write out + * @param outWriter {@code Writer} to write out * @throws java.io.IOException If writing to the writer fails */ public void dump(Writer outWriter) throws IOException { @@ -229,7 +225,7 @@ public final class PPTXMLDump { /** - * write a string to <code>out</code> with the specified padding + * write a string to {@code out} with the specified padding */ private static void write(Writer out, String str, int padding) throws IOException { for (int i = 0; i < padding; i++) out.write(" "); @@ -250,7 +246,7 @@ public final class PPTXMLDump { } /** - * dump binary data to <code>out</code> with the specified padding + * dump binary data to {@code out} with the specified padding */ private static void dump(Writer out, byte[] data, int offset, int length, int padding, boolean nl) throws IOException { int linesize = 25; diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java index e80cbc18ec..b335752e9c 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.record.Document; import org.apache.poi.hslf.record.Notes; import org.apache.poi.hslf.record.NotesAtom; @@ -136,7 +136,7 @@ public final class SlideIdListing { System.out.println(" Knows about sheet " + id); System.out.println(" That sheet lives at " + offset); - Record atPos = findRecordAtPos(offset.intValue()); + Record atPos = findRecordAtPos(offset); 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()); @@ -147,7 +147,7 @@ public final class SlideIdListing { } // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); pos += baos.size(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java index 88b6407cab..eb7a1a7ece 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java @@ -17,12 +17,11 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; -import java.util.List; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherRecord; @@ -44,9 +43,9 @@ import org.apache.poi.util.HexDump; public final class SlideShowRecordDumper { static final String tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; - private boolean optVerbose; - private boolean optEscher; - private HSLFSlideShowImpl doc; + private final boolean optVerbose; + private final boolean optEscher; + private final HSLFSlideShowImpl doc; private final PrintStream ps; /** @@ -59,7 +58,7 @@ public final class SlideShowRecordDumper { int ndx = 0; for (; ndx < args.length; ndx++) { - if (!args[ndx].substring(0, 1).equals("-")) + if (args[ndx].charAt(0) != '-') break; if (args[ndx].equals("-escher")) { @@ -147,7 +146,7 @@ public final class SlideShowRecordDumper { public int getDiskLen(org.apache.poi.hslf.record.Record r) throws IOException { int diskLen = 0; if (r != null) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); diskLen = baos.size(); } @@ -159,7 +158,7 @@ public final class SlideShowRecordDumper { return "<<null>>"; } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); byte[] b = baos.toByteArray(); return HexDump.dump(b, 0, 0); @@ -259,7 +258,7 @@ public final class SlideShowRecordDumper { if (optEscher && cname.equals("PPDrawing")) { DefaultEscherRecordFactory factory = new HSLFEscherRecordFactory(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); byte[] b = baos.toByteArray(); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java index 116582e7f3..d17eafc346 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.record.CurrentUserAtom; import org.apache.poi.hslf.record.PersistPtrHolder; import org.apache.poi.hslf.record.PositionDependentRecord; @@ -68,7 +68,7 @@ public final class UserEditAndPersistListing { System.out.println(" Knows about sheet " + id); System.out.println(" That sheet lives at " + offset); - Record atPos = findRecordAtPos(offset.intValue()); + Record atPos = findRecordAtPos(offset); 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()); @@ -79,7 +79,7 @@ public final class UserEditAndPersistListing { } // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); pos += baos.size(); } @@ -99,7 +99,7 @@ public final class UserEditAndPersistListing { } // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); pos += baos.size(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java index 9155731dcd..62c2f935f3 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.model.textproperties; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -29,6 +28,7 @@ import java.util.Map; import java.util.Objects; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.common.Duplicatable; @@ -355,10 +355,10 @@ public class TextPropCollection implements GenericRecord, Duplicatable { public String toString() { StringBuilder out = new StringBuilder(); - out.append(" chars covered: " + getCharactersCovered()); - out.append(" special mask flags: 0x" + HexDump.toHex(getSpecialMask()) + "\n"); + out.append(" chars covered: ").append(getCharactersCovered()); + out.append(" special mask flags: 0x").append(HexDump.toHex(getSpecialMask())).append("\n"); if (textPropType == TextPropType.paragraph) { - out.append(" indent level: "+getIndentLevel()+"\n"); + out.append(" indent level: ").append(getIndentLevel()).append("\n"); } for(TextProp p : getTextPropList()) { out.append(" "); @@ -369,7 +369,7 @@ public class TextPropCollection implements GenericRecord, Duplicatable { int i = 0; for (String s : bm.getSubPropNames()) { if (bm.getSubPropMatches()[i]) { - out.append(" " + s + " = " + bm.getSubValue(i) + "\n"); + out.append(" ").append(s).append(" = ").append(bm.getSubValue(i)).append("\n"); } i++; } @@ -379,7 +379,7 @@ public class TextPropCollection implements GenericRecord, Duplicatable { out.append(" bytes that would be written: \n"); try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); writeOut(baos); byte[] b = baos.toByteArray(); out.append(HexDump.dump(b, 0, 0)); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java index bd2ac34d98..7a8dc9dbf6 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; @@ -26,6 +25,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.LittleEndian; @@ -36,9 +36,9 @@ import org.apache.poi.util.LittleEndian; * defines the colours to be used */ public final class ColorSchemeAtom extends RecordAtom { - private byte[] _header; - private static long _type = 2032l; + private static final long _type = 2032L; + private final byte[] _header; private int backgroundColourRGB; private int textAndLinesColourRGB; private int shadowsColourRGB; @@ -99,8 +99,7 @@ public final class ColorSchemeAtom extends RecordAtom { */ protected ColorSchemeAtom(byte[] source, int start, int len) { // Sanity Checking - we're always 40 bytes long - if(len < 40) { - len = 40; + if (len < 40) { if(source.length - start < 40) { throw new HSLFException("Not enough data to form a ColorSchemeAtom (always 40 bytes long) - found " + (source.length - start)); } @@ -155,7 +154,7 @@ public final class ColorSchemeAtom extends RecordAtom { byte[] ret = new byte[3]; // Serialise to bytes, then grab the right ones out - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try { writeLittleEndian(rgb,baos); } catch(IOException ie) { diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java index ebb3fc01b9..e9e16b91ed 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java @@ -23,12 +23,11 @@ package org.apache.poi.hslf.record; import static org.apache.logging.log4j.util.Unbox.box; import static org.apache.poi.hslf.usermodel.HSLFSlideShow.PP95_DOCUMENT; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; @@ -267,12 +266,12 @@ public class CurrentUserAtom */ public void writeToFS(POIFSFileSystem fs) throws IOException { // Grab contents - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - writeOut(baos); - ByteArrayInputStream bais = - new ByteArrayInputStream(baos.toByteArray()); - - // Write out - fs.createOrUpdateDocument(bais,"Current User"); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + writeOut(baos); + try (InputStream is = baos.toInputStream()) { + // Write out + fs.createOrUpdateDocument(is, "Current User"); + } + } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java index 273c3a6a2c..4764c91d21 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java @@ -66,7 +66,7 @@ public final class DocumentAtom extends RecordAtom { private final byte[] _header = new byte[8]; - private static long _type = RecordTypes.DocumentAtom.typeID; + private static final long _type = RecordTypes.DocumentAtom.typeID; private long slideSizeX; // PointAtom, assume 1st 4 bytes = X private long slideSizeY; // PointAtom, assume 2nd 4 bytes = Y @@ -75,18 +75,18 @@ public final class DocumentAtom extends RecordAtom { private long serverZoomFrom; // RatioAtom, assume 1st 4 bytes = from private long serverZoomTo; // RatioAtom, assume 2nd 4 bytes = to - private long notesMasterPersist; // ref to NotesMaster, 0 if none - private long handoutMasterPersist; // ref to HandoutMaster, 0 if none + private final long notesMasterPersist; // ref to NotesMaster, 0 if none + private final long handoutMasterPersist; // ref to HandoutMaster, 0 if none - private int firstSlideNum; + private final int firstSlideNum; private int slideSizeType; // see DocumentAtom.SlideSize private byte saveWithFonts; - private byte omitTitlePlace; - private byte rightToLeft; - private byte showComments; + private final byte omitTitlePlace; + private final byte rightToLeft; + private final byte showComments; - private byte[] reserved; + private final byte[] reserved; public long getSlideSizeX() { return slideSizeX; } @@ -197,12 +197,14 @@ public final class DocumentAtom extends RecordAtom { /** * We are of type 1001 */ + @Override public long getRecordType() { return _type; } /** * Write the contents of the record back, so it can be written * to disk */ + @Override public void writeOut(OutputStream out) throws IOException { // Header out.write(_header); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java index 7a47e9fd4e..751bf291f9 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java @@ -17,12 +17,12 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherTextboxRecord; import org.apache.poi.util.GenericRecordUtil; @@ -34,7 +34,7 @@ import org.apache.poi.util.GenericRecordUtil; * parent PPDrawing) will do the actual write out */ public final class EscherTextboxWrapper extends RecordContainer { - private EscherTextboxRecord _escherRecord; + private final EscherTextboxRecord _escherRecord; private long _type; private int shapeId; private StyleTextPropAtom styleTextPropAtom; @@ -75,6 +75,7 @@ public final class EscherTextboxWrapper extends RecordContainer { /** * Return the type of the escher record (normally in the 0xFnnn range) */ + @Override public long getRecordType() { return _type; } /** @@ -83,11 +84,12 @@ public final class EscherTextboxWrapper extends RecordContainer { * layer to do. Must be called before writeOut/serialize is called * on the underlying Escher object! */ + @Override public void writeOut(OutputStream out) throws IOException { // Write out our children, and stuff them into the Escher layer // Grab the children's data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); for (org.apache.poi.hslf.record.Record r : _children) r.writeOut(baos); byte[] data = baos.toByteArray(); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java index 4fc8a838e0..8aa091fdb2 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java @@ -18,7 +18,6 @@ package org.apache.poi.hslf.record; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,7 +27,8 @@ import java.util.function.Supplier; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import org.apache.poi.util.BoundedInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.commons.io.input.BoundedInputStream; import org.apache.poi.util.GenericRecordUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; @@ -124,7 +124,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * @param data the embedded data. */ public void setData(byte[] data) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); //first four bytes is the length of the raw data byte[] b = new byte[4]; LittleEndian.putInt(b, 0, data.length); @@ -133,6 +133,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR DeflaterOutputStream def = new DeflaterOutputStream(out); def.write(data, 0, data.length); def.finish(); + // TODO: CHECK if it's correct that DeflaterOutputStream is only finished and not closed? _data = out.toByteArray(); LittleEndian.putInt(_header, 4, _data.length); } @@ -142,6 +143,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * * @return the record type. */ + @Override public long getRecordType() { return RecordTypes.ExOleObjStg.typeID; } @@ -162,6 +164,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * @param out the output stream to write to. * @throws IOException if an error occurs. */ + @Override public void writeOut(OutputStream out) throws IOException { out.write(_header); out.write(_data); @@ -171,6 +174,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * Fetch our sheet ID, as found from a PersistPtrHolder. * Should match the RefId of our matching SlidePersistAtom */ + @Override public int getPersistId() { return _persistId; } @@ -178,6 +182,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR /** * Set our sheet ID, as found from a PersistPtrHolder */ + @Override public void setPersistId(int id) { _persistId = id; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java index af0e0a5ec5..47efe8e829 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherClientDataRecord; import org.apache.poi.ddf.EscherRecordFactory; import org.apache.poi.ddf.EscherSerializationListener; @@ -49,7 +49,7 @@ public class HSLFEscherClientDataRecord extends EscherClientDataRecord { super(other); // TODO: for now only reference others children, later copy them when Record.copy is available // other._childRecords.stream().map(Record::copy).forEach(_childRecords::add); - other._childRecords.addAll(other._childRecords); + _childRecords.addAll(other._childRecords); } @@ -96,15 +96,14 @@ public class HSLFEscherClientDataRecord extends EscherClientDataRecord { @Override public byte[] getRemainingData() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { for (org.apache.poi.hslf.record.Record r : _childRecords) { r.writeOut(bos); } + return bos.toByteArray(); } catch (IOException e) { throw new HSLFException(e); } - return bos.toByteArray(); } @Override @@ -121,6 +120,7 @@ public class HSLFEscherClientDataRecord extends EscherClientDataRecord { } } + @Override public String getRecordName() { return "HSLFClientData"; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java index 6ff8b4577f..3bc4f0fe57 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java @@ -17,13 +17,13 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherDggRecord; @@ -44,8 +44,8 @@ public final class PPDrawingGroup extends RecordAtom { private static final int MAX_RECORD_LENGTH = 10_485_760; - private byte[] _header; - private EscherContainerRecord dggContainer; + private final byte[] _header; + private final EscherContainerRecord dggContainer; //cached dgg private EscherDggRecord dgg; @@ -65,6 +65,7 @@ public final class PPDrawingGroup extends RecordAtom { /** * We are type 1035 */ + @Override public long getRecordType() { return RecordTypes.PPDrawingGroup.typeID; } @@ -72,17 +73,19 @@ public final class PPDrawingGroup extends RecordAtom { /** * We're pretending to be an atom, so return null */ + @Override public org.apache.poi.hslf.record.Record[] getChildRecords() { return null; } + @Override public void writeOut(OutputStream out) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream(); for (EscherRecord r : dggContainer) { if (r.getRecordId() == EscherContainerRecord.BSTORE_CONTAINER){ EscherContainerRecord bstore = (EscherContainerRecord)r; - ByteArrayOutputStream b2 = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream b2 = new UnsynchronizedByteArrayOutputStream(); for (EscherRecord br : bstore) { byte[] b = new byte[36+8]; br.serialize(0, b); @@ -114,8 +117,7 @@ public final class PPDrawingGroup extends RecordAtom { out.write(dgghead); // Finally, write out the children - out.write(bout.toByteArray()); - + bout.writeTo(out); } public EscherContainerRecord getDggContainer(){ diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java index 1ee2403cf7..4e47cb7195 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java @@ -17,24 +17,23 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.TreeMap; import java.util.function.Supplier; import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; import org.apache.poi.util.GenericRecordUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; +import org.apache.poi.util.LittleEndianConsts; /** * General holder for PersistPtrFullBlock and PersistPtrIncrementalBlock @@ -54,14 +53,14 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom private final byte[] _header; private byte[] _ptrData; // Will need to update this once we allow updates to _slideLocations - private long _type; + private final long _type; /** * Holds the lookup for slides to their position on disk. * You always need to check the most recent PersistPtrHolder * that knows about a given slide to find the right location */ - private Map<Integer,Integer> _slideLocations; + private final Map<Integer,Integer> _slideLocations; private static final BitField persistIdFld = BitFieldFactory.getInstance(0X000FFFFF); private static final BitField cntPersistFld = BitFieldFactory.getInstance(0XFFF00000); @@ -185,51 +184,47 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom } private void normalizePersistDirectory() { - TreeMap<Integer,Integer> orderedSlideLocations = new TreeMap<>(_slideLocations); - - @SuppressWarnings("resource") - BufAccessBAOS bos = new BufAccessBAOS(); // NOSONAR - byte[] intbuf = new byte[4]; - int lastPersistEntry = -1; - int lastSlideId = -1; - for (Entry<Integer,Integer> me : orderedSlideLocations.entrySet()) { - int nextSlideId = me.getKey(); - int offset = me.getValue(); - try { - // Building the info block - // First 20 bits = offset number = slide ID (persistIdFld, i.e. first slide ID of a continuous group) - // Remaining 12 bits = offset count = 1 (cntPersistFld, i.e. continuous entries in a group) - - if (lastSlideId+1 == nextSlideId) { - // use existing PersistDirectoryEntry, need to increase entry count - assert(lastPersistEntry != -1); - int infoBlock = LittleEndian.getInt(bos.getBuf(), lastPersistEntry); - int entryCnt = cntPersistFld.getValue(infoBlock); - infoBlock = cntPersistFld.setValue(infoBlock, entryCnt+1); - LittleEndian.putInt(bos.getBuf(), lastPersistEntry, infoBlock); - } else { - // start new PersistDirectoryEntry - lastPersistEntry = bos.size(); - int infoBlock = persistIdFld.setValue(0, nextSlideId); - infoBlock = cntPersistFld.setValue(infoBlock, 1); - LittleEndian.putInt(intbuf, 0, infoBlock); - bos.write(intbuf); - } - // Add to the ptrData offset lookup hash - LittleEndian.putInt(intbuf, 0, offset); - bos.write(intbuf); - lastSlideId = nextSlideId; - } catch (IOException e) { - // ByteArrayOutputStream is very unlikely throwing a IO exception (maybe because of OOM ...) - throw new HSLFException(e); - } - } + // Building the info block + // First 20 bits = offset number = slide ID (persistIdFld, i.e. first slide ID of a continuous group) + // Remaining 12 bits = offset count = 1 (cntPersistFld, i.e. continuous entries in a group) + // + // the info block is then followed by the slide offset (32 bits) + + int[] infoBlocks = new int[_slideLocations.size()*2]; + int lastSlideId = -1; + int lastPersistIdx = 0; + int lastIdx = -1; + int entryCnt = 0; + int baseSlideId = -1; + + Iterable<Entry<Integer,Integer>> iter = _slideLocations.entrySet().stream() + .sorted(Comparator.comparingInt(Entry::getKey))::iterator; + for (Entry<Integer, Integer> me : iter) { + int nextSlideId = me.getKey(); + if (lastSlideId + 1 < nextSlideId) { + // start new PersistDirectoryEntry + lastPersistIdx = ++lastIdx; + entryCnt = 0; + baseSlideId = nextSlideId; + } + + int infoBlock = persistIdFld.setValue(0, baseSlideId); + infoBlock = cntPersistFld.setValue(infoBlock, ++entryCnt); + infoBlocks[lastPersistIdx] = infoBlock; + // add the offset + infoBlocks[++lastIdx] = me.getValue(); + + lastSlideId = nextSlideId; + } - // Save the new ptr data - _ptrData = bos.toByteArray(); + // Save the new ptr data + _ptrData = new byte[(lastIdx+1)*LittleEndianConsts.INT_SIZE]; + for (int idx = 0; idx<=lastIdx; idx++) { + LittleEndian.putInt(_ptrData, idx*LittleEndianConsts.INT_SIZE, infoBlocks[idx]); + } - // Update the atom header - LittleEndian.putInt(_header,4,bos.size()); + // Update the atom header + LittleEndian.putInt(_header, 4, _ptrData.length); } /** @@ -243,12 +238,6 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom out.write(_ptrData); } - private static class BufAccessBAOS extends ByteArrayOutputStream { - public byte[] getBuf() { - return buf; - } - } - @Override public Map<String, Supplier<?>> getGenericProperties() { return GenericRecordUtil.getGenericProperties( diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java index 635ad85b28..98e48067c2 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -25,6 +24,7 @@ import java.util.Arrays; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.ArrayUtil; import org.apache.poi.util.LittleEndian; @@ -226,8 +226,8 @@ public abstract class RecordContainer extends Record * @param out the stream to write to */ public void writeOut(byte headerA, byte headerB, long type, Record[] children, OutputStream out) throws IOException { - // Create a ByteArrayOutputStream to hold everything in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // Create a UnsynchronizedByteArrayOutputStream to hold everything in + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); // Write out our header, less the size baos.write(new byte[] {headerA,headerB}); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java index de2b28c311..e758d57fce 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java @@ -17,7 +17,8 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; +import static org.apache.logging.log4j.util.Unbox.box; + import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -26,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.hslf.model.textproperties.TextPropCollection; import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType; @@ -34,8 +36,6 @@ import org.apache.poi.util.HexDump; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; -import static org.apache.logging.log4j.util.Unbox.box; - /** * A StyleTextPropAtom (type 4001). Holds basic character properties * (bold, italic, underline, font size etc) and paragraph properties @@ -55,7 +55,7 @@ public final class StyleTextPropAtom extends RecordAtom { //arbitrarily selected; may need to increase private static final int MAX_RECORD_LENGTH = 1_000_000; - private byte[] _header; + private final byte[] _header; private byte[] reserved; private byte[] rawContents; // Holds the contents between write-outs @@ -312,7 +312,7 @@ public final class StyleTextPropAtom extends RecordAtom { // Only update the style bytes, if the styles have been potentially // changed - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); // First up, we need to serialise the paragraph properties for(TextPropCollection tpc : paragraphStyles) { diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java index 5de317cc0c..a9b083b236 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java @@ -19,7 +19,6 @@ package org.apache.poi.hslf.record; import static org.apache.poi.util.BitFieldFactory.getInstance; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -28,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.model.textproperties.HSLFTabStop; import org.apache.poi.hslf.model.textproperties.HSLFTabStopPropCollection; import org.apache.poi.util.BitField; @@ -120,7 +120,7 @@ public final class TextRulerAtom extends RecordAtom { */ @Override public void writeOut(final OutputStream out) throws IOException { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(200); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(200); final LittleEndianOutputStream lbos = new LittleEndianOutputStream(bos); int mask = 0; mask |= writeIf(lbos, numLevels, C_LEVELS); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java index fdc16db465..1071422e3b 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -26,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.GenericRecordUtil; import org.apache.poi.util.IOUtils; @@ -46,7 +46,7 @@ public final class TextSpecInfoAtom extends RecordAtom { /** * Record header. */ - private byte[] _header; + private final byte[] _header; /** * Record data. @@ -112,7 +112,7 @@ public final class TextSpecInfoAtom extends RecordAtom { */ public void reset(int size){ TextSpecInfoRun sir = new TextSpecInfoRun(size); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { sir.writeOut(bos); } catch (IOException e) { @@ -127,13 +127,11 @@ public final class TextSpecInfoAtom extends RecordAtom { /** * Adapts the size by enlarging the last {@link TextSpecInfoRun} * or chopping the runs to the given length - * - * @param size */ public void setParentSize(int size) { assert(size > 0); int covered = 0; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); TextSpecInfoRun[] runs = getTextSpecInfoRuns(); assert(runs.length > 0); for (int i=0; i<runs.length && covered < size; i++) { diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java index a396cd95bf..ee419faf31 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -26,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hslf.exceptions.HSLFException; @@ -64,7 +64,7 @@ public final class TxMasterStyleAtom extends RecordAtom { private static final long _type = RecordTypes.TxMasterStyleAtom.typeID; - private byte[] _header; + private final byte[] _header; private byte[] _data; private List<TextPropCollection> paragraphStyles; @@ -89,6 +89,7 @@ public final class TxMasterStyleAtom extends RecordAtom { * @return type of this record * @see RecordTypes#TxMasterStyleAtom */ + @Override public long getRecordType() { return _type; } @@ -97,6 +98,7 @@ public final class TxMasterStyleAtom extends RecordAtom { * Write the contents of the record back, so it can be written * to disk */ + @Override public void writeOut(OutputStream out) throws IOException { // Write out the (new) header out.write(_header); @@ -126,7 +128,7 @@ public final class TxMasterStyleAtom extends RecordAtom { /** * Return type of the text. - * Must be a constant defined in <code>TextHeaderAtom</code> + * Must be a constant defined in {@code TextHeaderAtom} * * @return type of the text * @see TextHeaderAtom @@ -187,7 +189,7 @@ public final class TxMasterStyleAtom extends RecordAtom { int type = getTextType(); try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); int levels = paragraphStyles.size(); leos.writeShort(levels); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java index 60f864188d..3bc921dc96 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java @@ -16,7 +16,6 @@ ==================================================================== */ package org.apache.poi.hslf.usermodel; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -25,8 +24,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.poi.common.usermodel.GenericRecord; import org.apache.poi.hslf.record.ExOleObjStg; import org.apache.poi.sl.usermodel.ObjectData; @@ -35,12 +33,10 @@ import org.apache.poi.sl.usermodel.ObjectData; * A class that represents object data embedded in a slide show. */ public class HSLFObjectData implements ObjectData, GenericRecord { - private static final Logger LOG = LogManager.getLogger(HSLFObjectData.class); - /** * The record that contains the object data. */ - private ExOleObjStg storage; + private final ExOleObjStg storage; /** * Creates the object data wrapping the record that contains the object data. @@ -55,10 +51,12 @@ public class HSLFObjectData implements ObjectData, GenericRecord { public InputStream getInputStream() { return storage.getData(); } - + @Override - public OutputStream getOutputStream() throws IOException { - return new ByteArrayOutputStream(100000) { + public OutputStream getOutputStream() { + // can't use UnsynchronizedByteArrayOutputStream here, because it's final + return new ByteArrayOutputStream() { + @Override public void close() throws IOException { setData(getBytes()); } @@ -71,7 +69,7 @@ public class HSLFObjectData implements ObjectData, GenericRecord { * @param data the embedded data. */ public void setData(byte[] data) throws IOException { - storage.setData(data); + storage.setData(data); } /** diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java index 344e038374..a5414672b9 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java @@ -17,11 +17,12 @@ package org.apache.poi.hslf.usermodel; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.AbstractByteArrayOutputStream; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherContainerRecord; @@ -51,7 +52,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha private ExEmbed _exEmbed; /** - * Create a new <code>OLEShape</code> + * Create a new {@code OLEShape} * * @param data the picture data */ @@ -60,7 +61,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } /** - * Create a new <code>OLEShape</code> + * Create a new {@code OLEShape} * * @param data the picture data * @param parent the parent shape @@ -70,10 +71,10 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } /** - * Create a <code>OLEShape</code> object + * Create a {@code OLEShape} object * - * @param escherRecord the <code>EscherSpContainer</code> record which holds information about - * this picture in the <code>Slide</code> + * @param escherRecord the {@code EscherSpContainer} record which holds information about + * this picture in the {@code Slide} * @param parent the parent shape of this picture */ public HSLFObjectShape(EscherContainerRecord escherRecord, ShapeContainer<HSLFShape,HSLFTextParagraph> parent){ @@ -100,7 +101,11 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha EscherContainerRecord ecr = getSpContainer(); EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID); - spRecord.setFlags(spRecord.getFlags()|EscherSpRecord.FLAG_OLESHAPE); + if (spRecord != null) { + spRecord.setFlags(spRecord.getFlags() | EscherSpRecord.FLAG_OLESHAPE); + } else { + LOG.atWarn().log("Ole shape record not found."); + } HSLFEscherClientDataRecord cldata = getClientData(true); ExObjRefAtom uer = null; @@ -123,6 +128,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha * * @return the unique identifier for the OLE object */ + @Override public HSLFObjectData getObjectData(){ HSLFSlideShow ppt = getSheet().getSlideShow(); HSLFObjectData[] ole = ppt.getEmbeddedObjects(); @@ -184,7 +190,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } } } - + if (_exEmbed == null && create) { _exEmbed = new ExEmbed(); _exEmbed.getExOleObjAtom().setObjID(id); @@ -193,8 +199,8 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } return _exEmbed; } - - + + /** * Returns the instance name of the embedded object, e.g. "Document" or "Workbook". * @@ -231,45 +237,51 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } } - public OutputStream updateObjectData(final Application application, final ObjectMetaData metaData) throws IOException { + @Override + public OutputStream updateObjectData(final Application application, final ObjectMetaData metaData) { final ObjectMetaData md = (application != null) ? application.getMetaData() : metaData; if (md == null) { throw new RuntimeException("either application or metaData needs to be set"); } - return new ByteArrayOutputStream(100000) { + // can't use UnsynchronizedByteArrayOutputStream here, because it's final + return new ByteArrayOutputStream() { + @Override public void close() throws IOException { - final FileMagic fm = FileMagic.valueOf(this.buf); - final ByteArrayInputStream bis = new ByteArrayInputStream(this.buf, 0, this.count); - final HSLFSlideShow ppt = getSheet().getSlideShow(); - - try (POIFSFileSystem poifs = (fm == FileMagic.OLE2) ? new POIFSFileSystem(bis) : new POIFSFileSystem()) { - if (fm != FileMagic.OLE2) { - poifs.createDocument(bis, md.getOleEntry()); - } + addUpdatedData(md,this); + } + }; + } - Ole10Native.createOleMarkerEntry(poifs); - - poifs.getRoot().setStorageClsid(md.getClassID()); - - int oid = getObjectID(); - if (oid == 0) { - // assign new embedding - oid = ppt.addEmbed(poifs); - setObjectID(oid); - } else { - final HSLFObjectData od = getObjectData(); - if (od != null) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(this.size()+1000); - poifs.writeFilesystem(bos); - od.setData(bos.toByteArray()); - } + private void addUpdatedData(ObjectMetaData md, AbstractByteArrayOutputStream baos) throws IOException { + try (InputStream bis = FileMagic.prepareToCheckMagic(baos.toInputStream())) { + final FileMagic fm = FileMagic.valueOf(bis); + try (POIFSFileSystem poifs = (fm == FileMagic.OLE2) ? new POIFSFileSystem(bis) : new POIFSFileSystem()) { + if (fm != FileMagic.OLE2) { + poifs.createDocument(bis, md.getOleEntry()); + } + baos.reset(); + + Ole10Native.createOleMarkerEntry(poifs); + + poifs.getRoot().setStorageClsid(md.getClassID()); + + int oid = getObjectID(); + if (oid == 0) { + // assign new embedding + oid = getSheet().getSlideShow().addEmbed(poifs); + setObjectID(oid); + } else { + final HSLFObjectData od = getObjectData(); + if (od != null) { + poifs.writeFilesystem(baos); + od.setData(baos.toByteArray()); } - - setProgId(md.getProgId()); - setFullName(md.getObjectName()); } + + setProgId(md.getProgId()); + setFullName(md.getObjectName()); } - }; + } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java index 5e2e5d9ebc..e2a3b51155 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java @@ -17,8 +17,9 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.logging.log4j.util.Unbox.box; + import java.awt.Dimension; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; @@ -33,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.POIDocument; @@ -66,8 +68,6 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.Internal; import org.apache.poi.util.Units; -import static org.apache.logging.log4j.util.Unbox.box; - /** * This class is a friendly wrapper on top of the more scary HSLFSlideShow. * @@ -708,9 +708,9 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh } /** - * Create a blank <code>Slide</code>. + * Create a blank {@code Slide}. * - * @return the created <code>Slide</code> + * @return the created {@code Slide} */ @Override public HSLFSlide createSlide() { @@ -882,6 +882,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh * * @since POI 4.1.0 */ + @Override public HSLFFontInfo addFont(InputStream fontData) throws IOException { Document doc = getDocumentRecord(); doc.getDocumentAtom().setSaveWithFonts(true); @@ -893,7 +894,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh * * @param idx * 0-based index of the font - * @return of an instance of <code>PPFont</code> or <code>null</code> if not + * @return of an instance of {@code PPFont} or {@code null} if not * found */ public HSLFFontInfo getFont(int idx) { @@ -1040,7 +1041,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh ExOleObjStg exOleObjStg = new ExOleObjStg(); try { Ole10Native.createOleMarkerEntry(poiData); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); poiData.writeFilesystem(bos); exOleObjStg.setData(bos.toByteArray()); } catch (IOException e) { @@ -1246,7 +1247,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh } @Override - public EncryptionInfo getEncryptionInfo() throws IOException { + public EncryptionInfo getEncryptionInfo() { return getSlideShowImpl().getEncryptionInfo(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java index f697e859ce..62a9d997b1 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java @@ -23,17 +23,18 @@ import static org.apache.poi.hslf.usermodel.HSLFSlideShow.PP95_DOCUMENT; import static org.apache.poi.hslf.usermodel.HSLFSlideShow.PP97_DOCUMENT; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; +import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -44,6 +45,8 @@ import java.util.Objects; import java.util.TreeMap; import java.util.stream.Collectors; +import org.apache.commons.collections4.IteratorUtils; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.POIDocument; @@ -659,7 +662,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { /** * Writes out the slideshow to the currently open file. * <p> - * <p>This will fail (with an {@link IllegalStateException} if the + * This will fail (with an {@link IllegalStateException} if the * slideshow was opened read-only, opened from an {@link InputStream} * instead of a File, or if this is not the root document. For those cases, * you must use {@link #write(OutputStream)} or {@link #write(File)} to @@ -686,7 +689,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * of this class. * <p>This will write out only the common OLE2 streams. If you require all * streams to be written out, use {@link #write(File, boolean)} - * with <code>preserveNodes</code> set to <code>true</code>. + * with {@code preserveNodes} set to {@code true}. * * @param newFile The File to write to. * @throws IOException If there is an unexpected IOException from writing to the File @@ -701,7 +704,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * Writes out the slideshow file the is represented by an instance * of this class. * If you require all streams to be written out (eg Marcos, embeded - * documents), then set <code>preserveNodes</code> set to <code>true</code> + * documents), then set {@code preserveNodes} set to {@code true} * * @param newFile The File to write to. * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones? @@ -724,7 +727,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * of this class. * <p>This will write out only the common OLE2 streams. If you require all * streams to be written out, use {@link #write(OutputStream, boolean)} - * with <code>preserveNodes</code> set to <code>true</code>. + * with {@code preserveNodes} set to {@code true}. * * @param out The OutputStream to write to. * @throws IOException If there is an unexpected IOException from @@ -740,7 +743,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * Writes out the slideshow file the is represented by an instance * of this class. * If you require all streams to be written out (eg Marcos, embeded - * documents), then set <code>preserveNodes</code> set to <code>true</code> + * documents), then set {@code preserveNodes} set to {@code true} * * @param out The OutputStream to write to. * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones? @@ -776,16 +779,16 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { // Write out the Property Streams writeProperties(outFS, writtenEntries); - BufAccessBAOS baos = new BufAccessBAOS(); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { - // For position dependent records, hold where they were and now are - // As we go along, update, and hand over, to any Position Dependent - // records we happen across - updateAndWriteDependantRecords(baos, null); + // For position dependent records, hold where they were and now are + // As we go along, update, and hand over, to any Position Dependent + // records we happen across + updateAndWriteDependantRecords(baos, null); - // Update our cached copy of the bytes that make up the PPT stream - _docstream = baos.toByteArray(); - baos.close(); + // Update our cached copy of the bytes that make up the PPT stream + _docstream = baos.toByteArray(); + } // Write the PPT stream into the POIFS layer ByteArrayInputStream bais = new ByteArrayInputStream(_docstream); @@ -796,20 +799,18 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { currentUser.writeToFS(outFS); writtenEntries.add("Current User"); - if (_pictures.size() > 0) { - BufAccessBAOS pict = new BufAccessBAOS(); - for (HSLFPictureData p : _pictures) { - int offset = pict.size(); - p.write(pict); - encryptedSS.encryptPicture(pict.getBuf(), offset); - } - outFS.createOrUpdateDocument( - new ByteArrayInputStream(pict.getBuf(), 0, pict.size()), "Pictures" + if (!_pictures.isEmpty()) { + Enumeration<InputStream> pictEnum = IteratorUtils.asEnumeration( + _pictures.stream().map(data -> encryptOnePicture(encryptedSS, data)).iterator() ); - writtenEntries.add("Pictures"); - pict.close(); - } + try (SequenceInputStream sis = new SequenceInputStream(pictEnum)) { + outFS.createOrUpdateDocument(sis, "Pictures"); + writtenEntries.add("Pictures"); + } catch (IllegalStateException e) { + throw (IOException)e.getCause(); + } + } } // If requested, copy over any other streams we spot, eg Macros @@ -818,6 +819,17 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { } } + private static InputStream encryptOnePicture(HSLFSlideShowEncrypted encryptedSS, HSLFPictureData data) { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + data.write(baos); + byte[] pictBytes = baos.toByteArray(); + encryptedSS.encryptPicture(pictBytes, 0); + return new ByteArrayInputStream(pictBytes); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + @Override public EncryptionInfo getEncryptionInfo() { @@ -1017,12 +1029,6 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { super.replaceDirectory(newDirectory); } - private static class BufAccessBAOS extends ByteArrayOutputStream { - public byte[] getBuf() { - return buf; - } - } - private static class CountingOS extends OutputStream { int count; diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java b/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java index 6cf92111a6..7915ca5c66 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java @@ -17,8 +17,9 @@ package org.apache.poi.hsmf.datatypes; +import static org.apache.logging.log4j.util.Unbox.box; + import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -30,6 +31,7 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hsmf.datatypes.PropertyValue.BooleanPropertyValue; @@ -47,8 +49,6 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndian.BufferUnderrunException; -import static org.apache.logging.log4j.util.Unbox.box; - /** * <p> * A Chunk which holds (single) fixed-length properties, and pointer to the @@ -76,13 +76,13 @@ public abstract class PropertiesChunk extends Chunk { * Holds properties, indexed by type. If a property is multi-valued, or * variable length, it will be held via a {@link ChunkBasedPropertyValue}. */ - private Map<MAPIProperty, PropertyValue> properties = new HashMap<>(); + private final Map<MAPIProperty, PropertyValue> properties = new HashMap<>(); /** * The ChunkGroup that these properties apply to. Used when matching chunks * to variable sized and multi-valued properties */ - private ChunkGroup parentGroup; + private final ChunkGroup parentGroup; /** * Creates a Properties Chunk. @@ -254,7 +254,7 @@ public abstract class PropertiesChunk extends Chunk { } // Wrap and store - PropertyValue propVal = null; + PropertyValue propVal; if (isPointer) { // We'll match up the chunk later propVal = new ChunkBasedPropertyValue(prop, flags, data, type); @@ -302,16 +302,17 @@ public abstract class PropertiesChunk extends Chunk { * If an I/O error occurs. */ public void writeProperties(DirectoryEntry directory) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - List<PropertyValue> values = writeProperties(baos); - baos.close(); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + List<PropertyValue> values = writeProperties(baos); - // write the header data with the properties declaration - directory.createDocument(PropertiesChunk.NAME, - new ByteArrayInputStream(baos.toByteArray())); + // write the header data with the properties declaration + try (InputStream is = baos.toInputStream()) { + directory.createDocument(PropertiesChunk.NAME, is); + } - // write the property values - writeNodeData(directory, values); + // write the property values + writeNodeData(directory, values); + } } /** diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java index 82baf52036..c56ae3f17f 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java @@ -190,7 +190,7 @@ public class HwmfEscape implements HwmfRecord { } public interface HwmfEscapeData { - public int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException; + int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java index 19fda80509..fb24af7cb4 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java @@ -17,13 +17,13 @@ package org.apache.poi.hwmf.usermodel; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hwmf.record.HwmfEscape; import org.apache.poi.hwmf.record.HwmfEscape.EscapeFunction; import org.apache.poi.hwmf.record.HwmfEscape.WmfEscapeEMF; @@ -120,7 +120,7 @@ public class HwmfEmbeddedIterator implements Iterator<HwmfEmbedded> { final HwmfEmbedded emb = new HwmfEmbedded(); emb.setEmbeddedType(HwmfEmbeddedType.EMF); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { for (;;) { bos.write(img.getEmfData()); @@ -132,8 +132,8 @@ public class HwmfEmbeddedIterator implements Iterator<HwmfEmbedded> { return emb; } } - } catch (IOException e) { - // ByteArrayOutputStream doesn't throw IOException + } catch (IOException ignored) { + // UnsynchronizedByteArrayOutputStream doesn't throw IOException return null; } finally { emb.setData(bos.toByteArray()); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java index 8fb9055bc5..71079c3b1b 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java @@ -17,8 +17,6 @@ package org.apache.poi.hwpf.dev; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -31,6 +29,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocumentCore; import org.apache.poi.hwpf.HWPFOldDocument; @@ -262,12 +261,11 @@ public final class HWPFLister { private static HWPFDocumentCore writeOutAndReadBack( HWPFDocumentCore original ) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream( 4096 ); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { original.write( baos ); - ByteArrayInputStream bais = new ByteArrayInputStream( - baos.toByteArray() ); - return loadDoc( bais ); + try (InputStream is = baos.toInputStream()) { + return loadDoc(is); + } } catch ( IOException e ) { throw new RuntimeException( e ); @@ -388,7 +386,7 @@ public final class HWPFLister { } } - public void dumpFileSystem() throws Exception { + public void dumpFileSystem() { System.out.println( dumpFileSystem( _doc.getDirectory() ) ); } @@ -439,8 +437,7 @@ public final class HWPFLister { } } - public void dumpPapx( boolean withProperties, boolean withSprms ) - throws Exception { + public void dumpPapx( boolean withProperties, boolean withSprms ) { if ( _doc instanceof HWPFDocument ) { System.out.println( "binary PAP pages " ); @@ -514,8 +511,8 @@ public final class HWPFLister { if ( dumpAssotiatedPapx ) { boolean hasAssotiatedPapx = false; for ( PAPX papx : _doc.getParagraphTable().getParagraphs() ) { - if ( papx.getStart() <= endOfParagraphCharOffset.intValue() - && endOfParagraphCharOffset.intValue() < papx + if ( papx.getStart() <= endOfParagraphCharOffset + && endOfParagraphCharOffset < papx .getEnd() ) { hasAssotiatedPapx = true; System.out.println( "* " + papx ); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java index 913b4950ae..d4283a612b 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java @@ -18,13 +18,13 @@ package org.apache.poi.hwpf.usermodel; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.List; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherBSERecord; @@ -37,6 +37,7 @@ import org.apache.poi.ddf.EscherRecord; import org.apache.poi.hwpf.model.PICF; import org.apache.poi.hwpf.model.PICFAndOfficeArtData; import org.apache.poi.sl.image.ImageHeaderPNG; +import org.apache.poi.util.IOUtils; import org.apache.poi.util.StringUtil; /** @@ -120,10 +121,10 @@ public final class Picture { } } - private void fillImageContent() - { - if ( content != null && content.length > 0 ) + private void fillImageContent() { + if ( content != null && content.length > 0 ) { return; + } byte[] rawContent = getRawContent(); @@ -134,33 +135,21 @@ public final class Picture { * similarity in the data block contents. */ if ( matchSignature( rawContent, COMPRESSED1, 32 ) - || matchSignature( rawContent, COMPRESSED2, 32 ) ) - { - try - { - InflaterInputStream in = new InflaterInputStream( - new ByteArrayInputStream( rawContent, 33, - rawContent.length - 33 ) ); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - int readBytes; - while ( ( readBytes = in.read( buf ) ) > 0 ) - { - out.write( buf, 0, readBytes ); - } + || matchSignature( rawContent, COMPRESSED2, 32 ) ) { + try (ByteArrayInputStream bis = new ByteArrayInputStream( rawContent, 33, rawContent.length - 33 ); + InflaterInputStream in = new InflaterInputStream(bis); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + + IOUtils.copy(in, out); content = out.toByteArray(); - } - catch ( IOException e ) - { + } catch (IOException e) { /* * Problems reading from the actual ByteArrayInputStream should * never happen so this will only ever be a ZipException. */ LOGGER.atInfo().withThrowable(e).log("Possibly corrupt compression or non-compressed data"); } - } - else - { + } else { // Raw data is not compressed. content = new ImageHeaderPNG(rawContent).extractPNG(); } @@ -186,8 +175,8 @@ public final class Picture { byte[] jpegContent = getContent(); int pointer = 2; - int firstByte = jpegContent[pointer]; - int secondByte = jpegContent[pointer + 1]; + int firstByte; + int secondByte; int endOfPicture = jpegContent.length; while ( pointer < endOfPicture - 1 ) { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java b/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java index 302eacc928..6a1a830a0b 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java @@ -26,7 +26,7 @@ import java.io.File; import java.io.PrintStream; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.Test; public class TestVSDDumper { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java b/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java index 6d39586729..d52873779c 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java @@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.geom.Point2D; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -34,6 +33,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hemf.record.emf.HemfComment; import org.apache.poi.hemf.record.emf.HemfComment.EmfComment; @@ -52,7 +52,6 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; import org.junit.jupiter.api.Test; -@SuppressWarnings("StatementWithEmptyBody") public class TestHemfPicture { private static final POIDataSamples ss_samples = POIDataSamples.getSpreadSheetInstance(); @@ -286,10 +285,10 @@ public class TestHemfPicture { @Test void testInfiniteLoopOnByteArray() throws Exception { try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(is, bos); - HemfPicture pic = new HemfPicture(new ByteArrayInputStream(bos.toByteArray())); + HemfPicture pic = new HemfPicture(bos.toInputStream()); assertThrows(RecordFormatException.class, () -> pic.forEach(r -> {})); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java index d0359a6d2e..5717e5157d 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java @@ -21,15 +21,16 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hmef.attribute.MAPIAttribute; import org.apache.poi.hmef.attribute.MAPIRtfAttribute; @@ -83,10 +84,10 @@ public final class TestHMEFMessage { assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_MAPIPROPERTIES)); // Check the order - assertEquals(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty()); - assertEquals(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty()); - assertEquals(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty()); - assertEquals(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty()); + assertSame(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty()); + assertSame(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty()); + assertSame(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty()); + assertSame(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty()); // Check some that aren't there assertNull(msg.getMessageAttribute(TNEFProperty.ID_AIDOWNER)); @@ -168,7 +169,7 @@ public final class TestHMEFMessage { @Test void testNoData() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); // Header LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out); @@ -176,16 +177,14 @@ public final class TestHMEFMessage { // field LittleEndian.putUShort(0, out); - byte[] bytes = out.toByteArray(); - InputStream str = new ByteArrayInputStream(bytes); - HMEFMessage msg = new HMEFMessage(str); + HMEFMessage msg = new HMEFMessage(out.toInputStream()); assertNull(msg.getSubject()); assertNull(msg.getBody()); } @Test void testInvalidLevel() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); // Header LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out); @@ -196,10 +195,9 @@ public final class TestHMEFMessage { // invalid level LittleEndian.putUShort(90, out); - InputStream str = new ByteArrayInputStream(out.toByteArray()); IllegalStateException ex = assertThrows( IllegalStateException.class, - () -> new HMEFMessage(str) + () -> new HMEFMessage(out.toInputStream()) ); assertEquals("Unhandled level 90", ex.getMessage()); } @@ -226,7 +224,7 @@ public final class TestHMEFMessage { MAPIStringAttribute propE28b = (MAPIStringAttribute)msg.getMessageMAPIAttribute(propE28); assertNotNull(propE28b); - assertEquals(MAPIStringAttribute.class, propE28b.getClass()); + assertSame(MAPIStringAttribute.class, propE28b.getClass()); assertEquals("Zimbra - Mark Rogers", propE28b.getDataString().substring(10)); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java index a24901a96d..49ef65cb83 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java @@ -28,7 +28,7 @@ import java.io.File; import java.io.PrintStream; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.Test; public class TestHMEFDumper { @@ -38,13 +38,13 @@ public class TestHMEFDumper { } @Test - void main() throws Exception { + void main() { File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat"); assertDoesNotThrow(() -> doMain(file.getAbsolutePath())); } @Test - void mainFull() throws Exception { + void mainFull() { File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat"); assertDoesNotThrow(() -> doMain("--full", file.getAbsolutePath())); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java index 4a786f5bca..81912bbba5 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java @@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.TempFile; import org.junit.jupiter.api.Test; @@ -62,13 +62,13 @@ public class TestHMEFContentsExtractor { POIDataSamples samples = POIDataSamples.getHMEFInstance(); File winmailTNEFFile = samples.getFile("quick-winmail.dat"); HMEFContentsExtractor extractor = new HMEFContentsExtractor(winmailTNEFFile); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - extractor.extractMessageBody(out); - assertTrue(out.size() > 0); - byte[] expectedMagic = new byte[] { '{', '\\', 'r', 't', 'f' }; - byte[] magic = Arrays.copyOf(out.toByteArray(), 5); - assertArrayEquals(expectedMagic, magic, "RTF magic number"); - out.close(); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + extractor.extractMessageBody(out); + assertTrue(out.size() > 0); + byte[] expectedMagic = new byte[]{'{', '\\', 'r', 't', 'f'}; + byte[] magic = Arrays.copyOf(out.toByteArray(), 5); + assertArrayEquals(expectedMagic, magic, "RTF magic number"); + } } @Test diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java index 82b3a46091..9a08f18eb6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java @@ -17,12 +17,11 @@ package org.apache.poi.hslf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -50,32 +49,30 @@ public class HSLFTestDataSamples { } /** - * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back + * Writes a slideshow to a {@code UnsynchronizedByteArrayOutputStream} and reads it back * from a {@code ByteArrayInputStream}.<p> * Useful for verifying that the serialisation round trip */ public static HSLFSlideShowImpl writeOutAndReadBack(HSLFSlideShowImpl original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSLFSlideShowImpl(bais); + try (InputStream is = baos.toInputStream()) { + return new HSLFSlideShowImpl(is); + } } catch (IOException e) { throw new RuntimeException(e); } } /** - * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back + * Writes a slideshow to a {@code UnsynchronizedByteArrayOutputStream} and reads it back * from a {@code ByteArrayInputStream}.<p> * Useful for verifying that the serialisation round trip */ public static HSLFSlideShow writeOutAndReadBack(HSLFSlideShow original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSLFSlideShow(bais); + return new HSLFSlideShow(baos.toInputStream()); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java index 774b1fb91b..2d795452b9 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java @@ -21,22 +21,18 @@ package org.apache.poi.hslf; +import static org.apache.poi.POIDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -47,23 +43,11 @@ import org.junit.jupiter.api.Test; * which are part of the scratchpad (not main) */ public final class TestPOIDocumentScratchpad { - // The POI Documents to work on - private POIDocument doc; - private POIDocument doc2; - - /** - * Set things up, using a PowerPoint document and - * a Word Document for our testing - */ - @BeforeEach - void setUp() throws IOException { - doc = new HSLFSlideShowImpl(POIDataSamples.getSlideShowInstance().openResourceAsStream("basic_test_ppt_file.ppt")); - doc2 = HWPFTestDataSamples.openSampleFile("test2.doc"); - } - @Test - void testReadProperties() { - testReadPropertiesHelper(doc); + void testReadProperties() throws IOException { + try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt")) { + testReadPropertiesHelper(doc); + } } private void testReadPropertiesHelper(POIDocument docPH) { @@ -77,49 +61,46 @@ public final class TestPOIDocumentScratchpad { } @Test - void testReadProperties2() { - // Check again on the word one - assertNotNull(doc2.getDocumentSummaryInformation()); - assertNotNull(doc2.getSummaryInformation()); - - assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor()); - assertEquals("", doc2.getSummaryInformation().getKeywords()); - assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); + void testReadProperties2() throws IOException { + try (POIDocument doc2 = HWPFTestDataSamples.openSampleFile("test2.doc")) { + // Check again on the word one + assertNotNull(doc2.getDocumentSummaryInformation()); + assertNotNull(doc2.getSummaryInformation()); + + assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor()); + assertEquals("", doc2.getSummaryInformation().getKeywords()); + assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); + } } @Test void testWriteProperties() throws IOException { // Just check we can write them back out into a filesystem - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.writeProperties(outFS); - - // Should now hold them - assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)); - outFS.close(); + try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); + POIFSFileSystem outFS = new POIFSFileSystem()) { + doc.writeProperties(outFS); + + // Should now hold them + assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); + assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)); + } } @Test void testWriteReadProperties() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // Write them out - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.writeProperties(outFS); - outFS.writeFilesystem(baos); - - // Create a new version - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem inFS = new POIFSFileSystem(bais); - - // Check they're still there - POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS); - ppt.readProperties(); - - // Delegate test - testReadPropertiesHelper(ppt); - - ppt.close(); - inFS.close(); + try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); + POIFSFileSystem outFS = new POIFSFileSystem()) { + doc.writeProperties(outFS); + + // Check they're still there + try (POIFSFileSystem inFS = writeOutAndReadBack(outFS); + POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS)) { + ppt.readProperties(); + + // Delegate test + testReadPropertiesHelper(ppt); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java index 5aec58964a..687888a69a 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java @@ -25,12 +25,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -56,7 +55,7 @@ public final class TestReWrite { HSLFSlideShowImpl hss = new HSLFSlideShowImpl(pfs)) { // Write out to a byte array, and to a temp file - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); hss.write(baos); final File file = TempFile.createTempFile("TestHSLF", ".ppt"); @@ -66,8 +65,7 @@ public final class TestReWrite { // Build an input stream of it, and read back as a POIFS from the stream - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - try (POIFSFileSystem npfS = new POIFSFileSystem(bais); + try (POIFSFileSystem npfS = new POIFSFileSystem(baos.toInputStream()); // And the same on the temp file POIFSFileSystem npfF = new POIFSFileSystem(file)) { @@ -97,18 +95,16 @@ public final class TestReWrite { assertNotNull(pfsC.getRoot().getEntry("Macros")); // Write out normally, will loose the macro stream - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); hssC.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - try (POIFSFileSystem pfsNew = new POIFSFileSystem(bais)) { + try (POIFSFileSystem pfsNew = new POIFSFileSystem(baos.toInputStream())) { assertFalse(pfsNew.getRoot().hasEntry("Macros")); } // But if we write out with nodes preserved, will be there baos.reset(); hssC.write(baos, true); - bais = new ByteArrayInputStream(baos.toByteArray()); - try (POIFSFileSystem pfsNew = new POIFSFileSystem(bais)) { + try (POIFSFileSystem pfsNew = new POIFSFileSystem(baos.toInputStream())) { assertTrue(pfsNew.getRoot().hasEntry("Macros")); } } @@ -138,14 +134,11 @@ public final class TestReWrite { assertDoesNotThrow(ss::getNotes); // Now write out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); hss.write(baos); - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - // Use POIFS to query that lot - try (POIFSFileSystem npfs = new POIFSFileSystem(bais)) { + try (POIFSFileSystem npfs = new POIFSFileSystem(baos.toInputStream())) { assertSame(pfs, npfs); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java index 3aca727bee..b2991c1533 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java @@ -18,14 +18,15 @@ package org.apache.poi.hslf; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.POITestCase.assertContains; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; +import org.apache.commons.io.output.CountingOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.record.CurrentUserAtom; import org.apache.poi.hslf.record.PersistPtrHolder; @@ -63,55 +64,50 @@ public final class TestReWriteSanity { @Test void testUserEditAtomsRight() throws Exception { // Write out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ss.write(baos); - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - // Create a new one from that - HSLFSlideShowImpl wss = new HSLFSlideShowImpl(bais); - - // Find the location of the PersistPtrIncrementalBlocks and - // UserEditAtoms - Record[] r = wss.getRecords(); - Map<Integer,Record> pp = new HashMap<>(); - Map<Integer,Object> ue = new HashMap<>(); - ue.put(Integer.valueOf(0),Integer.valueOf(0)); // Will show 0 if first - int pos = 0; - int lastUEPos = -1; - - for (final Record rec : r) { - if(rec instanceof PersistPtrHolder) { - pp.put(Integer.valueOf(pos), rec); - } - if(rec instanceof UserEditAtom) { - ue.put(Integer.valueOf(pos), rec); - lastUEPos = pos; + try (HSLFSlideShowImpl wss = new HSLFSlideShowImpl(baos.toInputStream())) { + + // Find the location of the PersistPtrIncrementalBlocks and + // UserEditAtoms + Record[] r = wss.getRecords(); + Map<Integer, Record> pp = new HashMap<>(); + Map<Integer, Object> ue = new HashMap<>(); + ue.put(0, 0); // Will show 0 if first + int lastUEPos = -1; + + CountingOutputStream cos = new CountingOutputStream(NULL_OUTPUT_STREAM); + for (final Record rec : r) { + int pos = cos.getCount(); + if (rec instanceof PersistPtrHolder) { + pp.put(pos, rec); + } + if (rec instanceof UserEditAtom) { + ue.put(pos, rec); + lastUEPos = pos; + } + + rec.writeOut(cos); } - ByteArrayOutputStream bc = new ByteArrayOutputStream(); - rec.writeOut(bc); - pos += bc.size(); - } - - // Check that the UserEditAtom's point to right stuff - for (final Record rec : r) { - if(rec instanceof UserEditAtom) { - UserEditAtom uea = (UserEditAtom)rec; - int luPos = uea.getLastUserEditAtomOffset(); - int ppPos = uea.getPersistPointersOffset(); + // Check that the UserEditAtom's point to right stuff + for (final Record rec : r) { + if (rec instanceof UserEditAtom) { + UserEditAtom uea = (UserEditAtom) rec; + int luPos = uea.getLastUserEditAtomOffset(); + int ppPos = uea.getPersistPointersOffset(); - assertContains(ue, Integer.valueOf(luPos)); - assertContains(pp, Integer.valueOf(ppPos)); + assertContains(ue, luPos); + assertContains(pp, ppPos); + } } - } - - // Check that the CurrentUserAtom points to the right UserEditAtom - CurrentUserAtom cua = wss.getCurrentUserAtom(); - int listedUEPos = (int)cua.getCurrentEditOffset(); - assertEquals(lastUEPos,listedUEPos); - wss.close(); + // Check that the CurrentUserAtom points to the right UserEditAtom + CurrentUserAtom cua = wss.getCurrentUserAtom(); + int listedUEPos = (int) cua.getCurrentEditOffset(); + assertEquals(lastUEPos, listedUEPos); + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java index 980d6538e8..ca5b1ac380 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java @@ -34,7 +34,7 @@ import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.exceptions.OldPowerPointFormatException; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.parallel.Isolated; diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java index 8ee2010fa7..3ac7adb84d 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java @@ -23,7 +23,7 @@ import java.io.IOException; import java.io.PrintStream; import org.apache.poi.EmptyFileException; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java index bd8d634b12..5525cdf808 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java @@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -35,7 +34,6 @@ import java.util.List; import com.zaxxer.sparsebits.SparseBitSet; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFObjectShape; import org.apache.poi.hslf.usermodel.HSLFSlideShow; @@ -50,7 +48,6 @@ import org.apache.poi.sl.usermodel.ObjectShape; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullOutputStream; import org.junit.jupiter.api.Test; /** diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java index a90c591190..336f6bc4f2 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java @@ -22,9 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFSlide; @@ -33,11 +32,11 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.junit.jupiter.api.Test; /** - * Test <code>MovieShape</code> object. + * Test {@code MovieShape} object. */ public final class TestMovieShape { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); @Test void testCreate() throws Exception { @@ -58,10 +57,10 @@ public final class TestMovieShape { shape.setAutoPlay(false); assertFalse(shape.isAutoPlay()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ppt.write(out); - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); + ppt = new HSLFSlideShow(out.toInputStream()); slide = ppt.getSlides().get(0); shape = (MovieShape)slide.getShapes().get(0); assertEquals(path, shape.getPath()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java index 9c561fb18e..dbab7b9fdc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java @@ -21,13 +21,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFObjectData; import org.apache.poi.hslf.usermodel.HSLFObjectShape; @@ -146,10 +145,10 @@ public final class TestOleEmbedding { slide2.addShape(oleShape2); oleShape2.setAnchor(new Rectangle2D.Double(100,100,100,100)); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); ppt.write(bos); - ppt = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); + ppt = new HSLFSlideShow(bos.toInputStream()); HSLFObjectShape comp = (HSLFObjectShape)ppt.getSlides().get(0).getShapes().get(0); byte[] compData = IOUtils.toByteArray(comp.getObjectData().getInputStream()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java index e47467c2ba..426eee09fb 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java @@ -17,12 +17,16 @@ package org.apache.poi.hslf.model; -import static org.junit.jupiter.api.Assertions.*; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.usermodel.HSLFSlide; +import org.apache.poi.hslf.usermodel.HSLFSlideShow; +import org.apache.poi.hslf.usermodel.HSLFTextBox; +import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.junit.jupiter.api.Test; /** @@ -35,46 +39,46 @@ public final class TestSetBoldItalic { */ @Test void testTextBoxWrite() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide sl = ppt.createSlide(); - HSLFTextRun rt; - - String val = "Hello, World!"; + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide sl = ppt.createSlide(); + HSLFTextRun rt; - // Create a new textbox, and give it lots of properties - HSLFTextBox txtbox = new HSLFTextBox(); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - txtbox.setText(val); - rt.setFontSize(42d); - rt.setBold(true); - rt.setItalic(true); - rt.setUnderlined(false); - sl.addShape(txtbox); + String val = "Hello, World!"; - // Check it before save - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); + // Create a new textbox, and give it lots of properties + HSLFTextBox txtbox = new HSLFTextBox(); + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + txtbox.setText(val); + rt.setFontSize(42d); + rt.setBold(true); + rt.setItalic(true); + rt.setUnderlined(false); + sl.addShape(txtbox); - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); + // Check it before save + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - sl = ppt.getSlides().get(0); + // Serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + sl = ppt2.getSlides().get(0); - txtbox = (HSLFTextBox)sl.getShapes().get(0); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + txtbox = (HSLFTextBox) sl.getShapes().get(0); + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - // Check after save - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); + // Check after save + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertFalse(rt.isUnderlined()); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java index 774fe06468..84af931507 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java @@ -17,6 +17,9 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.openSampleFileStream; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -27,14 +30,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.AbstractEscherOptRecord; import org.apache.poi.ddf.EscherDgRecord; import org.apache.poi.ddf.EscherDggRecord; @@ -56,68 +55,52 @@ import org.apache.poi.hslf.usermodel.HSLFTextShape; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Test drawing shapes via Graphics2D */ public final class TestShapes { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - private HSLFSlideShow ppt; - private HSLFSlideShow pptB; - - @BeforeEach - void setUp() throws Exception { - try (InputStream is1 = _slTests.openResourceAsStream("empty.ppt"); - InputStream is2 = _slTests.openResourceAsStream("empty_textbox.ppt")) { - ppt = new HSLFSlideShow(is1); - pptB = new HSLFSlideShow(is2); - } - } - @Test void graphics() throws IOException { - HSLFSlide slide = ppt.createSlide(); - - HSLFLine line = new HSLFLine(); - java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60); - line.setAnchor(lineAnchor); - line.setLineWidth(3); - line.setLineDash(LineDash.DASH); - line.setLineColor(Color.red); - slide.addShape(line); - - HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE); - Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111); - ellipse.setAnchor(ellipseAnchor); - ellipse.setLineWidth(2); - ellipse.setLineDash(LineDash.SOLID); - ellipse.setLineColor(Color.green); - ellipse.setFillColor(Color.lightGray); - slide.addShape(ellipse); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - //read ppt from byte array - - HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - assertEquals(1, ppt2.getSlides().size()); - - slide = ppt2.getSlides().get(0); - List<HSLFShape> shape = slide.getShapes(); - assertEquals(2, shape.size()); - - assertTrue(shape.get(0) instanceof HSLFLine); //group shape - assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape + try (HSLFSlideShow ppt = getSlideShow("empty.ppt")) { + HSLFSlide slide = ppt.createSlide(); + + HSLFLine line = new HSLFLine(); + java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60); + line.setAnchor(lineAnchor); + line.setLineWidth(3); + line.setLineDash(LineDash.DASH); + line.setLineColor(Color.red); + slide.addShape(line); + + HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE); + Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111); + ellipse.setAnchor(ellipseAnchor); + ellipse.setLineWidth(2); + ellipse.setLineDash(LineDash.SOLID); + ellipse.setLineColor(Color.green); + ellipse.setFillColor(Color.lightGray); + slide.addShape(ellipse); + + //read ppt from byte array + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + assertEquals(1, ppt2.getSlides().size()); + + slide = ppt2.getSlides().get(0); + List<HSLFShape> shape = slide.getShapes(); + assertEquals(2, shape.size()); + + assertTrue(shape.get(0) instanceof HSLFLine); //group shape + assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape + + assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape + assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape - assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape - assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape - - ppt2.close(); + } + } } /** @@ -125,40 +108,41 @@ public final class TestShapes { */ @Test void textBoxRead() throws IOException { - ppt = new HSLFSlideShow(_slTests.openResourceAsStream("with_textbox.ppt")); - HSLFSlide sl = ppt.getSlides().get(0); - for (HSLFShape sh : sl.getShapes()) { - assertTrue(sh instanceof HSLFTextBox); - HSLFTextBox txtbox = (HSLFTextBox)sh; - String text = txtbox.getText(); - assertNotNull(text); - - assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1); - HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - switch (text) { - case "Hello, World!!!": - assertNotNull(rt.getFontSize()); - assertEquals(32, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - break; - case "I am just a poor boy": - assertNotNull(rt.getFontSize()); - assertEquals(44, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - break; - case "This is Times New Roman": - assertNotNull(rt.getFontSize()); - assertEquals(16, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertTrue(rt.isUnderlined()); - break; - case "Plain Text": - assertNotNull(rt.getFontSize()); - assertEquals(18, rt.getFontSize(), 0); - break; + try (HSLFSlideShow ppt = getSlideShow("with_textbox.ppt")) { + HSLFSlide sl = ppt.getSlides().get(0); + for (HSLFShape sh : sl.getShapes()) { + assertTrue(sh instanceof HSLFTextBox); + HSLFTextBox txtbox = (HSLFTextBox) sh; + String text = txtbox.getText(); + assertNotNull(text); + + assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1); + HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + + switch (text) { + case "Hello, World!!!": + assertNotNull(rt.getFontSize()); + assertEquals(32, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + break; + case "I am just a poor boy": + assertNotNull(rt.getFontSize()); + assertEquals(44, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + break; + case "This is Times New Roman": + assertNotNull(rt.getFontSize()); + assertEquals(16, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertTrue(rt.isUnderlined()); + break; + case "Plain Text": + assertNotNull(rt.getFontSize()); + assertEquals(18, rt.getFontSize(), 0); + break; + } } } } @@ -166,43 +150,42 @@ public final class TestShapes { @SuppressWarnings("unused") @Test void testParagraphs() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - HSLFSlide slide = ss.createSlide(); - HSLFTextBox shape = new HSLFTextBox(); - HSLFTextRun p1r1 = shape.setText("para 1 run 1. "); - HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false); - HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true); - HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false); - p1r1.setFontColor(Color.black); - p1r2.setFontColor(Color.red); - p2r1.setFontColor(Color.yellow); - p2r2.setStrikethrough(true); - // run 3 has same text properties as run 2 and will be merged when saving - HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false); - shape.setAnchor(new Rectangle2D.Double(100,100,100,10)); - slide.addShape(shape); - shape.resizeToFitText(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ss.write(bos); - - ss = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); - slide = ss.getSlides().get(0); - HSLFTextBox tb = (HSLFTextBox)slide.getShapes().get(0); - List<HSLFTextParagraph> para = tb.getTextParagraphs(); - HSLFTextRun tr = para.get(0).getTextRuns().get(0); - assertEquals("para 1 run 1. ", tr.getRawText()); - assertEquals(Color.black, getColor(tr.getFontColor())); - tr = para.get(0).getTextRuns().get(1); - assertEquals("para 1 run 2.\r", tr.getRawText()); - assertEquals(Color.red, getColor(tr.getFontColor())); - tr = para.get(1).getTextRuns().get(0); - assertEquals("para 2 run 1. ", tr.getRawText()); - assertEquals(Color.yellow, getColor(tr.getFontColor())); - tr = para.get(1).getTextRuns().get(1); - assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText()); - assertEquals(Color.black, getColor(tr.getFontColor())); - assertTrue(tr.isStrikethrough()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide = ppt1.createSlide(); + HSLFTextBox shape = new HSLFTextBox(); + HSLFTextRun p1r1 = shape.setText("para 1 run 1. "); + HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false); + HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true); + HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false); + p1r1.setFontColor(Color.black); + p1r2.setFontColor(Color.red); + p2r1.setFontColor(Color.yellow); + p2r2.setStrikethrough(true); + // run 3 has same text properties as run 2 and will be merged when saving + HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false); + shape.setAnchor(new Rectangle2D.Double(100, 100, 100, 10)); + slide.addShape(shape); + shape.resizeToFitText(); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + HSLFTextBox tb = (HSLFTextBox) slide.getShapes().get(0); + List<HSLFTextParagraph> para = tb.getTextParagraphs(); + HSLFTextRun tr = para.get(0).getTextRuns().get(0); + assertEquals("para 1 run 1. ", tr.getRawText()); + assertEquals(Color.black, getColor(tr.getFontColor())); + tr = para.get(0).getTextRuns().get(1); + assertEquals("para 1 run 2.\r", tr.getRawText()); + assertEquals(Color.red, getColor(tr.getFontColor())); + tr = para.get(1).getTextRuns().get(0); + assertEquals("para 2 run 1. ", tr.getRawText()); + assertEquals(Color.yellow, getColor(tr.getFontColor())); + tr = para.get(1).getTextRuns().get(1); + assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText()); + assertEquals(Color.black, getColor(tr.getFontColor())); + assertTrue(tr.isStrikethrough()); + } + } } @@ -212,169 +195,158 @@ public final class TestShapes { */ @Test void textBoxWriteBytes() throws IOException { - ppt = new HSLFSlideShow(); - HSLFSlide sl = ppt.createSlide(); - HSLFTextRun rt; - - String val = "Hello, World!"; - - // Create a new textbox, and give it lots of properties - HSLFTextBox txtbox = new HSLFTextBox(); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - txtbox.setText(val); - rt.setFontFamily("Arial"); - rt.setFontSize(42d); - rt.setBold(true); - rt.setItalic(true); - rt.setUnderlined(false); - rt.setFontColor(Color.red); - sl.addShape(txtbox); - - // Check it before save - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(val, rt.getRawText()); - assertNotNull(rt.getFontSize()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - assertEquals(Color.red, getColor(rt.getFontColor())); - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - sl = ppt2.getSlides().get(0); - - txtbox = (HSLFTextBox)sl.getShapes().get(0); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - // Check after save - assertEquals(val, rt.getRawText()); - assertNotNull(rt.getFontSize()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - assertEquals(Color.red, getColor(rt.getFontColor())); - - ppt2.close(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide sl = ppt1.createSlide(); + + String val = "Hello, World!"; + + // Create a new textbox, and give it lots of properties + HSLFTextBox txtbox = new HSLFTextBox(); + HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + txtbox.setText(val); + rt.setFontFamily("Arial"); + rt.setFontSize(42d); + rt.setBold(true); + rt.setItalic(true); + rt.setUnderlined(false); + rt.setFontColor(Color.red); + sl.addShape(txtbox); + + // Check it before save + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertFalse(rt.isUnderlined()); + assertEquals("Arial", rt.getFontFamily()); + assertEquals(Color.red, getColor(rt.getFontColor())); + + // Serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + sl = ppt2.getSlides().get(0); + + txtbox = (HSLFTextBox) sl.getShapes().get(0); + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + + // Check after save + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertFalse(rt.isUnderlined()); + assertEquals("Arial", rt.getFontFamily()); + assertEquals(Color.red, getColor(rt.getFontColor())); + } + } } /** * Test with an empty text box */ @Test - void emptyTextBox() { - assertEquals(2, pptB.getSlides().size()); - HSLFSlide s1 = pptB.getSlides().get(0); - HSLFSlide s2 = pptB.getSlides().get(1); - - // Check we can get the shapes count - assertEquals(2, s1.getShapes().size()); - assertEquals(2, s2.getShapes().size()); + void emptyTextBox() throws IOException { + try (HSLFSlideShow ppt = getSlideShow("empty_textbox.ppt")) { + assertEquals(2, ppt.getSlides().size()); + HSLFSlide s1 = ppt.getSlides().get(0); + HSLFSlide s2 = ppt.getSlides().get(1); + + // Check we can get the shapes count + assertEquals(2, s1.getShapes().size()); + assertEquals(2, s2.getShapes().size()); + } } /** * If you iterate over text shapes in a slide and collect them in a set * it must be the same as returned by Slide.getTextRuns(). */ - @Test - void textBoxSet() throws IOException { - textBoxSet("with_textbox.ppt"); - textBoxSet("basic_test_ppt_file.ppt"); - textBoxSet("next_test_ppt_file.ppt"); - textBoxSet("Single_Coloured_Page.ppt"); - textBoxSet("Single_Coloured_Page_With_Fonts_and_Alignments.ppt"); - textBoxSet("incorrect_slide_order.ppt"); - } - - private void textBoxSet(String filename) throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(filename)); - for (HSLFSlide sld : ss.getSlides()) { - ArrayList<String> lst1 = new ArrayList<>(); - for (List<HSLFTextParagraph> txt : sld.getTextParagraphs()) { - for (HSLFTextParagraph p : txt) { - for (HSLFTextRun r : p) { - lst1.add(r.getRawText()); + @ParameterizedTest + @ValueSource(strings = { + "with_textbox.ppt", + "basic_test_ppt_file.ppt", + "next_test_ppt_file.ppt", + "Single_Coloured_Page.ppt", + "Single_Coloured_Page_With_Fonts_and_Alignments.ppt", + "incorrect_slide_order.ppt" + }) + void textBoxSet(String filename) throws IOException { + try (HSLFSlideShow ppt = getSlideShow(filename)) { + for (HSLFSlide sld : ppt.getSlides()) { + ArrayList<String> lst1 = new ArrayList<>(); + for (List<HSLFTextParagraph> txt : sld.getTextParagraphs()) { + for (HSLFTextParagraph p : txt) { + for (HSLFTextRun r : p) { + lst1.add(r.getRawText()); + } } } - } - ArrayList<String> lst2 = new ArrayList<>(); - for (HSLFShape sh : sld.getShapes()) { - if (sh instanceof HSLFTextShape){ - HSLFTextShape tbox = (HSLFTextShape)sh; - for (HSLFTextParagraph p : tbox.getTextParagraphs()) { - for (HSLFTextRun r : p) { - lst2.add(r.getRawText()); + ArrayList<String> lst2 = new ArrayList<>(); + for (HSLFShape sh : sld.getShapes()) { + if (sh instanceof HSLFTextShape) { + HSLFTextShape tbox = (HSLFTextShape) sh; + for (HSLFTextParagraph p : tbox.getTextParagraphs()) { + for (HSLFTextRun r : p) { + lst2.add(r.getRawText()); + } } } } + assertTrue(lst1.containsAll(lst2)); + assertTrue(lst2.containsAll(lst1)); } - assertTrue(lst1.containsAll(lst2)); - assertTrue(lst2.containsAll(lst1)); } - ss.close(); } /** - * Test adding shapes to <code>ShapeGroup</code> + * Test adding shapes to {@code ShapeGroup} */ @Test void shapeGroup() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - - HSLFSlide slide = ss.createSlide(); - Dimension pgsize = ss.getPageSize(); - - HSLFGroupShape group = new HSLFGroupShape(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { - group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight())); - slide.addShape(group); + HSLFSlide slide = ppt1.createSlide(); + Dimension pgsize = ppt1.getPageSize(); - HSLFPictureData data = ss.addPicture(_slTests.readFile("clock.jpg"), PictureType.JPEG); - HSLFPictureShape pict = new HSLFPictureShape(data, group); - pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200)); - group.addShape(pict); + HSLFGroupShape group = new HSLFGroupShape(); - HSLFLine line = new HSLFLine(group); - line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0)); - group.addShape(line); + group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight())); + slide.addShape(group); - //serialize and read again. - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ss.write(out); - out.close(); - ss.close(); + HSLFPictureData data = ppt1.addPicture(openSampleFileStream("clock.jpg"), PictureType.JPEG); + HSLFPictureShape pict = new HSLFPictureShape(data, group); + pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200)); + group.addShape(pict); - ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray()); - ss = new HSLFSlideShow(is); - is.close(); + HSLFLine line = new HSLFLine(group); + line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0)); + group.addShape(line); - slide = ss.getSlides().get(0); + //serialize and read again. + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { - List<HSLFShape> shape = slide.getShapes(); - assertEquals(1, shape.size()); - assertTrue(shape.get(0) instanceof HSLFGroupShape); + slide = ppt2.getSlides().get(0); - group = (HSLFGroupShape)shape.get(0); - List<HSLFShape> grshape = group.getShapes(); - assertEquals(2, grshape.size()); - assertTrue(grshape.get(0) instanceof HSLFPictureShape); - assertTrue(grshape.get(1) instanceof HSLFLine); + List<HSLFShape> shape = slide.getShapes(); + assertEquals(1, shape.size()); + assertTrue(shape.get(0) instanceof HSLFGroupShape); - pict = (HSLFPictureShape)grshape.get(0); - assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor()); + group = (HSLFGroupShape) shape.get(0); + List<HSLFShape> grshape = group.getShapes(); + assertEquals(2, grshape.size()); + assertTrue(grshape.get(0) instanceof HSLFPictureShape); + assertTrue(grshape.get(1) instanceof HSLFLine); - line = (HSLFLine)grshape.get(1); - assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor()); + pict = (HSLFPictureShape) grshape.get(0); + assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor()); - ss.close(); + line = (HSLFLine) grshape.get(1); + assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor()); + } + } } /** @@ -382,29 +354,24 @@ public final class TestShapes { */ @Test void removeShapes() throws IOException { - String file = "with_textbox.ppt"; - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(file)); - HSLFSlide sl = ss.getSlides().get(0); - List<HSLFShape> sh = sl.getShapes(); - assertEquals(4, sh.size(), "expected four shaped in " + file); - //remove all - for (int i = 0; i < sh.size(); i++) { - boolean ok = sl.removeShape(sh.get(i)); - assertTrue(ok, "Failed to delete shape #" + i); + try (HSLFSlideShow ppt1 = getSlideShow("with_textbox.ppt")) { + HSLFSlide sl = ppt1.getSlides().get(0); + List<HSLFShape> sh = sl.getShapes(); + assertEquals(4, sh.size()); + //remove all + for (int i = 0; i < sh.size(); i++) { + boolean ok = sl.removeShape(sh.get(i)); + assertTrue(ok, "Failed to delete shape #" + i); + } + //now Slide.getShapes() should return an empty array + assertEquals(0, sl.getShapes().size()); + + //serialize and read again. The file should be readable and contain no shapes + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + sl = ppt2.getSlides().get(0); + assertEquals(0, sl.getShapes().size()); + } } - //now Slide.getShapes() should return an empty array - assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file); - - //serialize and read again. The file should be readable and contain no shapes - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ss.write(out); - out.close(); - ss.close(); - - ss = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - sl = ss.getSlides().get(0); - assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file); - ss.close(); } @Test @@ -424,79 +391,78 @@ public final class TestShapes { @Test void shapeId() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - HSLFSlide slide = ss.createSlide(); - - //EscherDgg is a document-level record which keeps track of the drawing groups - EscherDggRecord dgg = ss.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); - EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord(); - - int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt - int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId - - int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide - int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide - //insert 3 shapes and make sure the Ids are properly incremented - for (int i = 0; i < 3; i++) { - HSLFShape shape = new HSLFLine(); - assertEquals(0, shape.getShapeId()); - slide.addShape(shape); - assertTrue(shape.getShapeId() > 0); - - //check that EscherDgRecord is updated - assertEquals(shape.getShapeId(), dg.getLastMSOSPID()); - assertEquals(dgMaxId + 1, dg.getLastMSOSPID()); - assertEquals(dgShapesUsed + 1, dg.getNumShapes()); - - //check that EscherDggRecord is updated - assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @"+i); - assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @"+i); - assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @"+i); - - dggShapesUsed = dgg.getNumShapesSaved(); - dggMaxId = dgg.getShapeIdMax(); - dgMaxId = dg.getLastMSOSPID(); - dgShapesUsed = dg.getNumShapes(); - } + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide slide = ppt.createSlide(); + + //EscherDgg is a document-level record which keeps track of the drawing groups + EscherDggRecord dgg = ppt.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); + EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord(); + + int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt + int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId + + int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide + int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide + //insert 3 shapes and make sure the Ids are properly incremented + for (int i = 0; i < 3; i++) { + HSLFShape shape = new HSLFLine(); + assertEquals(0, shape.getShapeId()); + slide.addShape(shape); + assertTrue(shape.getShapeId() > 0); + + //check that EscherDgRecord is updated + assertEquals(shape.getShapeId(), dg.getLastMSOSPID()); + assertEquals(dgMaxId + 1, dg.getLastMSOSPID()); + assertEquals(dgShapesUsed + 1, dg.getNumShapes()); + + //check that EscherDggRecord is updated + assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @" + i); + assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @" + i); + assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @" + i); + + dggShapesUsed = dgg.getNumShapesSaved(); + dggMaxId = dgg.getShapeIdMax(); + dgMaxId = dg.getLastMSOSPID(); + dgShapesUsed = dg.getNumShapes(); + } - //For each drawing group PPT allocates clusters with size=1024 - //if the number of shapes is greater that 1024 a new cluster is allocated - //make sure it is so - int numClusters = dgg.getNumIdClusters(); - for (int i = 0; i < 1025; i++) { - HSLFShape shape = new HSLFLine(); - slide.addShape(shape); + //For each drawing group PPT allocates clusters with size=1024 + //if the number of shapes is greater that 1024 a new cluster is allocated + //make sure it is so + int numClusters = dgg.getNumIdClusters(); + for (int i = 0; i < 1025; i++) { + HSLFShape shape = new HSLFLine(); + slide.addShape(shape); + } + assertEquals(numClusters + 1, dgg.getNumIdClusters()); } - assertEquals(numClusters + 1, dgg.getNumIdClusters()); - ss.close(); } @Test void lineColor() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream("51731.ppt")); - List<HSLFShape> shape = ss.getSlides().get(0).getShapes(); - - assertEquals(4, shape.size()); + try (HSLFSlideShow ss = getSlideShow("51731.ppt")) { + List<HSLFShape> shape = ss.getSlides().get(0).getShapes(); - HSLFTextShape sh1 = (HSLFTextShape)shape.get(0); - assertEquals("Hello Apache POI", sh1.getText()); - assertNull(sh1.getLineColor()); + assertEquals(4, shape.size()); - HSLFTextShape sh2 = (HSLFTextShape)shape.get(1); - assertEquals("Why are you showing this border?", sh2.getText()); - assertNull(sh2.getLineColor()); + HSLFTextShape sh1 = (HSLFTextShape) shape.get(0); + assertEquals("Hello Apache POI", sh1.getText()); + assertNull(sh1.getLineColor()); - HSLFTextShape sh3 = (HSLFTextShape)shape.get(2); - assertEquals("Text in a black border", sh3.getText()); - assertEquals(Color.black, sh3.getLineColor()); - assertEquals(0.75, sh3.getLineWidth(), 0); + HSLFTextShape sh2 = (HSLFTextShape) shape.get(1); + assertEquals("Why are you showing this border?", sh2.getText()); + assertNull(sh2.getLineColor()); - HSLFTextShape sh4 = (HSLFTextShape)shape.get(3); - assertEquals("Border width is 5 pt", sh4.getText()); - assertEquals(Color.black, sh4.getLineColor()); - assertEquals(5.0, sh4.getLineWidth(), 0); + HSLFTextShape sh3 = (HSLFTextShape) shape.get(2); + assertEquals("Text in a black border", sh3.getText()); + assertEquals(Color.black, sh3.getLineColor()); + assertEquals(0.75, sh3.getLineWidth(), 0); - ss.close(); + HSLFTextShape sh4 = (HSLFTextShape) shape.get(3); + assertEquals("Border width is 5 pt", sh4.getText()); + assertEquals(Color.black, sh4.getLineColor()); + assertEquals(5.0, sh4.getLineWidth(), 0); + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java index a50958ff79..8c00994768 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java @@ -17,28 +17,32 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.BODY; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_BODY; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_TITLE; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.TITLE; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; +import java.util.Objects; +import java.util.stream.IntStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp; import org.apache.poi.hslf.model.textproperties.TextProp; import org.apache.poi.hslf.record.Environment; +import org.apache.poi.hslf.usermodel.HSLFFontInfo; import org.apache.poi.hslf.usermodel.HSLFMasterSheet; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideMaster; import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.hslf.usermodel.HSLFTextParagraph; import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.apache.poi.hslf.usermodel.HSLFTitleMaster; @@ -49,7 +53,7 @@ import org.junit.jupiter.api.Test; * Tests for SlideMaster */ public final class TestSlideMaster { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); /** * The reference ppt has two masters. @@ -57,46 +61,54 @@ public final class TestSlideMaster { */ @Test void testSlideMaster() throws IOException { - final HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - - final Environment env = ppt.getDocumentRecord().getEnvironment(); - - assertEquals(2, ppt.getSlideMasters().size()); - - //character attributes - assertEquals(40, getMasterVal(ppt, 0, TITLE, "font.size", true)); - assertEquals(48, getMasterVal(ppt, 1, TITLE, "font.size", true)); - - int font1 = getMasterVal(ppt, 0, TITLE, "font.index", true); - int font2 = getMasterVal(ppt, 1, TITLE, "font.index", true); - assertEquals("Arial", env.getFontCollection().getFontInfo(font1).getTypeface()); - assertEquals("Georgia", env.getFontCollection().getFontInfo(font2).getTypeface()); - - CharFlagsTextProp prop1 = getMasterProp(ppt, 0, TITLE, "char_flags", true); - assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - CharFlagsTextProp prop2 = getMasterProp(ppt, 1, TITLE, "char_flags", true); - assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertTrue(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - //now paragraph attributes - assertEquals(0x266B, getMasterVal(ppt, 0, BODY, "bullet.char", false)); - assertEquals(0x2022, getMasterVal(ppt, 1, BODY, "bullet.char", false)); - - int b1 = getMasterVal(ppt, 0, BODY, "bullet.font", false); - int b2 = getMasterVal(ppt, 1, BODY, "bullet.font", false); - assertEquals("Arial", env.getFontCollection().getFontInfo(b1).getTypeface()); - assertEquals("Georgia", env.getFontCollection().getFontInfo(b2).getTypeface()); - - ppt.close(); + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + + final Environment env = ppt.getDocumentRecord().getEnvironment(); + + assertEquals(2, ppt.getSlideMasters().size()); + + //character attributes + assertEquals(40, getMasterVal(ppt, 0, TITLE, "font.size", true)); + assertEquals(48, getMasterVal(ppt, 1, TITLE, "font.size", true)); + + int font1 = getMasterVal(ppt, 0, TITLE, "font.index", true); + int font2 = getMasterVal(ppt, 1, TITLE, "font.index", true); + HSLFFontInfo fontInfo = env.getFontCollection().getFontInfo(font1); + assertNotNull(fontInfo); + assertEquals("Arial", fontInfo.getTypeface()); + fontInfo = env.getFontCollection().getFontInfo(font2); + assertNotNull(fontInfo); + assertEquals("Georgia", fontInfo.getTypeface()); + + CharFlagsTextProp prop1 = getMasterProp(ppt, 0, TITLE, "char_flags", true); + assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + + CharFlagsTextProp prop2 = getMasterProp(ppt, 1, TITLE, "char_flags", true); + assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertTrue(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + + //now paragraph attributes + assertEquals(0x266B, getMasterVal(ppt, 0, BODY, "bullet.char", false)); + assertEquals(0x2022, getMasterVal(ppt, 1, BODY, "bullet.char", false)); + + int b1 = getMasterVal(ppt, 0, BODY, "bullet.font", false); + int b2 = getMasterVal(ppt, 1, BODY, "bullet.font", false); + fontInfo = env.getFontCollection().getFontInfo(b1); + assertNotNull(fontInfo); + assertEquals("Arial", fontInfo.getTypeface()); + fontInfo = env.getFontCollection().getFontInfo(b2); + assertNotNull(fontInfo); + assertEquals("Georgia", fontInfo.getTypeface()); + } } - @SuppressWarnings("unchecked") private static <T extends TextProp> T getMasterProp(HSLFSlideShow ppt, int masterIdx, TextPlaceholder txtype, String propName, boolean isCharacter) { - return (T)ppt.getSlideMasters().get(masterIdx).getPropCollection(txtype.nativeId, 0, propName, isCharacter).findByName(propName); + return Objects.requireNonNull(ppt.getSlideMasters().get(masterIdx) + .getPropCollection(txtype.nativeId, 0, propName, isCharacter)) + .findByName(propName); } private static int getMasterVal(HSLFSlideShow ppt, int masterIdx, TextPlaceholder txtype, String propName, boolean isCharacter) { @@ -109,22 +121,21 @@ public final class TestSlideMaster { */ @Test void testTitleMasterTextAttributes() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - assertEquals(1, ppt.getTitleMasters().size()); - - assertEquals(40, getMasterVal(ppt, 0, CENTER_TITLE, "font.size", true)); - CharFlagsTextProp prop1 = getMasterProp(ppt, 0, CENTER_TITLE, "char_flags", true); - assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - assertEquals(32, getMasterVal(ppt, 0, CENTER_BODY, "font.size", true)); - CharFlagsTextProp prop2 = getMasterProp(ppt, 0, CENTER_BODY, "char_flags", true); - assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertFalse(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - ppt.close(); + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + assertEquals(1, ppt.getTitleMasters().size()); + + assertEquals(40, getMasterVal(ppt, 0, CENTER_TITLE, "font.size", true)); + CharFlagsTextProp prop1 = getMasterProp(ppt, 0, CENTER_TITLE, "char_flags", true); + assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + + assertEquals(32, getMasterVal(ppt, 0, CENTER_BODY, "font.size", true)); + CharFlagsTextProp prop2 = getMasterProp(ppt, 0, CENTER_BODY, "char_flags", true); + assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertFalse(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + } } /** @@ -132,30 +143,32 @@ public final class TestSlideMaster { */ @Test void testTitleMaster() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - HSLFSlide slide = ppt.getSlides().get(2); - HSLFMasterSheet masterSheet = slide.getMasterSheet(); - assertTrue(masterSheet instanceof HSLFTitleMaster); - - for (List<HSLFTextParagraph> txt : slide.getTextParagraphs()) { - HSLFTextRun rt = txt.get(0).getTextRuns().get(0); - switch(TextPlaceholder.fromNativeId(txt.get(0).getRunType())){ - case CENTER_TITLE: - assertEquals("Arial", rt.getFontFamily()); - assertEquals(32, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isUnderlined()); - break; - case CENTER_BODY: - assertEquals("Courier New", rt.getFontFamily()); - assertEquals(20, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertFalse(rt.isUnderlined()); - break; + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + HSLFSlide slide = ppt.getSlides().get(2); + HSLFMasterSheet masterSheet = slide.getMasterSheet(); + assertTrue(masterSheet instanceof HSLFTitleMaster); + + for (List<HSLFTextParagraph> txt : slide.getTextParagraphs()) { + HSLFTextRun rt = txt.get(0).getTextRuns().get(0); + assertNotNull(rt.getFontSize()); + TextPlaceholder tp = TextPlaceholder.fromNativeId(txt.get(0).getRunType()); + assertNotNull(tp); + switch (tp) { + case CENTER_TITLE: + assertEquals("Arial", rt.getFontFamily()); + assertEquals(32, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isUnderlined()); + break; + case CENTER_BODY: + assertEquals("Courier New", rt.getFontFamily()); + assertEquals(20, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertFalse(rt.isUnderlined()); + break; + } } - } - ppt.close(); } /** @@ -163,48 +176,46 @@ public final class TestSlideMaster { */ @Test void testMasterAttributes() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List<HSLFSlide> slide = ppt.getSlides(); - assertEquals(3, slide.size()); - for (List<HSLFTextParagraph> tparas : slide.get(0).getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TITLE.nativeId){ - HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(40, rt.getFontSize(), 0); - assertTrue(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - } else if (tpara.getRunType() == BODY.nativeId){ + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + List<HSLFSlide> slide = ppt.getSlides(); + assertEquals(3, slide.size()); + for (List<HSLFTextParagraph> tparas : slide.get(0).getTextParagraphs()) { + HSLFTextParagraph tpara = tparas.get(0); HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(0, tpara.getIndentLevel()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals("Arial", rt.getFontFamily()); - - tpara = tparas.get(1); - rt = tpara.getTextRuns().get(0); - assertEquals(1, tpara.getIndentLevel()); - assertEquals(28, rt.getFontSize(), 0); - assertEquals("Arial", rt.getFontFamily()); + assertNotNull(rt.getFontSize()); + if (tpara.getRunType() == TITLE.nativeId) { + assertEquals(40, rt.getFontSize(), 0); + assertTrue(rt.isUnderlined()); + assertEquals("Arial", rt.getFontFamily()); + } else if (tpara.getRunType() == BODY.nativeId) { + assertEquals(0, tpara.getIndentLevel()); + assertEquals(32, rt.getFontSize(), 0); + assertEquals("Arial", rt.getFontFamily()); + tpara = tparas.get(1); + rt = tpara.getTextRuns().get(0); + assertEquals(1, tpara.getIndentLevel()); + assertNotNull(rt.getFontSize()); + assertEquals(28, rt.getFontSize(), 0); + assertEquals("Arial", rt.getFontFamily()); + } } - } - for (List<HSLFTextParagraph> tparas : slide.get(1).getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TITLE.nativeId){ + for (List<HSLFTextParagraph> tparas : slide.get(1).getTextParagraphs()) { + HSLFTextParagraph tpara = tparas.get(0); HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(48, rt.getFontSize(), 0); - assertTrue(rt.isItalic()); - assertEquals("Georgia", rt.getFontFamily()); - } else if (tpara.getRunType() == BODY.nativeId){ - HSLFTextRun rt; - rt = tpara.getTextRuns().get(0); - assertEquals(0, tpara.getIndentLevel()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals("Courier New", rt.getFontFamily()); + assertNotNull(rt.getFontSize()); + if (tpara.getRunType() == TITLE.nativeId) { + assertEquals(48, rt.getFontSize(), 0); + assertTrue(rt.isItalic()); + assertEquals("Georgia", rt.getFontFamily()); + } else if (tpara.getRunType() == BODY.nativeId) { + assertEquals(0, tpara.getIndentLevel()); + assertEquals(32, rt.getFontSize(), 0); + assertEquals("Courier New", rt.getFontFamily()); + } } } - - ppt.close(); } /** @@ -212,35 +223,32 @@ public final class TestSlideMaster { */ @Test void testChangeSlideMaster() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List<HSLFSlideMaster> master = ppt.getSlideMasters(); - List<HSLFSlide> slide = ppt.getSlides(); - int sheetNo; - - //each slide uses its own master - assertEquals(slide.get(0).getMasterSheet()._getSheetNumber(), master.get(0)._getSheetNumber()); - assertEquals(slide.get(1).getMasterSheet()._getSheetNumber(), master.get(1)._getSheetNumber()); - - //all slides use the first master slide - sheetNo = master.get(0)._getSheetNumber(); - for (HSLFSlide s : slide) { - s.setMasterSheet(master.get(0)); - } - - ByteArrayOutputStream out; - - out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - master = ppt.getSlideMasters(); - slide = ppt.getSlides(); - for (HSLFSlide s : slide) { - assertEquals(sheetNo, s.getMasterSheet()._getSheetNumber()); + try (HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"))) { + int[] masterIds = IntStream.concat( + ppt.getSlideMasters().stream().mapToInt(HSLFSlideMaster::_getSheetNumber), + ppt.getTitleMasters().stream().mapToInt(HSLFTitleMaster::_getSheetNumber) + ).toArray(); + //each slide uses its own master + int[] slideMasters = ppt.getSlides().stream().mapToInt(s -> { + HSLFMasterSheet m = s.getMasterSheet(); + assertNotNull(m); + return m._getSheetNumber(); + }).toArray(); + assertArrayEquals(masterIds, slideMasters); + + //all slides use the first master slide + HSLFSlideMaster master0 = ppt.getSlideMasters().get(0); + int sheetNo = master0._getSheetNumber(); + ppt.getSlides().forEach(s -> s.setMasterSheet(master0)); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + for (HSLFSlide s : ppt2.getSlides()) { + HSLFMasterSheet ms = s.getMasterSheet(); + assertNotNull(ms); + assertEquals(sheetNo, ms._getSheetNumber()); + } + } } - - ppt.close(); } /** @@ -256,6 +264,7 @@ public final class TestSlideMaster { HSLFTextParagraph tpara = tparas.get(0); if (tpara.getRunType() == TITLE.nativeId){ HSLFTextRun rt = tpara.getTextRuns().get(0); + assertNotNull(rt.getFontSize()); assertEquals(40, rt.getFontSize(), 0); assertTrue(rt.isUnderlined()); assertEquals("Arial", rt.getFontFamily()); @@ -263,6 +272,7 @@ public final class TestSlideMaster { int[] indents = {32, 28, 24}; for (HSLFTextRun rt : tpara.getTextRuns()) { int indent = tpara.getIndentLevel(); + assertNotNull(rt.getFontSize()); assertEquals(indents[indent], rt.getFontSize(), 0); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java index 31713bae88..15850e6047 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java @@ -17,14 +17,13 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.usermodel.HSLFSlide; +import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.junit.jupiter.api.Test; /** @@ -36,105 +35,96 @@ public final class TestSlides { /** * Add 1 slide to an empty ppt. - * @throws Exception */ @Test void testAddSlides1() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(1, ppt.getSlides().size()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + assertTrue(ppt1.getSlides().isEmpty()); + + HSLFSlide s1 = ppt1.createSlide(); + assertEquals(1, ppt1.getSlides().size()); + assertEquals(3, s1._getSheetRefId()); + assertEquals(256, s1._getSheetNumber()); + assertEquals(1, s1.getSlideNumber()); + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)){ + assertEquals(1, ppt2.getSlides().size()); + } + } } /** * Add 2 slides to an empty ppt - * @throws Exception */ @Test void testAddSlides2() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - HSLFSlide s2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(2, s2.getSlideNumber()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(2, ppt.getSlides().size()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + assertTrue(ppt1.getSlides().isEmpty()); + + HSLFSlide s1 = ppt1.createSlide(); + assertEquals(1, ppt1.getSlides().size()); + assertEquals(3, s1._getSheetRefId()); + assertEquals(256, s1._getSheetNumber()); + assertEquals(1, s1.getSlideNumber()); + + HSLFSlide s2 = ppt1.createSlide(); + assertEquals(2, ppt1.getSlides().size()); + assertEquals(4, s2._getSheetRefId()); + assertEquals(257, s2._getSheetNumber()); + assertEquals(2, s2.getSlideNumber()); + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + assertEquals(2, ppt2.getSlides().size()); + } + } } /** * Add 3 slides to an empty ppt - * @throws Exception */ @Test void testAddSlides3() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - HSLFSlide s2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(2, s2.getSlideNumber()); - - HSLFSlide s3 = ppt.createSlide(); - assertEquals(3, ppt.getSlides().size()); - assertEquals(5, s3._getSheetRefId()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(3, s3.getSlideNumber()); - - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(3, ppt.getSlides().size()); - - // Check IDs are still right - s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(4, s2._getSheetRefId()); - s3 = ppt.getSlides().get(2); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(5, s3._getSheetRefId()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + assertTrue(ppt1.getSlides().isEmpty()); + + HSLFSlide s1 = ppt1.createSlide(); + assertEquals(1, ppt1.getSlides().size()); + assertEquals(3, s1._getSheetRefId()); + assertEquals(256, s1._getSheetNumber()); + assertEquals(1, s1.getSlideNumber()); + + HSLFSlide s2 = ppt1.createSlide(); + assertEquals(2, ppt1.getSlides().size()); + assertEquals(4, s2._getSheetRefId()); + assertEquals(257, s2._getSheetNumber()); + assertEquals(2, s2.getSlideNumber()); + + HSLFSlide s3 = ppt1.createSlide(); + assertEquals(3, ppt1.getSlides().size()); + assertEquals(5, s3._getSheetRefId()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(3, s3.getSlideNumber()); + + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + assertEquals(3, ppt2.getSlides().size()); + + // Check IDs are still right + s1 = ppt2.getSlides().get(0); + assertEquals(256, s1._getSheetNumber()); + assertEquals(3, s1._getSheetRefId()); + s2 = ppt2.getSlides().get(1); + assertEquals(257, s2._getSheetNumber()); + assertEquals(4, s2._getSheetRefId()); + s3 = ppt2.getSlides().get(2); + assertEquals(3, ppt2.getSlides().size()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(5, s3._getSheetRefId()); + } + } } /** @@ -142,48 +132,42 @@ public final class TestSlides { */ @Test void testAddSlides2to3() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - HSLFSlideShow ppt = new HSLFSlideShow(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - - assertEquals(2, ppt.getSlides().size()); - - // First slide is 256 / 4 - HSLFSlide s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - - // Last slide is 257 / 6 - HSLFSlide s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - - // Add another slide, goes in at the end - HSLFSlide s3 = ppt.createSlide(); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); - - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(3, ppt.getSlides().size()); - - - // Check IDs are still right - s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - s3 = ppt.getSlides().get(2); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); + try (HSLFSlideShow ppt1 = getSlideShow("basic_test_ppt_file.ppt")) { + + assertEquals(2, ppt1.getSlides().size()); + + // First slide is 256 / 4 + HSLFSlide s1 = ppt1.getSlides().get(0); + assertEquals(256, s1._getSheetNumber()); + assertEquals(4, s1._getSheetRefId()); + + // Last slide is 257 / 6 + HSLFSlide s2 = ppt1.getSlides().get(1); + assertEquals(257, s2._getSheetNumber()); + assertEquals(6, s2._getSheetRefId()); + + // Add another slide, goes in at the end + HSLFSlide s3 = ppt1.createSlide(); + assertEquals(3, ppt1.getSlides().size()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(8, s3._getSheetRefId()); + + // Serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + assertEquals(3, ppt2.getSlides().size()); + + // Check IDs are still right + s1 = ppt2.getSlides().get(0); + assertEquals(256, s1._getSheetNumber()); + assertEquals(4, s1._getSheetRefId()); + s2 = ppt2.getSlides().get(1); + assertEquals(257, s2._getSheetNumber()); + assertEquals(6, s2._getSheetRefId()); + s3 = ppt2.getSlides().get(2); + assertEquals(3, ppt2.getSlides().size()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(8, s3._getSheetRefId()); + } + } } - } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java index 1777ffed2c..b97dcef413 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java @@ -17,18 +17,17 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; -import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; @@ -42,18 +41,15 @@ import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; import org.junit.jupiter.api.Test; /** - * Test <code>Table</code> object. + * Test {@code Table} object. */ public final class TestTable { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - /** - * Test that ShapeFactory works properly and returns <code>Table</code> + * Test that ShapeFactory works properly and returns {@code Table} */ @Test void testShapeFactory() throws IOException { final int noColumns, noRows; - ByteArrayOutputStream out = new ByteArrayOutputStream(); try (HSLFSlideShow ppt = new HSLFSlideShow()) { HSLFSlide slide = ppt.createSlide(); @@ -73,16 +69,15 @@ public final class TestTable { assertEquals(noColumns, tbl2.getNumberOfColumns()); assertEquals(noRows, tbl2.getNumberOfRows()); - ppt.write(out); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + HSLFSlide slide2 = ppt2.getSlides().get(0); + assertTrue(slide2.getShapes().get(0) instanceof HSLFTable); + HSLFTable tbl3 = (HSLFTable) slide2.getShapes().get(0); + assertEquals(noColumns, tbl3.getNumberOfColumns()); + assertEquals(noRows, tbl3.getNumberOfRows()); + } } - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()))) { - HSLFSlide slide = ppt.getSlides().get(0); - assertTrue(slide.getShapes().get(0) instanceof HSLFTable); - HSLFTable tbl3 = (HSLFTable) slide.getShapes().get(0); - assertEquals(noColumns, tbl3.getNumberOfColumns()); - assertEquals(noRows, tbl3.getNumberOfRows()); - } } /** @@ -132,7 +127,7 @@ public final class TestTable { */ @Test void test57820() throws IOException { - try (SlideShow<?,?> ppt = new HSLFSlideShow(_slTests.openResourceAsStream("bug57820-initTableNullRefrenceException.ppt"))) { + try (SlideShow<?,?> ppt = getSlideShow("bug57820-initTableNullRefrenceException.ppt")) { List<? extends Slide<?, ?>> slides = ppt.getSlides(); assertEquals(1, slides.size()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java index f6f7fe6f7c..9509ca6c94 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java @@ -17,22 +17,20 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.POIDataSamples.writeOutAndReadBack; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; -import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFTextParagraph; import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -41,137 +39,111 @@ import org.junit.jupiter.api.Test; * that we don't break anything in the process. */ public final class TestTextRunReWrite { - // HSLFSlideShow primed on the test data - private HSLFSlideShow ss; - - /** - * Load up a test PPT file with rich data - */ - @BeforeEach - void setUp() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - String filename = "Single_Coloured_Page_With_Fonts_and_Alignments.ppt"; - ss = new HSLFSlideShow(slTests.openResourceAsStream(filename)); - } - @Test void testWritesOutTheSameNonRich() throws IOException { - // Ensure the text lengths are as we'd expect to start with - assertEquals(1, ss.getSlides().size()); - assertEquals(2, ss.getSlides().get(0).getTextParagraphs().size()); - - // Grab the first text run on the first sheet - List<HSLFTextParagraph> tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - List<HSLFTextParagraph> tr2 = ss.getSlides().get(0).getTextParagraphs().get(1); - - - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); - - assertEquals(1, tr1.size()); - assertEquals(30, HSLFTextParagraph.getText(tr1).length()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - // Set the text to be as it is now - HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1)); - tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - - // Check the text lengths are still right - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); - - assertEquals(1, tr1.size()); - assertEquals(30, HSLFTextParagraph.getText(tr1).length()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - - // Write the slideshow out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DirectoryNode oDir = ss.getSlideShowImpl().getDirectory(); - - DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); - npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); - assertArrayEquals(_oData, _nData); - - npfs.close(); + try (HSLFSlideShow ppt1 = getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt")) { + // Ensure the text lengths are as we'd expect to start with + assertEquals(1, ppt1.getSlides().size()); + assertEquals(2, ppt1.getSlides().get(0).getTextParagraphs().size()); + + // Grab the first text run on the first sheet + List<HSLFTextParagraph> tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0); + List<HSLFTextParagraph> tr2 = ppt1.getSlides().get(0).getTextParagraphs().get(1); + + + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); + + assertEquals(1, tr1.size()); + assertEquals(30, HSLFTextParagraph.getText(tr1).length()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Set the text to be as it is now + HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1)); + tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0); + + // Check the text lengths are still right + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); + + assertEquals(1, tr1.size()); + assertEquals(30, HSLFTextParagraph.getText(tr1).length()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Use POIFS to query that lot + try (POIFSFileSystem npfs = writeOutAndReadBack(ppt1.getDirectory().getFileSystem())) { + // Check that the "PowerPoint Document" sections have the same size + DirectoryNode oDir = ppt1.getSlideShowImpl().getDirectory(); + + DocumentEntry oProps = (DocumentEntry) oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + DocumentEntry nProps = (DocumentEntry) npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + assertEquals(oProps.getSize(), nProps.getSize()); + + // Check that they contain the same data + byte[] _oData = new byte[oProps.getSize()]; + byte[] _nData = new byte[nProps.getSize()]; + int oLen = oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); + int nLen = npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); + assertEquals(_oData.length, oLen); + assertEquals(_nData.length, nLen); + assertArrayEquals(_oData, _nData); + } + } } @Test void testWritesOutTheSameRich() throws IOException { - // Grab the first text run on the first sheet - List<HSLFTextParagraph> tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - - // Get the first rich text run - HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0); - - - // Check that the text sizes are as expected - assertEquals(1, tr1.get(0).getTextRuns().size()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(30, rtr1.getLength()); - assertEquals(30, rtr1.getRawText().length()); - assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - // Set the text to be as it is now - rtr1.setText( rtr1.getRawText() ); - rtr1 = tr1.get(0).getTextRuns().get(0); - - // Check that the text sizes are still as expected - assertEquals(1, tr1.get(0).getTextRuns().size()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length()); - assertEquals(30, rtr1.getLength()); - assertEquals(30, rtr1.getRawText().length()); - assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - - // Write the slideshow out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DirectoryNode oDir = ss.getSlideShowImpl().getDirectory(); - - DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - - oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); - npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); - assertArrayEquals(_oData, _nData); - - npfs.close(); + try (HSLFSlideShow ppt1 = getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt")) { + // Grab the first text run on the first sheet + List<HSLFTextParagraph> tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0); + + // Get the first rich text run + HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0); + + // Check that the text sizes are as expected + assertEquals(1, tr1.get(0).getTextRuns().size()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(30, rtr1.getLength()); + assertEquals(30, rtr1.getRawText().length()); + assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Set the text to be as it is now + rtr1.setText(rtr1.getRawText()); + rtr1 = tr1.get(0).getTextRuns().get(0); + + // Check that the text sizes are still as expected + assertEquals(1, tr1.get(0).getTextRuns().size()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length()); + assertEquals(30, rtr1.getLength()); + assertEquals(30, rtr1.getRawText().length()); + assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Use POIFS to query that lot + try (POIFSFileSystem npfs = writeOutAndReadBack(ppt1.getDirectory().getFileSystem())) { + // Check that the "PowerPoint Document" sections have the same size + DirectoryNode oDir = ppt1.getSlideShowImpl().getDirectory(); + + DocumentEntry oProps = (DocumentEntry) oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + DocumentEntry nProps = (DocumentEntry) npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + assertEquals(oProps.getSize(), nProps.getSize()); + + // Check that they contain the same data + byte[] _oData = new byte[oProps.getSize()]; + byte[] _nData = new byte[nProps.getSize()]; + + int oLen = oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); + int nLen = npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); + assertEquals(_oData.length, oLen); + assertEquals(_nData.length, nLen); + assertArrayEquals(_oData, _nData); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java index 21d25007db..dac20b569b 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -66,7 +65,7 @@ public final class TestAnimationInfoAtom { @Test void testWrite() throws Exception { AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); @@ -82,7 +81,7 @@ public final class TestAnimationInfoAtom { record.setFlag(AnimationInfoAtom.Play, true); record.setFlag(AnimationInfoAtom.Synchronous, true); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java index a117037832..054b5c9790 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -70,24 +70,16 @@ public final class TestCString { @Test void testWrite() throws Exception { CString ca = new CString(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); CString cb = new CString(data_b, 0, data_a.length); - ByteArrayOutputStream baosB = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baosB = new UnsynchronizedByteArrayOutputStream(); cb.writeOut(baosB); b = baosB.toByteArray(); - - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, b); } // Turn data_a into data_b @@ -107,14 +99,9 @@ public final class TestCString { } assertFalse(equals, "Arrays should not be equals"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - // Should now be the same - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, b); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java index 768ca20623..fc74f17613 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java @@ -18,10 +18,10 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -81,13 +81,10 @@ public final class TestColorSchemeAtom { @Test void testWrite() throws Exception { ColorSchemeAtom csa = new ColorSchemeAtom(data_a,0,data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); csa.writeOut(baos); byte[] b = baos.toByteArray(); - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java index f518b9ffee..ffff00f289 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java @@ -18,16 +18,17 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LocaleUtil; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -143,14 +144,10 @@ public final class TestComment2000 { @Test void testWrite() throws Exception { Comment2000 ca = new Comment2000(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } // Change a few things @@ -199,22 +196,16 @@ public final class TestComment2000 { assertFalse(equals, "Arrays should not be equals"); // Check bytes are now the same - ByteArrayOutputStream baosa = new ByteArrayOutputStream(); - ByteArrayOutputStream baosn = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baosa = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baosn = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baosa); cn.writeOut(baosn); byte[] ba = baosa.toByteArray(); byte[] bn = baosn.toByteArray(); // Should now be the same - assertEquals(data_b.length, ba.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],ba[i]); - } - assertEquals(data_b.length, bn.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],bn[i]); - } + assertArrayEquals(data_b, ba); + assertArrayEquals(data_b, bn); } /** diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java index 59660e4947..f3bbdcaa8f 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java @@ -18,13 +18,14 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LocaleUtil; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -35,18 +36,18 @@ import org.junit.jupiter.api.Test; public final class TestComment2000Atom { // From a real file private final byte[] data_a = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 01, 00, 00, 00, 0xD6-256, 07, 01, 00, - 02, 00, 0x18, 00, 0x0A, 00, 0x1A, 00, - 0x0F, 00, 0xCD-256, 00, 0x92-256, 00, - 00, 00, 0x92-256, 00, 00, 00 + 0, 0, 0xE1-256, 0x2E, 0x1C, 0, 0, 0, + 1, 0, 0, 0, 0xD6-256, 7, 1, 0, + 2, 0, 0x18, 0, 0x0A, 0, 0x1A, 0, + 0x0F, 0, 0xCD-256, 0, 0x92-256, 0, + 0, 0, 0x92-256, 0, 0, 0 }; private final byte[] data_b = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 05, 00, 00, 00, 0xD6-256, 0x07, 01, 00, - 02, 00, 0x18, 00, 0x15, 00, 0x19, 00, 03, - 00, 0xD5-256, 02, 0x0A, 00, 00, 00, - 0x0E, 00, 00, 00 + 0, 0, 0xE1-256, 0x2E, 0x1C, 0, 0, 0, + 5, 0, 0, 0, 0xD6-256, 0x07, 1, 0, + 2, 0, 0x18, 0, 0x15, 0, 0x19, 0, 3, + 0, 0xD5-256, 2, 0x0A, 0, 0, 0, + 0x0E, 0, 0, 0 }; private static SimpleDateFormat sdf; @@ -60,7 +61,7 @@ public final class TestComment2000Atom { @Test void testRecordType() { Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - assertEquals(12001l, ca.getRecordType()); + assertEquals(12001L, ca.getRecordType()); } @Test @@ -105,14 +106,10 @@ public final class TestComment2000Atom { @Test void testWrite() throws Exception { Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } // Create A from scratch @@ -130,14 +127,10 @@ public final class TestComment2000Atom { a.setDate(date_a); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); a.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } // Try to turn a into b @@ -157,14 +150,9 @@ public final class TestComment2000Atom { ca.setYOffset(0x0E); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - // Should now be the same - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, b); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java index 138e127024..b21e0d8b67 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java @@ -21,9 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.ByteArrayOutputStream; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -89,7 +89,7 @@ public final class TestCurrentUserAtom { cu.setCurrentEditOffset(0x2942); // Check it matches - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); cu.writeOut(baos); byte[] out = baos.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java index 06bca9df9b..c831a478c6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -41,7 +40,7 @@ public final class TestDocumentAtom { @Test void testRecordType() { DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(1001l, da.getRecordType()); + assertEquals(1001L, da.getRecordType()); } @Test @@ -67,7 +66,7 @@ public final class TestDocumentAtom { void testSlideDetails() { DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); assertEquals(1, da.getFirstSlideNum()); - assertEquals(0, da.getSlideSizeType()); + assertEquals(DocumentAtom.SlideSize.ON_SCREEN, da.getSlideSizeTypeEnum()); } @Test @@ -82,7 +81,7 @@ public final class TestDocumentAtom { @Test void testWrite() throws Exception { DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); da.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java index 55944a5246..34945764f2 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java @@ -23,12 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.security.MessageDigest; import java.util.List; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.PropertySet; @@ -44,7 +44,6 @@ import org.apache.poi.poifs.crypt.CryptoFunctions; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIDecryptor; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -86,12 +85,12 @@ public class TestDocumentEncryption { DocumentEncryptionAtom documentEncryptionAtom = hss.getDocumentEncryptionAtom(); assertNotNull(documentEncryptionAtom); EncryptionInfo ei = documentEncryptionAtom.getEncryptionInfo(); - ((CryptoAPIEncryptionHeader) ei.getHeader()).setKeySize(0x78); + ei.getHeader().setKeySize(0x78); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); hss.write(bos); - try (POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); + try (POIFSFileSystem fs2 = new POIFSFileSystem(bos.toInputStream()); HSLFSlideShowImpl hss2 = new HSLFSlideShowImpl(fs2)) { List<HSLFPictureData> picsActual = hss2.getPictureData(); @@ -109,9 +108,9 @@ public class TestDocumentEncryption { void cryptoAPIEncryption() throws Exception { /* documents with multiple edits need to be normalized for encryption */ String pptFile = "57272_corrupted_usereditatom.ppt"; - ByteArrayOutputStream encrypted = new ByteArrayOutputStream(); - ByteArrayOutputStream expected = new ByteArrayOutputStream(); - ByteArrayOutputStream actual = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream encrypted = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream expected = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream actual = new UnsynchronizedByteArrayOutputStream(); try { try (POIFSFileSystem fs = new POIFSFileSystem(slTests.getFile(pptFile), true); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) { @@ -126,8 +125,9 @@ public class TestDocumentEncryption { } // decrypted - ByteArrayInputStream bis = new ByteArrayInputStream(encrypted.toByteArray()); - try (POIFSFileSystem fs = new POIFSFileSystem(bis); + + try (InputStream bis = encrypted.toInputStream(); + POIFSFileSystem fs = new POIFSFileSystem(bis); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) { Biff8EncryptionKey.setCurrentUserPassword(null); hss.write(actual); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java index c7bd84e116..2faa7ebfd8 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java @@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -93,7 +92,7 @@ public final class TestExControl { @Test void testWrite() throws Exception { ExControl record = new ExControl(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -116,7 +115,7 @@ public final class TestExControl { record.setProgId("ShockwaveFlash.ShockwaveFlash.9"); record.setClipboardName("Shockwave Flash Object"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java index 13fea4a83a..42a9867560 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java @@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -46,14 +46,14 @@ public final class TestExHyperlink { ExHyperlink exHyperlink = new ExHyperlink(exHyperlinkBytes, 0, exHyperlinkBytes.length); - assertEquals(4055l, exHyperlink.getRecordType()); + assertEquals(4055L, exHyperlink.getRecordType()); assertEquals(3, exHyperlink.getExHyperlinkAtom().getNumber()); String expURL = "http://jakarta.apache.org/poi/hssf/"; assertEquals(expURL, exHyperlink.getLinkURL()); assertEquals(expURL, exHyperlink._getDetailsA()); assertEquals(expURL, exHyperlink._getDetailsB()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); exHyperlink.writeOut(baos); assertArrayEquals(exHyperlinkBytes, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java index fb8072bd44..f868d96b16 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -57,7 +56,7 @@ public class TestExHyperlinkAtom { @Test void testWrite() throws Exception { ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eha.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -71,7 +70,7 @@ public class TestExHyperlinkAtom { eha.setNumber(1); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eha.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -85,7 +84,7 @@ public class TestExHyperlinkAtom { eha.setNumber(4); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eha.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java index 5b961d5816..606f0ac827 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -50,7 +49,7 @@ public final class TestExMediaAtom { @Test void testWrite() throws Exception { ExMediaAtom record = new ExMediaAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); @@ -68,7 +67,7 @@ public final class TestExMediaAtom { record.setFlag(HeadersFootersAtom.fHasTodayDate, false); record.setFlag(HeadersFootersAtom.fHasFooter, false); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java index 9256b01b9f..97d3ef1707 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java @@ -20,8 +20,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ss.formula.functions.BaseTestNumeric; import org.junit.jupiter.api.Test; @@ -57,7 +56,7 @@ public class TestExObjListAtom { @Test void testWrite() throws Exception { ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eoa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -71,7 +70,7 @@ public class TestExObjListAtom { eoa.setObjectIDSeed(1); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eoa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -85,7 +84,7 @@ public class TestExObjListAtom { eoa.setObjectIDSeed(4); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eoa.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java index 4c7771cac8..a0860abbbe 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java @@ -20,8 +20,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -50,7 +49,7 @@ public final class TestExOleObjAtom { @Test void testWrite() throws Exception { ExOleObjAtom record = new ExOleObjAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -65,7 +64,7 @@ public final class TestExOleObjAtom { record.setObjStgDataRef(2); record.setOptions(1283584); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java index fcdadfe211..f9d282a095 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java @@ -22,12 +22,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.IOUtils; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -58,7 +58,7 @@ public final class TestExOleObjStg { assertEquals(RecordTypes.ExOleObjStg.typeID, record.getRecordType()); int len = record.getDataLength(); - byte[] oledata = readAll(record.getData()); + byte[] oledata = IOUtils.toByteArray(record.getData()); assertEquals(len, oledata.length); try (POIFSFileSystem fs = new POIFSFileSystem(record.getData())) { @@ -70,7 +70,7 @@ public final class TestExOleObjStg { @Test void testWrite() throws Exception { ExOleObjStg record = new ExOleObjStg(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); @@ -80,7 +80,7 @@ public final class TestExOleObjStg { @Test void testNewRecord() throws Exception { ExOleObjStg src = new ExOleObjStg(data, 0, data.length); - byte[] oledata = readAll(src.getData()); + byte[] oledata = IOUtils.toByteArray(src.getData()); ExOleObjStg tgt = new ExOleObjStg(); tgt.setData(oledata); @@ -88,22 +88,11 @@ public final class TestExOleObjStg { assertEquals(src.getDataLength(), tgt.getDataLength()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); tgt.writeOut(out); byte[] b = out.toByteArray(); assertEquals(data.length, b.length); assertArrayEquals(data, b); } - - private byte[] readAll(InputStream is) throws IOException { - int pos; - byte[] chunk = new byte[1024]; - ByteArrayOutputStream out = new ByteArrayOutputStream(); - while((pos = is.read(chunk)) > 0){ - out.write(chunk, 0, pos); - } - return out.toByteArray(); - - } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java index 3933965ac2..ce02202335 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -68,7 +67,7 @@ public final class TestExVideoContainer { @Test void testWrite() throws Exception { ExVideoContainer record = new ExVideoContainer(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -79,7 +78,7 @@ public final class TestExVideoContainer { record.getExMediaAtom().setObjectId(1); record.getPathAtom().setText("D:\\projects\\SchulerAG\\mcom_v_1_0_4\\view\\data\\tests\\images\\cards.mpg"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java index f5b64da586..3592100af6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java @@ -19,12 +19,13 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFFontInfo; import org.apache.poi.hslf.usermodel.HSLFFontInfoPredefined; @@ -78,16 +79,22 @@ public final class TestFontCollection { assertEquals(child.length, 3); // Check we get the right font name for the indicies - assertEquals("Times New Roman", fonts.getFontInfo(0).getTypeface()); - assertEquals("Helvetica", fonts.getFontInfo(1).getTypeface()); - assertEquals("Arial", fonts.getFontInfo(2).getTypeface()); + fi = fonts.getFontInfo(0); + assertNotNull(fi); + assertEquals("Times New Roman", fi.getTypeface()); + fi = fonts.getFontInfo(1); + assertNotNull(fi); + assertEquals("Helvetica", fi.getTypeface()); + fi = fonts.getFontInfo(2); + assertNotNull(fi); + assertEquals("Arial", fi.getTypeface()); assertNull(fonts.getFontInfo(3)); } @Test void testWrite() throws Exception { FontCollection fonts = new FontCollection(data, 0, data.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); fonts.writeOut(out); byte[] recdata = out.toByteArray(); assertArrayEquals(recdata, data); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java index 3edfadb3de..7277fc4790 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -55,7 +54,7 @@ public final class TestHeadersFootersAtom { @Test void testWrite() throws Exception { HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -67,7 +66,7 @@ public final class TestHeadersFootersAtom { record.setFlag(HeadersFootersAtom.fHasTodayDate, true); record.setFlag(HeadersFootersAtom.fHasFooter, true); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java index f6a25739b2..5d6d15b798 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -76,7 +75,7 @@ public final class TestHeadersFootersContainer { @Test void testWriteSlideHeadersFootersContainer() throws Exception { HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(slideData, baos.toByteArray()); } @@ -100,7 +99,7 @@ public final class TestHeadersFootersContainer { assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); csFooter.setText("My Footer - 1"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(slideData, baos.toByteArray()); } @@ -129,7 +128,7 @@ public final class TestHeadersFootersContainer { @Test void testWriteNotesHeadersFootersContainer() throws Exception { HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(notesData, baos.toByteArray()); } @@ -161,7 +160,7 @@ public final class TestHeadersFootersContainer { assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); csFooter.setText("Note Footer"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(notesData, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java index 7da5ee6f5c..1b1ab55491 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java @@ -24,8 +24,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -57,7 +56,7 @@ public class TestInteractiveInfo { @Test void testWrite() throws Exception { InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ii.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -75,7 +74,7 @@ public class TestInteractiveInfo { ia.setHyperlinkType((byte)8); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ii.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java index 7f9bcde86e..9eeab59618 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -74,7 +73,7 @@ public class TestInteractiveInfoAtom { @Test void testWrite() throws Exception { InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -91,7 +90,7 @@ public class TestInteractiveInfoAtom { ia.setHyperlinkType((byte)8); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -105,7 +104,7 @@ public class TestInteractiveInfoAtom { ia.setHyperlinkID(4); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java index e2852088dc..d122f019dd 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java @@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -52,7 +51,7 @@ public final class TestNotesAtom { @Test void testWrite() throws Exception { NotesAtom na = new NotesAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); na.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java index ef3c7b84b4..7f67088716 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java @@ -22,9 +22,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.hslf.record.SlideAtomLayout.SlideLayoutType; import org.apache.poi.hslf.usermodel.HSLFSlide; @@ -43,7 +43,7 @@ public final class TestSlideAtom { @Test void testRecordType() { SlideAtom sa = new SlideAtom(data_a, 0, data_a.length); - assertEquals(1007l, sa.getRecordType()); + assertEquals(1007L, sa.getRecordType()); } @Test @@ -75,23 +75,23 @@ public final class TestSlideAtom { @Test void testWrite() throws IOException { SlideAtom sa = new SlideAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); sa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @Test void testSSSlideInfoAtom() throws IOException { - HSLFSlideShow ss1 = new HSLFSlideShow(); - HSLFSlide slide1 = ss1.createSlide(), slide2 = ss1.createSlide(); - slide2.setHidden(true); - - HSLFSlideShow ss2 = HSLFTestDataSamples.writeOutAndReadBack(ss1); - slide1 = ss2.getSlides().get(0); - slide2 = ss2.getSlides().get(1); - assertFalse(slide1.isHidden()); - assertTrue(slide2.isHidden()); - ss2.close(); - ss1.close(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide1 = ppt1.createSlide(), slide2 = ppt1.createSlide(); + slide2.setHidden(true); + + try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) { + slide1 = ppt2.getSlides().get(0); + slide2 = ppt2.getSlides().get(1); + assertFalse(slide1.isHidden()); + assertTrue(slide2.isHidden()); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java index 2a638d5a9a..d5f1105f47 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java @@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -53,7 +52,7 @@ public final class TestSlidePersistAtom { @Test void testWrite() throws Exception { SlidePersistAtom spa = new SlidePersistAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); spa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java index 3de5c8d131..1e57798caf 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java @@ -26,15 +26,14 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp; import org.apache.poi.hslf.model.textproperties.TextProp; import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.util.HexDump; import org.junit.jupiter.api.Test; /** @@ -467,14 +466,9 @@ public final class TestStyleTextPropAtom { tpc.setValue(0xFE0033FF); // Should now be the same as data_a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); stpa.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, baos.toByteArray()); } /** @@ -621,34 +615,20 @@ public final class TestStyleTextPropAtom { assertEquals(tpa.getValue(), tpb.getValue()); } - ByteArrayOutputStream ba = new ByteArrayOutputStream(); - ByteArrayOutputStream bb = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream ba = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bb = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(ba); cb.writeOut(bb); - byte[] cab = ba.toByteArray(); - byte[] cbb = bb.toByteArray(); - assertEquals(cbb.length, cab.length); - for(int j=0; j<cab.length; j++) { - //System.out.println("On tp " + z + " " + i + " " + j + "\t" + cab[j] + "\t" + cbb[j]); - assertEquals(cbb[j], cab[j]); - } + assertArrayEquals(bb.toByteArray(), ba.toByteArray()); } } - - // Check byte level with b - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); stpa.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - //System.out.println(i + "\t" + b[i] + "\t" + data_b[i] + "\t" + Integer.toHexString(b[i]) ); - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, baos.toByteArray()); } @Test @@ -694,13 +674,9 @@ public final class TestStyleTextPropAtom { StyleTextPropAtom stpb = new StyleTextPropAtom(data, 0,data.length); if(textlen != -1) stpb.setParentTextSize(textlen); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); stpb.writeOut(out); - byte[] bytes = out.toByteArray(); - - assertEquals(expected.length, bytes.length); - assertArrayEquals(expected, bytes, - "Had: " + HexDump.toHex(expected) + "\nand: " + HexDump.toHex(bytes)); + assertArrayEquals(expected, out.toByteArray()); } @Test @@ -759,12 +735,14 @@ public final class TestStyleTextPropAtom { * * From the test file attached to the bug: * + * {@code * <StyleTextPropAtom info="0" type="4001" size="94" offset="114782" header="00 00 A1 0F 5E 00 00 00 "> * 14 00 00 00 00 00 41 00 0A 00 06 00 50 00 07 00 01 00 00 00 00 00 00 00 02 * 00 00 00 01 04 00 00 01 04 01 00 00 00 01 08 00 00 01 08 0C 00 00 00 01 0C * 00 00 01 0C 01 00 00 00 01 10 00 00 01 10 01 00 00 00 01 14 00 00 01 14 01 * 00 00 00 01 18 00 00 01 18 01 00 00 00 01 1C 00 00 01 1C * </StyleTextPropAtom> + * } */ @Test void test45815() throws IOException { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java index 44f2dc4617..c06eff77d1 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java @@ -21,9 +21,9 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -64,7 +64,7 @@ public final class TestTextBytesAtom { TextBytesAtom tba = new TextBytesAtom(data,0,data.length); tba.setText(alt_text.getBytes(StandardCharsets.ISO_8859_1)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tba.writeOut(baos); assertArrayEquals(alt_data, baos.toByteArray()); } @@ -72,7 +72,7 @@ public final class TestTextBytesAtom { @Test void testWrite() throws Exception { TextBytesAtom tba = new TextBytesAtom(data,0,data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tba.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java index 4c1a71daa0..382719cdfc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -60,7 +59,7 @@ public final class TestTextCharsAtom { TextCharsAtom tca = new TextCharsAtom(data,0,data.length); tca.setText(alt_text); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tca.writeOut(baos); assertArrayEquals(alt_data, baos.toByteArray()); } @@ -68,7 +67,7 @@ public final class TestTextCharsAtom { @Test void testWrite() throws Exception { TextCharsAtom tca = new TextCharsAtom(data,0,data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tca.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -82,7 +81,7 @@ public final class TestTextCharsAtom { assertEquals(data_text, tca.getText()); // Check it's now like data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tca.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java index 4935940afb..6eddf527af 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; import org.junit.jupiter.api.Test; @@ -54,7 +53,7 @@ public final class TestTextHeaderAtom { @Test void testWrite() throws Exception { TextHeaderAtom tha = new TextHeaderAtom(notes_data,0,12); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tha.writeOut(baos); assertArrayEquals(notes_data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java index e50419c410..a24402ec2a 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java @@ -21,9 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.model.textproperties.HSLFTabStop; import org.junit.jupiter.api.Test; @@ -61,7 +61,7 @@ public final class TestTextRulerAtom { @Test void testWriteRuler() throws Exception { TextRulerAtom ruler = new TextRulerAtom(data_1, 0, data_1.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ruler.writeOut(out); byte[] result = out.toByteArray(); @@ -72,7 +72,7 @@ public final class TestTextRulerAtom { void testRead2() throws Exception { TextRulerAtom ruler = TextRulerAtom.getParagraphInstance(); ruler.setParagraphIndent((short)249, (short)321); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ruler.writeOut(out); byte[] result = out.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java index 77ded7d795..93e8b5e420 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java @@ -20,8 +20,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -54,7 +53,7 @@ public final class TestTextSpecInfoAtom { @Test void testWrite() throws Exception { TextSpecInfoAtom spec = new TextSpecInfoAtom(data_1, 0, data_1.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); spec.writeOut(out); assertArrayEquals(data_1, out.toByteArray()); } @@ -70,7 +69,7 @@ public final class TestTextSpecInfoAtom { assertEquals(32, run[0].getLength()); //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); spec.writeOut(out); byte[] result = out.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java index 12874ec041..601baf0dc6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -58,7 +57,7 @@ public final class TestTxInteractiveInfoAtom { @Test void testWrite() throws Exception { TxInteractiveInfoAtom atom = new TxInteractiveInfoAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); atom.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -73,7 +72,7 @@ public final class TestTxInteractiveInfoAtom { ia.setEndIndex(56); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -88,7 +87,7 @@ public final class TestTxInteractiveInfoAtom { ia.setEndIndex(78); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java index c09e1e55b3..42b34157d9 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -57,7 +56,7 @@ public final class TestUserEditAtom { @Test void testWrite() throws Exception { UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); uea.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java index e1f453327d..343c1117d9 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java @@ -18,10 +18,10 @@ package org.apache.poi.hslf.usermodel; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.usermodel.BaseTestSlideShow; import org.apache.poi.sl.usermodel.SlideShow; import org.junit.jupiter.api.Test; @@ -38,15 +38,13 @@ public class TestHSLFSlideShow extends BaseTestSlideShow<HSLFShape, HSLFTextPara assertNotNull(createSlideShow()); } + @Override public HSLFSlideShow reopen(SlideShow<HSLFShape, HSLFTextParagraph> show) throws IOException { - BufAccessBAOS bos = new BufAccessBAOS(); - show.write(bos); - return new HSLFSlideShow(new ByteArrayInputStream(bos.getBuf())); - } - - private static class BufAccessBAOS extends ByteArrayOutputStream { - byte[] getBuf() { - return buf; + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + show.write(bos); + try (InputStream is = bos.toInputStream()) { + return new HSLFSlideShow(is); + } } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java index 5e50aa9c1f..65a2716711 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java @@ -17,13 +17,18 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.awt.Dimension; +import java.awt.geom.Dimension2D; +import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.util.Arrays; @@ -31,12 +36,13 @@ import java.util.Collections; import java.util.List; import java.util.Random; +import javax.imageio.ImageIO; + +import org.apache.commons.io.output.CountingOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.blip.DIB; import org.apache.poi.hslf.blip.EMF; import org.apache.poi.hslf.blip.JPEG; import org.apache.poi.hslf.blip.PICT; @@ -50,6 +56,8 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.util.Units; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Test adding/reading pictures @@ -58,302 +66,101 @@ public final class TestPictures { private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); /** - * Test read/write Macintosh PICT - */ - @Test - void testPICT() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("cow.pict"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PICT); - ImageHeaderPICT nHeader = new ImageHeaderPICT(src_bytes, 512); - final int expWidth = 197, expHeight = 137; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.PICT, pd.getType()); - assertTrue(pd instanceof PICT); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertEquals(src_bytes.length, ppt_bytes.length); - //in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them - byte[] b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); - byte[] b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); - assertArrayEquals(b1, b2); - } - - /** - * Test read/write WMF - */ - @Test - void testWMF() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("santa.wmf"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.WMF); - ImageHeaderWMF nHeader = new ImageHeaderWMF(src_bytes, 0); - final int expWidth = 136, expHeight = 146; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(PictureType.WMF, pd.getType()); - assertTrue(pd instanceof WMF); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertEquals(src_bytes.length, ppt_bytes.length); - //in WMF the first 22 bytes - is a metafile header - byte[] b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); - byte[] b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); - assertArrayEquals(b1, b2); - } - - /** - * Test read/write EMF + * Test add/read/write images */ - @Test - void testEMF() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("wrench.emf"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.EMF); - ImageHeaderEMF nHeader = new ImageHeaderEMF(src_bytes, 0); - final int expWidth = 190, expHeight = 115; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can get this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.EMF, pd.getType()); - assertTrue(pd instanceof EMF); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write PNG - */ - @Test - void testPNG() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("tomcat.png"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PNG); - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.PNG, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof PNG); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write JPEG - */ - @Test - void testJPEG() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("clock.jpg"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.JPEG); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.JPEG, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof JPEG); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write DIB - */ - @Test - void testDIB() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("clock.dib"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.DIB); - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.DIB, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof DIB); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); + @ParameterizedTest() + @CsvSource(value = { + // in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them + "PICT, cow.pict, 197, 137, 512, org.apache.poi.hslf.blip.PICT", + // in WMF the first 22 bytes - is a metafile header + "WMF, santa.wmf, 136, 146, 22, org.apache.poi.hslf.blip.WMF", + "EMF, wrench.emf, 190, 115, 0, org.apache.poi.hslf.blip.EMF", + "PNG, tomcat.png, 129, 92, 0, org.apache.poi.hslf.blip.PNG", + "JPEG, clock.jpg, 192, 176, 0, org.apache.poi.hslf.blip.JPEG", + "DIB, clock.dib, 192, 176, 0, org.apache.poi.hslf.blip.DIB" + }) + void testAddPictures(PictureType pictureType, String imgFile, int expWidth, int expHeight, int headerOffset, Class<?> imgClazz) throws IOException { + byte[] src_bytes = slTests.readFile(imgFile); + + int dataIndex; + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + + HSLFSlide slide1 = ppt1.createSlide(); + HSLFPictureData data1 = ppt1.addPicture(src_bytes, pictureType); + dataIndex = data1.getIndex(); + + // TODO: Fix the differences in the frame sizes + Dimension2D dimN, dimFrame1, dimFrame2; + switch (pictureType) { + case PICT: + dimN = new ImageHeaderPICT(src_bytes, headerOffset).getSize(); + dimFrame1 = Units.pointsToPixel(dimN); + dimFrame2 = dimN; + break; + case WMF: + dimN = new ImageHeaderWMF(src_bytes, 0).getSize(); + dimFrame1 = Units.pointsToPixel(dimN); + dimFrame2 = dimN; + break; + case EMF: + dimN = new ImageHeaderEMF(src_bytes, 0).getSize(); + dimFrame1 = Units.pointsToPixel(dimN); + dimFrame2 = dimN; + break; + case JPEG: + case DIB: + case PNG: { + BufferedImage png = ImageIO.read(new ByteArrayInputStream(src_bytes)); + dimN = new Dimension(png.getWidth(), png.getHeight()); + dimFrame1 = dimN; + dimFrame2 = Units.pixelToPoints(dimN); + break; + } + default: + fail(); + return; + } + assertEquals(expWidth, dimN.getWidth(), 1); + assertEquals(expHeight, dimN.getHeight(), 1); + + Dimension dim1 = data1.getImageDimensionInPixels(); + assertEquals(dimFrame1.getWidth(), dim1.getWidth(), 1); + assertEquals(dimFrame1.getHeight(), dim1.getHeight(), 1); + + HSLFPictureShape pict1 = new HSLFPictureShape(data1); + assertEquals(data1.getIndex(), pict1.getPictureIndex()); + slide1.addShape(pict1); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + //make sure we can read this picture shape and it refers to the correct picture data + List<HSLFShape> sh2 = ppt2.getSlides().get(0).getShapes(); + assertEquals(1, sh2.size()); + HSLFPictureShape pict2 = (HSLFPictureShape) sh2.get(0); + assertEquals(dataIndex, pict2.getPictureIndex()); + + //check picture data + List<HSLFPictureData> pictures2 = ppt2.getPictureData(); + assertEquals(1, pictures2.size()); + + HSLFPictureData pd2 = pictures2.get(0); + Dimension dim2 = pd2.getImageDimension(); + assertEquals(dimFrame2.getWidth(), dim2.width, 1); + assertEquals(dimFrame2.getHeight(), dim2.height, 1); + + //the Picture shape refers to the PictureData object in the Presentation + assertEquals(pict2.getPictureData(), pd2); + + assertEquals(1, pictures2.size()); + assertEquals(pictureType, pd2.getType()); + assertTrue(imgClazz.isInstance(pd2)); + //compare the content of the initial file with what is stored in the PictureData + byte[] ppt_bytes = pd2.getData(); + assertEquals(src_bytes.length, ppt_bytes.length); + byte[] b1 = Arrays.copyOfRange(src_bytes, headerOffset, src_bytes.length); + byte[] b2 = Arrays.copyOfRange(ppt_bytes, headerOffset, ppt_bytes.length); + assertArrayEquals(b1, b2); + } + } } /** @@ -366,60 +173,59 @@ public final class TestPictures { HSLFPictureShape pict; HSLFPictureData pdata; - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt"); - List<HSLFSlide> slides = ppt.getSlides(); - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(5, pictures.size()); - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(0); //the first slide contains JPEG - pdata = pict.getPictureData(); - assertTrue(pdata instanceof JPEG); - assertEquals(PictureType.JPEG, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("clock.jpg"); - assertArrayEquals(src_bytes, ppt_bytes); - - pict = (HSLFPictureShape)slides.get(1).getShapes().get(0); //the second slide contains PNG - pdata = pict.getPictureData(); - assertTrue(pdata instanceof PNG); - assertEquals(PictureType.PNG, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("tomcat.png"); - assertArrayEquals(src_bytes, ppt_bytes); - - pict = (HSLFPictureShape)slides.get(2).getShapes().get(0); //the third slide contains WMF - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("santa.wmf"); - assertEquals(src_bytes.length, ppt_bytes.length); - //ignore the first 22 bytes - it is a WMF metafile header - b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); - b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); - assertArrayEquals(b1, b2); - - pict = (HSLFPictureShape)slides.get(3).getShapes().get(0); //the forth slide contains PICT - pdata = pict.getPictureData(); - assertTrue(pdata instanceof PICT); - assertEquals(PictureType.PICT, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("cow.pict"); - assertEquals(src_bytes.length, ppt_bytes.length); - //ignore the first 512 bytes - it is a MAC specific crap - b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); - b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); - assertArrayEquals(b1, b2); - - pict = (HSLFPictureShape)slides.get(4).getShapes().get(0); //the fifth slide contains EMF - pdata = pict.getPictureData(); - assertTrue(pdata instanceof EMF); - assertEquals(PictureType.EMF, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("wrench.emf"); - assertArrayEquals(src_bytes, ppt_bytes); - - ppt.close(); + try (HSLFSlideShow ppt = getSlideShow("pictures.ppt")) { + List<HSLFSlide> slides = ppt.getSlides(); + List<HSLFPictureData> pictures = ppt.getPictureData(); + assertEquals(5, pictures.size()); + + pict = (HSLFPictureShape) slides.get(0).getShapes().get(0); //the first slide contains JPEG + pdata = pict.getPictureData(); + assertTrue(pdata instanceof JPEG); + assertEquals(PictureType.JPEG, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("clock.jpg"); + assertArrayEquals(src_bytes, ppt_bytes); + + pict = (HSLFPictureShape) slides.get(1).getShapes().get(0); //the second slide contains PNG + pdata = pict.getPictureData(); + assertTrue(pdata instanceof PNG); + assertEquals(PictureType.PNG, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("tomcat.png"); + assertArrayEquals(src_bytes, ppt_bytes); + + pict = (HSLFPictureShape) slides.get(2).getShapes().get(0); //the third slide contains WMF + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("santa.wmf"); + assertEquals(src_bytes.length, ppt_bytes.length); + //ignore the first 22 bytes - it is a WMF metafile header + b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); + b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); + assertArrayEquals(b1, b2); + + pict = (HSLFPictureShape) slides.get(3).getShapes().get(0); //the forth slide contains PICT + pdata = pict.getPictureData(); + assertTrue(pdata instanceof PICT); + assertEquals(PictureType.PICT, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("cow.pict"); + assertEquals(src_bytes.length, ppt_bytes.length); + //ignore the first 512 bytes - it is a MAC specific crap + b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); + b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); + assertArrayEquals(b1, b2); + + pict = (HSLFPictureShape) slides.get(4).getShapes().get(0); //the fifth slide contains EMF + pdata = pict.getPictureData(); + assertTrue(pdata instanceof EMF); + assertEquals(PictureType.EMF, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("wrench.emf"); + assertArrayEquals(src_bytes, ppt_bytes); + } } /** @@ -428,35 +234,34 @@ public final class TestPictures { */ @Test void testZeroPictureType() throws IOException { - HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt")); - - // Should still have 2 real pictures - assertEquals(2, hslf.getPictureData().size()); - // Both are real pictures, both WMF - assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); - assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); - - // Now test what happens when we use the SlideShow interface - HSLFSlideShow ppt = new HSLFSlideShow(hslf); - List<HSLFSlide> slides = ppt.getSlides(); - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(12, slides.size()); - assertEquals(2, pictures.size()); - - HSLFPictureShape pict; - HSLFPictureData pdata; - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(1); // 2nd object on 1st slide - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(2); // 3rd object on 1st slide - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - ppt.close(); + try (HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt"))) { + + // Should still have 2 real pictures + assertEquals(2, hslf.getPictureData().size()); + // Both are real pictures, both WMF + assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); + assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); + + // Now test what happens when we use the SlideShow interface + HSLFSlideShow ppt = new HSLFSlideShow(hslf); + List<HSLFSlide> slides = ppt.getSlides(); + List<HSLFPictureData> pictures = ppt.getPictureData(); + assertEquals(12, slides.size()); + assertEquals(2, pictures.size()); + + HSLFPictureShape pict; + HSLFPictureData pdata; + + pict = (HSLFPictureShape) slides.get(0).getShapes().get(1); // 2nd object on 1st slide + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + + pict = (HSLFPictureShape) slides.get(0).getShapes().get(2); // 3rd object on 1st slide + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + } } /** @@ -490,75 +295,70 @@ public final class TestPictures { assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); // Now test what happens when we use the SlideShow interface - HSLFSlideShow ppt = new HSLFSlideShow(hslf); - List<HSLFSlide> slides = ppt.getSlides(); - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(27, slides.size()); - assertEquals(2, pictures.size()); - - HSLFPictureShape pict; - HSLFPictureData pdata; - - pict = (HSLFPictureShape)slides.get(6).getShapes().get(13); - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - pict = (HSLFPictureShape)slides.get(7).getShapes().get(13); - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - //add a new picture, it should be correctly appended to the Pictures stream - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(HSLFPictureData p : pictures) p.write(out); - out.close(); - - int streamSize = out.size(); - - HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG); - int offset = data.getOffset(); - assertEquals(streamSize, offset); - assertEquals(3, ppt.getPictureData().size()); - - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow(hslf)) { + List<HSLFSlide> slides = ppt.getSlides(); + List<HSLFPictureData> pictures = ppt.getPictureData(); + assertEquals(27, slides.size()); + assertEquals(2, pictures.size()); + + HSLFPictureShape pict; + HSLFPictureData pdata; + + pict = (HSLFPictureShape) slides.get(6).getShapes().get(13); + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + + pict = (HSLFPictureShape) slides.get(7).getShapes().get(13); + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + + //add a new picture, it should be correctly appended to the Pictures stream + CountingOutputStream out = new CountingOutputStream(NULL_OUTPUT_STREAM); + for (HSLFPictureData p : pictures) p.write(out); + + int streamSize = out.getCount(); + + HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG); + int offset = data.getOffset(); + assertEquals(streamSize, offset); + assertEquals(3, ppt.getPictureData().size()); + } } @Test void testGetPictureName() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt"); - HSLFSlide slide = ppt.getSlides().get(0); + try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) { + HSLFSlide slide = ppt.getSlides().get(0); - HSLFPictureShape p = (HSLFPictureShape)slide.getShapes().get(0); //the first slide contains JPEG - assertEquals("test", p.getPictureName()); - ppt.close(); + HSLFPictureShape p = (HSLFPictureShape) slide.getShapes().get(0); //the first slide contains JPEG + assertEquals("test", p.getPictureName()); + } } @Test void testSetPictureName() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] img = slTests.readFile("tomcat.png"); - HSLFPictureData data = ppt.addPicture(img, PictureType.PNG); - HSLFPictureShape pict = new HSLFPictureShape(data); - pict.setPictureName("tomcat.png"); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - - HSLFPictureShape p = (HSLFPictureShape)ppt.getSlides().get(0).getShapes().get(0); - assertEquals("tomcat.png", p.getPictureName()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + + HSLFSlide slide = ppt1.createSlide(); + byte[] img = slTests.readFile("tomcat.png"); + HSLFPictureData data = ppt1.addPicture(img, PictureType.PNG); + HSLFPictureShape pict = new HSLFPictureShape(data); + pict.setPictureName("tomcat.png"); + slide.addShape(pict); + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + HSLFPictureShape p = (HSLFPictureShape) ppt2.getSlides().get(0).getShapes().get(0); + assertEquals("tomcat.png", p.getPictureName()); + } + } } @Test void testPictureIndexIsOneBased() throws IOException { - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt")) { + try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) { HSLFPictureData picture = ppt.getPictureData().get(0); assertEquals(1, picture.getIndex()); } @@ -571,20 +371,18 @@ public final class TestPictures { @Test void testEditPictureData() throws IOException { byte[] newImage = slTests.readFile("tomcat.png"); - ByteArrayOutputStream modifiedSlideShow = new ByteArrayOutputStream(); // Load an existing slideshow and modify the image - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt")) { - HSLFPictureData picture = ppt.getPictureData().get(0); - picture.setData(newImage); - ppt.write(modifiedSlideShow); - } + try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png.ppt")) { + HSLFPictureData picture1 = ppt1.getPictureData().get(0); + picture1.setData(newImage); - // Load the modified slideshow and verify the image content - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(modifiedSlideShow.toByteArray()))) { - HSLFPictureData picture = ppt.getPictureData().get(0); - byte[] modifiedImageData = picture.getData(); - assertArrayEquals(newImage, modifiedImageData); + // Load the modified slideshow and verify the image content + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + HSLFPictureData picture2 = ppt2.getPictureData().get(0); + byte[] modifiedImageData = picture2.getData(); + assertArrayEquals(newImage, modifiedImageData); + } } } @@ -595,22 +393,20 @@ public final class TestPictures { @Test void testEditPictureDataEncrypted() throws IOException { byte[] newImage = slTests.readFile("tomcat.png"); - ByteArrayOutputStream modifiedSlideShow = new ByteArrayOutputStream(); Biff8EncryptionKey.setCurrentUserPassword("password"); try { // Load an existing slideshow and modify the image - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png_encrypted.ppt")) { - HSLFPictureData picture = ppt.getPictureData().get(0); - picture.setData(newImage); - ppt.write(modifiedSlideShow); - } - - // Load the modified slideshow and verify the image content - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(modifiedSlideShow.toByteArray()))) { - HSLFPictureData picture = ppt.getPictureData().get(0); - byte[] modifiedImageData = picture.getData(); - assertArrayEquals(newImage, modifiedImageData); + try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png_encrypted.ppt")) { + HSLFPictureData picture1 = ppt1.getPictureData().get(0); + picture1.setData(newImage); + + // Load the modified slideshow and verify the image content + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + HSLFPictureData picture2 = ppt2.getPictureData().get(0); + byte[] modifiedImageData = picture2.getData(); + assertArrayEquals(newImage, modifiedImageData); + } } } finally { Biff8EncryptionKey.setCurrentUserPassword(null); @@ -626,27 +422,23 @@ public final class TestPictures { int[] originalOffsets = {0, 12013, 15081, 34162, 59563}; int[] modifiedOffsets = {0, 35, 3103, 22184, 47585}; - ByteArrayOutputStream inMemory = new ByteArrayOutputStream(); - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) { - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(originalOffsets, offsets); + try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { + int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(originalOffsets, offsets1); - HSLFPictureData imageBeingChanged = ppt.getPictureData().get(0); + HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0); // It doesn't matter that this isn't a valid image. We are just testing offsets here. imageBeingChanged.setData(new byte[10]); // Verify that the in-memory representations have all been updated - offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(modifiedOffsets, offsets); - - ppt.write(inMemory); - } - - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) { + offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(modifiedOffsets, offsets1); - // Verify that the persisted representations have all been updated - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(modifiedOffsets, offsets); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // Verify that the persisted representations have all been updated + int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(modifiedOffsets, offsets2); + } } } @@ -662,11 +454,9 @@ public final class TestPictures { void testEditPictureDataOutOfOrderRecords() throws IOException { int[] modifiedOffsets = {0, 35, 3103, 22184, 47585}; - ByteArrayOutputStream inMemory = new ByteArrayOutputStream(); - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) { - + try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { // For this test we're going to intentionally manipulate the records into a shuffled order. - EscherContainerRecord container = ppt.getPictureData().get(0).bStore; + EscherContainerRecord container = ppt1.getPictureData().get(0).bStore; List<EscherRecord> children = container.getChildRecords(); for (EscherRecord child : children) { container.removeChildRecord(child); @@ -676,25 +466,21 @@ public final class TestPictures { container.addChildRecord(child); } - HSLFPictureData imageBeingChanged = ppt.getPictureData().get(0); + HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0); // It doesn't matter that this isn't a valid image. We are just testing offsets here. imageBeingChanged.setData(new byte[10]); // Verify that the in-memory representations have all been updated - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - Arrays.sort(offsets); - assertArrayEquals(modifiedOffsets, offsets); + int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray(); + assertArrayEquals(modifiedOffsets, offsets1); - ppt.write(inMemory); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // Verify that the persisted representations have all been updated + int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray(); + assertArrayEquals(modifiedOffsets, offsets2); + } } - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) { - - // Verify that the persisted representations have all been updated - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - Arrays.sort(offsets); - assertArrayEquals(modifiedOffsets, offsets); - } } /** @@ -707,28 +493,25 @@ public final class TestPictures { int originalNumberOfRecords; // Create a presentation that has records with unmatched offsets, but with matched UIDs. - ByteArrayOutputStream inMemory = new ByteArrayOutputStream(); - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) { - originalOffsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - originalNumberOfRecords = ppt.getPictureData().get(0).bStore.getChildCount(); + try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { + originalOffsets = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + originalNumberOfRecords = ppt1.getPictureData().get(0).bStore.getChildCount(); Random random = new Random(); - for (HSLFPictureData picture : ppt.getPictureData()) { + for (HSLFPictureData picture : ppt1.getPictureData()) { // Bound is arbitrary and irrelevant to the test. picture.bse.setOffset(random.nextInt(500_000)); } - ppt.write(inMemory); - } - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) { + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // Verify that the offsets all got fixed. + int[] offsets = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(originalOffsets, offsets); - // Verify that the offsets all got fixed. - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(originalOffsets, offsets); - - // Verify that there are the same number of records as in the original slideshow. - int numberOfRecords = ppt.getPictureData().get(0).bStore.getChildCount(); - assertEquals(originalNumberOfRecords, numberOfRecords); + // Verify that there are the same number of records as in the original slideshow. + int numberOfRecords = ppt2.getPictureData().get(0).bStore.getChildCount(); + assertEquals(originalNumberOfRecords, numberOfRecords); + } } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java index 8081528a9f..90a84b815e 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java @@ -24,12 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.hslf.record.Record; import org.apache.poi.hslf.record.SlideListWithText; @@ -230,30 +229,30 @@ public final class TestRichTextRun { assertEquals("Courier", rtr.getFontFamily()); // Write out and back in - HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h); - - // Tweak existing one again, to ensure really worked - rtr.setBold(false); - rtr.setFontSize(17d); - rtr.setFontFamily("CourierZZ"); - - // Check it took those changes - assertFalse(rtr.isBold()); - assertEquals(17., rtr.getFontSize(), 0); - assertEquals("CourierZZ", rtr.getFontFamily()); - - - // Now, look at the one we changed, wrote out, and read back in - // Ensure it does contain our original modifications - HSLFSlide slideOneRR = readS.getSlides().get(0); - List<List<HSLFTextParagraph>> textParassRR = slideOneRR.getTextParagraphs(); - HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0); - - assertTrue(rtrRRa.isBold()); - assertNotNull(rtrRRa.getFontSize()); - assertEquals(18., rtrRRa.getFontSize(), 0); - assertEquals("Courier", rtrRRa.getFontFamily()); - readS.close(); + try (HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h)) { + + // Tweak existing one again, to ensure really worked + rtr.setBold(false); + rtr.setFontSize(17d); + rtr.setFontFamily("CourierZZ"); + + // Check it took those changes + assertFalse(rtr.isBold()); + assertEquals(17., rtr.getFontSize(), 0); + assertEquals("CourierZZ", rtr.getFontFamily()); + + + // Now, look at the one we changed, wrote out, and read back in + // Ensure it does contain our original modifications + HSLFSlide slideOneRR = readS.getSlides().get(0); + List<List<HSLFTextParagraph>> textParassRR = slideOneRR.getTextParagraphs(); + HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0); + + assertTrue(rtrRRa.isBold()); + assertNotNull(rtrRRa.getFontSize()); + assertEquals(18., rtrRRa.getFontSize(), 0); + assertEquals("Courier", rtrRRa.getFontFamily()); + } } } @@ -370,29 +369,30 @@ public final class TestRichTextRun { */ private void assertMatchesSLTWC(HSLFSlideShow s) throws IOException { // Grab a new copy of slideshow C - HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC); + try (HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC)) { - // Write out the 2nd SLWT in the active document - SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1]; - byte[] raw_slwt = writeRecord(refSLWT); + // Write out the 2nd SLWT in the active document + SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1]; + byte[] raw_slwt = writeRecord(refSLWT); - // Write out the same for the supplied slideshow - SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1]; - byte[] s_slwt = writeRecord(s_SLWT); + // Write out the same for the supplied slideshow + SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1]; + byte[] s_slwt = writeRecord(s_SLWT); - // Check the records are the same - assertEquals(refSLWT.getChildRecords().length, s_SLWT.getChildRecords().length); - for(int i=0; i<refSLWT.getChildRecords().length; i++) { - Record ref_r = refSLWT.getChildRecords()[i]; - Record s_r = s_SLWT.getChildRecords()[i]; + // Check the records are the same + assertEquals(refSLWT.getChildRecords().length, s_SLWT.getChildRecords().length); + for (int i = 0; i < refSLWT.getChildRecords().length; i++) { + Record ref_r = refSLWT.getChildRecords()[i]; + Record s_r = s_SLWT.getChildRecords()[i]; - byte[] r_rb = writeRecord(ref_r); - byte[] s_rb = writeRecord(s_r); - assertArrayEquals(r_rb, s_rb); - } + byte[] r_rb = writeRecord(ref_r); + byte[] s_rb = writeRecord(s_r); + assertArrayEquals(r_rb, s_rb); + } - // Check the bytes are the same - assertArrayEquals(raw_slwt, s_slwt); + // Check the bytes are the same + assertArrayEquals(raw_slwt, s_slwt); + } } /** @@ -401,20 +401,20 @@ public final class TestRichTextRun { */ private static void assertMatchesFileC(HSLFSlideShow s) throws IOException { // Grab the bytes of the file - POIFSFileSystem fs = new POIFSFileSystem(HSLFTestDataSamples.openSampleFileStream(filenameC)); - InputStream is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT); - byte[] raw_file = IOUtils.toByteArray(is); - is.close(); - fs.close(); + byte[] raw_file; + try (POIFSFileSystem fs = new POIFSFileSystem(HSLFTestDataSamples.openSampleFileStream(filenameC)); + InputStream is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT)) { + raw_file = IOUtils.toByteArray(is); + } // Now write out the slideshow - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] raw_ss; + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); s.write(baos); - fs = new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); - is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT); - byte[] raw_ss = IOUtils.toByteArray(is); - is.close(); - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(baos.toInputStream()); + InputStream is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT)) { + raw_ss = IOUtils.toByteArray(is); + } // different paragraph mask, because of sanitizing raw_ss[169030] = 0x0a; @@ -424,24 +424,24 @@ public final class TestRichTextRun { } private byte[] writeRecord( org.apache.poi.hslf.record.Record r) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); return baos.toByteArray(); } @Test void testIndentationLevel() throws Exception { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ParagraphStylesShorterThanCharStyles.ppt"); - for (HSLFSlide sl : ppt.getSlides()) { - for (List<HSLFTextParagraph> txt : sl.getTextParagraphs()) { - for (HSLFTextParagraph p : txt) { - int indent = p.getIndentLevel(); - assertTrue(indent >= 0 && indent <= 4 ); - } + try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ParagraphStylesShorterThanCharStyles.ppt")) { + for (HSLFSlide sl : ppt.getSlides()) { + for (List<HSLFTextParagraph> txt : sl.getTextParagraphs()) { + for (HSLFTextParagraph p : txt) { + int indent = p.getIndentLevel(); + assertTrue(indent >= 0 && indent <= 4); + } + } } } - ppt.close(); } @Test @@ -502,54 +502,54 @@ public final class TestRichTextRun { @Test void testSetParagraphStyles() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { - HSLFSlide slide = ppt1.createSlide(); + HSLFSlide slide = ppt1.createSlide(); - HSLFTextBox shape = new HSLFTextBox(); - shape.setText( + HSLFTextBox shape = new HSLFTextBox(); + shape.setText( "Hello, World!\r" + - "This should be\r" + - "Multiline text"); - HSLFTextParagraph rt = shape.getTextParagraphs().get(0); - HSLFTextRun tr = rt.getTextRuns().get(0); - tr.setFontSize(42d); - rt.setBullet(true); - rt.setLeftMargin(50d); - rt.setIndent(0d); - rt.setBulletChar('\u263A'); - slide.addShape(shape); - - assertNotNull(tr.getFontSize()); - assertEquals(42.0, tr.getFontSize(), 0); - assertTrue(rt.isBullet()); - assertNotNull(rt.getLeftMargin()); - assertEquals(50.0, rt.getLeftMargin(), 0); - assertNotNull(rt.getIndent()); - assertEquals(0, rt.getIndent(), 0); - assertNotNull(rt.getBulletChar()); - assertEquals('\u263A', (char)rt.getBulletChar()); - - shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); - slide.addShape(shape); - - //serialize and read again - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - slide = ppt2.getSlides().get(0); - shape = (HSLFTextBox)slide.getShapes().get(0); - rt = shape.getTextParagraphs().get(0); - tr = rt.getTextRuns().get(0); - assertNotNull(tr.getFontSize()); - assertEquals(42.0, tr.getFontSize(), 0); - assertTrue(rt.isBullet()); - assertNotNull(rt.getLeftMargin()); - assertEquals(50.0, rt.getLeftMargin(), 0); - assertNotNull(rt.getIndent()); - assertEquals(0, rt.getIndent(), 0); - assertNotNull(rt.getBulletChar()); - assertEquals('\u263A', (char)rt.getBulletChar()); - ppt2.close(); - ppt1.close(); + "This should be\r" + + "Multiline text"); + HSLFTextParagraph rt = shape.getTextParagraphs().get(0); + HSLFTextRun tr = rt.getTextRuns().get(0); + tr.setFontSize(42d); + rt.setBullet(true); + rt.setLeftMargin(50d); + rt.setIndent(0d); + rt.setBulletChar('\u263A'); + slide.addShape(shape); + + assertNotNull(tr.getFontSize()); + assertEquals(42.0, tr.getFontSize(), 0); + assertTrue(rt.isBullet()); + assertNotNull(rt.getLeftMargin()); + assertEquals(50.0, rt.getLeftMargin(), 0); + assertNotNull(rt.getIndent()); + assertEquals(0, rt.getIndent(), 0); + assertNotNull(rt.getBulletChar()); + assertEquals('\u263A', (char) rt.getBulletChar()); + + shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); + slide.addShape(shape); + + //serialize and read again + try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + shape = (HSLFTextBox) slide.getShapes().get(0); + rt = shape.getTextParagraphs().get(0); + tr = rt.getTextRuns().get(0); + assertNotNull(tr.getFontSize()); + assertEquals(42.0, tr.getFontSize(), 0); + assertTrue(rt.isBullet()); + assertNotNull(rt.getLeftMargin()); + assertEquals(50.0, rt.getLeftMargin(), 0); + assertNotNull(rt.getIndent()); + assertEquals(0, rt.getIndent(), 0); + assertNotNull(rt.getBulletChar()); + assertEquals('\u263A', (char) rt.getBulletChar()); + } + } } @Test diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java index 1176003e7a..437cb592ff 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java @@ -19,6 +19,7 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -26,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; @@ -108,58 +107,49 @@ public class TestTable { @Test void testAddText() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlide slide = ppt1.createSlide(); - HSLFTable tab = slide.createTable(4, 5); - - int rows = tab.getNumberOfRows(); - int cols = tab.getNumberOfColumns(); - for (int row=0; row<rows; row++) { - for (int col=0; col<cols; col++) { - HSLFTableCell c = tab.getCell(row, col); - assertNotNull(c); - c.setText("r"+(row+1)+"c"+(col+1)); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide = ppt1.createSlide(); + HSLFTable tab = slide.createTable(4, 5); + + int rows = tab.getNumberOfRows(); + int cols = tab.getNumberOfColumns(); + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + HSLFTableCell c = tab.getCell(row, col); + assertNotNull(c); + c.setText("r" + (row + 1) + "c" + (col + 1)); + } } - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt1.write(bos); - ppt1.close(); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - HSLFSlideShow ppt2 = new HSLFSlideShow(bis); - slide = ppt2.getSlides().get(0); - tab = (HSLFTable)slide.getShapes().get(0); - - rows = tab.getNumberOfRows(); - cols = tab.getNumberOfColumns(); - for (int row=0; row<rows; row++) { - for (int col=0; col<cols; col++) { - HSLFTableCell c = tab.getCell(row, col); - assertNotNull(c); - c.setText(c.getText()+"..."); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + tab = (HSLFTable) slide.getShapes().get(0); + + rows = tab.getNumberOfRows(); + cols = tab.getNumberOfColumns(); + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + HSLFTableCell c = tab.getCell(row, col); + assertNotNull(c); + c.setText(c.getText() + "..."); + } + } + + try (HSLFSlideShow ppt3 = writeOutAndReadBack(ppt2)) { + slide = ppt3.getSlides().get(0); + tab = (HSLFTable) slide.getShapes().get(0); + + rows = tab.getNumberOfRows(); + cols = tab.getNumberOfColumns(); + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + HSLFTableCell c = tab.getCell(row, col); + assertNotNull(c); + assertEquals("r" + (row + 1) + "c" + (col + 1) + "...", c.getText()); + } + } + } } } - - bos.reset(); - ppt2.write(bos); - ppt2.close(); - - bis = new ByteArrayInputStream(bos.toByteArray()); - HSLFSlideShow ppt3 = new HSLFSlideShow(bis); - slide = ppt3.getSlides().get(0); - tab = (HSLFTable)slide.getShapes().get(0); - - rows = tab.getNumberOfRows(); - cols = tab.getNumberOfColumns(); - for (int row=0; row<rows; row++) { - for (int col=0; col<cols; col++) { - HSLFTableCell c = tab.getCell(row, col); - assertNotNull(c); - assertEquals("r"+(row+1)+"c"+(col+1)+"...", c.getText()); - } - } - - ppt3.close(); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java index 1b577eb273..10493a6998 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java @@ -17,27 +17,26 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; import org.junit.jupiter.api.Test; /** - * Verify behavior of <code>TextShape</code> and its sub-classes + * Verify behavior of {@code TextShape} and its sub-classes */ public final class TestTextShape { @Test @@ -72,153 +71,146 @@ public final class TestTextShape { */ @Test void read() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text_shapes.ppt"); - - List<String> lst1 = new ArrayList<>(); - HSLFSlide slide = ppt.getSlides().get(0); - for (HSLFShape shape : slide.getShapes()) { - assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName()); - HSLFTextShape tx = (HSLFTextShape)shape; - List<HSLFTextParagraph> paras = tx.getTextParagraphs(); - assertNotNull(paras); - int runType = paras.get(0).getRunType(); - - ShapeType type = shape.getShapeType(); - String rawText = HSLFTextParagraph.getRawText(paras); - switch (type){ - case TEXT_BOX: - assertEquals("Text in a TextBox", rawText); - break; - case RECT: - if(runType == TextPlaceholder.OTHER.nativeId) { - assertEquals("Rectangle", rawText); - } else if(runType == TextPlaceholder.TITLE.nativeId) { - assertEquals("Title Placeholder", rawText); - } - break; - case OCTAGON: - assertEquals("Octagon", rawText); - break; - case ELLIPSE: - assertEquals("Ellipse", rawText); - break; - case ROUND_RECT: - assertEquals("RoundRectangle", rawText); - break; - default: - fail("Unexpected shape: " + shape.getShapeName()); + try (HSLFSlideShow ppt = getSlideShow("text_shapes.ppt")) { + + List<String> lst1 = new ArrayList<>(); + HSLFSlide slide = ppt.getSlides().get(0); + for (HSLFShape shape : slide.getShapes()) { + assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName()); + HSLFTextShape tx = (HSLFTextShape) shape; + List<HSLFTextParagraph> paras = tx.getTextParagraphs(); + assertNotNull(paras); + int runType = paras.get(0).getRunType(); + + ShapeType type = shape.getShapeType(); + String rawText = HSLFTextParagraph.getRawText(paras); + switch (type) { + case TEXT_BOX: + assertEquals("Text in a TextBox", rawText); + break; + case RECT: + if (runType == TextPlaceholder.OTHER.nativeId) { + assertEquals("Rectangle", rawText); + } else if (runType == TextPlaceholder.TITLE.nativeId) { + assertEquals("Title Placeholder", rawText); + } + break; + case OCTAGON: + assertEquals("Octagon", rawText); + break; + case ELLIPSE: + assertEquals("Ellipse", rawText); + break; + case ROUND_RECT: + assertEquals("RoundRectangle", rawText); + break; + default: + fail("Unexpected shape: " + shape.getShapeName()); + + } + lst1.add(rawText); + } + List<String> lst2 = new ArrayList<>(); + for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) { + lst2.add(HSLFTextParagraph.getRawText(paras)); } - lst1.add(rawText); - } - List<String> lst2 = new ArrayList<>(); - for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) { - lst2.add(HSLFTextParagraph.getRawText(paras)); + assertTrue(lst1.containsAll(lst2)); } - - assertTrue(lst1.containsAll(lst2)); - ppt.close(); } @Test void readWrite() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - - HSLFTextShape shape1 = new HSLFTextBox(); - shape1.setText("Hello, World!"); - slide.addShape(shape1); - - shape1.moveTo(100, 100); - - HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW); - shape2.setText("Testing TextShape"); - slide.addShape(shape2); - shape2.moveTo(300, 300); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - slide = ppt.getSlides().get(0); - List<HSLFShape> shape = slide.getShapes(); - - assertTrue(shape.get(0) instanceof HSLFTextShape); - shape1 = (HSLFTextShape)shape.get(0); - assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType()); - assertEquals("Hello, World!", shape1.getText()); - - assertTrue(shape.get(1) instanceof HSLFTextShape); - shape1 = (HSLFTextShape)shape.get(1); - assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType()); - assertEquals("Testing TextShape", shape1.getText()); - ppt.close(); - } + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide = ppt1.createSlide(); - @Test - void margins() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text-margins.ppt"); + HSLFTextShape shape1 = new HSLFTextBox(); + shape1.setText("Hello, World!"); + slide.addShape(shape1); + + shape1.moveTo(100, 100); + + HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW); + shape2.setText("Testing TextShape"); + slide.addShape(shape2); + shape2.moveTo(300, 300); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + List<HSLFShape> shape = slide.getShapes(); - HSLFSlide slide = ppt.getSlides().get(0); + assertTrue(shape.get(0) instanceof HSLFTextShape); + shape1 = (HSLFTextShape) shape.get(0); + assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType()); + assertEquals("Hello, World!", shape1.getText()); - Map<String,HSLFTextShape> map = new HashMap<>(); - for (HSLFShape shape : slide.getShapes()) { - if(shape instanceof HSLFTextShape){ - HSLFTextShape tx = (HSLFTextShape)shape; - map.put(tx.getText(), tx); + assertTrue(shape.get(1) instanceof HSLFTextShape); + shape1 = (HSLFTextShape) shape.get(1); + assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType()); + assertEquals("Testing TextShape", shape1.getText()); } } - - HSLFTextShape tx; - - tx = map.get("TEST1"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(28.34, tx.getTopInset(), 0.01); - assertEquals(3.6, tx.getBottomInset(), 0); - - tx = map.get("TEST2"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(28.34, tx.getBottomInset(), 0.01); - - tx = map.get("TEST3"); - assertEquals(28.34, tx.getLeftInset(), 0.01); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(3.6, tx.getBottomInset(), 0); - - tx = map.get("TEST4"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(28.34, tx.getRightInset(), 0.01); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(3.6, tx.getBottomInset(), 0); - - ppt.close(); } @Test - void bug52599() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("52599.ppt"); + void margins() throws IOException { + try (HSLFSlideShow ppt = getSlideShow("text-margins.ppt")) { - HSLFSlide slide = ppt.getSlides().get(0); - List<HSLFShape> sh = slide.getShapes(); - assertEquals(3, sh.size()); + HSLFSlide slide = ppt.getSlides().get(0); - HSLFTextShape sh0 = (HSLFTextShape)sh.get(0); - assertNotNull(sh0.getTextParagraphs()); - assertEquals("", sh0.getText()); + Map<String, HSLFTextShape> map = new HashMap<>(); + for (HSLFShape shape : slide.getShapes()) { + if (shape instanceof HSLFTextShape) { + HSLFTextShape tx = (HSLFTextShape) shape; + map.put(tx.getText(), tx); + } + } - HSLFTextShape sh1 = (HSLFTextShape)sh.get(1); - assertNotNull(sh1.getTextParagraphs()); - assertEquals("", sh1.getText()); + HSLFTextShape tx = map.get("TEST1"); + assertEquals(7.2, tx.getLeftInset(), 0); + assertEquals(7.2, tx.getRightInset(), 0); + assertEquals(28.34, tx.getTopInset(), 0.01); + assertEquals(3.6, tx.getBottomInset(), 0); + + tx = map.get("TEST2"); + assertEquals(7.2, tx.getLeftInset(), 0); + assertEquals(7.2, tx.getRightInset(), 0); + assertEquals(3.6, tx.getTopInset(), 0); + assertEquals(28.34, tx.getBottomInset(), 0.01); + + tx = map.get("TEST3"); + assertEquals(28.34, tx.getLeftInset(), 0.01); + assertEquals(7.2, tx.getRightInset(), 0); + assertEquals(3.6, tx.getTopInset(), 0); + assertEquals(3.6, tx.getBottomInset(), 0); + + tx = map.get("TEST4"); + assertEquals(7.2, tx.getLeftInset(), 0); + assertEquals(28.34, tx.getRightInset(), 0.01); + assertEquals(3.6, tx.getTopInset(), 0); + assertEquals(3.6, tx.getBottomInset(), 0); + } + } - HSLFTextShape sh2 = (HSLFTextShape)sh.get(2); - assertEquals("this box should be shown just once", sh2.getText()); - assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex()); - ppt.close(); + @Test + void bug52599() throws IOException { + try (HSLFSlideShow ppt = getSlideShow("52599.ppt")) { + HSLFSlide slide = ppt.getSlides().get(0); + List<HSLFShape> sh = slide.getShapes(); + assertEquals(3, sh.size()); + + HSLFTextShape sh0 = (HSLFTextShape) sh.get(0); + assertNotNull(sh0.getTextParagraphs()); + assertEquals("", sh0.getText()); + + HSLFTextShape sh1 = (HSLFTextShape) sh.get(1); + assertNotNull(sh1.getTextParagraphs()); + assertEquals("", sh1.getText()); + + HSLFTextShape sh2 = (HSLFTextShape) sh.get(2); + assertEquals("this box should be shown just once", sh2.getText()); + assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex()); + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java index 4f0322b806..a11ba12c90 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java @@ -21,12 +21,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Map; import java.util.TimeZone; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.AttachmentChunks; import org.apache.poi.hsmf.datatypes.Chunk; @@ -54,8 +54,6 @@ public class TestExtractEmbeddedMSG { /** * Initialize this test, load up the attachment_msg_pdf.msg mapi message. - * - * @throws Exception */ @BeforeAll public static void setUp() throws IOException { @@ -71,9 +69,6 @@ public class TestExtractEmbeddedMSG { /** * Test to see if embedded message properties can be read, extracted, and * re-parsed - * - * @throws ChunkNotFoundException - * */ @Test void testEmbeddedMSGProperties() throws IOException, ChunkNotFoundException { @@ -86,11 +81,9 @@ public class TestExtractEmbeddedMSG { testFixedAndVariableLengthPropertiesOfAttachedMSG(attachedMsg); // rebuild top level message from embedded message try (POIFSFileSystem extractedAttachedMsg = rebuildFromAttached(attachedMsg)) { - try (ByteArrayOutputStream extractedAttachedMsgOut = new ByteArrayOutputStream()) { + try (UnsynchronizedByteArrayOutputStream extractedAttachedMsgOut = new UnsynchronizedByteArrayOutputStream()) { extractedAttachedMsg.writeFilesystem(extractedAttachedMsgOut); - byte[] extratedAttachedMsgRaw = extractedAttachedMsgOut.toByteArray(); - MAPIMessage extractedMsgTopLevel = new MAPIMessage( - new ByteArrayInputStream(extratedAttachedMsgRaw)); + MAPIMessage extractedMsgTopLevel = new MAPIMessage(extractedAttachedMsgOut.toInputStream()); // test properties of rebuilt embedded message testFixedAndVariableLengthPropertiesOfAttachedMSG(extractedMsgTopLevel); } @@ -104,7 +97,7 @@ public class TestExtractEmbeddedMSG { Calendar messageDate = msg.getMessageDate(); assertNotNull(messageDate); Calendar expectedMessageDate = LocaleUtil.getLocaleCalendar(); - expectedMessageDate.set(2010, 05, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT + expectedMessageDate.set(2010, Calendar.JUNE, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT expectedMessageDate.setTimeZone(TimeZone.getTimeZone("GMT")); expectedMessageDate.set(Calendar.MILLISECOND, 0); assertEquals(expectedMessageDate.getTimeInMillis(), messageDate.getTimeInMillis()); @@ -178,7 +171,7 @@ public class TestExtractEmbeddedMSG { MAPIType type = Types.getById(iType); if (type != null && type != Types.UNKNOWN) { MAPIProperty mprop = MAPIProperty.createCustom(chunk.getChunkId(), type, chunk.getEntryName()); - ByteArrayOutputStream data = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream data = new UnsynchronizedByteArrayOutputStream(); chunk.writeValue(data); PropertyValue pval = new PropertyValue(mprop, MessagePropertiesChunk.PROPERTIES_FLAG_READABLE | MessagePropertiesChunk.PROPERTIES_FLAG_WRITEABLE, data.toByteArray(), type); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java index 1d8cc9f98a..068fa10883 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java @@ -22,14 +22,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.AttachmentChunks; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Tests to verify that we can read attachments from msg file @@ -74,32 +76,21 @@ public class TestFileWithAttachmentsRead { /** * Bug 60550: Test to see if we get the correct Content-IDs of inline images`. */ - @Test - void testReadContentIDField() throws IOException { - AttachmentChunks[] attachments = inlineImgMsgAttachments.getAttachmentFiles(); - - AttachmentChunks attachment; - - // Check in Content-ID field - attachment = inlineImgMsgAttachments.getAttachmentFiles()[0]; - assertEquals("image001.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image001.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[1]; - assertEquals("image002.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image002.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[2]; - assertEquals("image003.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image003.png@01D0A526.B4C739C0", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[3]; - assertEquals("image006.jpg", attachment.getAttachFileName().getValue()); - assertEquals(".jpg", attachment.getAttachExtension().getValue()); - assertEquals("image006.jpg@01D0A526.B649E220", attachment.getAttachContentId().getValue()); + @ParameterizedTest + @CsvSource({ + "0, image001.png@01D0A524.96D40F30", + "1, image002.png@01D0A524.96D40F30", + "2, image003.png@01D0A526.B4C739C0", + "3, image006.jpg@01D0A526.B649E220" + }) + void testReadContentIDField(int index, String contentId) { + AttachmentChunks attachment = inlineImgMsgAttachments.getAttachmentFiles()[index]; + String fileName = contentId.substring(0, contentId.indexOf("@")); + String extension = fileName.substring(fileName.lastIndexOf(".")); + + assertEquals(fileName, attachment.getAttachFileName().getValue()); + assertEquals(extension, attachment.getAttachExtension().getValue()); + assertEquals(contentId, attachment.getAttachContentId().getValue()); } @@ -128,7 +119,7 @@ public class TestFileWithAttachmentsRead { assertEquals("test-unicode.doc", attachment.getAttachLongFileName().getValue()); assertEquals(".doc", attachment.getAttachExtension().getValue()); assertNull(attachment.getAttachMimeTag()); - ByteArrayOutputStream attachmentstream = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream attachmentstream = new UnsynchronizedByteArrayOutputStream(); attachment.getAttachData().writeValue(attachmentstream); assertEquals(24064, attachmentstream.size()); // or compare the hashes of the attachment data @@ -141,7 +132,7 @@ public class TestFileWithAttachmentsRead { assertNull(attachment.getAttachMimeTag()); // or compare the hashes of the attachment data assertEquals(89, attachment.getAttachData().getValue().length); - attachmentstream = new ByteArrayOutputStream(); + attachmentstream.reset(); attachment.getAttachData().writeValue(attachmentstream); assertEquals(89, attachmentstream.size()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java index 04131f3a23..74d6d27ec2 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashSet; @@ -33,6 +32,7 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; +import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.ChunkBasedPropertyValue; import org.apache.poi.hsmf.datatypes.Chunks; @@ -44,7 +44,6 @@ import org.apache.poi.hsmf.dev.HSMFDump; import org.apache.poi.hsmf.extractor.OutlookTextExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NullPrintStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -167,7 +166,7 @@ public final class TestFixedSizedProperties { * Test to see if we can read the Date Chunk with HSMFDump. */ @Test - void testReadMessageDateSucceedsWithHSMFDump() throws IOException { + void testReadMessageDateSucceedsWithHSMFDump() { HSMFDump dump = new HSMFDump(fsMessageSucceeds); assertDoesNotThrow(() -> dump.dump(new NullPrintStream())); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java index 937bb5367d..fba8bc97c0 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java @@ -17,10 +17,10 @@ package org.apache.poi.hwpf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -29,7 +29,7 @@ public abstract class HWPFTestCase { @BeforeEach void setUp() throws Exception { - /** @todo verify the constructors */ + // @TODO verify the constructors _hWPFDocFixture = new HWPFDocFixture(this, getTestFile()); _hWPFDocFixture.setUp(); @@ -40,7 +40,7 @@ public abstract class HWPFTestCase { } @AfterEach - void tearDown() throws Exception { + void tearDown() { if (_hWPFDocFixture != null) { _hWPFDocFixture.tearDown(); } @@ -49,15 +49,13 @@ public abstract class HWPFTestCase { } public HWPFDocument writeOutAndRead(HWPFDocument doc) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - HWPFDocument newDoc; - try { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - newDoc = new HWPFDocument(bais); + try (InputStream is = baos.toInputStream()) { + return new HWPFDocument(is); + } } catch (IOException e) { throw new RuntimeException(e); } - return newDoc; } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java index b8f11dc40f..0d6ce9bc8c 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java @@ -16,74 +16,24 @@ ==================================================================== */ package org.apache.poi.hwpf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.zip.ZipInputStream; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; - -import static org.apache.logging.log4j.util.Unbox.box; public class HWPFTestDataSamples { - - private static final Logger LOG = LogManager.getLogger(HWPFTestDataSamples.class); + private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); public static HWPFDocument openSampleFile(String sampleFileName) { - try { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); - try { - return new HWPFDocument(is); - } catch (Throwable e) { - is.close(); - throw e; - } + try (InputStream is = SAMPLES.openResourceAsStream(sampleFileName)) { + return new HWPFDocument(is); } catch (IOException e) { throw new RuntimeException(e); } } - public static HWPFDocument openSampleFileFromArchive( String sampleFileName ) - { - final long start = System.currentTimeMillis(); - try - { - try (ZipInputStream is = new ZipInputStream(POIDataSamples - .getDocumentInstance() - .openResourceAsStream(sampleFileName))) { - is.getNextEntry(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - IOUtils.copy(is, baos); - } finally { - baos.close(); - } - - final long endUnzip = System.currentTimeMillis(); - byte[] byteArray = baos.toByteArray(); - - LOG.atDebug().log("Unzipped in {} ms -- {} byte(s)", box(endUnzip - start),box(byteArray.length)); - - ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); - HWPFDocument doc = new HWPFDocument(bais); - final long endParse = System.currentTimeMillis(); - - LOG.atDebug().log("Parsed in {} ms", box(endParse - start)); - - return doc; - } - } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - } - public static HWPFOldDocument openOldSampleFile(String sampleFileName) { try { InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); @@ -98,11 +48,9 @@ public class HWPFTestDataSamples { * Useful for verifying that the serialisation round trip */ public static HWPFDocument writeOutAndReadBack(HWPFDocument original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HWPFDocument(bais); + return new HWPFDocument(baos.toInputStream()); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java index 3a94a3efb4..c7cd45c1cc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java @@ -22,7 +22,7 @@ import java.io.PrintStream; import java.util.Arrays; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -38,7 +38,7 @@ public class TestHWPFLister { "", " --dop --textPieces --textPiecesText --chpx --chpxProperties --chpxSprms --papx --papxProperties --papxSprms --paragraphs --paragraphsText --bookmarks --escher --fields --pictures --officeDrawings --styles --writereadback" }) - void main(String args) throws Exception { + void main(String args) { String fileArgs = SAMPLES.getFile("SampleDoc.doc").getAbsolutePath() + args; PrintStream oldStdOut = System.out; diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java index 0ae2e4a87a..b98f5208a0 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java @@ -17,17 +17,15 @@ package org.apache.poi.hwpf.model; +import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; +import static org.apache.poi.hwpf.HWPFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Arrays; import java.util.List; import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; import org.junit.jupiter.api.Test; /** @@ -53,29 +51,21 @@ public final class TestSavedByTable { * Tests reading in the entries, comparing them against the expected * entries. Then tests writing the document out and reading the entries yet * again. - * - * @throws Exception if an unexpected error occurs. */ @Test void testReadWrite() throws IOException { // This document is widely available on the internet as "blair.doc". // I tried stripping the content and saving the document but my version // of Word (from Office XP) strips this table out. - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc"); + try (HWPFDocument doc = openSampleFile("saved-by-table.doc")) { + // Check what we just read. + assertEquals(expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected"); - // Check what we just read. - assertEquals( expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected" ); - - // Now write the entire document out, and read it back in... - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - doc.write(byteStream); - InputStream copyStream = new ByteArrayInputStream(byteStream.toByteArray()); - doc.close(); - HWPFDocument copy = new HWPFDocument(copyStream); - - // And check again. - assertEquals( expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing" ); - - copy.close(); + // Now write the entire document out, and read it back in... + try (HWPFDocument copy = writeOutAndReadBack(doc)) { + // And check again. + assertEquals(expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing"); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java index 65c5dac5a8..d8cbba82c8 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java @@ -19,43 +19,29 @@ package org.apache.poi.hwpf.sprm; +import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; +import static org.apache.poi.hwpf.HWPFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Locale; -import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.junit.jupiter.api.Test; public class TestSprms { - private static HWPFDocument reload( HWPFDocument hwpfDocument ) - throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hwpfDocument.write( baos ); - return new HWPFDocument( new ByteArrayInputStream( baos.toByteArray() ) ); - } - /** * Test correct processing of "sprmPItap" (0x6649) and "sprmPFInTable" * (0x2416) */ @Test void testInnerTable() throws Exception { - InputStream resourceAsStream = POIDataSamples.getDocumentInstance() - .openResourceAsStream( "innertable.doc" ); - try (HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream )) { - resourceAsStream.close(); - + try (HWPFDocument hwpfDocument = openSampleFile("innertable.doc")) { testInnerTable(hwpfDocument); - try (HWPFDocument hwpfDocument2 = reload(hwpfDocument)) { + try (HWPFDocument hwpfDocument2 = writeOutAndReadBack(hwpfDocument)) { testInnerTable(hwpfDocument2); } } @@ -87,20 +73,12 @@ public class TestSprms { */ @Test void testSprmPJc() throws IOException { - try (InputStream resourceAsStream = POIDataSamples.getDocumentInstance() - .openResourceAsStream( "Bug49820.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream )) { - resourceAsStream.close(); + try (HWPFDocument hwpfDocument = openSampleFile( "Bug49820.doc" )) { + assertEquals(1, hwpfDocument.getStyleSheet().getParagraphStyle(8).getJustification()); - assertEquals(1, hwpfDocument.getStyleSheet().getParagraphStyle(8) - .getJustification()); - - try (HWPFDocument hwpfDocument2 = reload(hwpfDocument)) { - - assertEquals(1, hwpfDocument2.getStyleSheet().getParagraphStyle(8) - .getJustification()); + try (HWPFDocument hwpfDocument2 = writeOutAndReadBack(hwpfDocument)) { + assertEquals(1, hwpfDocument2.getStyleSheet().getParagraphStyle(8).getJustification()); } } - } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java index 3f0f8b7ce0..36ad393a51 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java @@ -20,14 +20,13 @@ package org.apache.poi.hwpf.usermodel; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestCase; @@ -48,20 +47,17 @@ public final class TestHWPFWrite extends HWPFTestCase { */ @Test void testWriteStream() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); - - Range r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - doc.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + try (HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc")) { + Range r = doc.getRange(); + assertEquals("I am a test document\r", r.getParagraph(0).text()); + doc.write(baos); + } - doc = new HWPFDocument(bais); - r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - doc.close(); + try (HWPFDocument doc = new HWPFDocument(baos.toInputStream())) { + Range r = doc.getRange(); + assertEquals("I am a test document\r", r.getParagraph(0).text()); + } } /** diff --git a/poi/build.gradle b/poi/build.gradle index d4388eebfc..23d024c516 100644 --- a/poi/build.gradle +++ b/poi/build.gradle @@ -39,6 +39,7 @@ dependencies { api "commons-codec:commons-codec:${commonsCodecVersion}" api 'org.apache.commons:commons-collections4:4.4' api "org.apache.commons:commons-math3:${commonsMathVersion}" + api "commons-io:commons-io:${commonsIoVersion}" api 'com.zaxxer:SparseBitSet:1.2' implementation "org.apache.logging.log4j:log4j-api:${log4jVersion}" implementation 'javax.activation:activation:1.1.1' diff --git a/poi/src/main/java/org/apache/poi/POIDocument.java b/poi/src/main/java/org/apache/poi/POIDocument.java index e2f613af64..e1405f9977 100644 --- a/poi/src/main/java/org/apache/poi/POIDocument.java +++ b/poi/src/main/java/org/apache/poi/POIDocument.java @@ -21,8 +21,6 @@ import static org.apache.logging.log4j.util.Unbox.box; import static org.apache.poi.hpsf.PropertySetFactory.newDocumentSummaryInformation; import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; @@ -32,6 +30,7 @@ import java.io.OutputStream; import java.security.GeneralSecurityException; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hpsf.DocumentSummaryInformation; @@ -323,18 +322,16 @@ public abstract class POIDocument implements Closeable { * {@link POIFSFileSystem} occurs */ private void writePropertySet(String name, PropertySet set, POIFSFileSystem outFS) throws IOException { - try { + try (UnsynchronizedByteArrayOutputStream bOut = new UnsynchronizedByteArrayOutputStream()) { PropertySet mSet = new PropertySet(set); - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - mSet.write(bOut); - byte[] data = bOut.toByteArray(); - ByteArrayInputStream bIn = new ByteArrayInputStream(data); - // Create or Update the Property Set stream in the POIFS - outFS.createOrUpdateDocument(bIn, name); + try (InputStream bIn = bOut.toInputStream()) { + // Create or Update the Property Set stream in the POIFS + outFS.createOrUpdateDocument(bIn, name); + } - LOG.atInfo().log("Wrote property set {} of size {}", name, box(data.length)); + LOG.atInfo().log("Wrote property set {} of size {}", name, box(bOut.size())); } catch(WritingNotSupportedException ignored) { LOG.atError().log("Couldn't write property set with name {} as not supported by HPSF yet", name); } diff --git a/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java b/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java index 249e74cb2e..e7f02f471b 100644 --- a/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java +++ b/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java @@ -22,7 +22,6 @@ import java.util.function.Supplier; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.Removal; /** * Generates escher records when provided the byte array containing those records. @@ -73,23 +72,4 @@ public class DefaultEscherRecordFactory implements EscherRecordFactory { // catch all return UnknownEscherRecord::new; } - - - /** - * @deprecated this method is not used anymore to identify container records - */ - @Deprecated - @Removal(version = "5.0.0") - public static boolean isContainer(short options, short recordId){ - if(recordId >= EscherContainerRecord.DGG_CONTAINER && recordId - <= EscherContainerRecord.SOLVER_CONTAINER){ - return true; - } else { - if (recordId == EscherTextboxRecord.RECORD_ID) { - return false; - } else { - return ( options & (short) 0x000F ) == (short) 0x000F; - } - } - } } diff --git a/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java b/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java index 6713b5fc17..75062a7005 100644 --- a/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java +++ b/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java @@ -17,10 +17,11 @@ package org.apache.poi.ddf; +import static org.apache.logging.log4j.util.Unbox.box; + import java.awt.Dimension; import java.awt.Rectangle; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashMap; @@ -29,21 +30,30 @@ import java.util.function.Supplier; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFPictureData; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; - -import static org.apache.logging.log4j.util.Unbox.box; +import org.apache.poi.util.Removal; public final class EscherMetafileBlip extends EscherBlipRecord { private static final Logger LOGGER = LogManager.getLogger(EscherMetafileBlip.class); //arbitrarily selected; may need to increase private static final int MAX_RECORD_LENGTH = 100_000_000; + /** @deprecated use EscherRecordTypes.BLIP_EMF.typeID */ + @Deprecated + @Removal(version = "5.3") public static final short RECORD_ID_EMF = EscherRecordTypes.BLIP_EMF.typeID; + /** @deprecated use EscherRecordTypes.BLIP_WMF.typeID */ + @Deprecated + @Removal(version = "5.3") public static final short RECORD_ID_WMF = EscherRecordTypes.BLIP_WMF.typeID; + /** @deprecated use EscherRecordTypes.BLIP_PICT.typeID */ + @Deprecated + @Removal(version = "5.3") public static final short RECORD_ID_PICT = EscherRecordTypes.BLIP_PICT.typeID; private static final int HEADER_SIZE = 8; @@ -150,9 +160,10 @@ public final class EscherMetafileBlip extends EscherBlipRecord { data[pos] = field_6_fCompression; pos++; data[pos] = field_7_fFilter; pos++; - System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length ); pos += raw_pictureData.length; + System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length ); + pos += raw_pictureData.length; if(remainingData != null) { - System.arraycopy( remainingData, 0, data, pos, remainingData.length ); pos += remainingData.length; + System.arraycopy( remainingData, 0, data, pos, remainingData.length ); } listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this); @@ -166,15 +177,9 @@ public final class EscherMetafileBlip extends EscherBlipRecord { * @return the inflated picture data. */ private static byte[] inflatePictureData(byte[] data) { - try { - InflaterInputStream in = new InflaterInputStream( - new ByteArrayInputStream( data ) ); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - int readBytes; - while ((readBytes = in.read(buf)) > 0) { - out.write(buf, 0, readBytes); - } + try (InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(data)); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + IOUtils.copy(in, out); return out.toByteArray(); } catch (IOException e) { LOGGER.atWarn().withThrowable(e).log("Possibly corrupt compression or non-compressed data"); @@ -390,11 +395,10 @@ public final class EscherMetafileBlip extends EscherBlipRecord { // "... LZ compression algorithm in the format used by GNU Zip deflate/inflate with a 32k window ..." // not sure what to do, when lookup tables exceed 32k ... - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - DeflaterOutputStream dos = new DeflaterOutputStream(bos); - dos.write(pictureData); - dos.close(); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + try (DeflaterOutputStream dos = new DeflaterOutputStream(bos)) { + dos.write(pictureData); + } raw_pictureData = bos.toByteArray(); } catch (IOException e) { throw new RuntimeException("Can't compress metafile picture data", e); diff --git a/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java b/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java index a0a5d68fb8..b5fffd5d84 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java +++ b/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java @@ -41,16 +41,18 @@ public class HPSFPropertiesOnlyDocument extends POIDocument { /** * Write out to the currently open file the properties changes, but nothing else */ + @Override public void write() throws IOException { POIFSFileSystem fs = getDirectory().getFileSystem(); - - validateInPlaceWritePossible(); + + validateInPlaceWritePossible(); writeProperties(fs, null); fs.writeFilesystem(); } /** * Write out, with any properties changes, but nothing else */ + @Override public void write(File newFile) throws IOException { try (POIFSFileSystem fs = POIFSFileSystem.create(newFile)) { write(fs); @@ -60,25 +62,26 @@ public class HPSFPropertiesOnlyDocument extends POIDocument { /** * Write out, with any properties changes, but nothing else */ + @Override public void write(OutputStream out) throws IOException { try (POIFSFileSystem fs = new POIFSFileSystem()) { write(fs); fs.writeFilesystem(out); } } - + private void write(POIFSFileSystem fs) throws IOException { // For tracking what we've written out, so far List<String> excepts = new ArrayList<>(2); // Write out our HPFS properties, with any changes writeProperties(fs, excepts); - + // Copy over everything else unchanged FilteringDirectoryNode src = new FilteringDirectoryNode(getDirectory(), excepts); FilteringDirectoryNode dest = new FilteringDirectoryNode(fs.getRoot(), excepts); EntryUtils.copyNodes(src, dest); - + // Caller will save the resultant POIFSFileSystem to the stream/file } } diff --git a/poi/src/main/java/org/apache/poi/hpsf/MarkUnsupportedException.java b/poi/src/main/java/org/apache/poi/hpsf/MarkUnsupportedException.java deleted file mode 100644 index 450c892abc..0000000000 --- a/poi/src/main/java/org/apache/poi/hpsf/MarkUnsupportedException.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf; - -/** - * <p>This exception is thrown if an {@link java.io.InputStream} does - * not support the {@link java.io.InputStream#mark} operation.</p> - */ -public class MarkUnsupportedException extends HPSFException -{ - - /** - * <p>Constructor</p> - */ - public MarkUnsupportedException() - { - super(); - } - - - /** - * <p>Constructor</p> - * - * @param msg The exception's message string - */ - public MarkUnsupportedException(final String msg) - { - super(msg); - } - - - /** - * <p>Constructor</p> - * - * @param reason This exception's underlying reason - */ - public MarkUnsupportedException(final Throwable reason) - { - super(reason); - } - - - /** - * <p>Constructor</p> - * - * @param msg The exception's message string - * @param reason This exception's underlying reason - */ - public MarkUnsupportedException(final String msg, final Throwable reason) - { - super(msg, reason); - } - -} diff --git a/poi/src/main/java/org/apache/poi/hpsf/Property.java b/poi/src/main/java/org/apache/poi/hpsf/Property.java index 0e3e2cdea2..2b05f763af 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/Property.java +++ b/poi/src/main/java/org/apache/poi/hpsf/Property.java @@ -17,7 +17,8 @@ package org.apache.poi.hpsf; -import java.io.ByteArrayOutputStream; +import static org.apache.logging.log4j.util.Unbox.box; + import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; @@ -29,6 +30,7 @@ import java.util.Locale; import java.util.Objects; import java.util.concurrent.TimeUnit; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hpsf.wellknown.PropertyIDMap; @@ -39,8 +41,6 @@ import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.LocaleUtil; -import static org.apache.logging.log4j.util.Unbox.box; - /** * A property in a {@link Section} of a {@link PropertySet}.<p> * @@ -115,7 +115,7 @@ public class Property { } /** - * Creates a {@link Property} instance by reading its bytes + * Creates a Property instance by reading its bytes * from the property set stream. * * @param id The property's ID. @@ -153,7 +153,7 @@ public class Property { } /** - * Creates a {@link Property} instance by reading its bytes + * Creates a Property instance by reading its bytes * from the property set stream. * * @param id The property's ID. @@ -272,7 +272,7 @@ public class Property { /* Variable length: */ if (type == Variant.VT_LPSTR || type == Variant.VT_LPWSTR) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { length = write(bos, property) - 2*LittleEndianConsts.INT_SIZE; /* Pad to multiples of 4. */ @@ -295,8 +295,6 @@ public class Property { * ID == 0 is a special case: It does not have a type, and its value is the * section's dictionary. Another special case are strings: Two properties * may have the different types Variant.VT_LPSTR and Variant.VT_LPWSTR; - * - * @see Object#equals(Object) */ @Override public boolean equals(final Object o) { @@ -366,22 +364,12 @@ public class Property { (t2 == Variant.VT_LPSTR && t1 == Variant.VT_LPWSTR)); } - - - /** - * @see Object#hashCode() - */ @Override public int hashCode() { return Objects.hash(id,type,value); } - - - /** - * @see Object#toString() - */ @Override public String toString() { return toString(Property.DEFAULT_CODEPAGE, null); @@ -411,7 +399,7 @@ public class Property { if (value instanceof String) { b.append((String)value); b.append("\n"); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { write(bos, codepage); } catch (Exception e) { diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java index d110747d11..324fb4b4c9 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java +++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java @@ -18,7 +18,6 @@ package org.apache.poi.hpsf; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -27,6 +26,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EmptyFileException; import org.apache.poi.hpsf.wellknown.PropertyIDMap; import org.apache.poi.poifs.filesystem.DirectoryEntry; @@ -38,7 +38,6 @@ import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.LittleEndianOutputStream; import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.Removal; /** * Represents a property set in the Horrible Property Set Format @@ -166,7 +165,7 @@ public class PropertySet { /** - * Creates a {@link PropertySet} instance from an {@link + * Creates a PropertySet instance from an {@link * InputStream} in the Horrible Property Set Format.<p> * * The constructor reads the first few bytes from the stream @@ -198,7 +197,7 @@ public class PropertySet { /** - * Creates a {@link PropertySet} instance from a byte array that + * Creates a PropertySet instance from a byte array that * represents a stream in the Horrible Property Set Format. * * @param stream The byte array holding the stream data. @@ -220,7 +219,7 @@ public class PropertySet { } /** - * Creates a {@link PropertySet} instance from a byte array + * Creates a PropertySet instance from a byte array * that represents a stream in the Horrible Property Set Format. * * @param stream The byte array holding the stream data. The @@ -439,7 +438,7 @@ public class PropertySet { /** - * Initializes this {@link PropertySet} instance from a byte + * Initializes this PropertySet instance from a byte * array. The method assumes that it has been checked already that * the byte array indeed represents a property set stream. It does * no more checks on its own. @@ -515,7 +514,7 @@ public class PropertySet { } private byte[] toBytes() throws WritingNotSupportedException, IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); /* Write the number of sections in this property set stream. */ @@ -590,7 +589,7 @@ public class PropertySet { * document. The input stream represents a snapshot of the property set. * If the latter is modified while the input stream is still being * read, the modifications will not be reflected in the input stream but in - * the {@link PropertySet} only. + * the PropertySet only. * * @return the contents of this property set stream * @@ -657,9 +656,9 @@ public class PropertySet { } /** - * Checks whether this {@link PropertySet} represents a Summary Information. + * Checks whether this PropertySet represents a Summary Information. * - * @return {@code true} if this {@link PropertySet} + * @return {@code true} if this PropertySet * represents a Summary Information, else {@code false}. */ public boolean isSummaryInformation() { @@ -667,9 +666,9 @@ public class PropertySet { } /** - * Checks whether this {@link PropertySet} is a Document Summary Information. + * Checks whether this PropertySet is a Document Summary Information. * - * @return {@code true} if this {@link PropertySet} + * @return {@code true} if this PropertySet * represents a Document Summary Information, else {@code false}. */ public boolean isDocumentSummaryInformation() { @@ -687,13 +686,13 @@ public class PropertySet { /** * Convenience method returning the {@link Property} array contained in this - * property set. It is a shortcut for getting he {@link PropertySet}'s + * property set. It is a shortcut for getting he PropertySets * {@link Section}s list and then getting the {@link Property} array from the * first {@link Section}. * * @return The properties of the only {@link Section} of this - * {@link PropertySet}. - * @throws NoSingleSectionException if the {@link PropertySet} has + * PropertySet. + * @throws NoSingleSectionException if the PropertySet has * more or less than one {@link Section}. */ public Property[] getProperties() throws NoSingleSectionException { @@ -709,7 +708,7 @@ public class PropertySet { * * @param id The property ID * @return The property value - * @throws NoSingleSectionException if the {@link PropertySet} has + * @throws NoSingleSectionException if the PropertySet has * more or less than one {@link Section}. */ protected Object getProperty(final int id) throws NoSingleSectionException { @@ -726,7 +725,7 @@ public class PropertySet { * * @param id The property ID * @return The property value - * @throws NoSingleSectionException if the {@link PropertySet} has + * @throws NoSingleSectionException if the PropertySet has * more or less than one {@link Section}. */ boolean getPropertyBooleanValue(final int id) throws NoSingleSectionException { @@ -744,7 +743,7 @@ public class PropertySet { * * @param id The property ID * @return The propertyIntValue value - * @throws NoSingleSectionException if the {@link PropertySet} has + * @throws NoSingleSectionException if the PropertySet has * more or less than one {@link Section}. */ int getPropertyIntValue(final int id) throws NoSingleSectionException { @@ -765,7 +764,7 @@ public class PropertySet { * @return {@code true} if the last call to {@link * #getPropertyIntValue} or {@link #getProperty} tried to access a * property that was not available, else {@code false}. - * @throws NoSingleSectionException if the {@link PropertySet} has + * @throws NoSingleSectionException if the PropertySet has * more than one {@link Section}. */ public boolean wasNull() throws NoSingleSectionException { @@ -775,9 +774,9 @@ public class PropertySet { /** - * Gets the {@link PropertySet}'s first section. + * Gets the PropertySets first section. * - * @return The {@link PropertySet}'s first section. + * @return The PropertySets first section. */ @SuppressWarnings("WeakerAccess") public Section getFirstSection() { @@ -825,22 +824,12 @@ public class PropertySet { return getSections().containsAll(ps.getSections()); } - - - /** - * @see Object#hashCode() - */ @NotImplemented @Override public int hashCode() { throw new UnsupportedOperationException("FIXME: Not yet implemented."); } - - - /** - * @see Object#toString() - */ @Override public String toString() { final StringBuilder b = new StringBuilder(); @@ -888,7 +877,7 @@ public class PropertySet { getFirstSection().setProperty((int)id, value); } - private static void putClassId(final ByteArrayOutputStream out, final ClassID n) { + private static void putClassId(final UnsynchronizedByteArrayOutputStream out, final ClassID n) { byte[] b = new byte[16]; n.write(b, 0); out.write(b, 0, b.length); diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java b/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java index d5e0c5c0c2..ec2b8bc9dd 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java +++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java @@ -54,8 +54,6 @@ public class PropertySetFactory { throws FileNotFoundException, NoPropertySetStreamException, IOException, UnsupportedEncodingException { try (DocumentInputStream inp = ((DirectoryNode)dir).createDocumentInputStream(name)) { return create(inp); - } catch (MarkUnsupportedException e) { - return null; } } @@ -71,14 +69,12 @@ public class PropertySetFactory { * @return The created {@link PropertySet}. * @throws NoPropertySetStreamException if the stream does not * contain a property set. - * @throws MarkUnsupportedException if the stream does not support - * the {@code mark} operation. * @throws IOException if some I/O problem occurs. * @exception UnsupportedEncodingException if the specified codepage is not * supported. */ public static PropertySet create(final InputStream stream) - throws NoPropertySetStreamException, MarkUnsupportedException, UnsupportedEncodingException, IOException { + throws NoPropertySetStreamException, IOException { stream.mark(PropertySet.OFFSET_HEADER+ClassID.LENGTH+1); LittleEndianInputStream leis = new LittleEndianInputStream(stream); int byteOrder = leis.readUShort(); diff --git a/poi/src/main/java/org/apache/poi/hpsf/Section.java b/poi/src/main/java/org/apache/poi/hpsf/Section.java index c404e49858..90d20cf448 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/Section.java +++ b/poi/src/main/java/org/apache/poi/hpsf/Section.java @@ -17,7 +17,6 @@ package org.apache.poi.hpsf; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; @@ -31,6 +30,7 @@ import java.util.Set; import java.util.TreeMap; import org.apache.commons.collections4.bidimap.TreeBidiMap; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hpsf.wellknown.PropertyIDMap; @@ -66,7 +66,7 @@ public class Section { * established when the section's size is calculated and can be reused * later. If the array is empty, the section was modified and the bytes need to be regenerated. */ - private final ByteArrayOutputStream sectionBytes = new ByteArrayOutputStream(); + private final UnsynchronizedByteArrayOutputStream sectionBytes = new UnsynchronizedByteArrayOutputStream(); /** * The offset of the section in the stream. @@ -86,7 +86,7 @@ public class Section { private transient boolean wasNull; /** - * Creates an empty {@link Section}. + * Creates an empty Section. */ public Section() { this._offset = -1; @@ -112,7 +112,7 @@ public class Section { /** - * Creates a {@link Section} instance from a byte array. + * Creates a Section instance from a byte array. * * @param src Contains the complete property set stream. * @param offset The position in the stream that points to the @@ -428,7 +428,6 @@ public class Section { * @see #getProperty * @see Variant */ - @SuppressWarnings("deprecation") public void setProperty(final int id, final long variantType, final Object value) { setProperty(new Property(id, variantType, value)); } @@ -601,7 +600,7 @@ public class Section { /** * Returns the PID string associated with a property ID. The ID - * is first looked up in the {@link Section Sections} private dictionary. + * is first looked up in the Sections private dictionary. * If it is not found there, the property PID string is taken * from sections format IDs namespace. * If the PID is also undefined there, i.e. it is not well-known, @@ -641,14 +640,14 @@ public class Section { * * <ul> * - * <li>The other object is not a {@link Section}. + * <li>The other object is not a Section. * * <li>The format IDs of the two sections are not equal. * * <li>The sections have a different number of properties. However, * properties with ID 1 (codepage) are not counted. * - * <li>The other object is not a {@link Section}. + * <li>The other object is not a Section. * * <li>The properties have different values. The order of the properties * is irrelevant. @@ -736,7 +735,7 @@ public class Section { } final int[][] offsets = new int[properties.size()][2]; - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); final LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); /* Write the section's length - dummy value, fixed later */ @@ -932,19 +931,11 @@ public class Section { } } - - - /** - * @see Object#hashCode() - */ @Override public int hashCode() { return Arrays.deepHashCode(new Object[]{getFormatID(),getProperties()}); } - /** - * @see Object#toString() - */ @Override public String toString() { return toString(null); @@ -1008,7 +999,7 @@ public class Section { */ public int getCodepage() { final Integer codepage = (Integer) getProperty(PropertyIDMap.PID_CODEPAGE); - return (codepage == null) ? -1 : codepage.intValue(); + return (codepage == null) ? -1 : codepage; } /** diff --git a/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java b/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java index 4c85b8fda8..564146a94a 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java +++ b/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java @@ -50,14 +50,14 @@ public final class SummaryInformation extends PropertySet { } /** - * Creates an empty {@link SummaryInformation}. + * Creates an empty SummaryInformation. */ public SummaryInformation() { getFirstSection().setFormatID(FORMAT_ID); } /** - * Creates a {@link SummaryInformation} from a given {@link + * Creates a SummaryInformation from a given {@link * PropertySet}. * * @param ps A property set which should be created from a summary @@ -73,7 +73,7 @@ public final class SummaryInformation extends PropertySet { } /** - * Creates a {@link SummaryInformation} instance from an {@link + * Creates a SummaryInformation instance from an {@link * InputStream} in the Horrible Property Set Format.<p> * * The constructor reads the first few bytes from the stream @@ -85,8 +85,6 @@ public final class SummaryInformation extends PropertySet { * * @param stream Holds the data making out the property set * stream. - * @throws MarkUnsupportedException - * if the stream does not support the {@link InputStream#markSupported} method. * @throws IOException * if the {@link InputStream} cannot be accessed as needed. * @exception NoPropertySetStreamException @@ -95,7 +93,7 @@ public final class SummaryInformation extends PropertySet { * if a character encoding is not supported. */ public SummaryInformation(final InputStream stream) - throws NoPropertySetStreamException, MarkUnsupportedException, IOException, UnsupportedEncodingException { + throws NoPropertySetStreamException, IOException { super(stream); } @@ -481,10 +479,10 @@ public final class SummaryInformation extends PropertySet { /** - * Returns the page count or 0 if the {@link SummaryInformation} does + * Returns the page count or 0 if the SummaryInformation does * not contain a page count. * - * @return The page count or 0 if the {@link SummaryInformation} does not + * @return The page count or 0 if the SummaryInformation does not * contain a page count. */ public int getPageCount() { @@ -514,7 +512,7 @@ public final class SummaryInformation extends PropertySet { /** - * Returns the word count or 0 if the {@link SummaryInformation} does + * Returns the word count or 0 if the SummaryInformation does * not contain a word count. * * @return The word count or {@code null} @@ -546,7 +544,7 @@ public final class SummaryInformation extends PropertySet { /** - * Returns the character count or 0 if the {@link SummaryInformation} + * Returns the character count or 0 if the SummaryInformation * does not contain a char count. * * @return The character count or {@code null} @@ -665,7 +663,7 @@ public final class SummaryInformation extends PropertySet { * * <ul> * - * <li>0 if the {@link SummaryInformation} does not contain a + * <li>0 if the SummaryInformation does not contain a * security field or if there is no security on the document. Use * {@link PropertySet#wasNull()} to distinguish between the two * cases! diff --git a/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java b/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java index 2f31eb48d8..2254ed58fe 100644 --- a/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java +++ b/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.dev; -import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -60,7 +60,7 @@ public class ReSave { System.out.print("saving to " + outputFile + "..."); } - try (OutputStream os = saveToMemory ? new ByteArrayOutputStream() : new FileOutputStream(outputFile)) { + try (OutputStream os = saveToMemory ? new UnsynchronizedByteArrayOutputStream() : new FileOutputStream(outputFile)) { wb.write(os); } System.out.println("done"); diff --git a/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java index ac6bc6bf5c..8a1925e102 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java @@ -19,7 +19,6 @@ package org.apache.poi.hssf.record; import static org.apache.poi.hssf.record.RecordInputStream.MAX_RECORD_DATA_SIZE; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -31,6 +30,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherClientDataRecord; import org.apache.poi.ddf.EscherContainerRecord; @@ -40,9 +40,11 @@ import org.apache.poi.ddf.EscherSerializationListener; import org.apache.poi.ddf.EscherSpRecord; import org.apache.poi.ddf.EscherSpgrRecord; import org.apache.poi.ddf.EscherTextboxRecord; +import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.util.GenericRecordXmlWriter; import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; +import org.apache.poi.util.Removal; /** * This class is used to aggregate the MSODRAWING and OBJ record @@ -93,210 +95,825 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { private static final int MAX_RECORD_LENGTH = 100_000_000; + /** @deprecated not used */ + @Deprecated + @Removal(version = "5.3") public static final short ST_MIN = (short) 0; - public static final short ST_NOT_PRIMATIVE = ST_MIN; + /** @deprecated use {@link ShapeType#NOT_PRIMITIVE} */ + @Deprecated + @Removal(version = "5.3") + public static final short ST_NOT_PRIMATIVE = (short) 0; + /** @deprecated use {@link ShapeType#RECT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RECTANGLE = (short) 1; + /** @deprecated use {@link ShapeType#ROUND_RECT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ROUNDRECTANGLE = (short) 2; + /** @deprecated use {@link ShapeType#ELLIPSE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ELLIPSE = (short) 3; + /** @deprecated use {@link ShapeType#DIAMOND} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_DIAMOND = (short) 4; + /** @deprecated use {@link ShapeType#TRIANGLE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ISOCELESTRIANGLE = (short) 5; + /** @deprecated use {@link ShapeType#RT_TRIANGLE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RIGHTTRIANGLE = (short) 6; + /** @deprecated use {@link ShapeType#PARALLELOGRAM} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_PARALLELOGRAM = (short) 7; + /** @deprecated use {@link ShapeType#TRAPEZOID} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TRAPEZOID = (short) 8; + /** @deprecated use {@link ShapeType#HEXAGON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_HEXAGON = (short) 9; + /** @deprecated use {@link ShapeType#OCTAGON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_OCTAGON = (short) 10; + /** @deprecated use {@link ShapeType#PLUS} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_PLUS = (short) 11; + /** @deprecated use {@link ShapeType#STAR_5} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_STAR = (short) 12; + /** @deprecated use {@link ShapeType#RIGHT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ARROW = (short) 13; + /** @deprecated use {@link ShapeType#THICK_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_THICKARROW = (short) 14; + /** @deprecated use {@link ShapeType#HOME_PLATE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_HOMEPLATE = (short) 15; + /** @deprecated use {@link ShapeType#CUBE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CUBE = (short) 16; + /** @deprecated use {@link ShapeType#BALLOON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BALLOON = (short) 17; + /** @deprecated use {@link ShapeType#SEAL} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SEAL = (short) 18; + /** @deprecated use {@link ShapeType#ARC} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ARC = (short) 19; + /** @deprecated use {@link ShapeType#LINE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LINE = (short) 20; + /** @deprecated use {@link ShapeType#PLAQUE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_PLAQUE = (short) 21; + /** @deprecated use {@link ShapeType#CAN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CAN = (short) 22; + /** @deprecated use {@link ShapeType#DONUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_DONUT = (short) 23; + /** @deprecated use {@link ShapeType#TEXT_SIMPLE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTSIMPLE = (short) 24; + /** @deprecated use {@link ShapeType#TEXT_OCTAGON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTOCTAGON = (short) 25; + /** @deprecated use {@link ShapeType#TEXT_HEXAGON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTHEXAGON = (short) 26; + /** @deprecated use {@link ShapeType#TEXT_CURVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCURVE = (short) 27; + /** @deprecated use {@link ShapeType#TEXT_WAVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTWAVE = (short) 28; + /** @deprecated use {@link ShapeType#TEXT_RING} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTRING = (short) 29; + /** @deprecated use {@link ShapeType#TEXT_ON_CURVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTONCURVE = (short) 30; + /** @deprecated use {@link ShapeType#TEXT_ON_RING} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTONRING = (short) 31; + /** @deprecated use {@link ShapeType#STRAIGHT_CONNECTOR_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_STRAIGHTCONNECTOR1 = (short) 32; + /** @deprecated use {@link ShapeType#BENT_CONNECTOR_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BENTCONNECTOR2 = (short) 33; + /** @deprecated use {@link ShapeType#BENT_CONNECTOR_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BENTCONNECTOR3 = (short) 34; + /** @deprecated use {@link ShapeType#BENT_CONNECTOR_4} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BENTCONNECTOR4 = (short) 35; + /** @deprecated use {@link ShapeType#BENT_CONNECTOR_5} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BENTCONNECTOR5 = (short) 36; + /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDCONNECTOR2 = (short) 37; + /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDCONNECTOR3 = (short) 38; + /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDCONNECTOR4 = (short) 39; + /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_5} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDCONNECTOR5 = (short) 40; + /** @deprecated use {@link ShapeType#CALLOUT_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CALLOUT1 = (short) 41; + /** @deprecated use {@link ShapeType#CALLOUT_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CALLOUT2 = (short) 42; + /** @deprecated use {@link ShapeType#CALLOUT_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CALLOUT3 = (short) 43; + /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTCALLOUT1 = (short) 44; + /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTCALLOUT2 = (short) 45; + /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTCALLOUT3 = (short) 46; + /** @deprecated use {@link ShapeType#BORDER_CALLOUT_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BORDERCALLOUT1 = (short) 47; + /** @deprecated use {@link ShapeType#BORDER_CALLOUT_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BORDERCALLOUT2 = (short) 48; + /** @deprecated use {@link ShapeType#BORDER_CALLOUT_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BORDERCALLOUT3 = (short) 49; + /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTBORDERCALLOUT1 = (short) 50; + /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTBORDERCALLOUT2 = (short) 51; + /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTBORDERCALLOUT3 = (short) 52; + /** @deprecated use {@link ShapeType#RIBBON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RIBBON = (short) 53; + /** @deprecated use {@link ShapeType#RIBBON_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RIBBON2 = (short) 54; + /** @deprecated use {@link ShapeType#CHEVRON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CHEVRON = (short) 55; + /** @deprecated use {@link ShapeType#PENTAGON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_PENTAGON = (short) 56; + /** @deprecated use {@link ShapeType#NO_SMOKING} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_NOSMOKING = (short) 57; + /** @deprecated use {@link ShapeType#STAR_8} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SEAL8 = (short) 58; + /** @deprecated use {@link ShapeType#STAR_16} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SEAL16 = (short) 59; + /** @deprecated use {@link ShapeType#STAR_32} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SEAL32 = (short) 60; + /** @deprecated use {@link ShapeType#WEDGE_RECT_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_WEDGERECTCALLOUT = (short) 61; + /** @deprecated use {@link ShapeType#WEDGE_ROUND_RECT_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_WEDGERRECTCALLOUT = (short) 62; + /** @deprecated use {@link ShapeType#WEDGE_ELLIPSE_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_WEDGEELLIPSECALLOUT = (short) 63; + /** @deprecated use {@link ShapeType#WAVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_WAVE = (short) 64; + /** @deprecated use {@link ShapeType#FOLDED_CORNER} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FOLDEDCORNER = (short) 65; + /** @deprecated use {@link ShapeType#LEFT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTARROW = (short) 66; + /** @deprecated use {@link ShapeType#DOWN_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_DOWNARROW = (short) 67; + /** @deprecated use {@link ShapeType#UP_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_UPARROW = (short) 68; + /** @deprecated use {@link ShapeType#LEFT_RIGHT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTRIGHTARROW = (short) 69; + /** @deprecated use {@link ShapeType#UP_DOWN_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_UPDOWNARROW = (short) 70; + /** @deprecated use {@link ShapeType#IRREGULAR_SEAL_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_IRREGULARSEAL1 = (short) 71; + /** @deprecated use {@link ShapeType#IRREGULAR_SEAL_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_IRREGULARSEAL2 = (short) 72; + /** @deprecated use {@link ShapeType#LIGHTNING_BOLT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LIGHTNINGBOLT = (short) 73; + /** @deprecated use {@link ShapeType#HEART} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_HEART = (short) 74; + /** @deprecated use {@link ShapeType#FRAME} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_PICTUREFRAME = (short) 75; + /** @deprecated use {@link ShapeType#QUAD_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_QUADARROW = (short) 76; + /** @deprecated use {@link ShapeType#LEFT_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTARROWCALLOUT = (short) 77; + /** @deprecated use {@link ShapeType#RIGHT_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RIGHTARROWCALLOUT = (short) 78; + /** @deprecated use {@link ShapeType#UP_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_UPARROWCALLOUT = (short) 79; + /** @deprecated use {@link ShapeType#DOWN_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_DOWNARROWCALLOUT = (short) 80; + /** @deprecated use {@link ShapeType#LEFT_RIGHT_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTRIGHTARROWCALLOUT = (short) 81; + /** @deprecated use {@link ShapeType#UP_DOWN_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_UPDOWNARROWCALLOUT = (short) 82; + /** @deprecated use {@link ShapeType#QUAD_ARROW_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_QUADARROWCALLOUT = (short) 83; + /** @deprecated use {@link ShapeType#BEVEL} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BEVEL = (short) 84; + /** @deprecated use {@link ShapeType#LEFT_BRACKET} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTBRACKET = (short) 85; + /** @deprecated use {@link ShapeType#RIGHT_BRACKET} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RIGHTBRACKET = (short) 86; + /** @deprecated use {@link ShapeType#LEFT_BRACE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTBRACE = (short) 87; + /** @deprecated use {@link ShapeType#RIGHT_BRACE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_RIGHTBRACE = (short) 88; + /** @deprecated use {@link ShapeType#LEFT_UP_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTUPARROW = (short) 89; + /** @deprecated use {@link ShapeType#BENT_UP_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BENTUPARROW = (short) 90; + /** @deprecated use {@link ShapeType#BENT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BENTARROW = (short) 91; + /** @deprecated use {@link ShapeType#STAR_24} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SEAL24 = (short) 92; + /** @deprecated use {@link ShapeType#STRIPED_RIGHT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_STRIPEDRIGHTARROW = (short) 93; + /** @deprecated use {@link ShapeType#NOTCHED_RIGHT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_NOTCHEDRIGHTARROW = (short) 94; + /** @deprecated use {@link ShapeType#BLOCK_ARC} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BLOCKARC = (short) 95; + /** @deprecated use {@link ShapeType#SMILEY_FACE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SMILEYFACE = (short) 96; + /** @deprecated use {@link ShapeType#VERTICAL_SCROLL} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_VERTICALSCROLL = (short) 97; + /** @deprecated use {@link ShapeType#HORIZONTAL_SCROLL} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_HORIZONTALSCROLL = (short) 98; + /** @deprecated use {@link ShapeType#CIRCULAR_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CIRCULARARROW = (short) 99; + /** @deprecated use {@link ShapeType#NOTCHED_CIRCULAR_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_NOTCHEDCIRCULARARROW = (short) 100; + /** @deprecated use {@link ShapeType#UTURN_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_UTURNARROW = (short) 101; + /** @deprecated use {@link ShapeType#CURVED_RIGHT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDRIGHTARROW = (short) 102; + /** @deprecated use {@link ShapeType#CURVED_LEFT_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDLEFTARROW = (short) 103; + /** @deprecated use {@link ShapeType#CURVED_UP_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDUPARROW = (short) 104; + /** @deprecated use {@link ShapeType#CURVED_DOWN_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CURVEDDOWNARROW = (short) 105; + /** @deprecated use {@link ShapeType#CLOUD_CALLOUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CLOUDCALLOUT = (short) 106; + /** @deprecated use {@link ShapeType#ELLIPSE_RIBBON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ELLIPSERIBBON = (short) 107; + /** @deprecated use {@link ShapeType#ELLIPSE_RIBBON_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ELLIPSERIBBON2 = (short) 108; + /** @deprecated use {@link ShapeType#FLOW_CHART_PROCESS} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTPROCESS = (short) 109; + /** @deprecated use {@link ShapeType#FLOW_CHART_DECISION} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTDECISION = (short) 110; + /** @deprecated use {@link ShapeType#FLOW_CHART_INPUT_OUTPUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTINPUTOUTPUT = (short) 111; + /** @deprecated use {@link ShapeType#FLOW_CHART_PREDEFINED_PROCESS} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTPREDEFINEDPROCESS = (short) 112; + /** @deprecated use {@link ShapeType#FLOW_CHART_INTERNAL_STORAGE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTINTERNALSTORAGE = (short) 113; + /** @deprecated use {@link ShapeType#FLOW_CHART_DOCUMENT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTDOCUMENT = (short) 114; + /** @deprecated use {@link ShapeType#FLOW_CHART_MULTIDOCUMENT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMULTIDOCUMENT = (short) 115; + /** @deprecated use {@link ShapeType#FLOW_CHART_TERMINATOR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTTERMINATOR = (short) 116; + /** @deprecated use {@link ShapeType#FLOW_CHART_PREPARATION} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTPREPARATION = (short) 117; + /** @deprecated use {@link ShapeType#FLOW_CHART_MANUAL_INPUT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMANUALINPUT = (short) 118; + /** @deprecated use {@link ShapeType#FLOW_CHART_MANUAL_OPERATION} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMANUALOPERATION = (short) 119; + /** @deprecated use {@link ShapeType#FLOW_CHART_CONNECTOR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTCONNECTOR = (short) 120; + /** @deprecated use {@link ShapeType#FLOW_CHART_PUNCHED_CARD} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTPUNCHEDCARD = (short) 121; + /** @deprecated use {@link ShapeType#FLOW_CHART_PUNCHED_TAPE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTPUNCHEDTAPE = (short) 122; + /** @deprecated use {@link ShapeType#FLOW_CHART_SUMMING_JUNCTION} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTSUMMINGJUNCTION = (short) 123; + /** @deprecated use {@link ShapeType#FLOW_CHART_OR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTOR = (short) 124; + /** @deprecated use {@link ShapeType#FLOW_CHART_COLLATE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTCOLLATE = (short) 125; + /** @deprecated use {@link ShapeType#FLOW_CHART_SORT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTSORT = (short) 126; + /** @deprecated use {@link ShapeType#FLOW_CHART_EXTRACT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTEXTRACT = (short) 127; + /** @deprecated use {@link ShapeType#FLOW_CHART_MERGE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMERGE = (short) 128; + /** @deprecated use {@link ShapeType#FLOW_CHART_OFFLINE_STORAGE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTOFFLINESTORAGE = (short) 129; + /** @deprecated use {@link ShapeType#FLOW_CHART_ONLINE_STORAGE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTONLINESTORAGE = (short) 130; + /** @deprecated use {@link ShapeType#FLOW_CHART_MAGNETIC_TAPE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMAGNETICTAPE = (short) 131; + /** @deprecated use {@link ShapeType#FLOW_CHART_MAGNETIC_DISK} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMAGNETICDISK = (short) 132; + /** @deprecated use {@link ShapeType#FLOW_CHART_MAGNETIC_DRUM} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTMAGNETICDRUM = (short) 133; + /** @deprecated use {@link ShapeType#FLOW_CHART_DISPLAY} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTDISPLAY = (short) 134; + /** @deprecated use {@link ShapeType#FLOW_CHART_DELAY} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTDELAY = (short) 135; + /** @deprecated use {@link ShapeType#TEXT_PLAIN_TEXT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTPLAINTEXT = (short) 136; + /** @deprecated use {@link ShapeType#TEXT_STOP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTSTOP = (short) 137; + /** @deprecated use {@link ShapeType#TEXT_TRIANGLE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTTRIANGLE = (short) 138; + /** @deprecated use {@link ShapeType#TEXT_TRIANGLE_INVERTED} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTTRIANGLEINVERTED = (short) 139; + /** @deprecated use {@link ShapeType#TEXT_CHEVRON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCHEVRON = (short) 140; + /** @deprecated use {@link ShapeType#TEXT_CHEVRON_INVERTED} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCHEVRONINVERTED = (short) 141; + /** @deprecated use {@link ShapeType#TEXT_RING_INSIDE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTRINGINSIDE = (short) 142; + /** @deprecated use {@link ShapeType#TEXT_RING_OUTSIDE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTRINGOUTSIDE = (short) 143; + /** @deprecated use {@link ShapeType#TEXT_ARCH_UP_CURVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTARCHUPCURVE = (short) 144; + /** @deprecated use {@link ShapeType#TEXT_ARCH_DOWN_CURVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTARCHDOWNCURVE = (short) 145; + /** @deprecated use {@link ShapeType#TEXT_CIRCLE_CURVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCIRCLECURVE = (short) 146; + /** @deprecated use {@link ShapeType#TEXT_BUTTON_CURVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTBUTTONCURVE = (short) 147; + /** @deprecated use {@link ShapeType#TEXT_ARCH_UP_POUR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTARCHUPPOUR = (short) 148; + /** @deprecated use {@link ShapeType#TEXT_ARCH_DOWN_POUR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTARCHDOWNPOUR = (short) 149; + /** @deprecated use {@link ShapeType#TEXT_CIRCLE_POUR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCIRCLEPOUR = (short) 150; + /** @deprecated use {@link ShapeType#TEXT_BUTTON_POUR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTBUTTONPOUR = (short) 151; + /** @deprecated use {@link ShapeType#TEXT_CURVE_UP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCURVEUP = (short) 152; + /** @deprecated use {@link ShapeType#TEXT_CURVE_DOWN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCURVEDOWN = (short) 153; + /** @deprecated use {@link ShapeType#TEXT_CASCADE_UP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCASCADEUP = (short) 154; + /** @deprecated use {@link ShapeType#TEXT_CASCADE_DOWN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCASCADEDOWN = (short) 155; + /** @deprecated use {@link ShapeType#TEXT_WAVE_1} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTWAVE1 = (short) 156; + /** @deprecated use {@link ShapeType#TEXT_WAVE_2} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTWAVE2 = (short) 157; + /** @deprecated use {@link ShapeType#TEXT_WAVE_3} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTWAVE3 = (short) 158; + /** @deprecated use {@link ShapeType#TEXT_WAVE_4} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTWAVE4 = (short) 159; + /** @deprecated use {@link ShapeType#TEXT_INFLATE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTINFLATE = (short) 160; + /** @deprecated use {@link ShapeType#TEXT_DEFLATE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTDEFLATE = (short) 161; + /** @deprecated use {@link ShapeType#TEXT_INFLATE_BOTTOM} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTINFLATEBOTTOM = (short) 162; + /** @deprecated use {@link ShapeType#TEXT_DEFLATE_BOTTOM} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTDEFLATEBOTTOM = (short) 163; + /** @deprecated use {@link ShapeType#TEXT_INFLATE_TOP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTINFLATETOP = (short) 164; + /** @deprecated use {@link ShapeType#TEXT_DEFLATE_TOP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTDEFLATETOP = (short) 165; + /** @deprecated use {@link ShapeType#TEXT_DEFLATE_INFLATE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTDEFLATEINFLATE = (short) 166; + /** @deprecated use {@link ShapeType#TEXT_DEFLATE_INFLATE_DEFLATE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTDEFLATEINFLATEDEFLATE = (short) 167; + /** @deprecated use {@link ShapeType#TEXT_FADE_RIGHT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTFADERIGHT = (short) 168; + /** @deprecated use {@link ShapeType#TEXT_FADE_LEFT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTFADELEFT = (short) 169; + /** @deprecated use {@link ShapeType#TEXT_FADE_UP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTFADEUP = (short) 170; + /** @deprecated use {@link ShapeType#TEXT_FADE_DOWN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTFADEDOWN = (short) 171; + /** @deprecated use {@link ShapeType#TEXT_SLANT_UP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTSLANTUP = (short) 172; + /** @deprecated use {@link ShapeType#TEXT_SLANT_DOWN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTSLANTDOWN = (short) 173; + /** @deprecated use {@link ShapeType#TEXT_CAN_UP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCANUP = (short) 174; + /** @deprecated use {@link ShapeType#TEXT_CAN_DOWN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTCANDOWN = (short) 175; + /** @deprecated use {@link ShapeType#FLOW_CHART_ALTERNATE_PROCESS} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTALTERNATEPROCESS = (short) 176; + /** @deprecated use {@link ShapeType#FLOW_CHART_OFFPAGE_CONNECTOR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_FLOWCHARTOFFPAGECONNECTOR = (short) 177; + /** @deprecated use {@link ShapeType#CALLOUT_90} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_CALLOUT90 = (short) 178; + /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_90} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTCALLOUT90 = (short) 179; + /** @deprecated use {@link ShapeType#BORDER_CALLOUT_90} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BORDERCALLOUT90 = (short) 180; + /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_90} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACCENTBORDERCALLOUT90 = (short) 181; + /** @deprecated use {@link ShapeType#LEFT_RIGHT_UP_ARROW} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_LEFTRIGHTUPARROW = (short) 182; + /** @deprecated use {@link ShapeType#SUN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SUN = (short) 183; + /** @deprecated use {@link ShapeType#MOON} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_MOON = (short) 184; + /** @deprecated use {@link ShapeType#BRACKET_PAIR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BRACKETPAIR = (short) 185; + /** @deprecated use {@link ShapeType#BRACE_PAIR} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_BRACEPAIR = (short) 186; + /** @deprecated use {@link ShapeType#STAR_4} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_SEAL4 = (short) 187; + /** @deprecated use {@link ShapeType#DOUBLE_WAVE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_DOUBLEWAVE = (short) 188; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_BLANK} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONBLANK = (short) 189; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_HOME} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONHOME = (short) 190; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_HELP} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONHELP = (short) 191; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_INFORMATION} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONINFORMATION = (short) 192; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_FORWARD_NEXT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONFORWARDNEXT = (short) 193; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_BACK_PREVIOUS} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONBACKPREVIOUS = (short) 194; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_END} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONEND = (short) 195; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_BEGINNING} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONBEGINNING = (short) 196; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_RETURN} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONRETURN = (short) 197; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_DOCUMENT} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONDOCUMENT = (short) 198; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_SOUND} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONSOUND = (short) 199; + /** @deprecated use {@link ShapeType#ACTION_BUTTON_MOVIE} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_ACTIONBUTTONMOVIE = (short) 200; + /** @deprecated use {@link ShapeType#HOST_CONTROL} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_HOSTCONTROL = (short) 201; + /** @deprecated use {@link ShapeType#TEXT_BOX} */ + @Deprecated + @Removal(version = "5.3") public static final short ST_TEXTBOX = (short) 202; + /** @deprecated not used */ + @Deprecated + @Removal(version = "5.3") public static final short ST_NIL = (short) 0x0FFF; /** @@ -330,6 +947,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { /** * @return Returns the current sid. */ + @Override public short getSid() { return sid; } @@ -402,7 +1020,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { private static class ShapeCollector extends DefaultEscherRecordFactory { final List<EscherRecord> objShapes = new ArrayList<>(); - final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream buffer = new UnsynchronizedByteArrayOutputStream(); void addBytes(byte[] data) { try { @@ -412,6 +1030,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { } } + @Override public EscherRecord createRecord(byte[] data, int offset) { EscherRecord r = super.createRecord(data, offset); short rid = r.getRecordId(); @@ -423,9 +1042,10 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { List<EscherRecord> parse(EscherAggregate agg) { byte[] buf = buffer.toByteArray(); - for (int pos = 0, bytesRead; pos < buf.length; pos += bytesRead) { + int pos = 0; + while (pos < buf.length) { EscherRecord r = createRecord(buf, pos); - bytesRead = r.fillFields(buf, pos, this); + pos += r.fillFields(buf, pos, this); agg.addEscherRecord(r); } return objShapes; @@ -440,6 +1060,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { * @param data The byte array to serialize to. * @return The number of bytes serialized. */ + @Override public int serialize(final int offset, final byte[] data) { // Determine buffer size List <EscherRecord>records = getEscherRecords(); @@ -450,12 +1071,13 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { final List <Integer>spEndingOffsets = new ArrayList<>(); final List <EscherRecord> shapes = new ArrayList<>(); int pos = 0; - for (Object record : records) { - EscherRecord e = (EscherRecord) record; - pos += e.serialize(pos, buffer, new EscherSerializationListener() { + for (EscherRecord record : records) { + pos += record.serialize(pos, buffer, new EscherSerializationListener() { + @Override public void beforeRecordSerialize(int offset, short recordId, EscherRecord record) { } + @Override public void afterRecordSerialize(int offset, short recordId, int size, EscherRecord record) { if (recordId == EscherClientDataRecord.RECORD_ID || recordId == EscherTextboxRecord.RECORD_ID) { spEndingOffsets.add(offset); @@ -545,6 +1167,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { /** * @return record size, including header size of obj, text, note, drawing, continue records */ + @Override public int getRecordSize() { // To determine size of aggregate record we have to know size of each DrawingRecord because if DrawingRecord // is split into several continue records we have to add header size to total EscherAggregate size @@ -557,9 +1180,11 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { int pos = 0; for (EscherRecord e : records) { pos += e.serialize(pos, buffer, new EscherSerializationListener() { + @Override public void beforeRecordSerialize(int offset, short recordId, EscherRecord record) { } + @Override public void afterRecordSerialize(int offset, short recordId, int size, EscherRecord record) { if (recordId == EscherClientDataRecord.RECORD_ID || recordId == EscherTextboxRecord.RECORD_ID) { spEndingOffsets.add(offset); @@ -615,6 +1240,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord { /** * @return "ESCHERAGGREGATE" */ + @Override protected String getRecordName() { return "ESCHERAGGREGATE"; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java index a7fccea0c9..cbb73a65e4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.EncryptionMode; @@ -47,7 +47,7 @@ public final class FilePassRecord extends StandardRecord { private static final int ENCRYPTION_OTHER = 1; private final int encryptionType; - private EncryptionInfo encryptionInfo; + private final EncryptionInfo encryptionInfo; private FilePassRecord(FilePassRecord other) { super(other); @@ -122,7 +122,7 @@ public final class FilePassRecord extends StandardRecord { @Override protected int getDataSize() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); serialize(leos); return bos.size(); diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java index a8af77c2e1..84c5faf29c 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java @@ -17,11 +17,11 @@ package org.apache.poi.hssf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.dev.BiffViewer; import org.apache.poi.hssf.record.crypto.Biff8DecryptingStream; import org.apache.poi.poifs.crypt.EncryptionInfo; @@ -56,7 +56,6 @@ public final class RecordInputStream implements LittleEndianInput { * For use in {@link BiffViewer} which may construct {@link Record}s that don't completely * read all available data. This exception should never be thrown otherwise. */ - @SuppressWarnings("serial") public static final class LeftoverDataException extends RuntimeException { public LeftoverDataException(int sid, int remainingByteCount) { super("Initialisation of record 0x" + Integer.toHexString(sid).toUpperCase(Locale.ROOT) @@ -311,6 +310,7 @@ public final class RecordInputStream implements LittleEndianInput { return Double.longBitsToDouble(readLong()); } + @Override public void readPlain(byte[] buf, int off, int len) { readFully(buf, 0, buf.length, true); } @@ -459,7 +459,7 @@ public final class RecordInputStream implements LittleEndianInput { */ @Deprecated public byte[] readAllContinuedRemainder() { - ByteArrayOutputStream out = new ByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE); while (true) { byte[] b = readRemainder(); @@ -486,7 +486,7 @@ public final class RecordInputStream implements LittleEndianInput { /** * - * @return <code>true</code> when a {@link ContinueRecord} is next. + * @return {@code true} when a {@link ContinueRecord} is next. */ private boolean isContinueNext() { if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ && _currentDataOffset != _currentDataLength) { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java index 0429267162..e67a9f2ca9 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java @@ -17,13 +17,13 @@ package org.apache.poi.hssf.record; -import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.common.Duplicatable; import org.apache.poi.common.usermodel.GenericRecord; import org.apache.poi.util.GenericRecordJsonWriter; @@ -121,7 +121,7 @@ public abstract class SubRecord implements Duplicatable, GenericRecord { protected abstract int getDataSize(); public byte[] serialize() { int size = getDataSize() + 4; - ByteArrayOutputStream baos = new ByteArrayOutputStream(size); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(size); serialize(new LittleEndianOutputStream(baos)); if (baos.size() != size) { throw new RuntimeException("write size mismatch"); @@ -134,7 +134,7 @@ public abstract class SubRecord implements Duplicatable, GenericRecord { /** * Whether this record terminates the sub-record stream. - * There are two cases when this method must be overridden and return <code>true</code> + * There are two cases when this method must be overridden and return {@code true} * - EndSubRecord (sid = 0x00) * - LbsDataSubRecord (sid = 0x12) * diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java index 262eae5086..7295b74fea 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java @@ -27,15 +27,15 @@ import org.apache.poi.ddf.EscherSimpleProperty; import org.apache.poi.ddf.EscherSpRecord; import org.apache.poi.hssf.record.CommonObjectDataSubRecord; import org.apache.poi.hssf.record.EndSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; import org.apache.poi.hssf.record.FtCblsSubRecord; import org.apache.poi.hssf.record.LbsDataSubRecord; import org.apache.poi.hssf.record.ObjRecord; import org.apache.poi.hssf.record.TextObjectRecord; +import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; /** - * + * */ public class HSSFCombobox extends HSSFSimpleShape { @@ -65,7 +65,7 @@ public class HSSFCombobox extends HSSFSimpleShape { spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER); spContainer.setOptions((short) 0x000F); sp.setRecordId(EscherSpRecord.RECORD_ID); - sp.setOptions((short) ((EscherAggregate.ST_HOSTCONTROL << 4) | 0x2)); + sp.setOptions((short) ((ShapeType.HOST_CONTROL.nativeId << 4) | 0x2)); sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE); opt.setRecordId(EscherOptRecord.RECORD_ID); diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java index 430fe62798..023b47744b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java @@ -32,9 +32,9 @@ import org.apache.poi.ddf.EscherSimpleProperty; import org.apache.poi.ddf.EscherSpRecord; import org.apache.poi.hssf.record.CommonObjectDataSubRecord; import org.apache.poi.hssf.record.EndSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; import org.apache.poi.hssf.record.ObjRecord; import org.apache.poi.hssf.record.TextObjectRecord; +import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.util.LittleEndian; /** @@ -65,6 +65,7 @@ public class HSSFPolygon extends HSSFSimpleShape { /** * Generates the shape records for this shape. */ + @Override protected EscherContainerRecord createSpContainer() { EscherContainerRecord spContainer = new EscherContainerRecord(); EscherSpRecord sp = new EscherSpRecord(); @@ -74,7 +75,7 @@ public class HSSFPolygon extends HSSFSimpleShape { spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER); spContainer.setOptions((short) 0x000F); sp.setRecordId(EscherSpRecord.RECORD_ID); - sp.setOptions((short) ((EscherAggregate.ST_NOT_PRIMATIVE << 4) | 0x2)); + sp.setOptions((short) ((ShapeType.NOT_PRIMITIVE.nativeId << 4) | 0x2)); if (getParent() == null) { sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE); } else { @@ -115,6 +116,7 @@ public class HSSFPolygon extends HSSFSimpleShape { /** * Creates the low level OBJ record for this shape. */ + @Override protected ObjRecord createObjRecord() { ObjRecord obj = new ObjRecord(); CommonObjectDataSubRecord c = new CommonObjectDataSubRecord(); @@ -216,8 +218,6 @@ public class HSSFPolygon extends HSSFSimpleShape { /** * Defines the width and height of the points in the polygon - * @param width - * @param height */ public void setPolygonDrawArea(int width, int height) { setPropertyValue(new EscherSimpleProperty(EscherPropertyTypes.GEOMETRY__RIGHT, width)); diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java index 964356f5a6..d9c98e3063 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java @@ -17,11 +17,6 @@ package org.apache.poi.hssf.usermodel; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherBoolProperty; import org.apache.poi.ddf.EscherChildAnchorRecord; import org.apache.poi.ddf.EscherClientAnchorRecord; @@ -37,6 +32,7 @@ import org.apache.poi.hssf.record.CommonObjectDataSubRecord; import org.apache.poi.hssf.record.ObjRecord; import org.apache.poi.ss.usermodel.Shape; import org.apache.poi.util.LittleEndian; +import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.StringUtil; /** @@ -48,8 +44,6 @@ import org.apache.poi.util.StringUtil; * setFlipVertical() or setFlipHorizontally(). */ public abstract class HSSFShape implements Shape { - private static final Logger LOG = LogManager.getLogger(HSSFShape.class); - public static final int LINEWIDTH_ONE_PT = 12700; public static final int LINEWIDTH_DEFAULT = 9525; public static final int LINESTYLE__COLOR_DEFAULT = 0x08000040; @@ -85,8 +79,6 @@ public abstract class HSSFShape implements Shape { /** * creates shapes from existing file - * @param spContainer - * @param objRecord */ public HSSFShape(EscherContainerRecord spContainer, ObjRecord objRecord) { this._escherContainer = spContainer; @@ -115,7 +107,6 @@ public abstract class HSSFShape implements Shape { * remove escher container from the patriarch.escherAggregate * remove obj, textObj and note records if it's necessary * in case of ShapeGroup remove all contained shapes - * @param patriarch */ protected abstract void afterRemove(HSSFPatriarch patriarch); @@ -179,7 +170,7 @@ public abstract class HSSFShape implements Shape { * @see HSSFClientAnchor */ public void setAnchor(HSSFAnchor anchor) { - int i = 0; + int i; int recordId = -1; if (parent == null) { if (anchor instanceof HSSFChildAnchor) @@ -365,18 +356,13 @@ public abstract class HSSFShape implements Shape { * @return the rotation, in degrees, that is applied to a shape. */ public int getRotationDegree(){ - ByteArrayOutputStream bos = new ByteArrayOutputStream(); EscherSimpleProperty property = getOptRecord().lookup(EscherPropertyTypes.TRANSFORM__ROTATION); if (null == property){ return 0; } - try { - LittleEndian.putInt(property.getPropertyValue(), bos); - return LittleEndian.getShort(bos.toByteArray(), 2); - } catch (IOException e) { - LOG.atError().withThrowable(e).log("can't determine rotation degree"); - return 0; - } + byte[] buf = new byte[LittleEndianConsts.INT_SIZE]; + LittleEndian.putInt(buf, 0, property.getPropertyValue()); + return LittleEndian.getShort(buf, 2); } /** @@ -385,7 +371,6 @@ public abstract class HSSFShape implements Shape { * Negative values specify rotation in the counterclockwise direction. * Rotation occurs around the center of the shape. * The default value for this property is 0x00000000 - * @param value */ public void setRotationDegree(short value){ setPropertyValue(new EscherSimpleProperty(EscherPropertyTypes.TRANSFORM__ROTATION , (value << 16))); @@ -415,6 +400,7 @@ public abstract class HSSFShape implements Shape { /** * @return the name of this shape */ + @Override public String getShapeName() { EscherOptRecord eor = getOptRecord(); if (eor == null) { diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java index b8001fc651..623409d684 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java @@ -46,7 +46,7 @@ import org.apache.poi.hssf.record.ObjRecord; */ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { private final List<HSSFShape> shapes = new ArrayList<>(); - private EscherSpgrRecord _spgrRecord; + private final EscherSpgrRecord _spgrRecord; public HSSFShapeGroup(EscherContainerRecord spgrContainer, ObjRecord objRecord) { super(spgrContainer, objRecord); @@ -56,14 +56,13 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { _spgrRecord = (EscherSpgrRecord) spContainer.getChild(0); for (EscherRecord ch : spContainer) { switch (EscherRecordTypes.forTypeID(ch.getRecordId())) { - case SPGR: - break; case CLIENT_ANCHOR: anchor = new HSSFClientAnchor((EscherClientAnchorRecord) ch); break; case CHILD_ANCHOR: anchor = new HSSFChildAnchor((EscherChildAnchorRecord) ch); break; + case SPGR: default: break; } @@ -141,10 +140,12 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { protected void afterRemove(HSSFPatriarch patriarch) { patriarch.getBoundAggregate().removeShapeToObjRecord(getEscherContainer().getChildContainers().get(0) .getChildById(EscherClientDataRecord.RECORD_ID)); - for ( int i=0; i<shapes.size(); i++ ) { - HSSFShape shape = shapes.get(i); - removeShape(shape); - shape.afterRemove(getPatriarch()); + EscherContainerRecord cont = getEscherContainer(); + HSSFPatriarch pat = getPatriarch(); + for (HSSFShape shape : shapes) { + if (cont.removeChildRecord(shape.getEscherContainer())){ + shape.afterRemove(pat); + } } shapes.clear(); } @@ -181,6 +182,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { return group; } + @Override public void addShape(HSSFShape shape) { shape.setPatriarch(this.getPatriarch()); shape.setParent(this); @@ -267,6 +269,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { /** * Return all children contained by this shape. */ + @Override public List<HSSFShape> getChildren() { return Collections.unmodifiableList(shapes); } @@ -275,6 +278,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { * Sets the coordinate space of this group. All children are constrained * to these coordinates. */ + @Override public void setCoordinates(int x1, int y1, int x2, int y2) { _spgrRecord.setRectX1(x1); _spgrRecord.setRectX2(x2); @@ -282,6 +286,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { _spgrRecord.setRectY2(y2); } + @Override public void clear() { ArrayList <HSSFShape> copy = new ArrayList<>(shapes); for (HSSFShape shape: copy){ @@ -292,6 +297,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { /** * The top left x coordinate of this group. */ + @Override public int getX1() { return _spgrRecord.getRectX1(); } @@ -299,6 +305,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { /** * The top left y coordinate of this group. */ + @Override public int getY1() { return _spgrRecord.getRectY1(); } @@ -306,6 +313,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { /** * The bottom right x coordinate of this group. */ + @Override public int getX2() { return _spgrRecord.getRectX2(); } @@ -313,6 +321,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { /** * The bottom right y coordinate of this group. */ + @Override public int getY2() { return _spgrRecord.getRectY2(); } @@ -320,6 +329,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { /** * Count of all children and their childrens children. */ + @Override public int countOfAllChildren() { int count = shapes.size(); for (HSSFShape shape : shapes) { @@ -386,10 +396,11 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer { return group; } + @Override public boolean removeShape(HSSFShape shape) { boolean isRemoved = getEscherContainer().removeChildRecord(shape.getEscherContainer()); if (isRemoved){ - shape.afterRemove(this.getPatriarch()); + shape.afterRemove(getPatriarch()); shapes.remove(shape); } return isRemoved; diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java index 5821a42f57..0a394d601b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java @@ -33,6 +33,7 @@ import org.apache.poi.hssf.record.EndSubRecord; import org.apache.poi.hssf.record.EscherAggregate; import org.apache.poi.hssf.record.ObjRecord; import org.apache.poi.hssf.record.TextObjectRecord; +import org.apache.poi.sl.usermodel.ShapeType; /** * A textbox is a shape that may hold a rich text string. @@ -68,7 +69,7 @@ public class HSSFTextbox extends HSSFSimpleShape { /** * Construct a new textbox with the given parent and anchor. * - * @param parent + * @param parent the parent shape * @param anchor One of HSSFClientAnchor or HSSFChildAnchor */ public HSSFTextbox(HSSFShape parent, HSSFAnchor anchor) { @@ -104,7 +105,7 @@ public class HSSFTextbox extends HSSFSimpleShape { spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER); spContainer.setOptions((short) 0x000F); sp.setRecordId(EscherSpRecord.RECORD_ID); - sp.setOptions((short) ((EscherAggregate.ST_TEXTBOX << 4) | 0x2)); + sp.setOptions((short) ((ShapeType.TEXT_BOX.nativeId << 4) | 0x2)); sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE); opt.setRecordId(EscherOptRecord.RECORD_ID); diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java index dc938d2de7..7a943a368e 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java @@ -23,7 +23,6 @@ import static org.apache.poi.hssf.model.InternalWorkbook.WORKBOOK_DIR_ENTRY_NAME import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -47,6 +46,7 @@ import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.EncryptedDocumentException; @@ -942,7 +942,6 @@ public final class HSSFWorkbook extends POIDocument implements Workbook { private final class SheetIterator<T extends Sheet> implements Iterator<T> { final private Iterator<T> it; - private T cursor; @SuppressWarnings("unchecked") public SheetIterator() { @@ -956,8 +955,7 @@ public final class HSSFWorkbook extends POIDocument implements Workbook { @Override public T next() throws NoSuchElementException { - cursor = it.next(); - return cursor; + return it.next(); } /** @@ -1994,9 +1992,10 @@ public final class HSSFWorkbook extends POIDocument implements Workbook { } } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - poiData.writeFilesystem(bos); - return addOlePackage(bos.toByteArray(), label, fileName, command); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + poiData.writeFilesystem(bos); + return addOlePackage(bos.toByteArray(), label, fileName, command); + } } @Override @@ -2021,9 +2020,10 @@ public final class HSSFWorkbook extends POIDocument implements Workbook { Ole10Native.createOleMarkerEntry(oleDir); Ole10Native oleNative = new Ole10Native(label, fileName, command, oleData); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - oleNative.writeOut(bos); - oleDir.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray())); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + oleNative.writeOut(bos); + oleDir.createDocument(Ole10Native.OLE10_NATIVE, bos.toInputStream()); + } return storageId; } diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java index df2a51bc38..36b44efbcc 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java @@ -17,7 +17,6 @@ package org.apache.poi.poifs.crypt.cryptoapi; -import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; @@ -29,6 +28,7 @@ import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.crypt.ChunkedCipherInputStream; import org.apache.poi.poifs.crypt.CryptoFunctions; @@ -43,7 +43,7 @@ import org.apache.poi.poifs.filesystem.DocumentNode; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.BoundedInputStream; +import org.apache.commons.io.input.BoundedInputStream; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndianInputStream; @@ -171,10 +171,10 @@ public class CryptoAPIDecryptor extends Decryptor { public POIFSFileSystem getSummaryEntries(DirectoryNode root, String encryptedStream) throws IOException, GeneralSecurityException { DocumentNode es = (DocumentNode) root.getEntry(encryptedStream); - DocumentInputStream dis = root.createDocumentInputStream(es); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - IOUtils.copy(dis, bos); - dis.close(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + try (DocumentInputStream dis = root.createDocumentInputStream(es)) { + IOUtils.copy(dis, bos); + } POIFSFileSystem fsOut = null; try ( CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray()); diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java index 3a9cae9b04..34c4a74675 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java @@ -16,11 +16,13 @@ ==================================================================== */ package org.apache.poi.poifs.crypt.cryptoapi; -import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.security.GeneralSecurityException; import javax.crypto.Cipher; +import org.apache.commons.io.input.BoundedInputStream; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.util.Internal; @@ -38,8 +40,8 @@ import org.apache.poi.util.Internal; cipher = encryptor.initCipherForBlock(null, 0); } - public byte[] getBuf() { - return buf; + public InputStream toInputStream(long maxSize) { + return new BoundedInputStream(toInputStream(), maxSize); } public void setSize(int count) { diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java index 652e7f51d7..176f431eec 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java @@ -17,7 +17,6 @@ package org.apache.poi.poifs.crypt.cryptoapi; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; @@ -188,7 +187,7 @@ public class CryptoAPIEncryptor extends Encryptor { bos.write(buf, 0, 8); bos.setSize(savedSize); - dir.createDocument(encryptedStream, new ByteArrayInputStream(bos.getBuf(), 0, savedSize)); + dir.createDocument(encryptedStream, bos.toInputStream(savedSize)); } // protected int getKeySizeInBytes() { diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java index 9fedce6122..1624fa97e2 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java @@ -38,7 +38,7 @@ import org.apache.poi.poifs.crypt.EncryptionVerifier; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.util.BoundedInputStream; +import org.apache.commons.io.input.BoundedInputStream; import org.apache.poi.util.LittleEndian; /** diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java index a1052d865c..f8b948ee38 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java @@ -18,10 +18,10 @@ package org.apache.poi.poifs.filesystem; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.common.POIFSConstants; import org.apache.poi.poifs.property.DocumentProperty; @@ -37,13 +37,13 @@ public final class DocumentOutputStream extends OutputStream { private boolean _closed = false; /** the actual Document */ - private POIFSDocument _document; + private final POIFSDocument _document; /** and its Property */ - private DocumentProperty _property; + private final DocumentProperty _property; /** our buffer, when null we're into normal blocks */ - private ByteArrayOutputStream _buffer = - new ByteArrayOutputStream(POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE); + private UnsynchronizedByteArrayOutputStream _buffer = + new UnsynchronizedByteArrayOutputStream(POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE); /** our main block stream, when we're into normal blocks */ private POIFSStream _stream; @@ -115,11 +115,11 @@ public final class DocumentOutputStream extends OutputStream { byte[] data = _buffer.toByteArray(); _buffer = null; write(data, 0, data.length); - } else { - // So far, mini stream will work, keep going } + // otherwise mini stream will work, keep going } + @Override public void write(int b) throws IOException { write(new byte[] { (byte)b }, 0, 1); } @@ -146,11 +146,12 @@ public final class DocumentOutputStream extends OutputStream { } } + @Override public void close() throws IOException { // Do we have a pending buffer for the mini stream? if (_buffer != null) { // It's not much data, so ask POIFSDocument to do it for us - _document.replaceContents(new ByteArrayInputStream(_buffer.toByteArray())); + _document.replaceContents(_buffer.toInputStream()); } else { // We've been writing to the stream as we've gone along diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java index bd21697fcf..81dd891a8c 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java @@ -25,7 +25,6 @@ import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; @@ -238,7 +237,7 @@ public final class EntryUtils { } else { return isEqual(inpA, inpB); } - } catch (MarkUnsupportedException | NoPropertySetStreamException | IOException ex) { + } catch (NoPropertySetStreamException | IOException ex) { throw new RuntimeException(ex); } } diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java index c2d4a73ae4..680763bac2 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java @@ -18,12 +18,12 @@ package org.apache.poi.poifs.filesystem; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianConsts; @@ -336,7 +336,7 @@ public class Ole10Native { /** * Returns the size of the embedded file. If the size is 0 (zero), no data * has been embedded. To be sure, that no data has been embedded, check - * whether {@link #getDataBuffer()} returns <code>null</code>. + * whether {@link #getDataBuffer()} returns {@code null}. * * @return the dataSize */ @@ -346,10 +346,10 @@ public class Ole10Native { /** * Returns the buffer containing the embedded file's data, or - * <code>null</code> if no data was embedded. Note that an embedding may + * {@code null} if no data was embedded. Note that an embedding may * provide information about the data, but the actual data is not included. * (So label, filename etc. are available, but this method returns - * <code>null</code>.) + * {@code null}.) * * @return the dataBuffer */ @@ -372,7 +372,7 @@ public class Ole10Native { switch (mode) { case parsed: { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (LittleEndianOutputStream leos = new LittleEndianOutputStream(bos)) { // total size, will be determined later .. diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java index 7ac288a8a8..ebee94394b 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java @@ -16,7 +16,6 @@ ==================================================================== */ package org.apache.poi.poifs.filesystem; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; @@ -33,6 +32,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.commons.math3.util.ArithmeticUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -733,7 +733,7 @@ public class POIFSFileSystem extends BlockStore // _header.setPropertyStart has been updated on write ... // HeaderBlock - ByteArrayOutputStream baos = new ByteArrayOutputStream( + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream( _header.getBigBlockSize().getBigBlockSize() ); _header.writeData(baos); diff --git a/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java b/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java index 76cfd66472..049a805318 100644 --- a/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java +++ b/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java @@ -22,7 +22,6 @@ import static org.apache.poi.util.StringUtil.endsWithIgnoreCase; import static org.apache.poi.util.StringUtil.startsWithIgnoreCase; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.EOFException; import java.io.File; @@ -38,6 +37,7 @@ import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.poifs.filesystem.DirectoryNode; @@ -167,10 +167,7 @@ public class VBAMacroReader implements Closeable { ModuleType moduleType; Charset charset; void read(InputStream in) throws IOException { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - IOUtils.copy(in, out); - out.close(); - buf = out.toByteArray(); + buf = IOUtils.toByteArray(in); } @Override public String getContent() { @@ -414,13 +411,12 @@ public class VBAMacroReader implements Closeable { UNKNOWN(-2); - private final int VARIABLE_LENGTH = -1; private final int id; private final int constantLength; RecordType(int id) { this.id = id; - this.constantLength = VARIABLE_LENGTH; + this.constantLength = -1; } RecordType(int id, int constantLength) { @@ -651,13 +647,13 @@ public class VBAMacroReader implements Closeable { return; } } - mbcs = readMBCS(b, is, charset, MAX_STRING_LENGTH); + mbcs = readMBCS(b, is, charset); } catch (EOFException e) { return; } try { - unicode = readUnicode(is, MAX_STRING_LENGTH); + unicode = readUnicode(is); } catch (EOFException e) { return; } @@ -669,14 +665,14 @@ public class VBAMacroReader implements Closeable { LOGGER.atWarn().log("Hit max name records to read (" + maxNameRecords + "). Stopped early."); } - private static String readUnicode(InputStream is, int maxLength) throws IOException { + private static String readUnicode(InputStream is) throws IOException { //reads null-terminated unicode string - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); int b0 = IOUtils.readByte(is); int b1 = IOUtils.readByte(is); int read = 2; - while ((b0 + b1) != 0 && read < maxLength) { + while ((b0 + b1) != 0 && read < MAX_STRING_LENGTH) { bos.write(b0); bos.write(b1); @@ -684,22 +680,22 @@ public class VBAMacroReader implements Closeable { b1 = IOUtils.readByte(is); read += 2; } - if (read >= maxLength) { + if (read >= MAX_STRING_LENGTH) { LOGGER.atWarn().log("stopped reading unicode name after {} bytes", box(read)); } - return new String (bos.toByteArray(), StandardCharsets.UTF_16LE); + return bos.toString(StandardCharsets.UTF_16LE); } - private static String readMBCS(int firstByte, InputStream is, Charset charset, int maxLength) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + private static String readMBCS(int firstByte, InputStream is, Charset charset) throws IOException { + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); int len = 0; int b = firstByte; - while (b > 0 && len < maxLength) { + while (b > 0 && len < MAX_STRING_LENGTH) { ++len; bos.write(b); b = IOUtils.readByte(is); } - return new String(bos.toByteArray(), charset); + return bos.toString(charset); } /** @@ -796,7 +792,7 @@ public class VBAMacroReader implements Closeable { */ private static byte[] findCompressedStreamWBruteForce(InputStream is) throws IOException { //buffer to memory for multiple tries - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(is, bos); byte[] compressed = bos.toByteArray(); byte[] decompressed = null; @@ -825,7 +821,7 @@ public class VBAMacroReader implements Closeable { } private static byte[] tryToDecompress(InputStream is) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { IOUtils.copy(new RLEDecompressingInputStream(is), bos); } catch (IllegalArgumentException | IOException | IllegalStateException e){ diff --git a/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java b/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java index aa2b13e64c..4f2ca0ffbb 100644 --- a/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java +++ b/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java @@ -28,7 +28,6 @@ import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.RescaleOp; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; @@ -40,6 +39,7 @@ import javax.imageio.ImageTypeSpecifier; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.sl.usermodel.PictureData.PictureType; @@ -73,11 +73,11 @@ public class BitmapImageRenderer implements ImageRenderer { public void loadImage(InputStream data, String contentType) throws IOException { InputStream in = data; if (doCache) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(data, bos); cachedImage = bos.toByteArray(); cachedContentType = contentType; - in = new ByteArrayInputStream(cachedImage); + in = bos.toInputStream(); } img = readImage(in, contentType); } @@ -107,13 +107,13 @@ public class BitmapImageRenderer implements ImageRenderer { IOException lastException = null; BufferedImage img = null; - final ByteArrayInputStream bis; + final InputStream bis; if (data instanceof ByteArrayInputStream) { - bis = (ByteArrayInputStream)data; + bis = data; } else { - ByteArrayOutputStream bos = new ByteArrayOutputStream(0x3FFFF); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(0x3FFFF); IOUtils.copy(data, bos); - bis = new ByteArrayInputStream(bos.toByteArray()); + bis = bos.toInputStream(); } @@ -257,7 +257,7 @@ public class BitmapImageRenderer implements ImageRenderer { @Override public BufferedImage getImage(Dimension2D dim) { if (img == null) { - return img; + return null; } double w_old = img.getWidth(); double h_old = img.getHeight(); diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java b/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java index c7d421950e..3c36c77827 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java @@ -17,12 +17,11 @@ package org.apache.poi.sl.usermodel; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.FileMagic; import org.apache.poi.poifs.filesystem.POIFSFileSystem; @@ -54,7 +53,7 @@ public interface ObjectShape< * @return the ProgID */ String getProgId(); - + /** * Returns the full name of the embedded object, * e.g. "Microsoft Word Document" or "Microsoft Office Excel Worksheet". @@ -62,11 +61,11 @@ public interface ObjectShape< * @return the full name of the embedded object */ String getFullName(); - + /** * Updates the ole data. If there wasn't an object registered before, a new * ole embedding is registered in the parent slideshow.<p> - * + * * For HSLF this needs to be a {@link POIFSFileSystem} stream. * * @param application a preset application enum @@ -81,10 +80,10 @@ public interface ObjectShape< /** * Reads the ole data as stream - the application specific stream is served * The {@link #readObjectDataRaw() raw data} serves the outer/wrapped object, which is usually a - * {@link POIFSFileSystem} stream, whereas this method return the unwrapped entry + * {@link POIFSFileSystem} stream, whereas this method return the unwrapped entry * * @return an {@link InputStream} which serves the object data - * + * * @throws IOException if the linked object data couldn't be found */ default InputStream readObjectData() throws IOException { @@ -97,8 +96,9 @@ public interface ObjectShape< final Application app = Application.lookup(progId); - final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000); - try (final InputStream is = FileMagic.prepareToCheckMagic(readObjectDataRaw())) { + try (final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + final InputStream is = FileMagic.prepareToCheckMagic(readObjectDataRaw())) { + final FileMagic fm = FileMagic.valueOf(is); if (fm == FileMagic.OLE2) { try (final POIFSFileSystem poifs = new POIFSFileSystem(is)) { @@ -129,11 +129,10 @@ public interface ObjectShape< } else { IOUtils.copy(is, bos); } + return bos.toInputStream(); } - - return new ByteArrayInputStream(bos.toByteArray()); } - + /** * Convenience method to return the raw data as {@code InputStream} * diff --git a/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java b/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java index dbce0249ea..18eef73108 100644 --- a/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java +++ b/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java @@ -19,7 +19,6 @@ package org.apache.poi.ss.extractor; import static org.apache.poi.util.StringUtil.endsWithIgnoreCase; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -28,6 +27,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hpsf.ClassID; @@ -162,7 +162,7 @@ public class EmbeddedExtractor implements Iterable<EmbeddedExtractor> { protected EmbeddedData extract(DirectoryNode dn) throws IOException { assert(canExtract(dn)); - ByteArrayOutputStream bos = new ByteArrayOutputStream(20000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(20000); try (POIFSFileSystem dest = new POIFSFileSystem()) { copyNodes(dn, dest.getRoot()); // start with a reasonable big size @@ -204,7 +204,7 @@ public class EmbeddedExtractor implements Iterable<EmbeddedExtractor> { @Override public EmbeddedData extract(DirectoryNode dn) throws IOException { - try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try(UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); InputStream is = dn.createDocumentInputStream("CONTENTS")) { IOUtils.copy(is, bos); return new EmbeddedData(dn.getName() + ".pdf", bos.toByteArray(), CONTENT_TYPE_PDF); diff --git a/poi/src/main/java/org/apache/poi/util/BoundedInputStream.java b/poi/src/main/java/org/apache/poi/util/BoundedInputStream.java deleted file mode 100644 index df63cbc11b..0000000000 --- a/poi/src/main/java/org/apache/poi/util/BoundedInputStream.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.poi.util; - -import java.io.IOException; -import java.io.InputStream; - -/** - * This is a stream that will only supply bytes up to a certain length - if its - * position goes above that, it will stop. - * <p> - * This is useful to wrap ServletInputStreams. The ServletInputStream will block - * if you try to read content from it that isn't there, because it doesn't know - * whether the content hasn't arrived yet or whether the content has finished. - * So, one of these, initialized with the Content-length sent in the - * ServletInputStream's header, will stop it blocking, providing it's been sent - * with a correct content length. - * - * @version $Id$ - * @since Commons IO 2.0 - */ -public class BoundedInputStream extends InputStream { - - /** the wrapped input stream */ - private final InputStream in; - - /** the max length to provide */ - private final long max; - - /** the number of bytes already returned */ - private long pos; - - /** the marked position */ - private long mark = -1; - - /** flag if close shoud be propagated */ - private boolean propagateClose = true; - - /** - * Creates a new <code>BoundedInputStream</code> that wraps the given input - * stream and limits it to a certain size. - * - * @param in The wrapped input stream - * @param size The maximum number of bytes to return - */ - public BoundedInputStream(InputStream in, long size) { - // Some badly designed methods - eg the servlet API - overload length - // such that "-1" means stream finished - this.max = size; - this.in = in; - } - - /** - * Creates a new <code>BoundedInputStream</code> that wraps the given input - * stream and is unlimited. - * - * @param in The wrapped input stream - */ - public BoundedInputStream(InputStream in) { - this(in, -1); - } - - /** - * Invokes the delegate's <code>read()</code> method if - * the current position is less than the limit. - * @return the byte read or -1 if the end of stream or - * the limit has been reached. - * @throws IOException if an I/O error occurs - */ - @Override - public int read() throws IOException { - if (max>=0 && pos==max) { - return -1; - } - int result = in.read(); - pos++; - return result; - } - - /** - * Invokes the delegate's <code>read(byte[])</code> method. - * @param b the buffer to read the bytes into - * @return the number of bytes read or -1 if the end of stream or - * the limit has been reached. - * @throws IOException if an I/O error occurs - */ - @Override - public int read(byte[] b) throws IOException { - return this.read(b, 0, b.length); - } - - /** - * Invokes the delegate's <code>read(byte[], int, int)</code> method. - * @param b the buffer to read the bytes into - * @param off The start offset - * @param len The number of bytes to read - * @return the number of bytes read or -1 if the end of stream or - * the limit has been reached. - * @throws IOException if an I/O error occurs - */ - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (max>=0 && pos>=max) { - return -1; - } - long maxRead = max>=0 ? Math.min(len, max-pos) : len; - int bytesRead = in.read(b, off, (int)maxRead); - - if (bytesRead==-1) { - return -1; - } - - pos+=bytesRead; - return bytesRead; - } - - /** - * Invokes the delegate's <code>skip(long)</code> method. - * @param n the number of bytes to skip - * @return the actual number of bytes skipped; might be fewer than requested - * @throws IOException if an I/O error occurs - */ - @Override - public long skip(long n) throws IOException { - long toSkip = max>=0 ? Math.min(n, max-pos) : n; - long skippedBytes = IOUtils.skipFully(in, toSkip); - pos+=skippedBytes; - return skippedBytes; - } - - /** - * {@inheritDoc} - */ - @Override - @SuppressForbidden("just delegating") - public int available() throws IOException { - if (max>=0 && pos>=max) { - return 0; - } - return in.available(); - } - - /** - * Invokes the delegate's <code>toString()</code> method. - * @return the delegate's <code>toString()</code> - */ - @Override - public String toString() { - return in.toString(); - } - - /** - * Invokes the delegate's <code>close()</code> method - * if {@link #isPropagateClose()} is <code>true</code>. - * @throws IOException if an I/O error occurs - */ - @Override - public void close() throws IOException { - if (propagateClose) { - in.close(); - } - } - - /** - * Invokes the delegate's <code>reset()</code> method. - * @throws IOException if an I/O error occurs - */ - @Override - public synchronized void reset() throws IOException { - in.reset(); - pos = mark; - } - - /** - * Invokes the delegate's <code>mark(int)</code> method. - * @param readlimit read ahead limit - */ - @Override - public synchronized void mark(int readlimit) { - in.mark(readlimit); - mark = pos; - } - - /** - * Invokes the delegate's <code>markSupported()</code> method. - * @return true if mark is supported, otherwise false - */ - @Override - public boolean markSupported() { - return in.markSupported(); - } - - /** - * Indicates whether the {@link #close()} method - * should propagate to the underling {@link InputStream}. - * - * @return <code>true</code> if calling {@link #close()} - * propagates to the <code>close()</code> method of the - * underlying stream or <code>false</code> if it does not. - */ - public boolean isPropagateClose() { - return propagateClose; - } - - /** - * Set whether the {@link #close()} method - * should propagate to the underling {@link InputStream}. - * - * @param propagateClose <code>true</code> if calling - * {@link #close()} propagates to the <code>close()</code> - * method of the underlying stream or - * <code>false</code> if it does not. - */ - public void setPropagateClose(boolean propagateClose) { - this.propagateClose = propagateClose; - } -} diff --git a/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java b/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java index c46a535a0b..281b8180b0 100644 --- a/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java +++ b/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java @@ -19,6 +19,8 @@ package org.apache.poi.util; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; + import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; @@ -115,7 +117,7 @@ public class GenericRecordJsonWriter implements Closeable { protected int childIndex = 0; public GenericRecordJsonWriter(File fileName) throws IOException { - OutputStream os = ("null".equals(fileName.getName())) ? new NullOutputStream() : new FileOutputStream(fileName); + OutputStream os = ("null".equals(fileName.getName())) ? NULL_OUTPUT_STREAM : new FileOutputStream(fileName); aw = new AppendableWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)); fw = new PrintWriter(aw); } @@ -531,23 +533,6 @@ public class GenericRecordJsonWriter implements Closeable { return ZEROS.substring(0, Math.max(0,size-len)) + b.substring(Math.max(0,len-size), len); } - static class NullOutputStream extends OutputStream { - NullOutputStream() { - } - - @Override - public void write(byte[] b, int off, int len) { - } - - @Override - public void write(int b) { - } - - @Override - public void write(byte[] b) { - } - } - static class AppendableWriter extends Writer { private final Appendable appender; private final Writer writer; diff --git a/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java b/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java index c5a949cc63..a90f9c94fb 100644 --- a/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java +++ b/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java @@ -19,6 +19,8 @@ package org.apache.poi.util; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; + import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; @@ -50,7 +52,6 @@ import java.util.stream.Stream; import org.apache.poi.common.usermodel.GenericRecord; import org.apache.poi.util.GenericRecordJsonWriter.AppendableWriter; -import org.apache.poi.util.GenericRecordJsonWriter.NullOutputStream; @SuppressWarnings("WeakerAccess") public class GenericRecordXmlWriter implements Closeable { @@ -73,7 +74,7 @@ public class GenericRecordXmlWriter implements Closeable { boolean print(GenericRecordXmlWriter record, String name, Object object); } - private static final List<Map.Entry<Class, GenericRecordHandler>> handler = new ArrayList<>(); + private static final List<Map.Entry<Class<?>, GenericRecordHandler>> handler = new ArrayList<>(); static { char[] t = new char[255]; @@ -97,7 +98,7 @@ public class GenericRecordXmlWriter implements Closeable { handler(Object.class, GenericRecordXmlWriter::printObject); } - private static void handler(Class c, GenericRecordHandler printer) { + private static void handler(Class<?> c, GenericRecordHandler printer) { handler.add(new AbstractMap.SimpleEntry<>(c, printer)); } @@ -108,7 +109,7 @@ public class GenericRecordXmlWriter implements Closeable { private boolean attributePhase = true; public GenericRecordXmlWriter(File fileName) throws IOException { - OutputStream os = ("null".equals(fileName.getName())) ? new NullOutputStream() : new FileOutputStream(fileName); + OutputStream os = ("null".equals(fileName.getName())) ? NULL_OUTPUT_STREAM : new FileOutputStream(fileName); fw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)); } @@ -150,10 +151,10 @@ public class GenericRecordXmlWriter implements Closeable { protected void write(final String name, GenericRecord record) { final String tabs = tabs(); - Enum type = record.getGenericRecordType(); + Enum<?> type = record.getGenericRecordType(); String recordName = (type != null) ? type.name() : record.getClass().getSimpleName(); fw.append(tabs); - fw.append("<"+name+" type=\""); + fw.append("<").append(name).append(" type=\""); fw.append(recordName); fw.append("\""); if (childIndex > 0) { @@ -279,7 +280,7 @@ public class GenericRecordXmlWriter implements Closeable { } } - protected static boolean matchInstanceOrArray(Class key, Object instance) { + protected static boolean matchInstanceOrArray(Class<?> key, Object instance) { return key.isInstance(instance) || (Array.class.equals(key) && instance.getClass().isArray()); } @@ -332,8 +333,7 @@ public class GenericRecordXmlWriter implements Closeable { openName(name+">"); int oldChildIndex = childIndex; childIndex = 0; - //noinspection unchecked - ((List)o).forEach(e -> { writeValue("item>", e); childIndex++; }); + ((List<?>)o).forEach(e -> { writeValue("item>", e); childIndex++; }); childIndex = oldChildIndex; closeName(name+">"); return true; @@ -478,7 +478,7 @@ public class GenericRecordXmlWriter implements Closeable { case "&": fw.write("&"); break; - case "\'": + case "'": fw.write("'"); break; case "\"": diff --git a/poi/src/main/java/org/apache/poi/util/IOUtils.java b/poi/src/main/java/org/apache/poi/util/IOUtils.java index ec348b67a2..279b56974c 100644 --- a/poi/src/main/java/org/apache/poi/util/IOUtils.java +++ b/poi/src/main/java/org/apache/poi/util/IOUtils.java @@ -17,7 +17,6 @@ package org.apache.poi.util; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.EOFException; import java.io.File; @@ -33,6 +32,8 @@ import java.util.Locale; import java.util.zip.CRC32; import java.util.zip.Checksum; +import org.apache.commons.io.input.BoundedInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.EmptyFileException; @@ -106,7 +107,7 @@ public final class IOUtils { checkByteSizeLimit(limit); stream.mark(limit); - ByteArrayOutputStream bos = new ByteArrayOutputStream(limit); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(limit); copy(new BoundedInputStream(stream, limit), bos); int readBytes = bos.size(); @@ -177,7 +178,7 @@ public final class IOUtils { } final int len = Math.min(length, maxLength); - ByteArrayOutputStream baos = new ByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len); byte[] buffer = new byte[4096]; int totalBytes = 0, readBytes; diff --git a/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java b/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java index 0ebae8a0ac..1a0052e08b 100644 --- a/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java +++ b/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java @@ -16,11 +16,12 @@ ==================================================================== */ package org.apache.poi.util; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; + /** * This class provides common functionality for the * various LZW implementations in the different file @@ -86,7 +87,7 @@ public abstract class LZWDecompresser { * of the decompressed input. */ public byte[] decompress(InputStream src) throws IOException { - ByteArrayOutputStream res = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream res = new UnsynchronizedByteArrayOutputStream(); decompress(src, res); return res.toByteArray(); } diff --git a/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java b/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java index 6bd7fef86e..aa2211eb1a 100644 --- a/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java +++ b/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java @@ -18,11 +18,12 @@ package org.apache.poi.util; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; + /** * Wrapper of InputStream which provides Run Length Encoding (RLE) * decompression on the fly. Uses MS-OVBA decompression algorithm. See @@ -68,7 +69,6 @@ public class RLEDecompressingInputStream extends InputStream { * Creates a new wrapper RLE Decompression InputStream. * * @param in The stream to wrap with the RLE Decompression - * @throws IOException */ public RLEDecompressingInputStream(InputStream in) throws IOException { this.in = in; @@ -152,7 +152,6 @@ public class RLEDecompressingInputStream extends InputStream { * Reads a single chunk from the underlying inputstream. * * @return number of bytes that were read, or -1 if the end of the stream was reached. - * @throws IOException */ private int readChunk() throws IOException { pos = 0; @@ -216,7 +215,6 @@ public class RLEDecompressingInputStream extends InputStream { /** * Helper method to determine how many bits in the CopyToken are used for the CopyLength. * - * @param offset * @return returns the number of bits in the copy token (a value between 4 and 12) */ static int getCopyLenBits(int offset) { @@ -232,7 +230,6 @@ public class RLEDecompressingInputStream extends InputStream { * Convenience method for read a 2-bytes short in little endian encoding. * * @return short value from the stream, -1 if end of stream is reached - * @throws IOException */ public int readShort() throws IOException { return readShort(this); @@ -242,7 +239,6 @@ public class RLEDecompressingInputStream extends InputStream { * Convenience method for read a 4-bytes int in little endian encoding. * * @return integer value from the stream, -1 if end of stream is reached - * @throws IOException */ public int readInt() throws IOException { return readInt(this); @@ -281,12 +277,12 @@ public class RLEDecompressingInputStream extends InputStream { } public static byte[] decompress(byte[] compressed, int offset, int length) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - InputStream instream = new ByteArrayInputStream(compressed, offset, length); - InputStream stream = new RLEDecompressingInputStream(instream); - IOUtils.copy(stream, out); - stream.close(); - out.close(); - return out.toByteArray(); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + InputStream instream = new ByteArrayInputStream(compressed, offset, length); + InputStream stream = new RLEDecompressingInputStream(instream)) { + + IOUtils.copy(stream, out); + return out.toByteArray(); + } } } diff --git a/poi/src/test/java/org/apache/poi/POIDataSamples.java b/poi/src/test/java/org/apache/poi/POIDataSamples.java index 0772017d0a..dc9066c1bc 100644 --- a/poi/src/test/java/org/apache/poi/POIDataSamples.java +++ b/poi/src/test/java/org/apache/poi/POIDataSamples.java @@ -16,13 +16,16 @@ ==================================================================== */ package org.apache.poi; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.IOUtils; + /** * Centralises logic for finding/opening sample files */ @@ -47,7 +50,7 @@ public final class POIDataSamples { private static POIDataSamples _instXmlDSign; private File _resolvedDataDir; - /** {@code true} if standard system propery is not set, + /** {@code true} if standard system property is not set, * but the data is available on the test runtime classpath */ private boolean _sampleDataIsAvaliableOnClassPath; private final String _moduleDir; @@ -260,24 +263,19 @@ public final class POIDataSamples { * @return byte array of sample file content from file found in standard test-data directory */ public byte[] readFile(String fileName) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - try { - InputStream fis = openResourceAsStream(fileName); - - byte[] buf = new byte[512]; - while (true) { - int bytesRead = fis.read(buf); - if (bytesRead < 1) { - break; - } - bos.write(buf, 0, bytesRead); - } - fis.close(); + try (InputStream fis = openResourceAsStream(fileName); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + IOUtils.copy(fis, bos); + return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } - return bos.toByteArray(); } + public static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + original.writeFilesystem(baos); + return new POIFSFileSystem(baos.toInputStream()); + } + } } diff --git a/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java b/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java index c2c44529b8..78fd9db41b 100644 --- a/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java +++ b/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java @@ -17,21 +17,20 @@ package org.apache.poi; +import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook; +import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -42,22 +41,11 @@ import org.junit.jupiter.api.Test; * which are part of the Main (not scratchpad) */ final class TestPOIDocumentMain { - // The POI Documents to work on - private POIDocument doc; - private POIDocument doc2; - - /** - * Set things up, two spreadsheets for our testing - */ - @BeforeEach - void setUp() { - doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls"); - doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls"); - } - @Test - void readProperties() { - readPropertiesHelper(doc); + void readProperties() throws IOException { + try (POIDocument xls = openSampleWorkbook("DateFormats.xls")) { + readPropertiesHelper(xls); + } } private void readPropertiesHelper(POIDocument docWB) { @@ -71,130 +59,108 @@ final class TestPOIDocumentMain { } @Test - void readProperties2() { - // Check again on the word one - assertNotNull(doc2.getDocumentSummaryInformation()); - assertNotNull(doc2.getSummaryInformation()); - - assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor()); - assertNull(doc2.getSummaryInformation().getKeywords()); - assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); + void readProperties2() throws IOException { + try (POIDocument xls = openSampleWorkbook("StringFormulas.xls")) { + // Check again on the word one + assertNotNull(xls.getDocumentSummaryInformation()); + assertNotNull(xls.getSummaryInformation()); + + assertEquals("Avik Sengupta", xls.getSummaryInformation().getAuthor()); + assertNull(xls.getSummaryInformation().getKeywords()); + assertEquals(0, xls.getDocumentSummaryInformation().getByteCount()); + } } @Test void writeProperties() throws IOException { // Just check we can write them back out into a filesystem - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.readProperties(); - doc.writeProperties(outFS); - - // Should now hold them - assertNotNull( - outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME) - ); - assertNotNull( - outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME) - ); + try (POIDocument xls = openSampleWorkbook("DateFormats.xls"); + POIFSFileSystem outFS = new POIFSFileSystem()) { + xls.readProperties(); + xls.writeProperties(outFS); + + // Should now hold them + assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); + assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)); + } } @Test void WriteReadProperties() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); // Write them out - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.readProperties(); - doc.writeProperties(outFS); - outFS.writeFilesystem(baos); + try (POIDocument xls = openSampleWorkbook("DateFormats.xls"); + POIFSFileSystem outFS = new POIFSFileSystem()) { + xls.readProperties(); + xls.writeProperties(outFS); + outFS.writeFilesystem(baos); + } // Create a new version - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem inFS = new POIFSFileSystem(bais); + try (POIFSFileSystem inFS = new POIFSFileSystem(baos.toInputStream()); + POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS)) { - // Check they're still there - POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS); - doc3.readProperties(); + // Check they're still there + doc3.readProperties(); - // Delegate test - readPropertiesHelper(doc3); - doc3.close(); + // Delegate test + readPropertiesHelper(doc3); + } } @Test void createNewProperties() throws IOException { - POIDocument doc = new HSSFWorkbook(); - - // New document won't have them - assertNull(doc.getSummaryInformation()); - assertNull(doc.getDocumentSummaryInformation()); - - // Add them in - doc.createInformationProperties(); - assertNotNull(doc.getSummaryInformation()); - assertNotNull(doc.getDocumentSummaryInformation()); - - // Write out and back in again, no change - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + try (HSSFWorkbook xls1 = new HSSFWorkbook()) { + // New document won't have them + assertNull(xls1.getSummaryInformation()); + assertNull(xls1.getDocumentSummaryInformation()); + + // Add them in + xls1.createInformationProperties(); + assertNotNull(xls1.getSummaryInformation()); + assertNotNull(xls1.getDocumentSummaryInformation()); + + try (HSSFWorkbook xls2 = writeOutAndReadBack(xls1)) { + assertNotNull(xls2.getSummaryInformation()); + assertNotNull(xls2.getDocumentSummaryInformation()); + } + } - doc.close(); - - doc = new HSSFWorkbook(bais); - - assertNotNull(doc.getSummaryInformation()); - assertNotNull(doc.getDocumentSummaryInformation()); - - doc.close(); } @Test void createNewPropertiesOnExistingFile() throws IOException { - POIDocument doc = new HSSFWorkbook(); - - // New document won't have them - assertNull(doc.getSummaryInformation()); - assertNull(doc.getDocumentSummaryInformation()); - - // Write out and back in again, no change - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - - doc.close(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - doc = new HSSFWorkbook(bais); - - assertNull(doc.getSummaryInformation()); - assertNull(doc.getDocumentSummaryInformation()); - - // Create, and change - doc.createInformationProperties(); - doc.getSummaryInformation().setAuthor("POI Testing"); - doc.getDocumentSummaryInformation().setCompany("ASF"); - - // Save and re-load - baos = new ByteArrayOutputStream(); - doc.write(baos); - - doc.close(); - - bais = new ByteArrayInputStream(baos.toByteArray()); - doc = new HSSFWorkbook(bais); - - // Check - assertNotNull(doc.getSummaryInformation()); - assertNotNull(doc.getDocumentSummaryInformation()); - assertEquals("POI Testing", doc.getSummaryInformation().getAuthor()); - assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany()); - - // Asking to re-create will make no difference now - doc.createInformationProperties(); - assertNotNull(doc.getSummaryInformation()); - assertNotNull(doc.getDocumentSummaryInformation()); - assertEquals("POI Testing", doc.getSummaryInformation().getAuthor()); - assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany()); - - doc.close(); + try (HSSFWorkbook xls1 = new HSSFWorkbook()) { + // New document won't have them + assertNull(xls1.getSummaryInformation()); + assertNull(xls1.getDocumentSummaryInformation()); + + try (HSSFWorkbook xls2 = writeOutAndReadBack(xls1)) { + + assertNull(xls2.getSummaryInformation()); + assertNull(xls2.getDocumentSummaryInformation()); + + // Create, and change + xls2.createInformationProperties(); + xls2.getSummaryInformation().setAuthor("POI Testing"); + xls2.getDocumentSummaryInformation().setCompany("ASF"); + + try (HSSFWorkbook xls3 = writeOutAndReadBack(xls2)) { + // Check + assertNotNull(xls3.getSummaryInformation()); + assertNotNull(xls3.getDocumentSummaryInformation()); + assertEquals("POI Testing", xls3.getSummaryInformation().getAuthor()); + assertEquals("ASF", xls3.getDocumentSummaryInformation().getCompany()); + + // Asking to re-create will make no difference now + xls3.createInformationProperties(); + assertNotNull(xls3.getSummaryInformation()); + assertNotNull(xls3.getDocumentSummaryInformation()); + assertEquals("POI Testing", xls3.getSummaryInformation().getAuthor()); + assertEquals("ASF", xls3.getDocumentSummaryInformation().getCompany()); + } + } + } } } diff --git a/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java b/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java index a081f61c65..3130b6b9b2 100644 --- a/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java +++ b/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java @@ -17,6 +17,7 @@ package org.apache.poi.ddf; +import static org.apache.poi.ddf.EscherRecordTypes.BLIP_PICT; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -100,7 +101,7 @@ final class TestEscherBlipRecord { EscherMetafileBlip blip1 = (EscherMetafileBlip)bse1.getBlipRecord(); assertEquals(0x5430, blip1.getOptions()); - assertEquals(EscherMetafileBlip.RECORD_ID_PICT, blip1.getRecordId()); + assertEquals(BLIP_PICT.typeID, blip1.getRecordId()); assertArrayEquals(new byte[]{ 0x57, 0x32, 0x7B, (byte)0x91, 0x23, 0x5D, (byte)0xDB, 0x36, 0x7A, (byte)0xDB, (byte)0xFF, 0x17, (byte)0xFE, (byte)0xF3, (byte)0xA7, 0x05 @@ -151,11 +152,13 @@ final class TestEscherBlipRecord { byte[] data = _samples.readFile("47143.dat"); EscherBSERecord bse = new EscherBSERecord(); bse.fillFields(data, 0, new DefaultEscherRecordFactory()); - bse.toString(); //assert that toString() works + //assert that toString() works + assertNotNull(bse.toString()); assertTrue(bse.getBlipRecord() instanceof EscherMetafileBlip); EscherMetafileBlip blip = (EscherMetafileBlip)bse.getBlipRecord(); - blip.toString(); //assert that toString() works + //assert that toString() works + assertNotNull(blip.toString()); byte[] remaining = blip.getRemainingData(); assertNotNull(remaining); diff --git a/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java b/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java index 088d346bae..07c67c4c10 100644 --- a/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java +++ b/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; @@ -29,6 +28,7 @@ import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.poifs.storage.RawDataUtil; @@ -63,8 +63,8 @@ class TestEscherDump { "cT19LR+PfTgjN4CKCS5Es4LS+7nLt9hQ7ejwGQnEyxebOgJzlHjotWUACpoZsFkAgGqBeUDZAzB6h4N2MFCNhmIuFJMAgPsH" + "eJr+iZEHAAA="; - private EscherDump dumper = new EscherDump(); - private ByteArrayOutputStream baos = new ByteArrayOutputStream(); + private final EscherDump dumper = new EscherDump(); + private final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); private PrintStream stream; @BeforeEach @@ -126,7 +126,7 @@ class TestEscherDump { } private int countProperties() { - String data = new String(baos.toByteArray(), StandardCharsets.UTF_8); + String data = baos.toString(StandardCharsets.UTF_8); Matcher matcher = Pattern.compile(",? \"[^\"]+\": ").matcher(data); int count = 0; while (matcher.find()) { diff --git a/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java b/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java index 1cea118353..c3932c3b0a 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java +++ b/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java @@ -21,11 +21,12 @@ package org.apache.poi.hpsf; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.math.BigInteger; +import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.wellknown.PropertyIDMap; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.storage.RawDataUtil; @@ -51,7 +52,7 @@ class TestVariantSupport { Object hdrs = s.getProperty(PropertyIDMap.PID_HEADINGPAIR); assertNotNull(hdrs); - assertEquals(byte[].class, hdrs.getClass()); + assertSame(byte[].class, hdrs.getClass()); // parse the value Vector v = new Vector((short)Variant.VT_VARIANT); @@ -63,10 +64,10 @@ class TestVariantSupport { Object cp = items[0].getValue(); assertNotNull(cp); - assertEquals(CodePageString.class, cp.getClass()); + assertSame(CodePageString.class, cp.getClass()); Object i = items[1].getValue(); assertNotNull(i); - assertEquals(Integer.class, i.getClass()); + assertSame(Integer.class, i.getClass()); assertEquals(1, i); } @@ -91,34 +92,33 @@ class TestVariantSupport { {Variant.VT_R8, -999.99d}, }; - POIFSFileSystem poifs = new POIFSFileSystem(); - DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation(); - CustomProperties cpList = new CustomProperties(); - for (Object[] o : exp) { - int type = (Integer)o[0]; - Property p = new Property(PropertyIDMap.PID_MAX+type, type, o[1]); - cpList.put("testprop"+type, new CustomProperty(p, "testprop"+type)); + try (POIFSFileSystem poifs = new POIFSFileSystem()) { + DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation(); + CustomProperties cpList = new CustomProperties(); + for (Object[] o : exp) { + int type = (Integer) o[0]; + Property p = new Property(PropertyIDMap.PID_MAX + type, type, o[1]); + cpList.put("testprop" + type, new CustomProperty(p, "testprop" + type)); - } - dsi.setCustomProperties(cpList); - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - poifs.writeFilesystem(bos); - poifs.close(); - poifs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - dsi = (DocumentSummaryInformation)PropertySetFactory.create(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - assertNotNull(dsi); - cpList = dsi.getCustomProperties(); - int i=0; - for (Object[] o : exp) { - Object obj = cpList.get("testprop"+o[0]); - if (o[1] instanceof byte[]) { - assertArrayEquals((byte[])o[1], (byte[])obj, "property "+i); - } else { - assertEquals(o[1], obj, "property "+i); } - i++; + dsi.setCustomProperties(cpList); + dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); + + try (POIFSFileSystem poifs2 = POIDataSamples.writeOutAndReadBack(poifs)) { + DocumentSummaryInformation dsi2 = (DocumentSummaryInformation) PropertySetFactory.create(poifs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); + assertNotNull(dsi2); + CustomProperties cpList2 = dsi2.getCustomProperties(); + int i = 0; + for (Object[] o : exp) { + Object obj = cpList2.get("testprop" + o[0]); + if (o[1] instanceof byte[]) { + assertArrayEquals((byte[]) o[1], (byte[]) obj, "property " + i); + } else { + assertEquals(o[1], obj, "property " + i); + } + i++; + } + } } - poifs.close(); } } diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java index 6d95b38450..cc75abc874 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java @@ -19,6 +19,7 @@ package org.apache.poi.hpsf.basic; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; @@ -35,7 +36,6 @@ import org.apache.poi.hpsf.ClassID; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.Filetime; import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; @@ -109,8 +109,7 @@ final class TestBasic { * supported. */ @Test - void testCreatePropertySets() - throws UnsupportedEncodingException, IOException { + void testCreatePropertySets() throws IOException { Class<?>[] expected = { SummaryInformation.class, DocumentSummaryInformation.class, @@ -123,11 +122,11 @@ final class TestBasic { Object o; try { o = PropertySetFactory.create(in); - } catch (NoPropertySetStreamException | MarkUnsupportedException ex) { + } catch (NoPropertySetStreamException ex) { o = ex; } in.close(); - assertEquals(expected[i], o.getClass()); + assertSame(expected[i], o.getClass()); } } diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java index 9ef1289461..300f6f245a 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java @@ -20,6 +20,7 @@ package org.apache.poi.hpsf.basic; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import java.io.ByteArrayInputStream; import java.io.File; @@ -32,7 +33,6 @@ import java.util.List; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; @@ -101,8 +101,7 @@ final class TestEmptyProperties { * supported. */ @Test - void testCreatePropertySets() - throws UnsupportedEncodingException, IOException { + void testCreatePropertySets() throws IOException { Class<?>[] expected = { NoPropertySetStreamException.class, SummaryInformation.class, @@ -113,11 +112,11 @@ final class TestEmptyProperties { Object o; try { o = PropertySetFactory.create(in); - } catch (NoPropertySetStreamException | MarkUnsupportedException ex) { + } catch (NoPropertySetStreamException ex) { o = ex; } in.close(); - assertEquals(o.getClass(), expected[i]); + assertSame(o.getClass(), expected[i]); } } diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java index 6205713fa3..001fc2b238 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java @@ -21,17 +21,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; -import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.SummaryInformation; @@ -112,38 +110,37 @@ final class TestHPSFBugs { * reading junk */ @Test - void test54233() throws IOException, NoPropertySetStreamException, MarkUnsupportedException { - InputStream is = _samples.openResourceAsStream("TestNon4ByteBoundary.doc"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - SummaryInformation si = (SummaryInformation) - PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - DocumentSummaryInformation dsi = (DocumentSummaryInformation) - PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - // Test - assertEquals("Microsoft Word 10.0", si.getApplicationName()); - assertEquals("", si.getTitle()); - assertEquals("", si.getAuthor()); - assertEquals("Cour de Justice", dsi.getCompany()); - - - // Write out and read back, should still be valid - POIDocument doc = new HPSFPropertiesOnlyDocument(fs); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - doc = new HPSFPropertiesOnlyDocument(new POIFSFileSystem(bais)); - - // Check properties are still there - assertEquals("Microsoft Word 10.0", si.getApplicationName()); - assertEquals("", si.getTitle()); - assertEquals("", si.getAuthor()); - assertEquals("Cour de Justice", dsi.getCompany()); - - doc.close(); - fs.close(); + void test54233() throws IOException, NoPropertySetStreamException { + try (InputStream is = _samples.openResourceAsStream("TestNon4ByteBoundary.doc"); + POIFSFileSystem fs = new POIFSFileSystem(is)) { + + SummaryInformation si = (SummaryInformation) + PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); + DocumentSummaryInformation dsi = (DocumentSummaryInformation) + PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); + + // Test + assertEquals("Microsoft Word 10.0", si.getApplicationName()); + assertEquals("", si.getTitle()); + assertEquals("", si.getAuthor()); + assertEquals("Cour de Justice", dsi.getCompany()); + + + // Write out and read back, should still be valid + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + try (POIDocument doc = new HPSFPropertiesOnlyDocument(fs)) { + doc.write(baos); + } + try (POIDocument doc = new HPSFPropertiesOnlyDocument(new POIFSFileSystem(baos.toInputStream()))) { + si = doc.getSummaryInformation(); + dsi = doc.getDocumentSummaryInformation(); + // Check properties are still there + assertEquals("Microsoft Word 10.0", si.getApplicationName()); + assertEquals("", si.getTitle()); + assertEquals("", si.getAuthor()); + assertEquals("Cour de Justice", dsi.getCompany()); + } + } } /** diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java index f8fb0aad13..999d0a608b 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java @@ -23,13 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Random; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFException; @@ -44,7 +43,7 @@ import org.junit.jupiter.api.Test; /** * Basing on: src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java * This class tests reading and writing of meta data. No actual document is created. All information - * is stored in a virtual document in a ByteArrayOutputStream + * is stored in a virtual document in a UnsynchronizedByteArrayOutputStream */ final class TestMetaDataIPI { @@ -520,7 +519,7 @@ final class TestMetaDataIPI { /** - * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream. + * Closes the UnsynchronizedByteArrayOutputStream and reads it into a ByteArrayInputStream. * When finished writing information this method is used in the tests to * start reading from the created document and then the see if the results match. */ @@ -528,13 +527,13 @@ final class TestMetaDataIPI { dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - ByteArrayOutputStream bout = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream(); poifs.writeFilesystem(bout); poifs.close(); - InputStream is = new ByteArrayInputStream(bout.toByteArray()); - poifs = new POIFSFileSystem(is); - is.close(); + try (InputStream is = bout.toInputStream()) { + poifs = new POIFSFileSystem(is); + } /* Read the document summary information. */ DirectoryEntry dir = poifs.getRoot(); diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java index 13eb537fe2..057e16ae87 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,12 +30,12 @@ import java.util.Map; import java.util.Objects; import java.util.stream.Stream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.CustomProperty; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; @@ -70,7 +69,7 @@ class TestReadAllFiles { */ @ParameterizedTest @MethodSource("files") - void read(File file) throws IOException, NoPropertySetStreamException, MarkUnsupportedException { + void read(File file) throws IOException, NoPropertySetStreamException { /* Read the POI filesystem's property set streams: */ for (POIFile pf : Util.readPropertySets(file)) { try (InputStream in = new ByteArrayInputStream(pf.getBytes())) { @@ -84,7 +83,7 @@ class TestReadAllFiles { /** * This test method does a write and read back test with all POI * filesystems in the "data" directory by performing the following - * actions for each file:<p> + * actions for each file: * * <ul> * <li>Read its property set streams. @@ -102,35 +101,35 @@ class TestReadAllFiles { /* Create a new POI filesystem containing the origin file's * property set streams: */ - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - for (POIFile poifile : Util.readPropertySets(file)) { - final InputStream in = new ByteArrayInputStream(poifile.getBytes()); - final PropertySet psIn = PropertySetFactory.create(in); - psMap.put(poifile.getName(), psIn); - bos.reset(); - psIn.write(bos); - poiFs.createDocument(new ByteArrayInputStream(bos.toByteArray()), poifile.getName()); - } + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + try (POIFSFileSystem poiFs = new POIFSFileSystem()) { + for (POIFile poifile : Util.readPropertySets(file)) { + final InputStream in = new ByteArrayInputStream(poifile.getBytes()); + final PropertySet psIn = PropertySetFactory.create(in); + psMap.put(poifile.getName(), psIn); + bos.reset(); + psIn.write(bos); + poiFs.createDocument(bos.toInputStream(), poifile.getName()); + } - /* Read the property set streams from the POI filesystem just - * created. */ - for (Map.Entry<String,PropertySet> me : psMap.entrySet()) { - final PropertySet ps1 = me.getValue(); - final PropertySet ps2 = PropertySetFactory.create(poiFs.getRoot(), me.getKey()); - assertNotNull(ps2); + /* Read the property set streams from the POI filesystem just + * created. */ + for (Map.Entry<String, PropertySet> me : psMap.entrySet()) { + final PropertySet ps1 = me.getValue(); + final PropertySet ps2 = PropertySetFactory.create(poiFs.getRoot(), me.getKey()); + assertNotNull(ps2); - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ + /* Compare the property set stream with the corresponding one + * from the origin file and check whether they are equal. */ - // Because of missing 0-paddings in the original input files, the bytes might differ. - // This fixes the comparison - String ps1str = ps1.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)",""); - String ps2str = ps2.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)",""); + // Because of missing 0-paddings in the original input files, the bytes might differ. + // This fixes the comparison + String ps1str = ps1.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)", ""); + String ps2str = ps2.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)", ""); - assertEquals(ps1str, ps2str, "Equality for file " + file.getName()); + assertEquals(ps1str, ps2str, "Equality for file " + file.getName()); + } } - poiFs.close(); } /** diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java index 85ae090206..7d1df36fb8 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java @@ -26,10 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -44,6 +42,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.ClassID; import org.apache.poi.hpsf.ClassIDPredefined; @@ -118,9 +117,9 @@ class TestWrite { /* Write it to a POIFS and the latter to disk: */ try (OutputStream out = new FileOutputStream(filename); POIFSFileSystem poiFs = new POIFSFileSystem(); - ByteArrayOutputStream psStream = new ByteArrayOutputStream()) { + UnsynchronizedByteArrayOutputStream psStream = new UnsynchronizedByteArrayOutputStream()) { assertThrows(NoFormatIDException.class, () -> ps.write(psStream)); - poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME); + poiFs.createDocument(psStream.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); poiFs.writeFilesystem(out); } } @@ -142,12 +141,12 @@ class TestWrite { /* Create a mutable property set and write it to a POIFS: */ try (OutputStream out = new FileOutputStream(filename); POIFSFileSystem poiFs = new POIFSFileSystem(); - ByteArrayOutputStream psStream = new ByteArrayOutputStream()) { + UnsynchronizedByteArrayOutputStream psStream = new UnsynchronizedByteArrayOutputStream()) { final PropertySet ps = new PropertySet(); final Section s = ps.getSections().get(0); s.setFormatID(SummaryInformation.FORMAT_ID); ps.write(psStream); - poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME); + poiFs.createDocument(psStream.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); poiFs.writeFilesystem(out); } @@ -254,9 +253,8 @@ class TestWrite { /* Read the POIFS: */ final PropertySet[] psa = new PropertySet[1]; final POIFSReader r = new POIFSReader(); - final POIFSReaderListener listener = (event) -> { + final POIFSReaderListener listener = (event) -> assertDoesNotThrow(() -> psa[0] = PropertySetFactory.create(event.getStream())); - }; r.registerListener(listener,STREAM_NAME); r.read(filename); @@ -357,9 +355,8 @@ class TestWrite { p.setValue(TITLE); ms.setProperty(p); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); mps.write(out); - out.close(); byte[] bytes = out.toByteArray(); PropertySet psr = new PropertySet(bytes); @@ -388,9 +385,8 @@ class TestWrite { private void check(final long variantType, final Object value, final int codepage) throws UnsupportedVariantTypeException, IOException { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); VariantSupport.write(out, variantType, value, codepage); - out.close(); final byte[] b = out.toByteArray(); final Object objRead = VariantSupport.read(b, 0, b.length + LittleEndianConsts.INT_SIZE, variantType, codepage); @@ -402,7 +398,7 @@ class TestWrite { } /** - * <p>Tests writing and reading back a proper dictionary.</p> + * Tests writing and reading back a proper dictionary. */ @Test void dictionary() throws IOException, HPSFException { @@ -410,37 +406,36 @@ class TestWrite { copy.deleteOnExit(); /* Write: */ - final OutputStream out = new FileOutputStream(copy); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final PropertySet ps1 = new PropertySet(); - final Section s = ps1.getSections().get(0); - final Map<Long,String> m = new HashMap<>(3, 1.0f); - m.put(1L, "String 1"); - m.put(2L, "String 2"); - m.put(3L, "String 3"); - s.setDictionary(m); - s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]); - int codepage = CodePageUtil.CP_UNICODE; - s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage); - poiFs.createDocument(ps1.toInputStream(), "Test"); - poiFs.writeFilesystem(out); - poiFs.close(); - out.close(); - - /* Read back: */ - final List<POIFile> psf = Util.readPropertySets(copy); - assertEquals(1, psf.size()); - final byte[] bytes = psf.get(0).getBytes(); - final InputStream in = new ByteArrayInputStream(bytes); - final PropertySet ps2 = PropertySetFactory.create(in); - - /* Check if the result is a DocumentSummaryInformation stream, as - * specified. */ - assertTrue(ps2.isDocumentSummaryInformation()); - - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ - assertEquals(ps1, ps2); + try (OutputStream out = new FileOutputStream(copy); + POIFSFileSystem poiFs = new POIFSFileSystem()) { + final PropertySet ps1 = new PropertySet(); + final Section s = ps1.getSections().get(0); + final Map<Long, String> m = new HashMap<>(3, 1.0f); + m.put(1L, "String 1"); + m.put(2L, "String 2"); + m.put(3L, "String 3"); + s.setDictionary(m); + s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]); + int codepage = CodePageUtil.CP_UNICODE; + s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage); + poiFs.createDocument(ps1.toInputStream(), "Test"); + poiFs.writeFilesystem(out); + + /* Read back: */ + final List<POIFile> psf = Util.readPropertySets(copy); + assertEquals(1, psf.size()); + final byte[] bytes = psf.get(0).getBytes(); + final InputStream in = new ByteArrayInputStream(bytes); + final PropertySet ps2 = PropertySetFactory.create(in); + + /* Check if the result is a DocumentSummaryInformation stream, as + * specified. */ + assertTrue(ps2.isDocumentSummaryInformation()); + + /* Compare the property set stream with the corresponding one + * from the origin file and check whether they are equal. */ + assertEquals(ps1, ps2); + } } /** @@ -543,9 +538,9 @@ class TestWrite { doufStream.close(); // And also write to some bytes for checking - ByteArrayOutputStream sinfBytes = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream sinfBytes = new UnsynchronizedByteArrayOutputStream(); sinf.write(sinfBytes); - ByteArrayOutputStream dinfBytes = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream dinfBytes = new UnsynchronizedByteArrayOutputStream(); dinf.write(dinfBytes); @@ -656,7 +651,7 @@ class TestWrite { * codepage. (HPSF writes Unicode dictionaries only.) */ @Test - void dictionaryWithInvalidCodepage() throws IOException, HPSFException { + void dictionaryWithInvalidCodepage() throws IOException { final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); copy.deleteOnExit(); @@ -696,8 +691,8 @@ class TestWrite { * method checks whether the application is runing in an environment * where the default character set is 16-bit-capable.</p> * - * @return <code>true</code> if the default character set is 16-bit-capable, - * else <code>false</code>. + * @return {@code true} if the default character set is 16-bit-capable, + * else {@code false}. */ private boolean hasProperDefaultCharset() { final String charSetName = System.getProperty("file.encoding"); diff --git a/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java b/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java index 3835802725..fbef50b6af 100644 --- a/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java +++ b/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java @@ -17,12 +17,11 @@ package org.apache.poi.hssf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -56,11 +55,11 @@ public final class HSSFTestDataSamples { * Useful for verifying that the serialisation round trip */ public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSSFWorkbook(bais); + try (InputStream is = baos.toInputStream()) { + return new HSSFWorkbook(is); + } } catch (IOException e) { throw new RuntimeException(e); } diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java index 0f346f50ee..a957f67557 100644 --- a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java +++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java @@ -16,6 +16,8 @@ ==================================================================== */ package org.apache.poi.hssf.dev; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; + import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -23,7 +25,6 @@ import java.util.Map; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullOutputStream; class TestBiffDrawingToXml extends BaseTestIteratingXLS { @@ -44,7 +45,7 @@ class TestBiffDrawingToXml extends BaseTestIteratingXLS { @Override void runOneFile(File pFile) throws Exception { try (InputStream wb = new FileInputStream(pFile)) { - BiffDrawingToXml.writeToFile(new NullOutputStream(), wb, false, new String[0]); + BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[0]); } } } diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java index 0a99128a76..790ca14b58 100644 --- a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java +++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java @@ -16,6 +16,8 @@ ==================================================================== */ package org.apache.poi.hssf.dev; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -25,7 +27,6 @@ import java.util.Map; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NullOutputStream; import org.apache.poi.util.RecordFormatException; class TestBiffViewer extends BaseTestIteratingXLS { @@ -54,7 +55,7 @@ class TestBiffViewer extends BaseTestIteratingXLS { try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true); InputStream is = BiffViewer.getPOIFSInputStream(fs)) { // use a NullOutputStream to not write the bytes anywhere for best runtime - PrintWriter dummy = new PrintWriter(new OutputStreamWriter(new NullOutputStream(), LocaleUtil.CHARSET_1252)); + PrintWriter dummy = new PrintWriter(new OutputStreamWriter(NULL_OUTPUT_STREAM, LocaleUtil.CHARSET_1252)); BiffViewer.runBiffViewer(dummy, is, true, true, true, false); } } diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java index 9f072b37b3..79f8e7f426 100644 --- a/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java +++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java @@ -23,7 +23,7 @@ import java.util.Map; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.Resources; @@ -32,13 +32,16 @@ class TestEFBiffViewer extends BaseTestIteratingXLS { @Override protected Map<String, Class<? extends Throwable>> getExcludes() { Map<String, Class<? extends Throwable>> excludes = super.getExcludes(); - excludes.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header + // unsupported crypto api header + excludes.put("35897-type4.xls", EncryptedDocumentException.class); excludes.put("51832.xls", EncryptedDocumentException.class); excludes.put("xor-encryption-abc.xls", EncryptedDocumentException.class); excludes.put("password.xls", EncryptedDocumentException.class); - excludes.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well + // HSSFWorkbook cannot open it as well + excludes.put("43493.xls", RecordInputStream.LeftoverDataException.class); excludes.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - // EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" + // "Buffer overrun" + excludes.put("XRefCalc.xls", RuntimeException.class); return excludes; } diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java index df2247b22c..4f5a7295ac 100644 --- a/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java +++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java @@ -24,7 +24,7 @@ import java.util.Map; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.Resources; diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java index 1d890ef4a6..f5e3644acd 100644 --- a/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java +++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java @@ -25,7 +25,7 @@ import java.util.Map; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Isolated; diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java index 6087dab647..003f43896a 100644 --- a/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java +++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java @@ -20,7 +20,7 @@ import java.io.File; import java.io.IOException; import java.io.PrintStream; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.Resources; diff --git a/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java b/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java index 8bb1b6771c..990221b6d2 100644 --- a/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java +++ b/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java @@ -20,10 +20,10 @@ package org.apache.poi.hssf.eventmodel; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; @@ -31,6 +31,7 @@ import java.util.Iterator; import java.util.stream.Stream; import org.apache.commons.collections4.IteratorUtils; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.ContinueRecord; import org.apache.poi.hssf.record.EOFRecord; @@ -130,16 +131,15 @@ final class TestEventRecordFactory { * OBJECTIVE: Test that the RecordFactory given an InputStream * constructs the expected records.<P> * SUCCESS: Record factory creates the expected records.<P> - * FAILURE: The wrong records are created or contain the wrong values <P> - * + * FAILURE: The wrong records are created or contain the wrong values */ @Test void testContinuedUnknownRecord() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); for (byte[] b : CONTINUE_DATA) { bos.write(b); } - continueHelper(new ByteArrayInputStream(bos.toByteArray())); + continueHelper(bos.toInputStream()); } @Test @@ -156,7 +156,7 @@ final class TestEventRecordFactory { Iterator<byte[]> expectedData = Stream.of(CONTINUE_DATA).iterator(); ERFListener listener = rec -> { - assertEquals(expectedType.next(), rec.getClass()); + assertSame(expectedType.next(), rec.getClass()); assertArrayEquals(expectedData.next(), rec.serialize()); return true; }; diff --git a/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java b/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java index 7dbabe14b1..c9438fd990 100644 --- a/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java +++ b/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java @@ -23,15 +23,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; +import java.nio.charset.StandardCharsets; import java.security.Permission; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EmptyFileException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.POIDataSamples; @@ -39,7 +40,7 @@ import org.apache.poi.extractor.POITextExtractor; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.poifs.filesystem.OfficeXmlFileException; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.util.RecordFormatException; import org.junit.jupiter.api.Test; @@ -321,12 +322,11 @@ final class TestOldExcelExtractor { void testMain() throws IOException { File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); PrintStream save = System.out; - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintStream str = new PrintStream(out, false, "UTF-8"); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + PrintStream str = new PrintStream(out, false, StandardCharsets.UTF_8.displayName())) { System.setOut(str); OldExcelExtractor.main(new String[] {file.getAbsolutePath()}); - String string = out.toString("UTF-8"); + String string = out.toString(StandardCharsets.UTF_8); assertTrue(string.contains("Table C-13--Lemons"), "Had: " + string); } finally { System.setOut(save); diff --git a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java index 18138de8ed..59c9eba317 100644 --- a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java +++ b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -33,6 +32,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherDggRecord; @@ -113,7 +113,7 @@ class TestDrawingAggregate { * @return the raw data being aggregated */ byte[] getRawBytes(){ - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); for (RecordBase rb : aggRecords) { Record r = (org.apache.poi.hssf.record.Record) rb; try { @@ -216,7 +216,7 @@ class TestDrawingAggregate { assertEquals(dgBytes.length, pos, "data was not fully read"); // serialize to byte array - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); for(EscherRecord r : records) { out.write(r.serialize()); } @@ -242,7 +242,7 @@ class TestDrawingAggregate { } private static byte[] toByteArray(List<RecordBase> records) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); for (RecordBase rb : records) { Record r = (org.apache.poi.hssf.record.Record) rb; try { diff --git a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java index 22cd1ee11c..1618e03791 100644 --- a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java +++ b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java @@ -469,152 +469,152 @@ class TestDrawingShapes { @Test void testRemoveShapes() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); + try (HSSFWorkbook wb1 = new HSSFWorkbook()) { + HSSFSheet sheet1 = wb1.createSheet(); + HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch(); - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); + HSSFSimpleShape rectangle = patriarch1.createSimpleShape(new HSSFClientAnchor()); + rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - int idx = wb1.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG); - patriarch.createPicture(new HSSFClientAnchor(), idx); + int idx = wb1.addPicture(new byte[]{1, 2, 3}, Workbook.PICTURE_TYPE_JPEG); + patriarch1.createPicture(new HSSFClientAnchor(), idx); - patriarch.createCellComment(new HSSFClientAnchor()); + patriarch1.createCellComment(new HSSFClientAnchor()); - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPoints(new int[]{1,2}, new int[]{2,3}); + HSSFPolygon polygon1 = patriarch1.createPolygon(new HSSFClientAnchor()); + polygon1.setPoints(new int[]{1, 2}, new int[]{2, 3}); - patriarch.createTextbox(new HSSFClientAnchor()); + patriarch1.createTextbox(new HSSFClientAnchor()); - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - group.createTextbox(new HSSFChildAnchor()); - group.createPicture(new HSSFChildAnchor(), idx); + HSSFShapeGroup group1 = patriarch1.createGroup(new HSSFClientAnchor()); + group1.createTextbox(new HSSFChildAnchor()); + group1.createPicture(new HSSFChildAnchor(), idx); - assertEquals(patriarch.getChildren().size(), 6); - assertEquals(group.getChildren().size(), 2); + assertEquals(patriarch1.getChildren().size(), 6); + assertEquals(group1.getChildren().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch1).getShapeToObjMapping().size(), 12); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch1).getTailRecords().size(), 1); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { + HSSFSheet sheet2 = wb2.getSheetAt(0); + HSSFPatriarch patriarch2 = sheet2.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getShapeToObjMapping().size(), 12); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 6); + assertEquals(patriarch2.getChildren().size(), 6); - group = (HSSFShapeGroup) patriarch.getChildren().get(5); - group.removeShape(group.getChildren().get(0)); + HSSFShapeGroup group2 = (HSSFShapeGroup) patriarch2.getChildren().get(5); + group2.removeShape(group2.getChildren().get(0)); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getShapeToObjMapping().size(), 10); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getTailRecords().size(), 1); - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) { + HSSFSheet sheet3 = wb3.getSheetAt(0); + HSSFPatriarch patriarch3 = sheet3.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getShapeToObjMapping().size(), 10); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getTailRecords().size(), 1); - group = (HSSFShapeGroup) patriarch.getChildren().get(5); - patriarch.removeShape(group); + HSSFShapeGroup group3 = (HSSFShapeGroup) patriarch3.getChildren().get(5); + patriarch3.removeShape(group3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getShapeToObjMapping().size(), 8); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getTailRecords().size(), 1); - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - sheet = wb4.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3)) { + HSSFSheet sheet4 = wb4.getSheetAt(0); + HSSFPatriarch patriarch4 = sheet4.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 5); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getShapeToObjMapping().size(), 8); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getTailRecords().size(), 1); + assertEquals(patriarch4.getChildren().size(), 5); - HSSFShape shape = patriarch.getChildren().get(0); - patriarch.removeShape(shape); + HSSFShape shape4 = patriarch4.getChildren().get(0); + patriarch4.removeShape(shape4); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 4); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getShapeToObjMapping().size(), 6); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getTailRecords().size(), 1); + assertEquals(patriarch4.getChildren().size(), 4); - HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4); - wb4.close(); - sheet = wb5.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4)) { + HSSFSheet sheet5 = wb5.getSheetAt(0); + HSSFPatriarch patriarch5 = sheet5.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 4); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getShapeToObjMapping().size(), 6); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getTailRecords().size(), 1); + assertEquals(patriarch5.getChildren().size(), 4); - HSSFPicture picture = (HSSFPicture) patriarch.getChildren().get(0); - patriarch.removeShape(picture); + HSSFPicture picture5 = (HSSFPicture) patriarch5.getChildren().get(0); + patriarch5.removeShape(picture5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getShapeToObjMapping().size(), 5); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getTailRecords().size(), 1); + assertEquals(patriarch5.getChildren().size(), 3); - HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5); - wb5.close(); - sheet = wb6.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5)) { + HSSFSheet sheet6 = wb6.getSheetAt(0); + HSSFPatriarch patriarch6 = sheet6.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getShapeToObjMapping().size(), 5); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getTailRecords().size(), 1); + assertEquals(patriarch6.getChildren().size(), 3); - HSSFComment comment = (HSSFComment) patriarch.getChildren().get(0); - patriarch.removeShape(comment); + HSSFComment comment6 = (HSSFComment) patriarch6.getChildren().get(0); + patriarch6.removeShape(comment6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 2); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getShapeToObjMapping().size(), 3); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getTailRecords().size(), 0); + assertEquals(patriarch6.getChildren().size(), 2); - HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6); - wb6.close(); - sheet = wb7.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6)) { + HSSFSheet sheet7 = wb7.getSheetAt(0); + HSSFPatriarch patriarch7 = sheet7.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 2); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getShapeToObjMapping().size(), 3); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getTailRecords().size(), 0); + assertEquals(patriarch7.getChildren().size(), 2); - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - patriarch.removeShape(polygon); + HSSFPolygon polygon7 = (HSSFPolygon) patriarch7.getChildren().get(0); + patriarch7.removeShape(polygon7); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getShapeToObjMapping().size(), 2); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getTailRecords().size(), 0); + assertEquals(patriarch7.getChildren().size(), 1); - HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7); - wb7.close(); - sheet = wb8.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7)) { + HSSFSheet sheet8 = wb8.getSheetAt(0); + HSSFPatriarch patriarch8 = sheet8.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 1); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getShapeToObjMapping().size(), 2); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getTailRecords().size(), 0); + assertEquals(patriarch8.getChildren().size(), 1); - HSSFTextbox textbox = (HSSFTextbox) patriarch.getChildren().get(0); - patriarch.removeShape(textbox); + HSSFTextbox textbox8 = (HSSFTextbox) patriarch8.getChildren().get(0); + patriarch8.removeShape(textbox8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getShapeToObjMapping().size(), 0); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getTailRecords().size(), 0); + assertEquals(patriarch8.getChildren().size(), 0); - HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8); - wb8.close(); - sheet = wb9.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); + try (HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8)) { + HSSFSheet sheet9 = wb9.getSheetAt(0); + HSSFPatriarch patriarch9 = sheet9.getDrawingPatriarch(); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - wb9.close(); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch9).getShapeToObjMapping().size(), 0); + assertEquals(HSSFTestHelper.getEscherAggregate(patriarch9).getTailRecords().size(), 0); + assertEquals(patriarch9.getChildren().size(), 0); + } + } + } + } + } + } + } + } + } } @Test diff --git a/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java b/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java index efd3f5feff..69566e59f5 100644 --- a/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java +++ b/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java @@ -17,20 +17,16 @@ package org.apache.poi.hssf.model; -import static org.apache.poi.ddf.DefaultEscherRecordFactory.isContainer; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; -import java.util.Random; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherTextboxRecord; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.EscherAggregate; import org.apache.poi.hssf.record.Record; @@ -43,7 +39,7 @@ import org.junit.jupiter.api.Test; class TestEscherRecordFactory { private static byte[] toByteArray(List<RecordBase> records) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); for (RecordBase rb : records) { Record r = (org.apache.poi.hssf.record.Record) rb; try { @@ -56,31 +52,6 @@ class TestEscherRecordFactory { } @Test - void testDetectContainer() { - Random rnd = new Random(); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.DG_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.SOLVER_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.SP_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.DGG_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.BSTORE_CONTAINER)); - assertTrue(isContainer((short) 0x0, EscherContainerRecord.SPGR_CONTAINER)); - - for (short i=EscherContainerRecord.DGG_CONTAINER; i<= EscherContainerRecord.SOLVER_CONTAINER; i++){ - assertTrue(isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i)); - } - - assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER + 1).shortValue())); - - assertTrue(isContainer((short) 0x000F, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertTrue(isContainer((short) 0xFFFF, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0x000C, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0xCCCC, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue())); - assertFalse(isContainer((short) 0x000F, EscherTextboxRecord.RECORD_ID)); - assertFalse(isContainer((short) 0xCCCC, EscherTextboxRecord.RECORD_ID)); - } - - @Test void testDgContainerMustBeRootOfHSSFSheetEscherRecords() { HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47251.xls"); HSSFSheet sh = wb.getSheetAt(0); diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java index c6ea64d6b6..466f596650 100644 --- a/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java +++ b/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java @@ -24,10 +24,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LittleEndianOutputStream; import org.junit.jupiter.api.Test; @@ -209,7 +209,7 @@ class TestDConRefRecord { private void testReadWrite(byte[] data, String message) throws IOException { RecordInputStream is = TestcaseRecordInputStream.create(81, data); DConRefRecord d = new DConRefRecord(is); - ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(data.length); LittleEndianOutputStream o = new LittleEndianOutputStream(bos); d.serialize(o); o.flush(); diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java index bac766e08a..d519393c8c 100644 --- a/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java +++ b/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java @@ -21,12 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; final class TestDrawingRecord { @@ -39,7 +38,7 @@ final class TestDrawingRecord { void testReadContinued() throws IOException { //simulate a continues drawing record - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); //main part DrawingRecord dg = new DrawingRecord(); byte[] data1 = new byte[8224]; @@ -53,7 +52,7 @@ final class TestDrawingRecord { ContinueRecord cn = new ContinueRecord(data2); out.write(cn.serialize()); - List<org.apache.poi.hssf.record.Record> rec = RecordFactory.createRecords(new ByteArrayInputStream(out.toByteArray())); + List<org.apache.poi.hssf.record.Record> rec = RecordFactory.createRecords(out.toInputStream()); assertEquals(2, rec.size()); assertTrue(rec.get(0) instanceof DrawingRecord); assertTrue(rec.get(1) instanceof ContinueRecord); diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java index afd988fb37..005d03d6ef 100644 --- a/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java +++ b/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java @@ -25,9 +25,9 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ss.formula.ptg.AreaPtg; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.HexRead; @@ -166,7 +166,7 @@ final class TestLbsDataSubRecord { try (LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data))) { LbsDataSubRecord.LbsDropData lbs = new LbsDataSubRecord.LbsDropData(in); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) { lbs.serialize(out); diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java b/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java index 11f66367e1..01dee7e08e 100644 --- a/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java +++ b/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java @@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.HexRead; import org.junit.jupiter.api.Test; @@ -185,7 +185,7 @@ final class TestRecordFactory { assertTrue(records.get(4) instanceof ObjRecord); //serialize and verify that the serialized data is the same as the original - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); for(org.apache.poi.hssf.record.Record rec : records){ out.write(rec.serialize()); } @@ -204,7 +204,7 @@ final class TestRecordFactory { BOFRecord.createSheetBOF(), EOFRecord.instance, }; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); for (org.apache.poi.hssf.record.Record rec : recs) { try { baos.write(rec.serialize()); @@ -222,13 +222,13 @@ final class TestRecordFactory { } - POIFSFileSystem fs = new POIFSFileSystem(); - fs.createDocument(new ByteArrayInputStream(baos.toByteArray()), "dummy"); - InputStream is = fs.getRoot().createDocumentInputStream("dummy"); + try (POIFSFileSystem fs = new POIFSFileSystem()) { + fs.createDocument(baos.toInputStream(), "dummy"); + InputStream is = fs.getRoot().createDocumentInputStream("dummy"); - List<org.apache.poi.hssf.record.Record> outRecs = RecordFactory.createRecords(is); - // Buffer underrun - requested 512 bytes but 192 was available - assertEquals(5, outRecs.size()); - fs.close(); + List<org.apache.poi.hssf.record.Record> outRecs = RecordFactory.createRecords(is); + // Buffer underrun - requested 512 bytes but 192 was available + assertEquals(5, outRecs.size()); + } } } diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java index b2206b86b7..eed605b661 100644 --- a/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java +++ b/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java @@ -24,13 +24,13 @@ import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Iterator; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.common.UnicodeString; import org.apache.poi.hssf.usermodel.HSSFSheet; @@ -49,7 +49,7 @@ final class TestSSTRecord { */ private static byte[] concatHexDumps(String... hexDumpFileNames) throws IOException { int nFiles = hexDumpFileNames.length; - ByteArrayOutputStream baos = new ByteArrayOutputStream(nFiles * 8228); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(nFiles * 8228); for (String sampleFileName : hexDumpFileNames) { try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName)) { BufferedReader br = new BufferedReader(new InputStreamReader(is, LocaleUtil.CHARSET_1252)); diff --git a/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java b/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java index 35f84590f7..57b344bd25 100644 --- a/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java +++ b/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java @@ -21,10 +21,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.record.ContinueRecord; import org.apache.poi.hssf.record.RecordInputStream; import org.apache.poi.hssf.record.SSTRecord; @@ -36,11 +36,11 @@ import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; import org.apache.poi.util.LittleEndianConsts; import org.apache.poi.util.LittleEndianInput; import org.apache.poi.util.LittleEndianInputStream; import org.apache.poi.util.LittleEndianOutputStream; +import org.apache.poi.util.LittleEndianByteArrayOutputStream; import org.apache.poi.util.StringUtil; import org.junit.jupiter.api.Test; @@ -185,7 +185,7 @@ final class TestUnicodeString { assertEquals(4, fr.getCharacterPos()); assertEquals(0x15c, fr.getFontIndex()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); LittleEndianOutputStream out = new LittleEndianOutputStream(baos); fr.serialize(out); @@ -216,7 +216,7 @@ final class TestUnicodeString { assertEquals(0, ext.getPhRuns().length); assertEquals(10, ext.getDataSize()); // Excludes 4 byte header - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); LittleEndianOutputStream out = new LittleEndianOutputStream(baos); ContinuableRecordOutput cout = new ContinuableRecordOutput(out, 0xffff); diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java index b30f9f71ec..10cad91c66 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URL; @@ -46,6 +45,7 @@ import java.util.stream.IntStream; import javax.imageio.ImageIO; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hssf.HSSFITestDataProvider; @@ -1175,9 +1175,9 @@ final class TestBugs extends BaseTestBugzillaIssues { @Test void bug32191() throws IOException { try (HSSFWorkbook wb = openSampleWorkbook("27394.xls"); - ByteArrayOutputStream out1 = new ByteArrayOutputStream(); - ByteArrayOutputStream out2 = new ByteArrayOutputStream(); - ByteArrayOutputStream out3 = new ByteArrayOutputStream()) { + UnsynchronizedByteArrayOutputStream out1 = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out2 = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out3 = new UnsynchronizedByteArrayOutputStream()) { wb.write(out1); wb.write(out2); wb.write(out3); @@ -2220,7 +2220,7 @@ final class TestBugs extends BaseTestBugzillaIssues { /** * Read, write, read for formulas point to cells in other files. - * See {@link #bug46670()} for the main test, this just + * See bug46670() for the main test, this just * covers reading an existing file and checking it. * * See base-test-class for some related tests that still fail @@ -2331,7 +2331,7 @@ final class TestBugs extends BaseTestBugzillaIssues { } // Convert BufferedImage to byte[] - ByteArrayOutputStream imageBAOS = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream imageBAOS = new UnsynchronizedByteArrayOutputStream(); ImageIO.write(bimage, "jpeg", imageBAOS); imageBAOS.flush(); byte[] imageBytes = imageBAOS.toByteArray(); @@ -2552,7 +2552,7 @@ final class TestBugs extends BaseTestBugzillaIssues { "46904.xls, org.apache.poi.hssf.OldExcelFormatException, The supplied spreadsheet seems to be Excel", "51832.xls, org.apache.poi.EncryptedDocumentException, Default password is invalid for salt/verifier/verifierHash" }) - void simpleTest(String fileName, String exClazz, String exMessage) throws IOException, ClassNotFoundException { + void simpleTest(String fileName, String exClazz, String exMessage) throws ClassNotFoundException { Class<? extends Exception> ex = (Class<? extends Exception>)Class.forName(exClazz); Exception e = assertThrows(ex, () -> simpleTest(fileName, null)); assertTrue(e.getMessage().startsWith(exMessage)); diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java index 777e436e32..36c61a08d8 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java @@ -24,13 +24,13 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.hssf.record.DVRecord; @@ -61,7 +61,7 @@ final class TestDataValidation extends BaseTestDataValidation { void assertDataValidation(Workbook wb) { byte[] generatedContent; - try (ByteArrayOutputStream baos = new ByteArrayOutputStream(22000)) { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(22000)) { wb.write(baos); generatedContent = baos.toByteArray(); } catch (IOException e) { @@ -133,7 +133,7 @@ final class TestDataValidation extends BaseTestDataValidation { sheet.addValidationData(dv); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); wb.write(baos); byte[] wbData = baos.toByteArray(); diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java index 3ddac1b794..3b12a4dd32 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java @@ -17,6 +17,7 @@ package org.apache.poi.hssf.usermodel; +import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -24,8 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.jupiter.api.AfterEach; @@ -46,7 +45,7 @@ final class TestEscherGraphics { private EscherGraphics graphics; @BeforeEach - void setUp() throws IOException { + void setUp() { workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("test"); @@ -82,7 +81,7 @@ final class TestEscherGraphics { @Test void testSetFont() { - Font f = new Font("Helvetica", 0, 12); + Font f = new Font("Helvetica", Font.PLAIN, 12); graphics.setFont(f); assertEquals(f, graphics.getFont()); } @@ -112,18 +111,15 @@ final class TestEscherGraphics { } @Test - void testGetDataBackAgain() throws Exception { + void testGetDataBackAgain() { HSSFSheet s; HSSFShapeGroup s1; HSSFShapeGroup s2; patriarch.setCoordinates(10, 20, 30, 40); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - + workbook = writeOutAndReadBack(workbook); + s = workbook.getSheetAt(0); patriarch = s.getDrawingPatriarch(); assertNotNull(patriarch); @@ -160,11 +156,9 @@ final class TestEscherGraphics { // Write and re-load once more, to check that's ok - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - patriarch = s.getDrawingPatriarch(); + workbook = writeOutAndReadBack(workbook); + s = workbook.getSheetAt(0); + patriarch = s.getDrawingPatriarch(); assertNotNull(patriarch); assertEquals(10, patriarch.getX1()); @@ -202,11 +196,9 @@ final class TestEscherGraphics { // but not of their anchors s1.setCoordinates(2, 3, 1021, 242); - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - patriarch = s.getDrawingPatriarch(); + workbook = writeOutAndReadBack(workbook); + s = workbook.getSheetAt(0); + patriarch = s.getDrawingPatriarch(); assertNotNull(patriarch); assertEquals(10, patriarch.getX1()); @@ -254,12 +246,9 @@ final class TestEscherGraphics { assertEquals(3, patriarch.getChildren().size()); - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - - patriarch = s.getDrawingPatriarch(); + workbook = writeOutAndReadBack(workbook); + s = workbook.getSheetAt(0); + patriarch = s.getDrawingPatriarch(); assertNotNull(patriarch); assertEquals(10, patriarch.getX1()); diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java index b2a793f972..5e99f213f2 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java @@ -47,6 +47,7 @@ final class TestHSSFPicture extends BaseTestPicture { super(HSSFITestDataProvider.instance); } + @Override protected Picture getPictureShape(Drawing<?> pat, int picIdx) { return (Picture)((HSSFPatriarch)pat).getChildren().get(picIdx); } diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java index ac4f32cb0e..3110783837 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java @@ -28,8 +28,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -41,6 +39,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.hpsf.ClassID; @@ -72,6 +71,7 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -554,21 +554,17 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { */ @Test void bug47920() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls")); - HSSFWorkbook wb = new HSSFWorkbook(fs1); - ClassID clsid1 = fs1.getRoot().getStorageClsid(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(4096); - wb.write(out); - byte[] bytes = out.toByteArray(); - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes)); - ClassID clsid2 = fs2.getRoot().getStorageClsid(); - - assertEquals(clsid1, clsid2); - - fs2.close(); - wb.close(); - fs1.close(); + try (POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls")); + HSSFWorkbook wb = new HSSFWorkbook(fs1)) { + ClassID clsid1 = fs1.getRoot().getStorageClsid(); + + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(4096); + wb.write(out); + try (POIFSFileSystem fs2 = new POIFSFileSystem(out.toInputStream())) { + ClassID clsid2 = fs2.getRoot().getStorageClsid(); + assertEquals(clsid1, clsid2); + } + } } /** @@ -582,8 +578,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { "testEXCEL_95.xls,BIFF5" }) void helpfulExceptionOnOldFiles(String file, String format) throws Exception { - POIDataSamples xlsData = samples; - try (InputStream is = xlsData.openResourceAsStream(file)) { + try (InputStream is = samples.openResourceAsStream(file)) { OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new HSSFWorkbook(is), "Shouldn't be able to load an Excel " + format + " file"); assertContains(e.getMessage(), format); @@ -978,7 +973,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { assertNotNull(name); assertEquals("ASheet!A1", name.getRefersToFormula()); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(); wb.write(stream); assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); @@ -989,15 +984,15 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); assertEquals("ASheet!A1", name.getRefersToFormula()); - ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream stream2 = new UnsynchronizedByteArrayOutputStream(); wb.write(stream2); assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); assertEquals("ASheet!A1", name.getRefersToFormula()); - HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray())); + HSSFWorkbook wb2 = new HSSFWorkbook(stream.toInputStream()); expectName(wb2, nameName, "ASheet!A1"); - HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray())); + HSSFWorkbook wb3 = new HSSFWorkbook(stream2.toInputStream()); expectName(wb3, nameName, "ASheet!A1"); wb3.close(); wb2.close(); @@ -1078,7 +1073,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { private void writeAndCloseWorkbook(Workbook workbook, File file) throws IOException { - final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream bytesOut = new UnsynchronizedByteArrayOutputStream(); workbook.write(bytesOut); workbook.close(); @@ -1183,7 +1178,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } } - void createDrawing() throws Exception { + @Disabled + void createDrawing() { // the dimensions for this image are different than for XSSF and SXSSF } } diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java index 1183c5f6b5..60b15c8061 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java @@ -21,12 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.poifs.filesystem.DirectoryNode; @@ -60,73 +59,70 @@ final class TestOLE2Embeding { @Test void testReallyEmbedSomething() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); - byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg"); - int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); - POIFSFileSystem pptPoifs = getSamplePPT(); - int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt"); - POIFSFileSystem xlsPoifs = getSampleXLS(); - int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG); - int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls"); - int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt"); - - int rowoffset = 5; - int coloffset = 5; - - CreationHelper ch = wb1.getCreationHelper(); - HSSFClientAnchor anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(2+coloffset), 1+rowoffset, 0, 0, (short)(3+coloffset), 5+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, pptIdx, imgPPT); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(5+coloffset), 1+rowoffset, 0, 0, (short)(6+coloffset), 5+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, xlsIdx, imgIdx); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(3+coloffset), 10+rowoffset, 0, 0, (short)(5+coloffset), 11+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, txtIdx, imgIdx); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(1+coloffset), -2+rowoffset, 0, 0, (short)(7+coloffset), 14+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - HSSFSimpleShape circle = patriarch.createSimpleShape(anchor); - circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); - circle.setNoFill(true); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0); - Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - bos.reset(); - pptPoifs.writeFilesystem(bos); - assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); - - od = wb2.getAllEmbeddedObjects().get(1); - ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - bos.reset(); - xlsPoifs.writeFilesystem(bos); - assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); - - od = wb2.getAllEmbeddedObjects().get(2); - ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - assertArrayEquals(ole10.getDataBuffer(), getSampleTXT()); - - xlsPoifs.close(); - pptPoifs.close(); - wb2.close(); + try (HSSFWorkbook wb1 = new HSSFWorkbook(); + POIFSFileSystem pptPoifs = getSamplePPT(); + POIFSFileSystem xlsPoifs = getSampleXLS()) { + HSSFSheet sheet = wb1.createSheet(); + HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); + + byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); + byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg"); + int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); + + int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt"); + int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG); + int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls"); + int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt"); + + int rowoffset = 5; + int coloffset = 5; + + CreationHelper ch = wb1.getCreationHelper(); + HSSFClientAnchor anchor = (HSSFClientAnchor) ch.createClientAnchor(); + anchor.setAnchor((short) (2 + coloffset), 1 + rowoffset, 0, 0, (short) (3 + coloffset), 5 + rowoffset, 0, 0); + anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); + + patriarch.createObjectData(anchor, pptIdx, imgPPT); + + anchor = (HSSFClientAnchor) ch.createClientAnchor(); + anchor.setAnchor((short) (5 + coloffset), 1 + rowoffset, 0, 0, (short) (6 + coloffset), 5 + rowoffset, 0, 0); + anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); + + patriarch.createObjectData(anchor, xlsIdx, imgIdx); + + anchor = (HSSFClientAnchor) ch.createClientAnchor(); + anchor.setAnchor((short) (3 + coloffset), 10 + rowoffset, 0, 0, (short) (5 + coloffset), 11 + rowoffset, 0, 0); + anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); + + patriarch.createObjectData(anchor, txtIdx, imgIdx); + + anchor = (HSSFClientAnchor) ch.createClientAnchor(); + anchor.setAnchor((short) (1 + coloffset), -2 + rowoffset, 0, 0, (short) (7 + coloffset), 14 + rowoffset, 0, 0); + anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); + + HSSFSimpleShape circle = patriarch.createSimpleShape(anchor); + circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); + circle.setNoFill(true); + + try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) { + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0); + Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) od.getDirectory()); + bos.reset(); + pptPoifs.writeFilesystem(bos); + assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); + + od = wb2.getAllEmbeddedObjects().get(1); + ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) od.getDirectory()); + bos.reset(); + xlsPoifs.writeFilesystem(bos); + assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); + + od = wb2.getAllEmbeddedObjects().get(2); + ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) od.getDirectory()); + assertArrayEquals(ole10.getDataBuffer(), getSampleTXT()); + } + } } static POIFSFileSystem getSamplePPT() throws IOException { @@ -139,15 +135,15 @@ final class TestOLE2Embeding { } static POIFSFileSystem getSampleXLS() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file"); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + try (HSSFWorkbook wb = new HSSFWorkbook()) { + HSSFSheet sheet = wb.createSheet(); + sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file"); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - wb.write(bos); - wb.close(); + wb.write(bos); + } - return new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); + return new POIFSFileSystem(bos.toInputStream()); } static byte[] getSampleTXT() { diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java index 6d62955f0c..5ff7c4e5ca 100644 --- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java +++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java @@ -21,11 +21,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import org.apache.poi.hpsf.*; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySetFactory; +import org.apache.poi.hpsf.SummaryInformation; +import org.apache.poi.hpsf.WritingNotSupportedException; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.HexDump; @@ -38,12 +41,11 @@ class TestPOIFSProperties { private static final String title = "Testing POIFS properties"; @Test - void testFail() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - { // read the workbook, adjust the SummaryInformation and write the data to a byte array - POIFSFileSystem fs = openFileSystem(); - - HSSFWorkbook wb = new HSSFWorkbook(fs); + void testFail() throws IOException, NoPropertySetStreamException, WritingNotSupportedException { + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + // read the workbook, adjust the SummaryInformation and write the data to a byte array + try (POIFSFileSystem fs = openFileSystem(); + HSSFWorkbook wb = new HSSFWorkbook(fs)) { //set POIFS properties after constructing HSSFWorkbook //(a piece of code that used to work up to POI 3.0.2) @@ -51,8 +53,6 @@ class TestPOIFSProperties { //save the workbook and read the property wb.write(out); - out.close(); - wb.close(); } // process the byte array @@ -61,18 +61,16 @@ class TestPOIFSProperties { @Test void testOK() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - { // read the workbook, adjust the SummaryInformation and write the data to a byte array - POIFSFileSystem fs = openFileSystem(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + // read the workbook, adjust the SummaryInformation and write the data to a byte array + try (POIFSFileSystem fs = openFileSystem()) { //set POIFS properties before constructing HSSFWorkbook setTitle(fs); - HSSFWorkbook wb = new HSSFWorkbook(fs); - - wb.write(out); - out.close(); - wb.close(); + try (HSSFWorkbook wb = new HSSFWorkbook(fs)) { + wb.write(out); + } } // process the byte array @@ -80,13 +78,12 @@ class TestPOIFSProperties { } private POIFSFileSystem openFileSystem() throws IOException { - InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - return fs; + try (InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls")) { + return new POIFSFileSystem(is); + } } - private void setTitle(POIFSFileSystem fs) throws NoPropertySetStreamException, MarkUnsupportedException, IOException, WritingNotSupportedException { + private void setTitle(POIFSFileSystem fs) throws NoPropertySetStreamException, IOException, WritingNotSupportedException { SummaryInformation summary1 = (SummaryInformation) PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); assertNotNull(summary1); @@ -100,16 +97,15 @@ class TestPOIFSProperties { assertNotNull(summaryCheck); } - private void checkFromByteArray(byte[] bytes) throws IOException, NoPropertySetStreamException, MarkUnsupportedException { + private void checkFromByteArray(byte[] bytes) throws IOException, NoPropertySetStreamException { // on some environments in CI we see strange failures, let's verify that the size is exactly right // this can be removed again after the problem is identified assertEquals(5120, bytes.length, "Had: " + HexDump.toHex(bytes)); - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes)); - SummaryInformation summary2 = (SummaryInformation) PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertNotNull(summary2); - - assertEquals(title, summary2.getTitle()); - fs2.close(); + try (POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes))) { + SummaryInformation summary2 = (SummaryInformation) PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); + assertNotNull(summary2); + assertEquals(title, summary2.getTitle()); + } } } diff --git a/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java b/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java index 2bca550236..3250bc0307 100644 --- a/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java +++ b/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java @@ -17,12 +17,12 @@ package org.apache.poi.poifs.crypt; +import static org.apache.poi.hssf.HSSFTestDataSamples.getSampleFile; +import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -37,9 +37,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class TestXorEncryption { - - private static final HSSFTestDataSamples samples = new HSSFTestDataSamples(); - @Test void testXorEncryption() { // Xor-Password: abc @@ -56,10 +53,9 @@ class TestXorEncryption { assertThat(xorArrExp, equalTo(xorArrAct)); } - @SuppressWarnings("static-access") @Test void testUserFile() throws IOException { - File f = samples.getSampleFile("xor-encryption-abc.xls"); + File f = getSampleFile("xor-encryption-abc.xls"); Biff8EncryptionKey.setCurrentUserPassword("abc"); try (POIFSFileSystem fs = new POIFSFileSystem(f, true); HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true)) { @@ -75,16 +71,14 @@ class TestXorEncryption { @Test @Disabled("currently not supported") void encrypt() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { try (HSSFWorkbook hwb = HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")) { Biff8EncryptionKey.setCurrentUserPassword("abc"); hwb.getInternalWorkbook().getWorkbookRecordList() .add(1, new FilePassRecord(EncryptionMode.xor)); - hwb.write(bos); - } - try (HSSFWorkbook hwb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) { - assertEquals(3, hwb.getNumberOfSheets()); + try (HSSFWorkbook hwb2 = writeOutAndReadBack(hwb)) { + assertEquals(3, hwb2.getNumberOfSheets()); + } } } finally { Biff8EncryptionKey.setCurrentUserPassword(null); diff --git a/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java b/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java index 1fa1802bea..4482607e62 100644 --- a/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java +++ b/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java @@ -34,7 +34,7 @@ import org.apache.poi.poifs.filesystem.NotOLE2FileException; import org.apache.poi.poifs.filesystem.OfficeXmlFileException; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.util.TempFile; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -150,7 +150,7 @@ public class TestPOIFSDump { } @Test - void testMainNoArgs() throws Exception { + void testMainNoArgs() { SecurityManager sm = System.getSecurityManager(); try { System.setSecurityManager(new SecurityManager() { diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java index 15edc14e92..4994d5db98 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java @@ -21,14 +21,15 @@ import static org.apache.poi.poifs.common.POIFSConstants.LARGER_BIG_BLOCK_SIZE; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.stream.IntStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.property.DocumentProperty; import org.apache.poi.poifs.storage.RawDataUtil; import org.apache.poi.util.IOUtils; @@ -67,7 +68,7 @@ class TestDocument { // verify that output is correct POIFSDocument document = checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1); DocumentProperty property = document.getDocumentProperty(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(); property.writeData(stream); byte[] output = stream.toByteArray(); @@ -111,7 +112,7 @@ class TestDocument { private static byte[] checkValues(final int blockCountExp, POIFSDocument document, byte[] input) throws IOException { assertNotNull(document); assertNotNull(document.getDocumentProperty().getDocument()); - assertEquals(document, document.getDocumentProperty().getDocument()); + assertSame(document, document.getDocumentProperty().getDocument()); ByteArrayInputStream bis = new ByteArrayInputStream(input); @@ -134,7 +135,7 @@ class TestDocument { assertEquals(blockCountExp, blockCountAct); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(); try (DocumentInputStream dis = document.getFileSystem().createDocumentInputStream( document.getDocumentProperty().getName())) { IOUtils.copy(dis, stream); diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java index d2815e0254..95133ff478 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java @@ -22,10 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.IOUtils; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ final class TestDocumentOutputStream { try { for (byte b : expected) { - dstream.write((int)b); + dstream.write(b); } } catch (IOException ignored) { fail("stream exhausted too early"); @@ -115,7 +115,7 @@ final class TestDocumentOutputStream { root.createDocument("foo", expected.length, l); try (DocumentInputStream is = root.createDocumentInputStream("foo")) { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(expected.length); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(expected.length); IOUtils.copy(is, bos); assertArrayEquals(expected, bos.toByteArray()); } diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java index c594fb513d..ed08a1fa08 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java @@ -22,10 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.stream.Stream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.util.IOUtils; @@ -82,9 +82,9 @@ final class TestEmptyDocument { DirectoryEntry dir = fs.getRoot(); emptyDoc.handle(dir); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); fs.writeFilesystem(out); - assertDoesNotThrow(() -> new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()))); + assertDoesNotThrow(() -> new POIFSFileSystem(out.toInputStream())); } } @@ -92,7 +92,7 @@ final class TestEmptyDocument { void testEmptyDocumentBug11744() throws Exception { byte[] testData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); try (POIFSFileSystem fs = new POIFSFileSystem()) { fs.createDocument(new ByteArrayInputStream(new byte[0]), "Empty"); fs.createDocument(new ByteArrayInputStream(testData), "NotEmpty"); @@ -100,7 +100,7 @@ final class TestEmptyDocument { } // This line caused the error. - try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()))) { + try (POIFSFileSystem fs = new POIFSFileSystem(out.toInputStream())) { DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty"); assertEquals(0, entry.getSize(), "Expected zero size"); byte[] actualReadbackData; diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java index b85550cc15..e2abb090ab 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java @@ -24,12 +24,13 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; class TestEntryUtils { @@ -101,51 +102,52 @@ class TestEntryUtils { @Test void testAreDocumentsIdentical() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); + try (POIFSFileSystem fs = new POIFSFileSystem()) { + DirectoryEntry dirA = fs.createDirectory("DirA"); + DirectoryEntry dirB = fs.createDirectory("DirB"); - DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB)); - DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); + DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); + DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA)); + DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB)); + DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - // Names must match - assertNotEquals(entryA1.getName(), entryA1b.getName()); - assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA1b)); + // Names must match + assertNotEquals(entryA1.getName(), entryA1b.getName()); + assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA1b)); - // Contents must match - assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA2)); + // Contents must match + assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA2)); - // Parents don't matter if contents + names are the same - assertNotEquals(entryA1.getParent(), entryB1.getParent()); - assertTrue(EntryUtils.areDocumentsIdentical(entryA1, entryB1)); + // Parents don't matter if contents + names are the same + assertNotEquals(entryA1.getParent(), entryB1.getParent()); + assertTrue(EntryUtils.areDocumentsIdentical(entryA1, entryB1)); - // Can work with POIFS - ByteArrayOutputStream tmpO = new ByteArrayOutputStream(); - fs.writeFilesystem(tmpO); + // Can work with POIFS + try (UnsynchronizedByteArrayOutputStream tmpO = new UnsynchronizedByteArrayOutputStream()) { + fs.writeFilesystem(tmpO); - ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray()); - POIFSFileSystem nfs = new POIFSFileSystem(tmpI); + try (InputStream tmpI = tmpO.toInputStream(); + POIFSFileSystem nfs = new POIFSFileSystem(tmpI)) { - DirectoryEntry dN1 = (DirectoryEntry)nfs.getRoot().getEntry("DirA"); - DirectoryEntry dN2 = (DirectoryEntry)nfs.getRoot().getEntry("DirB"); - DocumentEntry eNA1 = (DocumentEntry)dN1.getEntry(entryA1.getName()); - DocumentEntry eNA2 = (DocumentEntry)dN1.getEntry(entryA2.getName()); - DocumentEntry eNB1 = (DocumentEntry)dN2.getEntry(entryB1.getName()); + DirectoryEntry dN1 = (DirectoryEntry) nfs.getRoot().getEntry("DirA"); + DirectoryEntry dN2 = (DirectoryEntry) nfs.getRoot().getEntry("DirB"); + DocumentEntry eNA1 = (DocumentEntry) dN1.getEntry(entryA1.getName()); + DocumentEntry eNA2 = (DocumentEntry) dN1.getEntry(entryA2.getName()); + DocumentEntry eNB1 = (DocumentEntry) dN2.getEntry(entryB1.getName()); - assertFalse(EntryUtils.areDocumentsIdentical(eNA1, eNA2)); - assertTrue(EntryUtils.areDocumentsIdentical(eNA1, eNB1)); + assertFalse(EntryUtils.areDocumentsIdentical(eNA1, eNA2)); + assertTrue(EntryUtils.areDocumentsIdentical(eNA1, eNB1)); - assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA1b)); - assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA2)); + assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA1b)); + assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA2)); - assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryA1)); - assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryB1)); - nfs.close(); - fs.close(); + assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryA1)); + assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryB1)); + } + } + } } @Test diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java index ef504aca69..dd52a10a58 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java @@ -20,8 +20,6 @@ package org.apache.poi.poifs.filesystem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; @@ -29,6 +27,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -141,11 +140,10 @@ final class TestFileSystemBugs { EntryUtils.copyNodes(root, dest); // Re-load - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); root.getFileSystem().writeFilesystem(baos); - POIFSFileSystem read = new POIFSFileSystem( - new ByteArrayInputStream(baos.toByteArray())); + POIFSFileSystem read = new POIFSFileSystem(baos.toInputStream()); // Check the structure matches checkSizes("/", read.getRoot(), entries); diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java index 6becf23aa1..3a3f2fa8dc 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java @@ -23,7 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,6 +30,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; @@ -62,25 +62,24 @@ class TestOle10Native { }; for (File f : files) { - POIFSFileSystem fs = new POIFSFileSystem(f, true); - List<Entry> entries = new ArrayList<>(); - findOle10(entries, fs.getRoot(), "/"); + try (POIFSFileSystem fs = new POIFSFileSystem(f, true)) { + List<Entry> entries = new ArrayList<>(); + findOle10(entries, fs.getRoot(), "/"); - for (Entry e : entries) { - ByteArrayOutputStream bosExp = new ByteArrayOutputStream(); - InputStream is = ((DirectoryNode)e.getParent()).createDocumentInputStream(e); - IOUtils.copy(is,bosExp); - is.close(); + for (Entry e : entries) { + UnsynchronizedByteArrayOutputStream bosExp = new UnsynchronizedByteArrayOutputStream(); + try (InputStream is = ((DirectoryNode) e.getParent()).createDocumentInputStream(e)) { + IOUtils.copy(is, bosExp); + } - Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)e.getParent()); + Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) e.getParent()); - ByteArrayOutputStream bosAct = new ByteArrayOutputStream(); - ole.writeOut(bosAct); + UnsynchronizedByteArrayOutputStream bosAct = new UnsynchronizedByteArrayOutputStream(); + ole.writeOut(bosAct); - assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray())); + assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray())); + } } - - fs.close(); } } diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java index c644fb1c60..db6a062872 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java @@ -23,13 +23,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.HashMap; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.Property; @@ -44,7 +44,6 @@ import org.apache.poi.util.IOUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.ValueSource; /** * Tests for the older OPOIFS-based POIFSFileSystem @@ -147,7 +146,7 @@ final class TestPOIFSFileSystem { try (POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream(file))) { // Write it into a temp output array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); fs.writeFilesystem(baos); // Check sizes @@ -186,7 +185,7 @@ final class TestPOIFSFileSystem { "BIG", new ByteArrayInputStream(hugeStream) ); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); fs.writeFilesystem(baos); byte[] fsData = baos.toByteArray(); diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java index 2a2a8122d1..430cd8e5d2 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java @@ -17,6 +17,7 @@ package org.apache.poi.poifs.filesystem; +import static org.apache.poi.POIDataSamples.writeOutAndReadBack; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; @@ -26,21 +27,28 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Collection; import java.util.Iterator; +import java.util.List; import java.util.NoSuchElementException; +import java.util.function.Function; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.DocumentSummaryInformation; +import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.hpsf.SummaryInformation; @@ -55,6 +63,9 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests {@link POIFSStream} @@ -67,26 +78,25 @@ final class TestPOIFSStream { */ @Test void testReadTinyStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // 98 is actually the last block in a two block stream... - POIFSStream stream = new POIFSStream(fs, 98); - Iterator<ByteBuffer> i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b = i.next(); - assertFalse(i.hasNext()); - - // Check the contents - assertEquals((byte) 0x81, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x82, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - assertEquals((byte) 0x00, b.get()); - - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) { + + // 98 is actually the last block in a two block stream... + POIFSStream stream = new POIFSStream(fs, 98); + Iterator<ByteBuffer> i = stream.getBlockIterator(); + assertTrue(i.hasNext()); + ByteBuffer b = i.next(); + assertFalse(i.hasNext()); + + // Check the contents + assertEquals((byte) 0x81, b.get()); + assertEquals((byte) 0x00, b.get()); + assertEquals((byte) 0x00, b.get()); + assertEquals((byte) 0x00, b.get()); + assertEquals((byte) 0x82, b.get()); + assertEquals((byte) 0x00, b.get()); + assertEquals((byte) 0x00, b.get()); + assertEquals((byte) 0x00, b.get()); + } } /** @@ -94,38 +104,37 @@ final class TestPOIFSStream { */ @Test void testReadShortStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // 97 -> 98 -> end - POIFSStream stream = new POIFSStream(fs, 97); - Iterator<ByteBuffer> i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b97 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b98 = i.next(); - assertFalse(i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte) 0x01, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x02, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - assertEquals((byte) 0x00, b97.get()); - - // Check the contents of the 2nd block - assertEquals((byte) 0x81, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x82, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - assertEquals((byte) 0x00, b98.get()); - - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) { + + // 97 -> 98 -> end + POIFSStream stream = new POIFSStream(fs, 97); + Iterator<ByteBuffer> i = stream.getBlockIterator(); + assertTrue(i.hasNext()); + ByteBuffer b97 = i.next(); + assertTrue(i.hasNext()); + ByteBuffer b98 = i.next(); + assertFalse(i.hasNext()); + + // Check the contents of the 1st block + assertEquals((byte) 0x01, b97.get()); + assertEquals((byte) 0x00, b97.get()); + assertEquals((byte) 0x00, b97.get()); + assertEquals((byte) 0x00, b97.get()); + assertEquals((byte) 0x02, b97.get()); + assertEquals((byte) 0x00, b97.get()); + assertEquals((byte) 0x00, b97.get()); + assertEquals((byte) 0x00, b97.get()); + + // Check the contents of the 2nd block + assertEquals((byte) 0x81, b98.get()); + assertEquals((byte) 0x00, b98.get()); + assertEquals((byte) 0x00, b98.get()); + assertEquals((byte) 0x00, b98.get()); + assertEquals((byte) 0x82, b98.get()); + assertEquals((byte) 0x00, b98.get()); + assertEquals((byte) 0x00, b98.get()); + assertEquals((byte) 0x00, b98.get()); + } } /** @@ -133,59 +142,58 @@ final class TestPOIFSStream { */ @Test void testReadLongerStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) { - ByteBuffer b0 = null; - ByteBuffer b1 = null; - ByteBuffer b22 = null; + ByteBuffer b0 = null; + ByteBuffer b1 = null; + ByteBuffer b22 = null; - // The stream at 0 has 23 blocks in it - POIFSStream stream = new POIFSStream(fs, 0); - Iterator<ByteBuffer> i = stream.getBlockIterator(); - int count = 0; - while (i.hasNext()) { - ByteBuffer b = i.next(); - if (count == 0) { - b0 = b; - } - if (count == 1) { - b1 = b; - } - if (count == 22) { - b22 = b; - } + // The stream at 0 has 23 blocks in it + POIFSStream stream = new POIFSStream(fs, 0); + Iterator<ByteBuffer> i = stream.getBlockIterator(); + int count = 0; + while (i.hasNext()) { + ByteBuffer b = i.next(); + if (count == 0) { + b0 = b; + } + if (count == 1) { + b1 = b; + } + if (count == 22) { + b22 = b; + } - count++; + count++; + } + assertEquals(23, count); + + // Check the contents + // 1st block is at 0 + assertNotNull(b0); + assertEquals((byte) 0x9e, b0.get()); + assertEquals((byte) 0x75, b0.get()); + assertEquals((byte) 0x97, b0.get()); + assertEquals((byte) 0xf6, b0.get()); + + // 2nd block is at 1 + assertNotNull(b1); + assertEquals((byte) 0x86, b1.get()); + assertEquals((byte) 0x09, b1.get()); + assertEquals((byte) 0x22, b1.get()); + assertEquals((byte) 0xfb, b1.get()); + + // last block is at 89 + assertNotNull(b22); + assertEquals((byte) 0xfe, b22.get()); + assertEquals((byte) 0xff, b22.get()); + assertEquals((byte) 0x00, b22.get()); + assertEquals((byte) 0x00, b22.get()); + assertEquals((byte) 0x05, b22.get()); + assertEquals((byte) 0x01, b22.get()); + assertEquals((byte) 0x02, b22.get()); + assertEquals((byte) 0x00, b22.get()); } - assertEquals(23, count); - - // Check the contents - // 1st block is at 0 - assertNotNull(b0); - assertEquals((byte) 0x9e, b0.get()); - assertEquals((byte) 0x75, b0.get()); - assertEquals((byte) 0x97, b0.get()); - assertEquals((byte) 0xf6, b0.get()); - - // 2nd block is at 1 - assertNotNull(b1); - assertEquals((byte) 0x86, b1.get()); - assertEquals((byte) 0x09, b1.get()); - assertEquals((byte) 0x22, b1.get()); - assertEquals((byte) 0xfb, b1.get()); - - // last block is at 89 - assertNotNull(b22); - assertEquals((byte) 0xfe, b22.get()); - assertEquals((byte) 0xff, b22.get()); - assertEquals((byte) 0x00, b22.get()); - assertEquals((byte) 0x00, b22.get()); - assertEquals((byte) 0x05, b22.get()); - assertEquals((byte) 0x01, b22.get()); - assertEquals((byte) 0x02, b22.get()); - assertEquals((byte) 0x00, b22.get()); - - fs.close(); } /** @@ -193,50 +201,48 @@ final class TestPOIFSStream { */ @Test void testReadStream4096() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - - // 0 -> 1 -> 2 -> end - POIFSStream stream = new POIFSStream(fs, 0); - Iterator<ByteBuffer> i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b0 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b1 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b2 = i.next(); - assertFalse(i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte) 0x9E, b0.get()); - assertEquals((byte) 0x75, b0.get()); - assertEquals((byte) 0x97, b0.get()); - assertEquals((byte) 0xF6, b0.get()); - assertEquals((byte) 0xFF, b0.get()); - assertEquals((byte) 0x21, b0.get()); - assertEquals((byte) 0xD2, b0.get()); - assertEquals((byte) 0x11, b0.get()); - - // Check the contents of the 2nd block - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x03, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - assertEquals((byte) 0x00, b1.get()); - - // Check the contents of the 3rd block - assertEquals((byte) 0x6D, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x03, b2.get()); - assertEquals((byte) 0x00, b2.get()); - assertEquals((byte) 0x46, b2.get()); - assertEquals((byte) 0x00, b2.get()); - - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"))) { + // 0 -> 1 -> 2 -> end + POIFSStream stream = new POIFSStream(fs, 0); + Iterator<ByteBuffer> i = stream.getBlockIterator(); + assertTrue(i.hasNext()); + ByteBuffer b0 = i.next(); + assertTrue(i.hasNext()); + ByteBuffer b1 = i.next(); + assertTrue(i.hasNext()); + ByteBuffer b2 = i.next(); + assertFalse(i.hasNext()); + + // Check the contents of the 1st block + assertEquals((byte) 0x9E, b0.get()); + assertEquals((byte) 0x75, b0.get()); + assertEquals((byte) 0x97, b0.get()); + assertEquals((byte) 0xF6, b0.get()); + assertEquals((byte) 0xFF, b0.get()); + assertEquals((byte) 0x21, b0.get()); + assertEquals((byte) 0xD2, b0.get()); + assertEquals((byte) 0x11, b0.get()); + + // Check the contents of the 2nd block + assertEquals((byte) 0x00, b1.get()); + assertEquals((byte) 0x00, b1.get()); + assertEquals((byte) 0x03, b1.get()); + assertEquals((byte) 0x00, b1.get()); + assertEquals((byte) 0x00, b1.get()); + assertEquals((byte) 0x00, b1.get()); + assertEquals((byte) 0x00, b1.get()); + assertEquals((byte) 0x00, b1.get()); + + // Check the contents of the 3rd block + assertEquals((byte) 0x6D, b2.get()); + assertEquals((byte) 0x00, b2.get()); + assertEquals((byte) 0x00, b2.get()); + assertEquals((byte) 0x00, b2.get()); + assertEquals((byte) 0x03, b2.get()); + assertEquals((byte) 0x00, b2.get()); + assertEquals((byte) 0x46, b2.get()); + assertEquals((byte) 0x00, b2.get()); + } } /** @@ -244,35 +250,33 @@ final class TestPOIFSStream { */ @Test void testReadFailsOnLoop() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // Hack the FAT so that it goes 0->1->2->0 - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - // Now try to read - POIFSStream stream = new POIFSStream(fs, 0); - Iterator<ByteBuffer> i = stream.getBlockIterator(); - assertTrue(i.hasNext()); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) { + // Hack the FAT so that it goes 0->1->2->0 + fs.setNextBlock(0, 1); + fs.setNextBlock(1, 2); + fs.setNextBlock(2, 0); - // 1st read works - i.next(); - assertTrue(i.hasNext()); + // Now try to read + POIFSStream stream = new POIFSStream(fs, 0); + Iterator<ByteBuffer> i = stream.getBlockIterator(); + assertTrue(i.hasNext()); - // 2nd read works - i.next(); - assertTrue(i.hasNext()); + // 1st read works + i.next(); + assertTrue(i.hasNext()); - // 3rd read works - i.next(); - assertTrue(i.hasNext()); + // 2nd read works + i.next(); + assertTrue(i.hasNext()); - // 4th read blows up as it loops back to 0 - assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!"); - assertTrue(i.hasNext()); + // 3rd read works + i.next(); + assertTrue(i.hasNext()); - fs.close(); + // 4th read blows up as it loops back to 0 + assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!"); + assertTrue(i.hasNext()); + } } /** @@ -281,51 +285,50 @@ final class TestPOIFSStream { */ @Test void testReadMiniStreams() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSMiniStore ministore = fs.getMiniStore(); - - // 178 -> 179 -> 180 -> end - POIFSStream stream = new POIFSStream(ministore, 178); - Iterator<ByteBuffer> i = stream.getBlockIterator(); - assertTrue(i.hasNext()); - ByteBuffer b178 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b179 = i.next(); - assertTrue(i.hasNext()); - ByteBuffer b180 = i.next(); - assertFalse(i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte) 0xfe, b178.get()); - assertEquals((byte) 0xff, b178.get()); - assertEquals((byte) 0x00, b178.get()); - assertEquals((byte) 0x00, b178.get()); - assertEquals((byte) 0x05, b178.get()); - assertEquals((byte) 0x01, b178.get()); - assertEquals((byte) 0x02, b178.get()); - assertEquals((byte) 0x00, b178.get()); - - // And the 2nd - assertEquals((byte) 0x6c, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x28, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - assertEquals((byte) 0x00, b179.get()); - - // And the 3rd - assertEquals((byte) 0x30, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x00, b180.get()); - assertEquals((byte) 0x80, b180.get()); - - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) { + POIFSMiniStore ministore = fs.getMiniStore(); + + // 178 -> 179 -> 180 -> end + POIFSStream stream = new POIFSStream(ministore, 178); + Iterator<ByteBuffer> i = stream.getBlockIterator(); + assertTrue(i.hasNext()); + ByteBuffer b178 = i.next(); + assertTrue(i.hasNext()); + ByteBuffer b179 = i.next(); + assertTrue(i.hasNext()); + ByteBuffer b180 = i.next(); + assertFalse(i.hasNext()); + + // Check the contents of the 1st block + assertEquals((byte) 0xfe, b178.get()); + assertEquals((byte) 0xff, b178.get()); + assertEquals((byte) 0x00, b178.get()); + assertEquals((byte) 0x00, b178.get()); + assertEquals((byte) 0x05, b178.get()); + assertEquals((byte) 0x01, b178.get()); + assertEquals((byte) 0x02, b178.get()); + assertEquals((byte) 0x00, b178.get()); + + // And the 2nd + assertEquals((byte) 0x6c, b179.get()); + assertEquals((byte) 0x00, b179.get()); + assertEquals((byte) 0x00, b179.get()); + assertEquals((byte) 0x00, b179.get()); + assertEquals((byte) 0x28, b179.get()); + assertEquals((byte) 0x00, b179.get()); + assertEquals((byte) 0x00, b179.get()); + assertEquals((byte) 0x00, b179.get()); + + // And the 3rd + assertEquals((byte) 0x30, b180.get()); + assertEquals((byte) 0x00, b180.get()); + assertEquals((byte) 0x00, b180.get()); + assertEquals((byte) 0x00, b180.get()); + assertEquals((byte) 0x00, b180.get()); + assertEquals((byte) 0x00, b180.get()); + assertEquals((byte) 0x00, b180.get()); + assertEquals((byte) 0x80, b180.get()); + } } /** @@ -333,32 +336,31 @@ final class TestPOIFSStream { */ @Test void testReplaceStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) { - byte[] data = new byte[512]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } + byte[] data = new byte[512]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) (i % 256); + } - // 98 is actually the last block in a two block stream... - POIFSStream stream = new POIFSStream(fs, 98); - stream.updateContents(data); - - // Check the reading of blocks - Iterator<ByteBuffer> it = stream.getBlockIterator(); - assertTrue(it.hasNext()); - ByteBuffer b = it.next(); - assertFalse(it.hasNext()); - - // Now check the contents - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); - } + // 98 is actually the last block in a two block stream... + POIFSStream stream = new POIFSStream(fs, 98); + stream.updateContents(data); - fs.close(); + // Check the reading of blocks + Iterator<ByteBuffer> it = stream.getBlockIterator(); + assertTrue(it.hasNext()); + ByteBuffer b = it.next(); + assertFalse(it.hasNext()); + + // Now check the contents + data = new byte[512]; + b.get(data); + for (int i = 0; i < data.length; i++) { + byte exp = (byte) (i % 256); + assertEquals(exp, data[i]); + } + } } /** @@ -455,92 +457,91 @@ final class TestPOIFSStream { */ @Test void testWriteNewStream() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) { - // 100 is our first free one - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); + // 100 is our first free one + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - // Add a single block one - byte[] data = new byte[512]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } + // Add a single block one + byte[] data = new byte[512]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) (i % 256); + } - POIFSStream stream = new POIFSStream(fs); - stream.updateContents(data); + POIFSStream stream = new POIFSStream(fs); + stream.updateContents(data); - // Check it was allocated properly - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); + // Check it was allocated properly + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - // And check the contents - Iterator<ByteBuffer> it = stream.getBlockIterator(); - int count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); + // And check the contents + Iterator<ByteBuffer> it = stream.getBlockIterator(); + int count = 0; + while (it.hasNext()) { + ByteBuffer b = it.next(); + data = new byte[512]; + b.get(data); + for (int i = 0; i < data.length; i++) { + byte exp = (byte) (i % 256); + assertEquals(exp, data[i]); + } + count++; + } + assertEquals(1, count); + + + // And a multi block one + data = new byte[512 * 3]; for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); + data[i] = (byte) (i % 256); } - count++; - } - assertEquals(1, count); + stream = new POIFSStream(fs); + stream.updateContents(data); - // And a multi block one - data = new byte[512 * 3]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } + // Check it was allocated properly + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); + assertEquals(102, fs.getNextBlock(101)); + assertEquals(103, fs.getNextBlock(102)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - stream = new POIFSStream(fs); - stream.updateContents(data); - - // Check it was allocated properly - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - assertEquals(102, fs.getNextBlock(101)); - assertEquals(103, fs.getNextBlock(102)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - - // And check the contents - it = stream.getBlockIterator(); - count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); + // And check the contents + it = stream.getBlockIterator(); + count = 0; + while (it.hasNext()) { + ByteBuffer b = it.next(); + data = new byte[512]; + b.get(data); + for (int i = 0; i < data.length; i++) { + byte exp = (byte) (i % 256); + assertEquals(exp, data[i]); + } + count++; } - count++; + assertEquals(3, count); + + // Free it + stream.free(); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); } - assertEquals(3, count); - - // Free it - stream.free(); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104)); - - fs.close(); } /** @@ -550,40 +551,39 @@ final class TestPOIFSStream { */ @Test void testWriteNewStreamExtraFATs() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - - // Allocate almost all the blocks - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127)); - for (int i = 100; i < 127; i++) { - fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127)); - assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) { + // Allocate almost all the blocks + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127)); + for (int i = 100; i < 127; i++) { + fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN); + } + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127)); + assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - // Write a 3 block stream - byte[] data = new byte[512 * 3]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); + + // Write a 3 block stream + byte[] data = new byte[512 * 3]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) (i % 256); + } + POIFSStream stream = new POIFSStream(fs); + stream.updateContents(data); + + // Check we got another BAT + assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); + assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); + + // the BAT will be in the first spot of the new block + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126)); + assertEquals(129, fs.getNextBlock(127)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128)); + assertEquals(130, fs.getNextBlock(129)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131)); } - POIFSStream stream = new POIFSStream(fs); - stream.updateContents(data); - - // Check we got another BAT - assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - - // the BAT will be in the first spot of the new block - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126)); - assertEquals(129, fs.getNextBlock(127)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128)); - assertEquals(130, fs.getNextBlock(129)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131)); - - fs.close(); } /** @@ -592,54 +592,53 @@ final class TestPOIFSStream { */ @Test void testWriteStream4096() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"))) { - // 0 -> 1 -> 2 -> end - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - assertEquals(4, fs.getNextBlock(3)); + // 0 -> 1 -> 2 -> end + assertEquals(1, fs.getNextBlock(0)); + assertEquals(2, fs.getNextBlock(1)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); + assertEquals(4, fs.getNextBlock(3)); - // First free one is at 15 - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15)); + // First free one is at 15 + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15)); - // Write a 5 block file - byte[] data = new byte[4096 * 5]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) (i % 256); - } - POIFSStream stream = new POIFSStream(fs, 0); - stream.updateContents(data); - - - // Check it - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(15, fs.getNextBlock(2)); // Jumps - assertEquals(4, fs.getNextBlock(3)); // Next stream - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); - assertEquals(16, fs.getNextBlock(15)); // Continues - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free - - // Check the contents too - Iterator<ByteBuffer> it = stream.getBlockIterator(); - int count = 0; - while (it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); + // Write a 5 block file + byte[] data = new byte[4096 * 5]; for (int i = 0; i < data.length; i++) { - byte exp = (byte) (i % 256); - assertEquals(exp, data[i]); + data[i] = (byte) (i % 256); } - count++; - } - assertEquals(5, count); + POIFSStream stream = new POIFSStream(fs, 0); + stream.updateContents(data); + - fs.close(); + // Check it + assertEquals(1, fs.getNextBlock(0)); + assertEquals(2, fs.getNextBlock(1)); + assertEquals(15, fs.getNextBlock(2)); // Jumps + assertEquals(4, fs.getNextBlock(3)); // Next stream + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); + assertEquals(16, fs.getNextBlock(15)); // Continues + assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free + + // Check the contents too + Iterator<ByteBuffer> it = stream.getBlockIterator(); + int count = 0; + while (it.hasNext()) { + ByteBuffer b = it.next(); + data = new byte[512]; + b.get(data); + for (int i = 0; i < data.length; i++) { + byte exp = (byte) (i % 256); + assertEquals(exp, data[i]); + } + count++; + } + assertEquals(5, count); + } } /** @@ -933,191 +932,192 @@ final class TestPOIFSStream { */ @Test void testWriteThenReplace() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(); - - // Starts empty, other that Properties and BAT - BATBlock bat = fs.getBATBlockAndIndex(0).getBlock(); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2)); - - // Write something that uses a main stream - byte[] main4106 = new byte[4106]; - main4106[0] = -10; - main4106[4105] = -11; - fs.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106)); - - // Should have used 9 blocks - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - - DocumentEntry normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4106, normal.getSize()); - assertEquals(4106, ((DocumentNode) normal).getProperty().getSize()); - - - // Replace with one still big enough for a main stream, but one block smaller - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - - DocumentOutputStream nout = new DocumentOutputStream(normal); - nout.write(main4096); - nout.close(); - - // Will have dropped to 8 - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - - // Write and check - fs = writeOutAndReadBack(fs); - bat = fs.getBATBlockAndIndex(0).getBlock(); - - // No change after write - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - - // Make longer, take 1 block at the end - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - nout = new DocumentOutputStream(normal); - nout.write(main4106); - nout.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(3, bat.getValueAt(2)); - assertEquals(4, bat.getValueAt(3)); - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4106, normal.getSize()); - assertEquals(4106, ((DocumentNode) normal).getProperty().getSize()); - - - // Make it small, will trigger the SBAT stream and free lots up - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - nout = new DocumentOutputStream(normal); - nout.write(mini); - nout.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(7, normal.getSize()); - assertEquals(7, ((DocumentNode) normal).getProperty().getSize()); - - - // Finally back to big again - nout = new DocumentOutputStream(normal); - nout.write(main4096); - nout.close(); - - // Will keep the mini stream, now empty - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(11, bat.getValueAt(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - - // Save, re-load, re-check - fs = writeOutAndReadBack(fs); - bat = fs.getBATBlockAndIndex(0).getBlock(); - - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream - assertEquals(5, bat.getValueAt(4)); - assertEquals(6, bat.getValueAt(5)); - assertEquals(7, bat.getValueAt(6)); - assertEquals(8, bat.getValueAt(7)); - assertEquals(9, bat.getValueAt(8)); - assertEquals(10, bat.getValueAt(9)); - assertEquals(11, bat.getValueAt(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13)); - - normal = (DocumentEntry) fs.getRoot().getEntry("Normal"); - assertEquals(4096, normal.getSize()); - assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); - - fs.close(); + try (POIFSFileSystem fs1 = new POIFSFileSystem()) { + + // Starts empty, other that Properties and BAT + BATBlock bat = fs1.getBATBlockAndIndex(0).getBlock(); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2)); + + // Write something that uses a main stream + byte[] main4106 = new byte[4106]; + main4106[0] = -10; + main4106[4105] = -11; + fs1.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106)); + + // Should have used 9 blocks + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(3, bat.getValueAt(2)); + assertEquals(4, bat.getValueAt(3)); + assertEquals(5, bat.getValueAt(4)); + assertEquals(6, bat.getValueAt(5)); + assertEquals(7, bat.getValueAt(6)); + assertEquals(8, bat.getValueAt(7)); + assertEquals(9, bat.getValueAt(8)); + assertEquals(10, bat.getValueAt(9)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); + + DocumentEntry normal = (DocumentEntry) fs1.getRoot().getEntry("Normal"); + assertEquals(4106, normal.getSize()); + assertEquals(4106, ((DocumentNode) normal).getProperty().getSize()); + + + // Replace with one still big enough for a main stream, but one block smaller + byte[] main4096 = new byte[4096]; + main4096[0] = -10; + main4096[4095] = -11; + + try (DocumentOutputStream nout = new DocumentOutputStream(normal)) { + nout.write(main4096); + } + + // Will have dropped to 8 + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(3, bat.getValueAt(2)); + assertEquals(4, bat.getValueAt(3)); + assertEquals(5, bat.getValueAt(4)); + assertEquals(6, bat.getValueAt(5)); + assertEquals(7, bat.getValueAt(6)); + assertEquals(8, bat.getValueAt(7)); + assertEquals(9, bat.getValueAt(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); + + normal = (DocumentEntry) fs1.getRoot().getEntry("Normal"); + assertEquals(4096, normal.getSize()); + assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); + + + // Write and check + try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) { + bat = fs2.getBATBlockAndIndex(0).getBlock(); + + // No change after write + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(3, bat.getValueAt(2)); + assertEquals(4, bat.getValueAt(3)); + assertEquals(5, bat.getValueAt(4)); + assertEquals(6, bat.getValueAt(5)); + assertEquals(7, bat.getValueAt(6)); + assertEquals(8, bat.getValueAt(7)); + assertEquals(9, bat.getValueAt(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); + + normal = (DocumentEntry) fs2.getRoot().getEntry("Normal"); + assertEquals(4096, normal.getSize()); + assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); + + + // Make longer, take 1 block at the end + normal = (DocumentEntry) fs2.getRoot().getEntry("Normal"); + try (DocumentOutputStream nout = new DocumentOutputStream(normal)) { + nout.write(main4106); + } + + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(3, bat.getValueAt(2)); + assertEquals(4, bat.getValueAt(3)); + assertEquals(5, bat.getValueAt(4)); + assertEquals(6, bat.getValueAt(5)); + assertEquals(7, bat.getValueAt(6)); + assertEquals(8, bat.getValueAt(7)); + assertEquals(9, bat.getValueAt(8)); + assertEquals(10, bat.getValueAt(9)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); + + normal = (DocumentEntry) fs2.getRoot().getEntry("Normal"); + assertEquals(4106, normal.getSize()); + assertEquals(4106, ((DocumentNode) normal).getProperty().getSize()); + + + // Make it small, will trigger the SBAT stream and free lots up + byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; + normal = (DocumentEntry) fs2.getRoot().getEntry("Normal"); + try (DocumentOutputStream nout = new DocumentOutputStream(normal)) { + nout.write(mini); + } + + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); + + normal = (DocumentEntry) fs2.getRoot().getEntry("Normal"); + assertEquals(7, normal.getSize()); + assertEquals(7, ((DocumentNode) normal).getProperty().getSize()); + + + // Finally back to big again + try (DocumentOutputStream nout = new DocumentOutputStream(normal)) { + nout.write(main4096); + } + + // Will keep the mini stream, now empty + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream + assertEquals(5, bat.getValueAt(4)); + assertEquals(6, bat.getValueAt(5)); + assertEquals(7, bat.getValueAt(6)); + assertEquals(8, bat.getValueAt(7)); + assertEquals(9, bat.getValueAt(8)); + assertEquals(10, bat.getValueAt(9)); + assertEquals(11, bat.getValueAt(10)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13)); + + normal = (DocumentEntry) fs2.getRoot().getEntry("Normal"); + assertEquals(4096, normal.getSize()); + assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); + + + // Save, re-load, re-check + try (POIFSFileSystem fs3 = writeOutAndReadBack(fs2)) { + bat = fs3.getBATBlockAndIndex(0).getBlock(); + + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream + assertEquals(5, bat.getValueAt(4)); + assertEquals(6, bat.getValueAt(5)); + assertEquals(7, bat.getValueAt(6)); + assertEquals(8, bat.getValueAt(7)); + assertEquals(9, bat.getValueAt(8)); + assertEquals(10, bat.getValueAt(9)); + assertEquals(11, bat.getValueAt(10)); + assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12)); + assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13)); + + normal = (DocumentEntry) fs3.getRoot().getEntry("Normal"); + assertEquals(4096, normal.getSize()); + assertEquals(4096, ((DocumentNode) normal).getProperty().getSize()); + } + } + } } @@ -1125,14 +1125,43 @@ final class TestPOIFSStream { * Returns test files with 512 byte and 4k block sizes, loaded * both from InputStreams and Files */ - private POIFSFileSystem[] get512and4kFileAndInput() throws IOException { - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - return new POIFSFileSystem[]{fsA, fsB, fsC, fsD}; + public static Collection<Arguments> get512and4kFileAndInput() { + return CollectionUtils.union(get512FileAndInput(), get4kFileAndInput()); + } + + public static List<Arguments> get512FileAndInput() { + return Arrays.asList( + Arguments.of("BlockSize512.zvi", (Function<String,POIFSFileSystem>)TestPOIFSStream::openAsFile), + Arguments.of("BlockSize512.zvi", (Function<String,POIFSFileSystem>)TestPOIFSStream::openAsStream) + ); } + public static List<Arguments> get4kFileAndInput() { + return Arrays.asList( + Arguments.of("BlockSize4096.zvi", (Function<String,POIFSFileSystem>)TestPOIFSStream::openAsFile), + Arguments.of("BlockSize4096.zvi", (Function<String,POIFSFileSystem>)TestPOIFSStream::openAsStream) + ); + } + + private static POIFSFileSystem openAsFile(String fileName) { + try { + return new POIFSFileSystem(_inst.getFile(fileName)); + } catch (IOException e) { + fail(e); + return null; + } + } + + private static POIFSFileSystem openAsStream(String fileName) { + try { + return new POIFSFileSystem(_inst.openResourceAsStream(fileName)); + } catch (IOException e) { + fail(e); + return null; + } + } + + private static void assertBATCount(POIFSFileSystem fs, int expectedBAT, int expectedXBAT) throws IOException { int foundBAT = 0; int foundXBAT = 0; @@ -1161,16 +1190,9 @@ final class TestPOIFSStream { } private static HeaderBlock writeOutAndReadHeader(POIFSFileSystem fs) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); fs.writeFilesystem(baos); - - return new HeaderBlock(new ByteArrayInputStream(baos.toByteArray())); - } - - private static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - original.writeFilesystem(baos); - return new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); + return new HeaderBlock(baos.toInputStream()); } private static POIFSFileSystem writeOutFileAndReadBack(POIFSFileSystem original) throws IOException { @@ -1181,37 +1203,29 @@ final class TestPOIFSStream { return new POIFSFileSystem(file, false); } - @Test - void basicOpen() throws IOException { - POIFSFileSystem fsA, fsB; - + @ParameterizedTest() + @MethodSource("get512FileAndInput") + void basicOpen512(String file, Function<String,POIFSFileSystem> opener) throws IOException { // With a simple 512 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { + try (POIFSFileSystem fs = opener.apply(file)) { assertEquals(512, fs.getBigBlockSize()); } - fsA.close(); - fsB.close(); + } + @ParameterizedTest() + @MethodSource("get4kFileAndInput") + void basicOpen4k(String file, Function<String,POIFSFileSystem> opener) throws IOException { // Now with a simple 4096 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { + try (POIFSFileSystem fs = opener.apply(file)) { assertEquals(4096, fs.getBigBlockSize()); } - fsA.close(); - fsB.close(); } - @Test - void propertiesAndFatOnRead() throws IOException { - POIFSFileSystem fsA, fsB; - + @ParameterizedTest() + @MethodSource("get512FileAndInput") + void propertiesAndFatOnRead512(String file, Function<String,POIFSFileSystem> opener) throws IOException { // With a simple 512 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { + try (POIFSFileSystem fs = opener.apply(file)) { // Check the FAT was properly processed: // Verify we only got one block fs.getBATBlockAndIndex(0); @@ -1266,14 +1280,14 @@ final class TestPOIFSStream { assertEquals(i + 1, ministore.getNextBlock(i)); } assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - fs.close(); } + } + @ParameterizedTest() + @MethodSource("get4kFileAndInput") + void propertiesAndFatOnRead4k(String file, Function<String,POIFSFileSystem> opener) throws IOException { // Now with a simple 4096 block file - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { + try (POIFSFileSystem fs = opener.apply(file)) { // Check the FAT was properly processed // Verify we only got one block fs.getBATBlockAndIndex(0); @@ -1330,8 +1344,6 @@ final class TestPOIFSStream { assertEquals(i + 1, ministore.getNextBlock(i)); } assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - fs.close(); } } @@ -1339,11 +1351,10 @@ final class TestPOIFSStream { * Check that for a given block, we can correctly figure * out what the next one is */ - @Test - void nextBlock() throws IOException { - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { + @ParameterizedTest() + @MethodSource("get512FileAndInput") + void nextBlock512(String file, Function<String,POIFSFileSystem> opener) throws IOException { + try (POIFSFileSystem fs = opener.apply(file)) { // 0 -> 21 are simple for (int i = 0; i < 21; i++) { assertEquals(i + 1, fs.getNextBlock(i)); @@ -1375,14 +1386,14 @@ final class TestPOIFSStream { for (int i = 100; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) { assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i)); } - - fs.close(); } + } + @ParameterizedTest() + @MethodSource("get4kFileAndInput") + void nextBlock4k(String file, Function<String,POIFSFileSystem> opener) throws IOException { // Quick check on 4096 byte blocks too - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { + try (POIFSFileSystem fs = opener.apply(file)) { // 0 -> 1 -> 2 -> end assertEquals(1, fs.getNextBlock(0)); assertEquals(2, fs.getNextBlock(1)); @@ -1393,23 +1404,18 @@ final class TestPOIFSStream { assertEquals(i + 1, fs.getNextBlock(i)); } assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11)); - - fs.close(); } } /** * Check we get the right data back for each block */ - @Test - void getBlock() throws IOException { - POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - ByteBuffer b; - + @ParameterizedTest() + @MethodSource("get512FileAndInput") + void getBlock512(String file, Function<String,POIFSFileSystem> opener) throws IOException { + try (POIFSFileSystem fs = opener.apply(file)) { // The 0th block is the first data block - b = fs.getBlockAt(0); + ByteBuffer b = fs.getBlockAt(0); assertEquals((byte) 0x9e, b.get()); assertEquals((byte) 0x75, b.get()); assertEquals((byte) 0x97, b.get()); @@ -1432,18 +1438,16 @@ final class TestPOIFSStream { assertEquals((byte) 0x00, b.get()); assertEquals((byte) 0x00, b.get()); assertEquals((byte) 0x00, b.get()); - - fs.close(); } + } + @ParameterizedTest() + @MethodSource("get4kFileAndInput") + void getBlock4k(String file, Function<String,POIFSFileSystem> opener) throws IOException { // Quick check on 4096 byte blocks too - fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) { - ByteBuffer b; - + try (POIFSFileSystem fs = opener.apply(file)) { // The 0th block is the first data block - b = fs.getBlockAt(0); + ByteBuffer b = fs.getBlockAt(0); assertEquals((byte) 0x9e, b.get()); assertEquals((byte) 0x75, b.get()); assertEquals((byte) 0x97, b.get()); @@ -1466,8 +1470,6 @@ final class TestPOIFSStream { assertEquals((byte) 0x00, b.get()); assertEquals((byte) 0x00, b.get()); assertEquals((byte) 0x00, b.get()); - - fs.close(); } } @@ -1477,29 +1479,26 @@ final class TestPOIFSStream { */ @Test void getFreeBlockWithSpare() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // Our first BAT block has spares - assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - - // First free one is 100 - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) { + // Our first BAT block has spares + assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - // Ask, will get 100 - assertEquals(100, fs.getFreeBlock()); + // First free one is 100 + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - // Ask again, will still get 100 as not written to - assertEquals(100, fs.getFreeBlock()); + // Ask, will get 100 + assertEquals(100, fs.getFreeBlock()); - // Allocate it, then ask again - fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN); - assertEquals(101, fs.getFreeBlock()); + // Ask again, will still get 100 as not written to + assertEquals(100, fs.getFreeBlock()); - // All done - fs.close(); + // Allocate it, then ask again + fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN); + assertEquals(101, fs.getFreeBlock()); + } } /** @@ -1508,136 +1507,134 @@ final class TestPOIFSStream { */ @Test void getFreeBlockWithNoneSpare() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - int free; + try (POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) { + int free; - // We have one BAT at block 99 - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99)); - assertBATCount(fs1, 1, 0); + // We have one BAT at block 99 + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99)); + assertBATCount(fs1, 1, 0); - // We've spare ones from 100 to 128 - for (int i = 100; i < 128; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i)); - } + // We've spare ones from 100 to 128 + for (int i = 100; i < 128; i++) { + assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i)); + } - // Check our BAT knows it's free - assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); + // Check our BAT knows it's free + assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - // Allocate all the spare ones - for (int i = 100; i < 128; i++) { - fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } + // Allocate all the spare ones + for (int i = 100; i < 128; i++) { + fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN); + } - // BAT is now full, but there's only the one - assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT"); - assertBATCount(fs1, 1, 0); + // BAT is now full, but there's only the one + assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); + assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT"); + assertBATCount(fs1, 1, 0); - // Now ask for a free one, will need to extend the file - assertEquals(129, fs1.getFreeBlock()); + // Now ask for a free one, will need to extend the file + assertEquals(129, fs1.getFreeBlock()); - assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129)); + assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); + assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129)); - // We now have 2 BATs, but no XBATs - assertBATCount(fs1, 2, 0); + // We now have 2 BATs, but no XBATs + assertBATCount(fs1, 2, 0); - // Fill up to hold 109 BAT blocks - for (int i = 0; i < 109; i++) { - fs1.getFreeBlock(); - int startOffset = i * 128; - while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) { - free = fs1.getFreeBlock(); - fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); + // Fill up to hold 109 BAT blocks + for (int i = 0; i < 109; i++) { + fs1.getFreeBlock(); + int startOffset = i * 128; + while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) { + free = fs1.getFreeBlock(); + fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); + } } - } - assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs"); + assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); + assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs"); - // We now have 109 BATs, but no XBATs - assertBATCount(fs1, 109, 0); + // We now have 109 BATs, but no XBATs + assertBATCount(fs1, 109, 0); - // Ask for it to be written out, and check the header - HeaderBlock header = writeOutAndReadHeader(fs1); - assertEquals(109, header.getBATCount()); - assertEquals(0, header.getXBATCount()); + // Ask for it to be written out, and check the header + HeaderBlock header = writeOutAndReadHeader(fs1); + assertEquals(109, header.getBATCount()); + assertEquals(0, header.getXBATCount()); - // Ask for another, will get our first XBAT - free = fs1.getFreeBlock(); - assertTrue(free > 0, "Had: " + free); + // Ask for another, will get our first XBAT + free = fs1.getFreeBlock(); + assertTrue(free > 0, "Had: " + free); - assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs"); - assertBATCount(fs1, 110, 1); + assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors()); + assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors()); + assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs"); + assertBATCount(fs1, 110, 1); - header = writeOutAndReadHeader(fs1); - assertEquals(110, header.getBATCount()); - assertEquals(1, header.getXBATCount()); + header = writeOutAndReadHeader(fs1); + assertEquals(110, header.getBATCount()); + assertEquals(1, header.getXBATCount()); - // Fill the XBAT, which means filling 127 BATs - for (int i = 109; i < 109 + 127; i++) { - fs1.getFreeBlock(); - int startOffset = i * 128; - while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) { - free = fs1.getFreeBlock(); - fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); + // Fill the XBAT, which means filling 127 BATs + for (int i = 109; i < 109 + 127; i++) { + fs1.getFreeBlock(); + int startOffset = i * 128; + while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) { + free = fs1.getFreeBlock(); + fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); + } + assertBATCount(fs1, i + 1, 1); } - assertBATCount(fs1, i + 1, 1); - } - - // Should now have 109+127 = 236 BATs - assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs"); - assertBATCount(fs1, 236, 1); - - // Ask for another, will get our 2nd XBAT - free = fs1.getFreeBlock(); - assertTrue(free > 0, "Had: " + free); + // Should now have 109+127 = 236 BATs + assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); + assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs"); + assertBATCount(fs1, 236, 1); - assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs"); + // Ask for another, will get our 2nd XBAT + free = fs1.getFreeBlock(); + assertTrue(free > 0, "Had: " + free); - // Check the counts now - assertBATCount(fs1, 237, 2); + assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); + assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); + assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs"); - // Check the header - header = writeOutAndReadHeader(fs1); - assertNotNull(header); + // Check the counts now + assertBATCount(fs1, 237, 2); - // Now, write it out, and read it back in again fully - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); + // Check the header + header = writeOutAndReadHeader(fs1); + assertNotNull(header); - // Check that it is seen correctly - assertBATCount(fs2, 237, 2); + // Now, write it out, and read it back in again fully + try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) { - assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); - assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); - assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs"); + // Check that it is seen correctly + assertBATCount(fs2, 237, 2); - // All done - fs2.close(); + assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors()); + assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors()); + assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs"); + } + } } /** * Test that we can correctly get the list of directory * entries, and the details on the files in them */ - @Test - void listEntries() throws IOException { - for (POIFSFileSystem fs : get512and4kFileAndInput()) { + @ParameterizedTest + @MethodSource("get512and4kFileAndInput") + void listEntries(String file, Function<String,POIFSFileSystem> opener) throws IOException { + try (POIFSFileSystem fs = opener.apply(file)) { DirectoryEntry root = fs.getRoot(); assertEquals(5, root.getEntryCount()); @@ -1665,8 +1662,6 @@ final class TestPOIFSStream { // Look inside another DirectoryEntry imageD = (DirectoryEntry) image; assertEquals(7, imageD.getEntryCount()); - - fs.close(); } } @@ -1674,9 +1669,11 @@ final class TestPOIFSStream { * Tests that we can get the correct contents for * a document in the filesystem */ - @Test - void getDocumentEntry() throws Exception { - for (POIFSFileSystem fs : get512and4kFileAndInput()) { + @ParameterizedTest + @MethodSource("get512and4kFileAndInput") + void getDocumentEntry(String file, Function<String,POIFSFileSystem> opener) + throws IOException, NoPropertySetStreamException { + try (POIFSFileSystem fs = opener.apply(file)) { DirectoryEntry root = fs.getRoot(); Entry si = root.getEntry("\u0005SummaryInformation"); @@ -1687,18 +1684,16 @@ final class TestPOIFSStream { assertContentsMatches(null, doc); // Now try to build the property set - DocumentInputStream inp = new DocumentInputStream(doc); - PropertySet ps = PropertySetFactory.create(inp); - SummaryInformation inf = (SummaryInformation) ps; - - // Check some bits in it - assertNull(inf.getApplicationName()); - assertNull(inf.getAuthor()); - assertNull(inf.getSubject()); - assertEquals(131333, inf.getOSVersion()); - - // Finish with this one - inp.close(); + try (DocumentInputStream inp = new DocumentInputStream(doc)) { + PropertySet ps = PropertySetFactory.create(inp); + SummaryInformation inf = (SummaryInformation) ps; + + // Check some bits in it + assertNull(inf.getApplicationName()); + assertNull(inf.getAuthor()); + assertNull(inf.getSubject()); + assertEquals(131333, inf.getOSVersion()); + } // Try the other summary information @@ -1707,12 +1702,11 @@ final class TestPOIFSStream { doc = (DocumentNode) si; assertContentsMatches(null, doc); - inp = new DocumentInputStream(doc); - ps = PropertySetFactory.create(inp); - DocumentSummaryInformation dinf = (DocumentSummaryInformation) ps; - assertEquals(131333, dinf.getOSVersion()); - - fs.close(); + try (DocumentInputStream inp = new DocumentInputStream(doc)) { + PropertySet ps = PropertySetFactory.create(inp); + DocumentSummaryInformation dinf = (DocumentSummaryInformation) ps; + assertEquals(131333, dinf.getOSVersion()); + } } } @@ -1720,13 +1714,14 @@ final class TestPOIFSStream { * Read a file, write it and read it again. * Then, alter+add some streams, write and read */ - @Test - void readWriteRead() throws Exception { + @ParameterizedTest + @MethodSource("get512and4kFileAndInput") + void readWriteRead(String file, Function<String,POIFSFileSystem> opener) throws IOException, NoPropertySetStreamException { SummaryInformation sinf; DocumentSummaryInformation dinf; DirectoryEntry root, testDir; - for (POIFSFileSystem fs1 : get512and4kFileAndInput()) { + try (POIFSFileSystem fs1 = opener.apply(file)) { // Check we can find the entries we expect root = fs1.getRoot(); assertEquals(5, root.getEntryCount()); @@ -1736,257 +1731,251 @@ final class TestPOIFSStream { assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - // Write out, re-load - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); + try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) { + // Check they're still there + root = fs2.getRoot(); + assertEquals(5, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Tags")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - // Check they're still there - root = fs2.getRoot(); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + // Check the contents of them - parse the summary block and check + sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, sinf.getOSVersion()); - // Check the contents of them - parse the summary block and check - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); + dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, dinf.getOSVersion()); - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); + // Add a test mini stream + testDir = root.createDirectory("Testing 123"); + testDir.createDirectory("Testing 456"); + testDir.createDirectory("Testing 789"); + byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; + testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - // Add a test mini stream - testDir = root.createDirectory("Testing 123"); - testDir.createDirectory("Testing 456"); - testDir.createDirectory("Testing 789"); - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); + // Write out, re-load + try (POIFSFileSystem fs3 = writeOutAndReadBack(fs2)) { - // Write out, re-load - POIFSFileSystem fs3 = writeOutAndReadBack(fs2); - fs2.close(); + root = fs3.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); + assertEquals(6, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Tags")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - root = fs3.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(6, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + // Check old and new are there + sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, sinf.getOSVersion()); - // Check old and new are there - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); + dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, dinf.getOSVersion()); - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); + assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); + // Write out and read once more, just to be sure + try (POIFSFileSystem fs4 = writeOutAndReadBack(fs3)) { - // Write out and read once more, just to be sure - POIFSFileSystem fs4 = writeOutAndReadBack(fs3); - fs3.close(); + root = fs4.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); + assertEquals(6, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Tags")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - root = fs4.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(6, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, sinf.getOSVersion()); - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); + dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, dinf.getOSVersion()); - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); + assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); + // Add a full stream, delete a full stream + byte[] main4096 = new byte[4096]; + main4096[0] = -10; + main4096[4095] = -11; + testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - // Add a full stream, delete a full stream - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - root.getEntry("Tags").delete(); - - - // Write out, re-load - POIFSFileSystem fs5 = writeOutAndReadBack(fs4); - fs4.close(); - - // Check it's all there - root = fs5.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + root.getEntry("Tags").delete(); - // Check old and new are there - sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); + // Write out, re-load + try (POIFSFileSystem fs5 = writeOutAndReadBack(fs4)) { - dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( - (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); + // Check it's all there + root = fs5.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); + assertEquals(5, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); + // Check old and new are there + sinf = (SummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, sinf.getOSVersion()); - // Delete a directory, and add one more - testDir.getEntry("Testing 456").delete(); - testDir.createDirectory("Testing ABC"); + dinf = (DocumentSummaryInformation) PropertySetFactory.create(new DocumentInputStream( + (DocumentEntry) root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); + assertEquals(131333, dinf.getOSVersion()); + assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); + assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); - // Save - POIFSFileSystem fs6 = writeOutAndReadBack(fs5); - fs5.close(); - // Check - root = fs6.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(4, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - - // Add another mini stream - byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); + // Delete a directory, and add one more + testDir.getEntry("Testing 456").delete(); + testDir.createDirectory("Testing ABC"); - // Save, load, check - POIFSFileSystem fs7 = writeOutAndReadBack(fs6); - fs6.close(); - root = fs7.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); + // Save + try (POIFSFileSystem fs6 = writeOutAndReadBack(fs5)) { - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + // Check + root = fs6.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini")); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); + assertEquals(5, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); - assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2")); - assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); + assertEquals(4, testDir.getEntryCount()); + assertThat(testDir.getEntryNames(), hasItem("Mini")); + assertThat(testDir.getEntryNames(), hasItem("Normal4096")); + assertThat(testDir.getEntryNames(), hasItem("Testing 789")); + assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - // Delete a mini stream, add one more - testDir.getEntry("Mini").delete(); + // Add another mini stream + byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; + testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - byte[] mini3 = new byte[]{42, 0, 42, 0, 42, 0, 42}; - testDir.createDocument("Mini3", new ByteArrayInputStream(mini3)); + // Save, load, check + try (POIFSFileSystem fs7 = writeOutAndReadBack(fs6)) { + root = fs7.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); - // Save, load, check - POIFSFileSystem fs8 = writeOutAndReadBack(fs7); - fs7.close(); + assertEquals(5, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - root = fs8.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); + assertEquals(5, testDir.getEntryCount()); + assertThat(testDir.getEntryNames(), hasItem("Mini")); + assertThat(testDir.getEntryNames(), hasItem("Mini2")); + assertThat(testDir.getEntryNames(), hasItem("Normal4096")); + assertThat(testDir.getEntryNames(), hasItem("Testing 789")); + assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini")); + assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2")); + assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Mini3")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2")); - assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3")); - assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); + // Delete a mini stream, add one more + testDir.getEntry("Mini").delete(); + byte[] mini3 = new byte[]{42, 0, 42, 0, 42, 0, 42}; + testDir.createDocument("Mini3", new ByteArrayInputStream(mini3)); - // Change some existing streams - POIFSDocument mini2Doc = new POIFSDocument((DocumentNode) testDir.getEntry("Mini2")); - mini2Doc.replaceContents(new ByteArrayInputStream(mini)); - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - POIFSDocument mainDoc = new POIFSDocument((DocumentNode) testDir.getEntry("Normal4096")); - mainDoc.replaceContents(new ByteArrayInputStream(main4106)); + // Save, load, check + try (POIFSFileSystem fs8 = writeOutAndReadBack(fs7)) { + root = fs8.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); - // Re-check - POIFSFileSystem fs9 = writeOutAndReadBack(fs8); - fs8.close(); + assertEquals(5, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + + assertEquals(5, testDir.getEntryCount()); + assertThat(testDir.getEntryNames(), hasItem("Mini2")); + assertThat(testDir.getEntryNames(), hasItem("Mini3")); + assertThat(testDir.getEntryNames(), hasItem("Normal4096")); + assertThat(testDir.getEntryNames(), hasItem("Testing 789")); + assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - root = fs9.getRoot(); - testDir = (DirectoryEntry) root.getEntry("Testing 123"); + assertContentsMatches(mini2, (DocumentEntry) testDir.getEntry("Mini2")); + assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3")); + assertContentsMatches(main4096, (DocumentEntry) testDir.getEntry("Normal4096")); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Mini3")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); + // Change some existing streams + POIFSDocument mini2Doc = new POIFSDocument((DocumentNode) testDir.getEntry("Mini2")); + mini2Doc.replaceContents(new ByteArrayInputStream(mini)); - assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini2")); - assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3")); - assertContentsMatches(main4106, (DocumentEntry) testDir.getEntry("Normal4096")); + byte[] main4106 = new byte[4106]; + main4106[0] = 41; + main4106[4105] = 42; + POIFSDocument mainDoc = new POIFSDocument((DocumentNode) testDir.getEntry("Normal4096")); + mainDoc.replaceContents(new ByteArrayInputStream(main4106)); - // All done - fs9.close(); + // Re-check + try (POIFSFileSystem fs9 = writeOutAndReadBack(fs8)) { + + root = fs9.getRoot(); + testDir = (DirectoryEntry) root.getEntry("Testing 123"); + + assertEquals(5, root.getEntryCount()); + assertThat(root.getEntryNames(), hasItem("Thumbnail")); + assertThat(root.getEntryNames(), hasItem("Image")); + assertThat(root.getEntryNames(), hasItem("Testing 123")); + assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); + assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); + + assertEquals(5, testDir.getEntryCount()); + assertThat(testDir.getEntryNames(), hasItem("Mini2")); + assertThat(testDir.getEntryNames(), hasItem("Mini3")); + assertThat(testDir.getEntryNames(), hasItem("Normal4096")); + assertThat(testDir.getEntryNames(), hasItem("Testing 789")); + assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); + + assertContentsMatches(mini, (DocumentEntry) testDir.getEntry("Mini2")); + assertContentsMatches(mini3, (DocumentEntry) testDir.getEntry("Mini3")); + assertContentsMatches(main4106, (DocumentEntry) testDir.getEntry("Normal4096")); + } + } + } + } + } + } + } + } } } @@ -1996,528 +1985,510 @@ final class TestPOIFSStream { */ @Test void createWriteRead() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - - // Initially has Properties + BAT but not SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); - - // Check that the SBAT is empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock()); - - // Check that properties table was given block 0 - assertEquals(0, fs1._get_property_table().getStartBlock()); - - // Write and read it - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // No change, SBAT remains empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock()); - assertEquals(0, fs2._get_property_table().getStartBlock()); - fs2.close(); + try (POIFSFileSystem fs1 = new POIFSFileSystem()) { + // Initially has Properties + BAT but not SBAT + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); + + // Check that the SBAT is empty + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock()); + + // Check that properties table was given block 0 + assertEquals(0, fs1._get_property_table().getStartBlock()); + + // Write and read it + try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) { + + // No change, SBAT remains empty + assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock()); + assertEquals(0, fs2._get_property_table().getStartBlock()); + } + } // Check the same but with saving to a file - POIFSFileSystem fs3 = new POIFSFileSystem(); - POIFSFileSystem fs4 = writeOutFileAndReadBack(fs3); - fs3.close(); - - // Same, no change, SBAT remains empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - assertEquals(0, fs4._get_property_table().getStartBlock()); - - - // Put everything within a new directory - DirectoryEntry testDir = fs4.createDirectory("Test Directory"); - - // Add a new Normal Stream (Normal Streams minimum 4096 bytes) - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11)); - // SBAT still unused - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - - - // Add a bigger Normal Stream - byte[] main5124 = new byte[5124]; - main5124[0] = -22; - main5124[5123] = -33; - testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - - assertEquals(11, fs4.getNextBlock(10)); - assertEquals(12, fs4.getNextBlock(11)); - assertEquals(13, fs4.getNextBlock(12)); - assertEquals(14, fs4.getNextBlock(13)); - assertEquals(15, fs4.getNextBlock(14)); - assertEquals(16, fs4.getNextBlock(15)); - assertEquals(17, fs4.getNextBlock(16)); - assertEquals(18, fs4.getNextBlock(17)); - assertEquals(19, fs4.getNextBlock(18)); - assertEquals(20, fs4.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - - - // Now Add a mini stream - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - // Mini stream will get one block for fat + one block for data - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - - assertEquals(11, fs4.getNextBlock(10)); - assertEquals(12, fs4.getNextBlock(11)); - assertEquals(13, fs4.getNextBlock(12)); - assertEquals(14, fs4.getNextBlock(13)); - assertEquals(15, fs4.getNextBlock(14)); - assertEquals(16, fs4.getNextBlock(15)); - assertEquals(17, fs4.getNextBlock(16)); - assertEquals(18, fs4.getNextBlock(17)); - assertEquals(19, fs4.getNextBlock(18)); - assertEquals(20, fs4.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23)); - - // Check the mini stream location was set - // (21 is mini fat, 22 is first mini stream block) - assertEquals(22, fs4.getRoot().getProperty().getStartBlock()); - - - // Write and read back - POIFSFileSystem fs5 = writeOutAndReadBack(fs4); - fs4.close(); - HeaderBlock header = writeOutAndReadHeader(fs5); - - // Check the header has the right points in it - assertEquals(1, header.getBATCount()); - assertEquals(1, header.getBATArray()[0]); - assertEquals(0, header.getPropertyStart()); - assertEquals(1, header.getSBATCount()); - assertEquals(21, header.getSBATStart()); - assertEquals(22, fs5._get_property_table().getRoot().getStartBlock()); - - // Block use should be almost the same, except the properties - // stream will have grown out to cover 2 blocks - // Check the block use is all unchanged - assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1)); - - assertEquals(3, fs5.getNextBlock(2)); - assertEquals(4, fs5.getNextBlock(3)); - assertEquals(5, fs5.getNextBlock(4)); - assertEquals(6, fs5.getNextBlock(5)); - assertEquals(7, fs5.getNextBlock(6)); - assertEquals(8, fs5.getNextBlock(7)); - assertEquals(9, fs5.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096 - - assertEquals(11, fs5.getNextBlock(10)); - assertEquals(12, fs5.getNextBlock(11)); - assertEquals(13, fs5.getNextBlock(12)); - assertEquals(14, fs5.getNextBlock(13)); - assertEquals(15, fs5.getNextBlock(14)); - assertEquals(16, fs5.getNextBlock(15)); - assertEquals(17, fs5.getNextBlock(16)); - assertEquals(18, fs5.getNextBlock(17)); - assertEquals(19, fs5.getNextBlock(18)); - assertEquals(20, fs5.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124 - - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2 - assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24)); - - - // Check some data - assertEquals(1, fs5.getRoot().getEntryCount()); - testDir = (DirectoryEntry) fs5.getRoot().getEntry("Test Directory"); - assertEquals(3, testDir.getEntryCount()); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal5124"); - assertContentsMatches(main5124, normDoc); - - - // Delete a couple of streams - miniDoc.delete(); - normDoc.delete(); - - - // Check - will have un-used sectors now - POIFSFileSystem fs6 = writeOutAndReadBack(fs5); - fs5.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1)); - - assertEquals(3, fs6.getNextBlock(2)); - assertEquals(4, fs6.getNextBlock(3)); - assertEquals(5, fs6.getNextBlock(4)); - assertEquals(6, fs6.getNextBlock(5)); - assertEquals(7, fs6.getNextBlock(6)); - assertEquals(8, fs6.getNextBlock(7)); - assertEquals(9, fs6.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096 - - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25)); - - // All done - fs6.close(); - } + try (POIFSFileSystem fs3 = new POIFSFileSystem(); + POIFSFileSystem fs4 = writeOutFileAndReadBack(fs3)) { - @Test - void addBeforeWrite() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - HeaderBlock hdr; - - // Initially has Properties + BAT but nothing else - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); - - hdr = writeOutAndReadHeader(fs1); - // No mini stream, and no xbats - // Will have fat then properties stream - assertEquals(1, hdr.getBATCount()); - assertEquals(1, hdr.getBATArray()[0]); - assertEquals(0, hdr.getPropertyStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 3, fs1.size()); - fs1.close(); + // Same, no change, SBAT remains empty + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); + assertEquals(0, fs4._get_property_table().getStartBlock()); - // Get a clean filesystem to start with - fs1 = new POIFSFileSystem(); - - // Put our test files in a non-standard place - DirectoryEntry parentDir = fs1.createDirectory("Parent Directory"); - DirectoryEntry testDir = parentDir.createDirectory("Test Directory"); - - - // Add to the mini stream - byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - // Add to the main stream - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - - // Check the mini stream was added, then the main stream - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream - assertEquals(5, fs1.getNextBlock(4)); // Main Stream - assertEquals(6, fs1.getNextBlock(5)); - assertEquals(7, fs1.getNextBlock(6)); - assertEquals(8, fs1.getNextBlock(7)); - assertEquals(9, fs1.getNextBlock(8)); - assertEquals(10, fs1.getNextBlock(9)); - assertEquals(11, fs1.getNextBlock(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12)); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 13, fs1.size()); + // Put everything within a new directory + DirectoryEntry testDir = fs4.createDirectory("Test Directory"); - // Check that we can read the right data pre-write - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - - // Write, read, check - hdr = writeOutAndReadHeader(fs1); - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check the header details - will have the sbat near the start, - // then the properties at the end - assertEquals(1, hdr.getBATCount()); - assertEquals(1, hdr.getBATArray()[0]); - assertEquals(2, hdr.getSBATStart()); - assertEquals(0, hdr.getPropertyStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); - - // Check the block allocation is unchanged, other than - // the properties stream going in at the end - assertEquals(12, fs2.getNextBlock(0)); // Properties - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3)); - assertEquals(5, fs2.getNextBlock(4)); - assertEquals(6, fs2.getNextBlock(5)); - assertEquals(7, fs2.getNextBlock(6)); - assertEquals(8, fs2.getNextBlock(7)); - assertEquals(9, fs2.getNextBlock(8)); - assertEquals(10, fs2.getNextBlock(9)); - assertEquals(11, fs2.getNextBlock(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13)); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 14, fs2.size()); + // Add a new Normal Stream (Normal Streams minimum 4096 bytes) + byte[] main4096 = new byte[4096]; + main4096[0] = -10; + main4096[4095] = -11; + testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); + assertEquals(3, fs4.getNextBlock(2)); + assertEquals(4, fs4.getNextBlock(3)); + assertEquals(5, fs4.getNextBlock(4)); + assertEquals(6, fs4.getNextBlock(5)); + assertEquals(7, fs4.getNextBlock(6)); + assertEquals(8, fs4.getNextBlock(7)); + assertEquals(9, fs4.getNextBlock(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11)); + // SBAT still unused + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); + + + // Add a bigger Normal Stream + byte[] main5124 = new byte[5124]; + main5124[0] = -22; + main5124[5123] = -33; + testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124)); + + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); + assertEquals(3, fs4.getNextBlock(2)); + assertEquals(4, fs4.getNextBlock(3)); + assertEquals(5, fs4.getNextBlock(4)); + assertEquals(6, fs4.getNextBlock(5)); + assertEquals(7, fs4.getNextBlock(6)); + assertEquals(8, fs4.getNextBlock(7)); + assertEquals(9, fs4.getNextBlock(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); + + assertEquals(11, fs4.getNextBlock(10)); + assertEquals(12, fs4.getNextBlock(11)); + assertEquals(13, fs4.getNextBlock(12)); + assertEquals(14, fs4.getNextBlock(13)); + assertEquals(15, fs4.getNextBlock(14)); + assertEquals(16, fs4.getNextBlock(15)); + assertEquals(17, fs4.getNextBlock(16)); + assertEquals(18, fs4.getNextBlock(17)); + assertEquals(19, fs4.getNextBlock(18)); + assertEquals(20, fs4.getNextBlock(19)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22)); + + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); + + + // Now Add a mini stream + byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; + testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - // Check the data - DirectoryEntry fsRoot = fs2.getRoot(); - assertEquals(1, fsRoot.getEntryCount()); + // Mini stream will get one block for fat + one block for data + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); + assertEquals(3, fs4.getNextBlock(2)); + assertEquals(4, fs4.getNextBlock(3)); + assertEquals(5, fs4.getNextBlock(4)); + assertEquals(6, fs4.getNextBlock(5)); + assertEquals(7, fs4.getNextBlock(6)); + assertEquals(8, fs4.getNextBlock(7)); + assertEquals(9, fs4.getNextBlock(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); + + assertEquals(11, fs4.getNextBlock(10)); + assertEquals(12, fs4.getNextBlock(11)); + assertEquals(13, fs4.getNextBlock(12)); + assertEquals(14, fs4.getNextBlock(13)); + assertEquals(15, fs4.getNextBlock(14)); + assertEquals(16, fs4.getNextBlock(15)); + assertEquals(17, fs4.getNextBlock(16)); + assertEquals(18, fs4.getNextBlock(17)); + assertEquals(19, fs4.getNextBlock(18)); + assertEquals(20, fs4.getNextBlock(19)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23)); + + // Check the mini stream location was set + // (21 is mini fat, 22 is first mini stream block) + assertEquals(22, fs4.getRoot().getProperty().getStartBlock()); + + + // Write and read back + try (POIFSFileSystem fs5 = writeOutAndReadBack(fs4)) { + HeaderBlock header = writeOutAndReadHeader(fs5); + + // Check the header has the right points in it + assertEquals(1, header.getBATCount()); + assertEquals(1, header.getBATArray()[0]); + assertEquals(0, header.getPropertyStart()); + assertEquals(1, header.getSBATCount()); + assertEquals(21, header.getSBATStart()); + assertEquals(22, fs5._get_property_table().getRoot().getStartBlock()); + + // Block use should be almost the same, except the properties + // stream will have grown out to cover 2 blocks + // Check the block use is all unchanged + assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1)); + + assertEquals(3, fs5.getNextBlock(2)); + assertEquals(4, fs5.getNextBlock(3)); + assertEquals(5, fs5.getNextBlock(4)); + assertEquals(6, fs5.getNextBlock(5)); + assertEquals(7, fs5.getNextBlock(6)); + assertEquals(8, fs5.getNextBlock(7)); + assertEquals(9, fs5.getNextBlock(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096 + + assertEquals(11, fs5.getNextBlock(10)); + assertEquals(12, fs5.getNextBlock(11)); + assertEquals(13, fs5.getNextBlock(12)); + assertEquals(14, fs5.getNextBlock(13)); + assertEquals(15, fs5.getNextBlock(14)); + assertEquals(16, fs5.getNextBlock(15)); + assertEquals(17, fs5.getNextBlock(16)); + assertEquals(18, fs5.getNextBlock(17)); + assertEquals(19, fs5.getNextBlock(18)); + assertEquals(20, fs5.getNextBlock(19)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124 + + assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT + assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data + assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2 + assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24)); + + + // Check some data + assertEquals(1, fs5.getRoot().getEntryCount()); + testDir = (DirectoryEntry) fs5.getRoot().getEntry("Test Directory"); + assertEquals(3, testDir.getEntryCount()); + + DocumentEntry miniDoc = (DocumentEntry) testDir.getEntry("Mini"); + assertContentsMatches(mini, miniDoc); + + DocumentEntry normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); + assertContentsMatches(main4096, normDoc); + + normDoc = (DocumentEntry) testDir.getEntry("Normal5124"); + assertContentsMatches(main5124, normDoc); + + + // Delete a couple of streams + miniDoc.delete(); + normDoc.delete(); + + + // Check - will have un-used sectors now + try (POIFSFileSystem fs6 = writeOutAndReadBack(fs5)) { + + assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1)); + + assertEquals(3, fs6.getNextBlock(2)); + assertEquals(4, fs6.getNextBlock(3)); + assertEquals(5, fs6.getNextBlock(4)); + assertEquals(6, fs6.getNextBlock(5)); + assertEquals(7, fs6.getNextBlock(6)); + assertEquals(8, fs6.getNextBlock(7)); + assertEquals(9, fs6.getNextBlock(8)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096 + + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20)); + + assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT + assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25)); + } + } + } - parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory"); - assertEquals(1, parentDir.getEntryCount()); + } - testDir = (DirectoryEntry) parentDir.getEntry("Test Directory"); - assertEquals(2, testDir.getEntryCount()); + @Test + void addBeforeWrite() throws IOException { + try (POIFSFileSystem fs1 = new POIFSFileSystem()) { + + // Initially has Properties + BAT but nothing else + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); + + HeaderBlock hdr = writeOutAndReadHeader(fs1); + // No mini stream, and no xbats + // Will have fat then properties stream + assertEquals(1, hdr.getBATCount()); + assertEquals(1, hdr.getBATArray()[0]); + assertEquals(0, hdr.getPropertyStart()); + assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart()); + assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); + assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 3, fs1.size()); + } - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); + // Get a clean filesystem to start with + try (POIFSFileSystem fs1 = new POIFSFileSystem()) { - normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); + // Put our test files in a non-standard place + DirectoryEntry parentDir = fs1.createDirectory("Parent Directory"); + DirectoryEntry testDir = parentDir.createDirectory("Test Directory"); - // Add one more stream to each, then save and re-load - byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); + // Add to the mini stream + byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42}; + testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - // Add to the main stream - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); + // Add to the main stream + byte[] main4096 = new byte[4096]; + main4096[0] = -10; + main4096[4095] = -11; + testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - // Recheck the data in all 4 streams - POIFSFileSystem fs3 = writeOutAndReadBack(fs2); - fs2.close(); - - fsRoot = fs3.getRoot(); - assertEquals(1, fsRoot.getEntryCount()); - - parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory"); - assertEquals(1, parentDir.getEntryCount()); - - testDir = (DirectoryEntry) parentDir.getEntry("Test Directory"); - assertEquals(4, testDir.getEntryCount()); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - // All done - fs3.close(); + // Check the mini stream was added, then the main stream + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream + assertEquals(5, fs1.getNextBlock(4)); // Main Stream + assertEquals(6, fs1.getNextBlock(5)); + assertEquals(7, fs1.getNextBlock(6)); + assertEquals(8, fs1.getNextBlock(7)); + assertEquals(9, fs1.getNextBlock(8)); + assertEquals(10, fs1.getNextBlock(9)); + assertEquals(11, fs1.getNextBlock(10)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12)); + assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 13, fs1.size()); + + + // Check that we can read the right data pre-write + DocumentEntry miniDoc = (DocumentEntry) testDir.getEntry("Mini"); + assertContentsMatches(mini, miniDoc); + + DocumentEntry normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); + assertContentsMatches(main4096, normDoc); + + + // Write, read, check + HeaderBlock hdr = writeOutAndReadHeader(fs1); + try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) { + // Check the header details - will have the sbat near the start, + // then the properties at the end + assertEquals(1, hdr.getBATCount()); + assertEquals(1, hdr.getBATArray()[0]); + assertEquals(2, hdr.getSBATStart()); + assertEquals(0, hdr.getPropertyStart()); + assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); + + // Check the block allocation is unchanged, other than + // the properties stream going in at the end + assertEquals(12, fs2.getNextBlock(0)); // Properties + assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3)); + assertEquals(5, fs2.getNextBlock(4)); + assertEquals(6, fs2.getNextBlock(5)); + assertEquals(7, fs2.getNextBlock(6)); + assertEquals(8, fs2.getNextBlock(7)); + assertEquals(9, fs2.getNextBlock(8)); + assertEquals(10, fs2.getNextBlock(9)); + assertEquals(11, fs2.getNextBlock(10)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11)); + assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12)); + assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13)); + assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE * 14, fs2.size()); + + + // Check the data + DirectoryEntry fsRoot = fs2.getRoot(); + assertEquals(1, fsRoot.getEntryCount()); + + parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory"); + assertEquals(1, parentDir.getEntryCount()); + + testDir = (DirectoryEntry) parentDir.getEntry("Test Directory"); + assertEquals(2, testDir.getEntryCount()); + + miniDoc = (DocumentEntry) testDir.getEntry("Mini"); + assertContentsMatches(mini, miniDoc); + + normDoc = (DocumentEntry) testDir.getEntry("Normal4096"); + assertContentsMatches(main4096, normDoc); + + + // Add one more stream to each, then save and re-load + byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; + testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); + + // Add to the main stream + byte[] main4106 = new byte[4106]; + main4106[0] = 41; + main4106[4105] = 42; + testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); + + // Recheck the data in all 4 streams + try (POIFSFileSystem fs3 = writeOutAndReadBack(fs2)) { + fsRoot = fs3.getRoot(); + assertEquals(1, fsRoot.getEntryCount()); + + parentDir = (DirectoryEntry) fsRoot.getEntry("Parent Directory"); + assertEquals(1, parentDir.getEntryCount()); + + testDir = (DirectoryEntry) parentDir.getEntry("Test Directory"); + assertEquals(4, testDir.getEntryCount()); + + miniDoc = (DocumentEntry) testDir.getEntry("Mini"); + assertContentsMatches(mini, miniDoc); + + miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); + assertContentsMatches(mini2, miniDoc); + + normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); + assertContentsMatches(main4106, normDoc); + } + } + } } @Test void readZeroLengthEntries() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2")); - DirectoryNode testDir = fs.getRoot(); - assertEquals(3, testDir.getEntryCount()); - DocumentEntry entry; + try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2"))) { + DirectoryNode testDir = fs.getRoot(); + assertEquals(3, testDir.getEntryCount()); - entry = (DocumentEntry) testDir.getEntry("test-zero-1"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); + DocumentEntry entry = (DocumentEntry) testDir.getEntry("test-zero-1"); + assertNotNull(entry); + assertEquals(0, entry.getSize()); - entry = (DocumentEntry) testDir.getEntry("test-zero-2"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); + entry = (DocumentEntry) testDir.getEntry("test-zero-2"); + assertNotNull(entry); + assertEquals(0, entry.getSize()); - entry = (DocumentEntry) testDir.getEntry("test-zero-3"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); + entry = (DocumentEntry) testDir.getEntry("test-zero-3"); + assertNotNull(entry); + assertEquals(0, entry.getSize()); - // Check properties, all have zero length, no blocks - PropertyTable props = fs._get_property_table(); - assertEquals(POIFSConstants.END_OF_CHAIN, props.getRoot().getStartBlock()); - for (Property prop : props.getRoot()) { - assertEquals("test-zero-", prop.getName().substring(0, 10)); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); + // Check properties, all have zero length, no blocks + PropertyTable props = fs._get_property_table(); + assertEquals(POIFSConstants.END_OF_CHAIN, props.getRoot().getStartBlock()); + for (Property prop : props.getRoot()) { + assertEquals("test-zero-", prop.getName().substring(0, 10)); + assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); + } } - - // All done - fs.close(); } @Test void writeZeroLengthEntries() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(); - DirectoryNode testDir = fs1.getRoot(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - DocumentEntry emptyDoc; - - // Add mini and normal sized entries to start - byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); + try (POIFSFileSystem fs1 = new POIFSFileSystem()) { + DirectoryNode testDir = fs1.getRoot(); + DocumentEntry miniDoc; + DocumentEntry normDoc; + DocumentEntry emptyDoc; - // Add to the main stream - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); + // Add mini and normal sized entries to start + byte[] mini2 = new byte[]{-42, 0, -1, -2, -3, -4, -42}; + testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - // Now add some empty ones - byte[] empty = new byte[0]; - testDir.createDocument("empty-1", new ByteArrayInputStream(empty)); - testDir.createDocument("empty-2", new ByteArrayInputStream(empty)); - testDir.createDocument("empty-3", new ByteArrayInputStream(empty)); + // Add to the main stream + byte[] main4106 = new byte[4106]; + main4106[0] = 41; + main4106[4105] = 42; + testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); - // Check - miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); + // Now add some empty ones + byte[] empty = new byte[0]; + testDir.createDocument("empty-1", new ByteArrayInputStream(empty)); + testDir.createDocument("empty-2", new ByteArrayInputStream(empty)); + testDir.createDocument("empty-3", new ByteArrayInputStream(empty)); - normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); + // Check + miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); + assertContentsMatches(mini2, miniDoc); - emptyDoc = (DocumentEntry) testDir.getEntry("empty-1"); - assertContentsMatches(empty, emptyDoc); + normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); + assertContentsMatches(main4106, normDoc); - emptyDoc = (DocumentEntry) testDir.getEntry("empty-2"); - assertContentsMatches(empty, emptyDoc); + emptyDoc = (DocumentEntry) testDir.getEntry("empty-1"); + assertContentsMatches(empty, emptyDoc); - emptyDoc = (DocumentEntry) testDir.getEntry("empty-3"); - assertContentsMatches(empty, emptyDoc); + emptyDoc = (DocumentEntry) testDir.getEntry("empty-2"); + assertContentsMatches(empty, emptyDoc); - // Look at the properties entry, and check the empty ones - // have zero size and no start block - PropertyTable props = fs1._get_property_table(); - Iterator<Property> propsIt = props.getRoot().getChildren(); + emptyDoc = (DocumentEntry) testDir.getEntry("empty-3"); + assertContentsMatches(empty, emptyDoc); - Property prop = propsIt.next(); - assertEquals("Mini2", prop.getName()); - assertEquals(0, prop.getStartBlock()); - assertEquals(7, prop.getSize()); + // Look at the properties entry, and check the empty ones + // have zero size and no start block + PropertyTable props = fs1._get_property_table(); + Iterator<Property> propsIt = props.getRoot().getChildren(); - prop = propsIt.next(); - assertEquals("Normal4106", prop.getName()); - assertEquals(4, prop.getStartBlock()); // BAT, Props, SBAT, MIni - assertEquals(4106, prop.getSize()); + Property prop = propsIt.next(); + assertEquals("Mini2", prop.getName()); + assertEquals(0, prop.getStartBlock()); + assertEquals(7, prop.getSize()); - prop = propsIt.next(); - assertEquals("empty-1", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); + prop = propsIt.next(); + assertEquals("Normal4106", prop.getName()); + assertEquals(4, prop.getStartBlock()); // BAT, Props, SBAT, MIni + assertEquals(4106, prop.getSize()); - prop = propsIt.next(); - assertEquals("empty-2", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); + prop = propsIt.next(); + assertEquals("empty-1", prop.getName()); + assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); + assertEquals(0, prop.getSize()); - prop = propsIt.next(); - assertEquals("empty-3", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); + prop = propsIt.next(); + assertEquals("empty-2", prop.getName()); + assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); + assertEquals(0, prop.getSize()); + prop = propsIt.next(); + assertEquals("empty-3", prop.getName()); + assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); + assertEquals(0, prop.getSize()); - // Save and re-check - POIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - testDir = fs2.getRoot(); - miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); + // Save and re-check + try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) { + testDir = fs2.getRoot(); - normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); + miniDoc = (DocumentEntry) testDir.getEntry("Mini2"); + assertContentsMatches(mini2, miniDoc); - emptyDoc = (DocumentEntry) testDir.getEntry("empty-1"); - assertContentsMatches(empty, emptyDoc); + normDoc = (DocumentEntry) testDir.getEntry("Normal4106"); + assertContentsMatches(main4106, normDoc); - emptyDoc = (DocumentEntry) testDir.getEntry("empty-2"); - assertContentsMatches(empty, emptyDoc); + emptyDoc = (DocumentEntry) testDir.getEntry("empty-1"); + assertContentsMatches(empty, emptyDoc); - emptyDoc = (DocumentEntry) testDir.getEntry("empty-3"); - assertContentsMatches(empty, emptyDoc); + emptyDoc = (DocumentEntry) testDir.getEntry("empty-2"); + assertContentsMatches(empty, emptyDoc); - // Check that a mini-stream was assigned, with one block used - assertEquals(3, testDir.getProperty().getStartBlock()); - assertEquals(64, testDir.getProperty().getSize()); + emptyDoc = (DocumentEntry) testDir.getEntry("empty-3"); + assertContentsMatches(empty, emptyDoc); - // All done - fs2.close(); + // Check that a mini-stream was assigned, with one block used + assertEquals(3, testDir.getProperty().getStartBlock()); + assertEquals(64, testDir.getProperty().getSize()); + } + } } /** @@ -2527,22 +2498,16 @@ final class TestPOIFSStream { @Test void POIFSReadCopyWritePOIFSRead() throws IOException { File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls"); - POIFSFileSystem src = new POIFSFileSystem(testFile); - byte[] wbDataExp = IOUtils.toByteArray(src.createDocumentInputStream("Workbook")); - - POIFSFileSystem nfs = new POIFSFileSystem(); - EntryUtils.copyNodes(src.getRoot(), nfs.getRoot()); - src.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - nfs.writeFilesystem(bos); - nfs.close(); - - POIFSFileSystem pfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - byte[] wbDataAct = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook")); - - assertThat(wbDataExp, equalTo(wbDataAct)); - pfs.close(); + try (POIFSFileSystem src = new POIFSFileSystem(testFile); + POIFSFileSystem nfs = new POIFSFileSystem()) { + byte[] wbDataExp = IOUtils.toByteArray(src.createDocumentInputStream("Workbook")); + EntryUtils.copyNodes(src.getRoot(), nfs.getRoot()); + + try (POIFSFileSystem pfs = writeOutFileAndReadBack(nfs)) { + byte[] wbDataAct = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook")); + assertThat(wbDataExp, equalTo(wbDataAct)); + } + } } /** @@ -2552,31 +2517,28 @@ final class TestPOIFSStream { @Test void RecursiveDelete() throws IOException { File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls"); - POIFSFileSystem src = new POIFSFileSystem(testFile); - - // Starts out with 5 entries: - // _VBA_PROJECT_CUR - // SummaryInformation <(0x05)SummaryInformation> - // DocumentSummaryInformation <(0x05)DocumentSummaryInformation> - // Workbook - // CompObj <(0x01)CompObj> - assertEquals(5, _countChildren(src._get_property_table().getRoot())); - assertEquals(5, src.getRoot().getEntryCount()); - - // Grab the VBA project root - DirectoryEntry vbaProj = (DirectoryEntry) src.getRoot().getEntry("_VBA_PROJECT_CUR"); - assertEquals(3, vbaProj.getEntryCount()); - // Can't delete yet, has stuff - assertFalse(vbaProj.delete()); - // Recursively delete - _recursiveDeletee(vbaProj); - - // Entries gone - assertEquals(4, _countChildren(src._get_property_table().getRoot())); - assertEquals(4, src.getRoot().getEntryCount()); - - // Done - src.close(); + try (POIFSFileSystem src = new POIFSFileSystem(testFile)) { + // Starts out with 5 entries: + // _VBA_PROJECT_CUR + // SummaryInformation <(0x05)SummaryInformation> + // DocumentSummaryInformation <(0x05)DocumentSummaryInformation> + // Workbook + // CompObj <(0x01)CompObj> + assertEquals(5, _countChildren(src._get_property_table().getRoot())); + assertEquals(5, src.getRoot().getEntryCount()); + + // Grab the VBA project root + DirectoryEntry vbaProj = (DirectoryEntry) src.getRoot().getEntry("_VBA_PROJECT_CUR"); + assertEquals(3, vbaProj.getEntryCount()); + // Can't delete yet, has stuff + assertFalse(vbaProj.delete()); + // Recursively delete + _recursiveDeletee(vbaProj); + + // Entries gone + assertEquals(4, _countChildren(src._get_property_table().getRoot())); + assertEquals(4, src.getRoot().getEntryCount()); + } } private void _recursiveDeletee(Entry entry) throws IOException { @@ -2628,82 +2590,80 @@ final class TestPOIFSStream { int s512mb = 512 * 1024 * 1024; long s2gb = 2L * 1024 * 1024 * 1024; DocumentEntry entry; - POIFSFileSystem fs; // Create a just-sub 2gb file - fs = POIFSFileSystem.create(big); - for (int i = 0; i < 19; i++) { - fs.createDocument(new DummyDataInputStream(s100mb), "Entry" + i); + try (POIFSFileSystem fs = POIFSFileSystem.create(big)) { + for (int i = 0; i < 19; i++) { + fs.createDocument(new DummyDataInputStream(s100mb), "Entry" + i); + } + fs.writeFilesystem(); } - fs.writeFilesystem(); - fs.close(); // Extend it past the 2gb mark - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 19; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s100mb, entry.getSize()); - } + try (POIFSFileSystem fs = new POIFSFileSystem(big, false)) { + for (int i = 0; i < 19; i++) { + entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); + assertNotNull(entry); + assertEquals(s100mb, entry.getSize()); + } - fs.createDocument(new DummyDataInputStream(s512mb), "Bigger"); - fs.writeFilesystem(); - fs.close(); + fs.createDocument(new DummyDataInputStream(s512mb), "Bigger"); + fs.writeFilesystem(); + } // Check it still works - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 19; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); + try (POIFSFileSystem fs = new POIFSFileSystem(big, false)) { + for (int i = 0; i < 19; i++) { + entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); + assertNotNull(entry); + assertEquals(s100mb, entry.getSize()); + } + entry = (DocumentEntry) fs.getRoot().getEntry("Bigger"); assertNotNull(entry); - assertEquals(s100mb, entry.getSize()); + assertEquals(s512mb, entry.getSize()); } - entry = (DocumentEntry) fs.getRoot().getEntry("Bigger"); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - // Tidy - fs.close(); assertTrue(big.delete()); // Create a >2gb file - fs = POIFSFileSystem.create(big); - for (int i = 0; i < 4; i++) { - fs.createDocument(new DummyDataInputStream(s512mb), "Entry" + i); + try (POIFSFileSystem fs = POIFSFileSystem.create(big)) { + for (int i = 0; i < 4; i++) { + fs.createDocument(new DummyDataInputStream(s512mb), "Entry" + i); + } + fs.writeFilesystem(); } - fs.writeFilesystem(); - fs.close(); // Read it - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 4; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - } + try (POIFSFileSystem fs = new POIFSFileSystem(big, false)) { + for (int i = 0; i < 4; i++) { + entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); + assertNotNull(entry); + assertEquals(s512mb, entry.getSize()); + } - // Extend it - fs.createDocument(new DummyDataInputStream(s512mb), "Entry4"); - fs.writeFilesystem(); - fs.close(); + // Extend it + fs.createDocument(new DummyDataInputStream(s512mb), "Entry4"); + fs.writeFilesystem(); + } // Check it worked - fs = new POIFSFileSystem(big, false); - for (int i = 0; i < 5; i++) { - entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); + try (POIFSFileSystem fs = new POIFSFileSystem(big, false)) { + for (int i = 0; i < 5; i++) { + entry = (DocumentEntry) fs.getRoot().getEntry("Entry" + i); + assertNotNull(entry); + assertEquals(s512mb, entry.getSize()); + } } - // Tidy - fs.close(); assertTrue(big.delete()); // Create a file with a 2gb entry - fs = POIFSFileSystem.create(big); - fs.createDocument(new DummyDataInputStream(s100mb), "Small"); - // TODO Check we get a helpful error about the max size - fs.createDocument(new DummyDataInputStream(s2gb), "Big"); + try (POIFSFileSystem fs = POIFSFileSystem.create(big)) { + fs.createDocument(new DummyDataInputStream(s100mb), "Small"); + // TODO Check we get a helpful error about the max size + fs.createDocument(new DummyDataInputStream(s2gb), "Big"); + } } private static final class DummyDataInputStream extends InputStream { @@ -2715,16 +2675,19 @@ final class TestPOIFSStream { this.size = 0; } + @Override public int read() { if (size >= maxSize) return -1; size++; return (int) (size % 128); } + @Override public int read(byte[] b) { return read(b, 0, b.length); } + @Override public int read(byte[] b, int offset, int len) { if (size >= maxSize) return -1; int sz = (int) Math.min(len, maxSize - size); @@ -2741,7 +2704,6 @@ final class TestPOIFSStream { void performance() throws Exception { int iterations = 200;//1_000; - System.out.println("NPOI:"); long start = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { @@ -2762,11 +2724,7 @@ final class TestPOIFSStream { } } - System.out.println(); System.out.println("NPOI took: " + (System.currentTimeMillis() - start)); - - System.out.println(); - System.out.println(); } private static void copyAllEntries(DirectoryEntry srcDirectory, DirectoryEntry destDirectory) throws IOException { @@ -2788,5 +2746,4 @@ final class TestPOIFSStream { } } } - } diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPropertySorter.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPropertySorter.java index 29ed3001f0..25e9031828 100644 --- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPropertySorter.java +++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPropertySorter.java @@ -17,17 +17,15 @@ package org.apache.poi.poifs.filesystem; +import static org.apache.poi.POIDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -38,7 +36,7 @@ import org.apache.poi.poifs.property.Property; import org.junit.jupiter.api.Test; /** - * Verify the order of entries <code>DirectoryProperty</code> . + * Verify the order of entries {@code DirectoryProperty} . * <p> * In particular it is important to serialize ROOT._VBA_PROJECT_CUR.VBA node. * See bug 39234 in bugzilla. Thanks to Bill Seddon for providing the solution. @@ -63,28 +61,29 @@ final class TestPropertySorter { } /** - * Test sorting of properties in <code>DirectoryProperty</code> + * Test sorting of properties in {@code DirectoryProperty} */ @Test void testSortProperties() throws IOException { - POIFSFileSystem fs = openSampleFS(); - Property[] props = getVBAProperties(fs); + try (POIFSFileSystem fs = openSampleFS()) { + Property[] props = getVBAProperties(fs); - assertEquals(_entries.length, props.length); + assertEquals(_entries.length, props.length); - // (1). See that there is a problem with the old case-sensitive property comparator - Arrays.sort(props, TestPropertySorter::oldCaseSensitivePropertyCompareTo); + // (1). See that there is a problem with the old case-sensitive property comparator + Arrays.sort(props, TestPropertySorter::oldCaseSensitivePropertyCompareTo); - String exp = String.join("", _entries); - String actOld = Stream.of(props).map(Property::getName).collect(Collectors.joining()); + String exp = String.join("", _entries); + String actOld = Stream.of(props).map(Property::getName).collect(Collectors.joining()); - assertNotEquals("expected old case-sensitive property comparator to return properties in wrong order", exp, actOld); + assertNotEquals("expected old case-sensitive property comparator to return properties in wrong order", exp, actOld); - // (2) Verify that the fixed property comparator works right - Arrays.sort(props, new DirectoryProperty.PropertyComparator()); - String[] actNew = Stream.of(props).map(Property::getName).toArray(String[]::new); + // (2) Verify that the fixed property comparator works right + Arrays.sort(props, new DirectoryProperty.PropertyComparator()); + String[] actNew = Stream.of(props).map(Property::getName).toArray(String[]::new); - assertArrayEquals(_entries, actNew); + assertArrayEquals(_entries, actNew); + } } private static int oldCaseSensitivePropertyCompareTo(Property o1, Property o2) { @@ -99,19 +98,14 @@ final class TestPropertySorter { */ @Test void testSerialization() throws IOException { - POIFSFileSystem fs = openSampleFS(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - out.close(); - InputStream is = new ByteArrayInputStream(out.toByteArray()); - fs = new POIFSFileSystem(is); - is.close(); - Property[] props = getVBAProperties(fs); - Arrays.sort(props, new DirectoryProperty.PropertyComparator()); - - String[] act = Stream.of(props).map(Property::getName).toArray(String[]::new); - assertArrayEquals(_entries, act); + try (POIFSFileSystem fs = openSampleFS(); + POIFSFileSystem fs2 = writeOutAndReadBack(fs)) { + Property[] props = getVBAProperties(fs2); + Arrays.sort(props, new DirectoryProperty.PropertyComparator()); + + String[] act = Stream.of(props).map(Property::getName).toArray(String[]::new); + assertArrayEquals(_entries, act); + } } /** @@ -128,10 +122,9 @@ final class TestPropertySorter { DirectoryProperty p = (DirectoryProperty)vba.getProperty(); List<Property> lst = new ArrayList<>(); - for (Iterator<Property> it = p.getChildren(); it.hasNext();){ - Property ch = it.next(); + for (Property ch : p){ lst.add(ch); } - return lst.toArray(new Property[ 0 ]); + return lst.toArray(new Property[0]); } } diff --git a/poi/src/test/java/org/apache/poi/poifs/property/TestDirectoryProperty.java b/poi/src/test/java/org/apache/poi/poifs/property/TestDirectoryProperty.java index 49b6553012..f3f855fd8d 100644 --- a/poi/src/test/java/org/apache/poi/poifs/property/TestDirectoryProperty.java +++ b/poi/src/test/java/org/apache/poi/poifs/property/TestDirectoryProperty.java @@ -22,13 +22,13 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.storage.RawDataUtil; import org.apache.poi.util.LocaleUtil; import org.junit.jupiter.api.Test; @@ -187,7 +187,7 @@ final class TestDirectoryProperty { } private void verifyProperty() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(512); _property.writeData(stream); byte[] output = stream.toByteArray(); @@ -253,7 +253,7 @@ final class TestDirectoryProperty { private static void verifyReadingProperty(int index, byte[] input, int offset, String name) { DirectoryProperty property = new DirectoryProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(128); byte[] expected = Arrays.copyOfRange(input, offset, offset+128); try { property.writeData(stream); diff --git a/poi/src/test/java/org/apache/poi/poifs/property/TestDocumentProperty.java b/poi/src/test/java/org/apache/poi/poifs/property/TestDocumentProperty.java index 17145cd9db..1bda3ab462 100644 --- a/poi/src/test/java/org/apache/poi/poifs/property/TestDocumentProperty.java +++ b/poi/src/test/java/org/apache/poi/poifs/property/TestDocumentProperty.java @@ -17,14 +17,15 @@ package org.apache.poi.poifs.property; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.poifs.storage.RawDataUtil; @@ -82,15 +83,13 @@ final class TestDocumentProperty { throws IOException { DocumentProperty property = new DocumentProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(128); byte[] expected = Arrays.copyOfRange(input, offset, offset+128); property.writeData(stream); byte[] output = stream.toByteArray(); assertEquals(128, output.length); - for (int j = 0; j < 128; j++) { - assertEquals(expected[ j ], output[ j ], "mismatch at offset " + j); - } + assertArrayEquals(expected, output); assertEquals(index, property.getIndex()); assertEquals(name, property.getName()); } @@ -146,15 +145,10 @@ final class TestDocumentProperty { { testblock[ index * 2 ] = name_bytes[ index ]; } - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(512); property.writeData(stream); byte[] output = stream.toByteArray(); - - assertEquals(testblock.length, output.length); - for (int j = 0; j < testblock.length; j++) - { - assertEquals(testblock[ j ], output[ j ], "mismatch at offset " + j); - } + assertArrayEquals(testblock, output); } } diff --git a/poi/src/test/java/org/apache/poi/poifs/property/TestPropertyTable.java b/poi/src/test/java/org/apache/poi/poifs/property/TestPropertyTable.java index e6ce6610f5..8a59f0f146 100644 --- a/poi/src/test/java/org/apache/poi/poifs/property/TestPropertyTable.java +++ b/poi/src/test/java/org/apache/poi/poifs/property/TestPropertyTable.java @@ -23,7 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -31,6 +30,7 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.poifs.common.POIFSConstants; @@ -45,7 +45,7 @@ import org.junit.jupiter.api.Test; final class TestPropertyTable { private static void confirmBlockEncoding(String expectedDataStr, PropertyTable table) throws IOException { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); byte[] expectedData = RawDataUtil.decompress(expectedDataStr); POIFSStream stream = new POIFSStream(null) { diff --git a/poi/src/test/java/org/apache/poi/poifs/property/TestRootProperty.java b/poi/src/test/java/org/apache/poi/poifs/property/TestRootProperty.java index de51fcefde..04b42eff2e 100644 --- a/poi/src/test/java/org/apache/poi/poifs/property/TestRootProperty.java +++ b/poi/src/test/java/org/apache/poi/poifs/property/TestRootProperty.java @@ -17,13 +17,15 @@ package org.apache.poi.poifs.property; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.poi.hpsf.ClassIDPredefined; import org.apache.poi.poifs.common.POIFSConstants; import org.apache.poi.poifs.storage.RawDataUtil; import org.apache.poi.util.LocaleUtil; @@ -39,7 +41,11 @@ final class TestRootProperty { @Test void testConstructor() throws IOException { createBasicRootProperty(); - verifyProperty(); + + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(512); + _property.writeData(stream); + assertArrayEquals(_testblock, stream.toByteArray()); + } private void createBasicRootProperty() { @@ -77,18 +83,6 @@ final class TestRootProperty { } } - private void verifyProperty() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - _property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(_testblock.length, output.length); - for (int j = 0; j < _testblock.length; j++) { - assertEquals(_testblock[j], output[j], "mismatch at offset " + j); - } - } - @Test void testSetSize() { for (int j = 0; j < 10; j++) { @@ -99,27 +93,21 @@ final class TestRootProperty { } @Test - void testReadingConstructor() { - String[] input = { + void testReadingConstructor() throws IOException { + String[] inputBytes = { "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", }; - verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Root Entry", - "{00020820-0000-0000-C000-000000000046}"); - } + int index = 0; + byte[] input = RawDataUtil.decode(inputBytes); + int offset = 0; - private void verifyReadingProperty(int index, byte[] input, int offset, String name, - String sClsId) { RootProperty property = new RootProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); + UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream(128); byte[] expected = Arrays.copyOfRange(input, offset, offset+128); - try { - property.writeData(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } + property.writeData(stream); byte[] output = stream.toByteArray(); assertEquals(128, output.length); @@ -127,8 +115,8 @@ final class TestRootProperty { assertEquals(expected[j], output[j], "mismatch at offset " + j); } assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - assertFalse(property.getChildren().hasNext()); - assertEquals(property.getStorageClsid().toString(), sClsId); + assertEquals("Root Entry", property.getName()); + assertFalse(property.getChildren().hasNext()); + assertEquals(ClassIDPredefined.EXCEL_V8.getClassID(), property.getStorageClsid()); } } diff --git a/poi/src/test/java/org/apache/poi/poifs/storage/RawDataUtil.java b/poi/src/test/java/org/apache/poi/poifs/storage/RawDataUtil.java index b04741fb06..a349b5bedf 100644 --- a/poi/src/test/java/org/apache/poi/poifs/storage/RawDataUtil.java +++ b/poi/src/test/java/org/apache/poi/poifs/storage/RawDataUtil.java @@ -17,25 +17,25 @@ package org.apache.poi.poifs.storage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import java.util.zip.GZIPInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.HexRead; import org.apache.poi.util.IOUtils; /** * Test utility class.<br> * - * Creates raw <code>byte[]</code> data from hex-dump String arrays. + * Creates raw {@code byte[]} data from hex-dump String arrays. */ public final class RawDataUtil { private RawDataUtil() {} public static byte[] decode(String[] hexDataLines) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(hexDataLines.length * 32 + 32); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(hexDataLines.length * 32 + 32); for (String hexDataLine : hexDataLines) { byte[] lineData = HexRead.readFromString(hexDataLine); @@ -64,7 +64,7 @@ public final class RawDataUtil { * @throws IOException usually not ... */ public static String compress(byte[] data) throws IOException { - java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); java.util.zip.GZIPOutputStream gz = new java.util.zip.GZIPOutputStream(bos); gz.write(data); gz.finish(); diff --git a/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShow.java b/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShow.java index 81f5931f34..0654012411 100644 --- a/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShow.java +++ b/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShow.java @@ -160,17 +160,16 @@ public abstract class BaseTestSlideShow< @Test void shapeAndSlideName() throws IOException { final String file = "SampleShow.ppt"+(getClass().getSimpleName().contains("XML")?"x":""); - //noinspection unchecked try (final InputStream is = slTests.openResourceAsStream(file); - final SlideShow<S,P> ppt = (SlideShow<S,P>)SlideShowFactory.create(is)) { - final List<S> shapes1 = ppt.getSlides().get(0).getShapes(); + final SlideShow<? extends Shape<?,?>,?> ppt = SlideShowFactory.create(is)) { + final List<? extends Shape<?,?>> shapes1 = ppt.getSlides().get(0).getShapes(); assertEquals("The Title", shapes1.get(0).getShapeName()); assertEquals("Another Subtitle", shapes1.get(1).getShapeName()); - final List<S> shapes2 = ppt.getSlides().get(1).getShapes(); + final List<? extends Shape<?,?>> shapes2 = ppt.getSlides().get(1).getShapes(); assertEquals("Title 1", shapes2.get(0).getShapeName()); assertEquals("Content Placeholder 2", shapes2.get(1).getShapeName()); - for (final Slide<S,P> slide : ppt.getSlides()) { + for (final Slide<? extends Shape<?,?>,?> slide : ppt.getSlides()) { final String expected = slide.getSlideNumber()==1 ? "FirstSlide" : "Slide2"; assertEquals(expected, slide.getSlideName()); } diff --git a/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java b/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java index 090aeb0aa8..02d84fac03 100644 --- a/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java +++ b/poi/src/test/java/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java @@ -21,13 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; @@ -133,10 +133,9 @@ public abstract class BaseTestSlideShowFactory { } private static byte[] readExternalFile(String path) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); - try { - InputStream fis = new FileInputStream(path); + try (InputStream fis = new FileInputStream(path)) { byte[] buf = new byte[512]; while (true) { int bytesRead = fis.read(buf); @@ -145,7 +144,6 @@ public abstract class BaseTestSlideShowFactory { } baos.write(buf, 0, bytesRead); } - fis.close(); } catch (final IOException e) { throw new RuntimeException(e); } diff --git a/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java b/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java index bcd8bf272a..5e7b5d87f7 100644 --- a/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java +++ b/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java @@ -32,13 +32,13 @@ import java.awt.font.FontRenderContext; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.AttributedString; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -1817,8 +1817,8 @@ public abstract class BaseTestBugzillaIssues { cell.setCellValue("Ernie & Bert are cool!"); cell.setCellFormula("A1 & \" are cool!\""); - try (ByteArrayOutputStream out1 = new ByteArrayOutputStream(); - ByteArrayOutputStream out2 = new ByteArrayOutputStream()) { + try (UnsynchronizedByteArrayOutputStream out1 = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out2 = new UnsynchronizedByteArrayOutputStream()) { wb.write(out1); wb.write(out2); diff --git a/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestPicture.java b/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestPicture.java index d79e594857..af3c773d00 100644 --- a/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestPicture.java +++ b/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestPicture.java @@ -32,12 +32,12 @@ import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import javax.imageio.ImageIO; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.ITestDataProvider; @@ -272,7 +272,7 @@ public abstract class BaseTestPicture { g.draw(ell); g.dispose(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(2000); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(2000); ImageIO.write(bi, "PNG", bos); return bos.toByteArray(); } diff --git a/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestWorkbook.java b/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestWorkbook.java index 11bb3c9357..a38ec3448f 100644 --- a/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestWorkbook.java +++ b/poi/src/test/java/org/apache/poi/ss/usermodel/BaseTestWorkbook.java @@ -17,6 +17,7 @@ package org.apache.poi.ss.usermodel; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -28,7 +29,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; -import java.io.OutputStream; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -37,7 +37,6 @@ import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.NullOutputStream; import org.junit.jupiter.api.Test; public abstract class BaseTestWorkbook { @@ -775,7 +774,7 @@ public abstract class BaseTestWorkbook { c.setCellStyle(cs); c.setCellValue("AAA"); } - assertDoesNotThrow(() -> workbook.write(new NullOutputStream())); + assertDoesNotThrow(() -> workbook.write(NULL_OUTPUT_STREAM)); } } diff --git a/poi/src/test/java/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java b/poi/src/test/java/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java index c2ef0dfdc1..1676d0daae 100644 --- a/poi/src/test/java/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java +++ b/poi/src/test/java/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java @@ -18,7 +18,6 @@ package org.apache.poi.ss.util; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; @@ -28,6 +27,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; @@ -148,25 +148,20 @@ public class NumberRenderingSpreadsheetGenerator { sw.addTestRow(example.getRawDoubleBits(), example.getExcelRendering()); } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - wb.write(baos); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] fileContent = baos.toByteArray(); - replaceNaNs(fileContent, sw.getReplacementNaNs()); + File outputFile = new File("ExcelNumberRendering.xls"); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + FileOutputStream os = new FileOutputStream(outputFile)) { + wb.write(baos); - File outputFile = new File("ExcelNumberRendering.xls"); + byte[] fileContent = baos.toByteArray(); + replaceNaNs(fileContent, sw.getReplacementNaNs()); - try { - FileOutputStream os = new FileOutputStream(outputFile); os.write(fileContent); - os.close(); } catch (IOException e) { throw new RuntimeException(e); } + System.out.println("Finished writing '" + outputFile.getAbsolutePath() + "'"); } diff --git a/poi/src/test/java/org/apache/poi/ss/util/TestCellRangeAddress.java b/poi/src/test/java/org/apache/poi/ss/util/TestCellRangeAddress.java index 01d12f41c3..033fb5f179 100644 --- a/poi/src/test/java/org/apache/poi/ss/util/TestCellRangeAddress.java +++ b/poi/src/test/java/org/apache/poi/ss/util/TestCellRangeAddress.java @@ -25,11 +25,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hssf.record.TestcaseRecordInputStream; import org.apache.poi.util.LittleEndianOutputStream; import org.junit.jupiter.api.Test; @@ -64,7 +64,7 @@ final class TestCellRangeAddress { CellRangeAddress ref = new CellRangeAddress(0, 0, 0, 0); byte[] recordBytes; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) { // With nothing set ref.serialize(out); @@ -100,7 +100,7 @@ final class TestCellRangeAddress { } @Test - void testCopy() throws IOException { + void testCopy() { CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); CellRangeAddress copy = ref.copy(); assertEquals(ref.toString(), copy.toString()); diff --git a/poi/src/test/java/org/apache/poi/ss/util/TestDateFormatConverter.java b/poi/src/test/java/org/apache/poi/ss/util/TestDateFormatConverter.java index befe219a16..0faf865e5a 100644 --- a/poi/src/test/java/org/apache/poi/ss/util/TestDateFormatConverter.java +++ b/poi/src/test/java/org/apache/poi/ss/util/TestDateFormatConverter.java @@ -22,6 +22,7 @@ package org.apache.poi.ss.util; import static java.text.DateFormat.getDateInstance; import static java.text.DateFormat.getDateTimeInstance; import static java.text.DateFormat.getTimeInstance; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.ss.util.DateFormatConverter.getPrefixForLocale; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -50,7 +51,6 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.LocaleID; -import org.apache.poi.util.NullOutputStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -122,7 +122,7 @@ final class TestDateFormatConverter { cell[6].setCellValue(excelFormatPattern); } - assertDoesNotThrow(() -> workbook.write(new NullOutputStream())); + assertDoesNotThrow(() -> workbook.write(NULL_OUTPUT_STREAM)); } } diff --git a/poi/src/test/java/org/apache/poi/util/NullOutputStream.java b/poi/src/test/java/org/apache/poi/util/NullOutputStream.java deleted file mode 100644 index ac76123a3c..0000000000 --- a/poi/src/test/java/org/apache/poi/util/NullOutputStream.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.OutputStream; - -/** - * Implementation of an OutputStream which does nothing, used - * to redirect stdout to avoid spamming the console with output - */ -public final class NullOutputStream extends OutputStream { - public NullOutputStream() { - } - - @Override - public void write(byte[] b, int off, int len) { - } - - @Override - public void write(int b) { - } - - @Override - public void write(byte[] b) { - } -} diff --git a/poi/src/test/java/org/apache/poi/util/NullPrintStream.java b/poi/src/test/java/org/apache/poi/util/NullPrintStream.java deleted file mode 100644 index 5fd6bc64ad..0000000000 --- a/poi/src/test/java/org/apache/poi/util/NullPrintStream.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.PrintStream; -import java.util.Locale; - -// need to override all methods to omit calls to UTF-handling methods -@SuppressForbidden("ignore super constructor with charset - omits declaring UnsupportedEncodingException") -public class NullPrintStream extends PrintStream { - @SuppressWarnings("resource") - public NullPrintStream() { - super(new NullOutputStream(), true); - } - @Override - public void write(int b) {} - @Override - public void write(byte[] buf, int off, int len) {} - @Override - public void print(boolean b) {} - @Override - public void print(char c) {} - @Override - public void print(int i) {} - @Override - public void print(long l) {} - @Override - public void print(float f) {} - @Override - public void print(double d) {} - @Override - public void print(char[] s) {} - @Override - public void print(String s) {} - @Override - public void print(Object obj) {} - @Override - public void println() {} - @Override - public void println(boolean x) {} - @Override - public void println(char x) {} - @Override - public void println(int x) {} - @Override - public void println(long x) {} - @Override - public void println(float x) {} - @Override - public void println(double x) {} - @Override - public void println(char[] x) {} - @Override - public void println(String x) {} - @Override - public void println(Object x) {} - @Override - public PrintStream printf(String format, Object... args) { return this; } - @Override - public PrintStream printf(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream format(String format, Object... args) { return this; } - @Override - public PrintStream format(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream append(CharSequence csq) { return this; } - @Override - public PrintStream append(CharSequence csq, int start, int end) { return this; } - @Override - public PrintStream append(char c) { return this; } - @Override - public void write(byte[] b) {} -} diff --git a/poi/src/test/java/org/apache/poi/util/TestHexDump.java b/poi/src/test/java/org/apache/poi/util/TestHexDump.java index 4a465cb4be..70ce3ab333 100644 --- a/poi/src/test/java/org/apache/poi/util/TestHexDump.java +++ b/poi/src/test/java/org/apache/poi/util/TestHexDump.java @@ -22,11 +22,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; +import org.apache.commons.io.output.NullPrintStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -51,7 +52,7 @@ class TestHexDump { @Test void testDump() throws IOException { byte[] testArray = testArray(); - ByteArrayOutputStream streamAct = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream streamAct = new UnsynchronizedByteArrayOutputStream(); HexDump.dump(testArray, 0, streamAct, 0); byte[] bytesAct = streamAct.toByteArray(); byte[] bytesExp = toHexDump(0, 0); diff --git a/poi/src/test/java/org/apache/poi/util/TestIOUtils.java b/poi/src/test/java/org/apache/poi/util/TestIOUtils.java index d09dc5912e..54e45ae557 100644 --- a/poi/src/test/java/org/apache/poi/util/TestIOUtils.java +++ b/poi/src/test/java/org/apache/poi/util/TestIOUtils.java @@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; @@ -39,6 +38,7 @@ import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.util.Random; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.EmptyFileException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -161,20 +161,20 @@ final class TestIOUtils { @Test void testSkipFullyByteArray() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (InputStream is = new FileInputStream(TMP)) { assertEquals(LENGTH, IOUtils.copy(is, bos)); - long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), 20000L); + long skipped = IOUtils.skipFully(bos.toInputStream(), 20000L); assertEquals(LENGTH, skipped); } } @Test void testSkipFullyByteArrayGtIntMax() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try (InputStream is = new FileInputStream(TMP)) { assertEquals(LENGTH, IOUtils.copy(is, bos)); - long skipped = IOUtils.skipFully(new ByteArrayInputStream(bos.toByteArray()), Integer.MAX_VALUE + 20000L); + long skipped = IOUtils.skipFully(bos.toInputStream(), Integer.MAX_VALUE + 20000L); assertEquals(LENGTH, skipped); } } diff --git a/poi/src/test/java/org/apache/poi/util/TestLittleEndianStreams.java b/poi/src/test/java/org/apache/poi/util/TestLittleEndianStreams.java index 54ebefa5b5..dcb89d5a35 100644 --- a/poi/src/test/java/org/apache/poi/util/TestLittleEndianStreams.java +++ b/poi/src/test/java/org/apache/poi/util/TestLittleEndianStreams.java @@ -23,10 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -36,7 +35,7 @@ final class TestLittleEndianStreams { @Test void testRead() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try (LittleEndianOutputStream leo = new LittleEndianOutputStream(baos)) { leo.writeInt(12345678); leo.writeShort(12345); @@ -47,7 +46,7 @@ final class TestLittleEndianStreams { leo.writeDouble(123.456); } - try (LittleEndianInputStream lei = new LittleEndianInputStream(new ByteArrayInputStream(baos.toByteArray()))) { + try (LittleEndianInputStream lei = new LittleEndianInputStream(baos.toInputStream())) { assertEquals(12345678, lei.readInt()); assertEquals(12345, lei.readShort()); assertEquals(123, lei.readByte()); diff --git a/poi/src/test/java/org/apache/poi/util/TestRLEDecompressingInputStream.java b/poi/src/test/java/org/apache/poi/util/TestRLEDecompressingInputStream.java index 219e1460b1..0c8fad889e 100644 --- a/poi/src/test/java/org/apache/poi/util/TestRLEDecompressingInputStream.java +++ b/poi/src/test/java/org/apache/poi/util/TestRLEDecompressingInputStream.java @@ -21,11 +21,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; class TestRLEDecompressingInputStream { @@ -55,7 +54,7 @@ class TestRLEDecompressingInputStream { * */ @Test - void noCompressionExample() { + void noCompressionExample() throws IOException { final byte[] compressed = { 0x01, 0x19, (byte)0xB0, 0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x00, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x00, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x2E @@ -92,7 +91,7 @@ class TestRLEDecompressingInputStream { * 76 77 78 79 7A 61 61 61 */ @Test - void normalCompressionExample() { + void normalCompressionExample() throws IOException { final byte[] compressed = { 0x01, 0x2F, (byte)0xB0, 0x00, 0x23, 0x61, 0x61, 0x61, 0x62, 0x63, 0x64, 0x65, (byte)0x82, 0x66, 0x00, 0x70, 0x61, 0x67, 0x68, 0x69, 0x6A, 0x01, 0x38, 0x08, 0x61, 0x6B, 0x6C, 0x00, 0x30, 0x6D, 0x6E, 0x6F, @@ -129,7 +128,7 @@ class TestRLEDecompressingInputStream { * 61 61 61 61 61 61 61 61 61 */ @Test - void maximumCompressionExample() { + void maximumCompressionExample() throws IOException { final byte[] compressed = { 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 }; @@ -147,26 +146,13 @@ class TestRLEDecompressingInputStream { assertArrayEquals(expected, expanded); } - private static void checkRLEDecompression(String expected, byte[] runLengthEncodedData) { + private static void checkRLEDecompression(String expected, byte[] runLengthEncodedData) throws IOException { InputStream compressedStream = new ByteArrayInputStream(runLengthEncodedData); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - InputStream stream = new RLEDecompressingInputStream(compressedStream); - try { - IOUtils.copy(stream, out); - } finally { - out.close(); - stream.close(); - } - } catch (final IOException e) { - throw new RuntimeException(e); - } - String expanded; - try { - expanded = out.toString(StringUtil.UTF8.name()); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException(e); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + try (InputStream stream = new RLEDecompressingInputStream(compressedStream)) { + IOUtils.copy(stream, out); } + String expanded = out.toString(StringUtil.UTF8); assertEquals(expected, expanded); } } diff --git a/sonar/main/pom.xml b/sonar/main/pom.xml index d5c2aeefa7..b8b44e301a 100644 --- a/sonar/main/pom.xml +++ b/sonar/main/pom.xml @@ -124,6 +124,11 @@ <version>3.6.1</version> </dependency> <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>2.8.0</version> + </dependency> + <dependency> <groupId>com.zaxxer</groupId> <artifactId>SparseBitSet</artifactId> <version>1.2</version> |