#65304 - Add commons-io as a dependency

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1889871 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Andreas Beeker 2021-05-14 00:37:50 +00:00
parent fe753d4737
commit 0614835c55
288 changed files with 7857 additions and 8834 deletions

View File

@ -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")

View File

@ -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}" />

View File

@ -76,6 +76,11 @@
<artifactId>commons-math3</artifactId>
<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>

View File

@ -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

View File

@ -101,6 +101,7 @@
SparseBitSet,
curvesapi,
commons-math3,
commons-io,
commons-compress,
commons-collections4,
commons-codec,

View File

@ -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();

View File

@ -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());

View File

@ -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");

View File

@ -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);

View File

@ -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;

View File

@ -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);
}
}

View File

@ -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);
}

View File

@ -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;

View File

@ -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));
}

View File

@ -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 {

View File

@ -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

View File

@ -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();

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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);
}
}

View File

@ -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 {

View File

@ -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;
}

View File

@ -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

View File

@ -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.

View File

@ -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);

View File

@ -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);

View File

@ -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();
}

View File

@ -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) {
/*

View File

@ -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 {

View File

@ -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) {

View File

@ -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;
}
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);
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);
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();

View File

@ -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);

View File

@ -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) {
}

View File

@ -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;
}

View File

@ -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){

View File

@ -17,7 +17,6 @@
package org.apache.poi.xssf.usermodel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ -65,9 +64,6 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
super(drawing, ctShape);
}
/**
* Prototype with the default structure of a new auto-shape.
*/
/**
* Prototype with the default structure of a new auto-shape.
*/
@ -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();
}

View File

@ -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

View File

@ -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();
}

View File

@ -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;
}

View File

@ -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);
int idx = outputFileName.lastIndexOf('.');
return TempFile.createTempFile(outputFileName.substring(0,idx), outputFileName.substring(idx));
}
public static InputStream openComplianceSampleStream(String sampleFileName) {
return _samples.openResourceAsStream(sampleFileName);
}
}

View File

@ -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!"));
}

View File

@ -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();
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());
// 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());
// 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();
// 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();
try (OPCPackage pkg1 = OPCPackage.open(openSampleStream("51444.xlsx"))) {
PackageProperties props1 = pkg1.getPackageProperties();
assertFalse(props1.getTitleProperty().isPresent());
props1.setTitleProperty("Bug 51444 fixed");
pkg1.save(out);
}
OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()));
PackageProperties props2 = pkg2.getPackageProperties();
props2.setTitleProperty("Bug 51444 fixed");
pkg2.close();
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());
UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx");
OPCPackage pkg1 = OPCPackage.open(is)) {
PackagePropertiesPart props1 = (PackagePropertiesPart) pkg1.getPackageProperties();
// 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()));
// Check text properties first
assertEquals("Lorem Ipsum", props1.getTitleProperty().orElse(null));
assertEquals("Apache POI", props1.getCreatorProperty().orElse(null));
// 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()));
// 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)));
// 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)));
// 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");
// 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");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pkg.save(baos);
pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()));
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", props.getTitleProperty().get());
assertEquals("Apache POI", props.getCreatorProperty().get());
// 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(props.getCreatedProperty().get()));
// 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
assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().get()));
// 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)));
}
}
}

View File

@ -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");

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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) {

View File

@ -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");

View File

@ -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());
boolean b = si.verifySignature();
assertTrue(b, "test-file: " + testFile);
pkg.revert();
}
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();
}
}
@ -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());

View File

@ -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");

View File

@ -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) {

View File

@ -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);
}
}

View File

@ -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());

View File

@ -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);

View File

@ -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);

View File

@ -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);
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);
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);
// 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);
// 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();
// 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();
}
}
}

View File

@ -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();

File diff suppressed because it is too large Load Diff

View File

@ -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);
}
}
}
}

View File

@ -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);
try (XMLSlideShow xml = new XMLSlideShow(pack)) {
assertNull(xml.getCommentAuthors());
assertNull(xml.getCommentAuthors());
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());
for (XSLFSlide slide : xml.getSlides()) {
assertTrue(slide.getComments().isEmpty());
}
}
xmlComments.close();
xml.close();
// Try another with comments
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());
}
}
}
}
@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);
}
}

View File

@ -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;

View File

@ -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());
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());
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());
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());
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());
ppt2.close();
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();
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());
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());
}
// 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());
}
}
}
// 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());
}
// serialize, read back and check that all images are there
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());
}
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());
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());
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();
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();
try (XMLSlideShow ppt = openSampleDocument("shapes.pptx")) {
XSLFSlide slide = ppt.getSlides().get(0);
XSLFPictureShape ps = (XSLFPictureShape) slide.getShapes().get(3);
slide.removeShape(ps);
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();
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);
try (XMLSlideShow slideShow = new XMLSlideShow();
InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif")) {
final byte[] pictureData = IOUtils.toByteArray(tiffStream);
XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF);
assertEquals("image/tiff", pic.getContentType());
assertEquals("image1.tiff", pic.getFileName());
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");
}
}
}
}

View File

@ -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());

View File

@ -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

View File

@ -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);
}

View File

@ -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

View File

@ -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));
}
}

View File

@ -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 */
}
}

View File

@ -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());

View File

@ -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");
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
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());
wb1.close();
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
@SuppressWarnings("resource")
XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
assertEquals(3, wb2.getNumberOfSheets());
assertNotNull(wb2.getSheetAt(0));
assertNotNull(wb2.getSheetAt(1));
assertNotNull(wb2.getSheetAt(2));
// 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());
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());
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();
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
PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
// 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());
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");
try (XSSFWorkbook wb1 = openSampleWorkbook("Formatting.xlsx")) {
StylesTable ss = wb1.getStylesSource();
assertNotNull(ss);
StylesTable st = ss;
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());
// 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,
// 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();
// Save, load back in again, and check
try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
ss = wb2.getStylesSource();
assertNotNull(ss);
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());
}
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();
}
/**
@ -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());
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 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();
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());
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));
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());
wb1.removeSheetAt(2);
assertEquals(2, wb1.getNumberOfSheets());
assertNull(wb1.getCalculationChain());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
assertEquals(2, wb2.getNumberOfSheets());
assertNull(wb2.getCalculationChain());
try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
assertEquals(2, wb2.getNumberOfSheets());
assertNull(wb2.getCalculationChain());
assertEquals("Numbers", wb2.getSheetName(0));
assertEquals("Chart", wb2.getSheetName(1));
wb2.close();
wb1.close();
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");
try (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);
sheet = workbook.createSheet();
sheet.setColumnWidth(4, 5000);
sheet.setColumnWidth(5, 5000);
sheet.groupColumn((short) 4, (short) 5);
sheet.groupColumn((short) 4, (short) 5);
accessWorkbook(workbook);
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");
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);
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);
assertSheetOrder(wb, "Sheet1", "Sheet1 (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));
// 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");
// 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);
// 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());
wb3.close();
wb2.close();
wb1.close();
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);
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
@SuppressWarnings("resource")
XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
assertEquals(1, wb2.getNumberOfSheets());
assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType());
pkg.close();
// 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");

View File

@ -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);
}
}
}

View File

@ -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 {

View File

@ -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());
}
}
}
}
}

View File

@ -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);
}
}

View File

@ -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();
try (XWPFDocument document = new XWPFDocument()) {
final XWPFRun run = document.createParagraph().createRun();
final XWPFRun run = document.createParagraph().createRun();
assertEquals(-1, run.getFontSize());
assertEquals(-1, run.getFontSize());
run.setFontSize(10);
assertEquals(10, run.getFontSize());
run.setFontSize(10);
assertEquals(10, 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(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(Integer.MAX_VALUE-1);
assertEquals(Integer.MAX_VALUE-1, run.getFontSize());
run.setFontSize(Integer.MAX_VALUE - 1);
assertEquals(Integer.MAX_VALUE - 1, run.getFontSize());
run.setFontSize(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, run.getFontSize());
run.setFontSize(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, run.getFontSize());
run.setFontSize(-1);
assertEquals(-1, run.getFontSize());
run.setFontSize(-1);
assertEquals(-1, run.getFontSize());
assertEquals(-1, run.getTextPosition());
assertEquals(-1, run.getTextPosition());
run.setTextPosition(10);
assertEquals(10, run.getTextPosition());
run.setTextPosition(10);
assertEquals(10, 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);
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+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(Integer.MAX_VALUE - 1);
assertEquals(Integer.MAX_VALUE - 1, run.getTextPosition());
run.setTextPosition(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, run.getTextPosition());
run.setTextPosition(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, run.getTextPosition());
run.setTextPosition(-1);
assertEquals(-1, run.getTextPosition());
document.close();
run.setTextPosition(-1);
assertEquals(-1, run.getTextPosition());
}
}
@Test
void testSetters() {
XWPFDocument document = new XWPFDocument();
final XWPFRun run = document.createParagraph().createRun();
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);
// 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();
try (XWPFDocument document = 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);
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);
assertEquals(styleId, run.getStyle());
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());
}
}
}
}

View File

@ -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();
}

View File

@ -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;

View File

@ -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());

View File

@ -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;
}

View File

@ -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());

View File

@ -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);

View File

@ -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");
}
}
}
}

View File

@ -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();
}

View File

@ -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:

View File

@ -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:

View File

@ -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;

View File

@ -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();
}

View File

@ -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();

View File

@ -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();
}

View File

@ -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));

View File

@ -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) {

View File

@ -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");
}
}
}
}

View File

@ -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);

View File

@ -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();

View File

@ -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;
}

View File

@ -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";
}

View File

@ -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(){

Some files were not shown because too many files have changed in this diff Show More