aboutsummaryrefslogtreecommitdiffstats
path: root/poi-ooxml
diff options
context:
space:
mode:
authorAndreas Beeker <kiwiwings@apache.org>2021-05-14 00:37:50 +0000
committerAndreas Beeker <kiwiwings@apache.org>2021-05-14 00:37:50 +0000
commit0614835c55f44ab6f3e9b0850ca51e0e53a65a49 (patch)
tree586c68c89edb0978a441facf0066ff56d84fa2c7 /poi-ooxml
parentfe753d473788fc24030d7066654c56c33fff23b5 (diff)
downloadpoi-0614835c55f44ab6f3e9b0850ca51e0e53a65a49.tar.gz
poi-0614835c55f44ab6f3e9b0850ca51e0e53a65a49.zip
#65304 - Add commons-io as a dependency
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1889871 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'poi-ooxml')
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java10
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java12
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java9
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java99
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java14
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java8
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java8
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java8
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java13
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java8
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java71
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java11
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java11
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java2
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java4
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java28
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java13
-rw-r--r--poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java99
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java8
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java16
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java32
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java306
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java35
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java16
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java30
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java9
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java10
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java180
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java7
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java4
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java38
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java35
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java9
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java7
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java89
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java8
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java922
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java40
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java172
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java2
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java362
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java29
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java13
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java4
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java33
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java36
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java40
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java59
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java35
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java2002
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java4
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java26
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java706
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java27
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java8
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java18
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java11
-rw-r--r--poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java399
58 files changed, 2925 insertions, 3290 deletions
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java
index 9c92fb5f3e..70b50e4d63 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/OPCPackage.java
@@ -898,16 +898,12 @@ public abstract class OPCPackage implements RelationshipSource, Closeable {
}
// Extract the zip entry content to put it in the part content
if (content != null) {
- try {
- OutputStream partOutput = addedPart.getOutputStream();
+ try (OutputStream partOutput = addedPart.getOutputStream()) {
if (partOutput == null) {
return null;
}
-
- partOutput.write(content.toByteArray(), 0, content.size());
- partOutput.close();
-
- } catch (IOException ioe) {
+ content.writeTo(partOutput);
+ } catch (IOException ignored) {
return null;
}
} else {
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java
index 0df7364903..c4ab456fd8 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java
@@ -18,11 +18,11 @@
package org.apache.poi.openxml4j.opc.internal;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
@@ -113,17 +113,15 @@ public final class MemoryPackagePart extends PackagePart {
@Override
public boolean load(InputStream ios) throws InvalidFormatException {
- // Grab the data
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try {
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
+ // Grab the data
IOUtils.copy(ios, baos);
+ // Save it
+ data = baos.toByteArray();
} catch(IOException e) {
throw new InvalidFormatException(e.getMessage());
}
- // Save it
- data = baos.toByteArray();
-
// All done
return true;
}
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java
index 5cd07238e3..7fce830721 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java
@@ -17,22 +17,23 @@
package org.apache.poi.openxml4j.opc.internal;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+
/**
* Build an output stream for MemoryPackagePart.
*/
public final class MemoryPackagePartOutputStream extends OutputStream {
- private MemoryPackagePart _part;
+ private final MemoryPackagePart _part;
- private ByteArrayOutputStream _buff;
+ private final UnsynchronizedByteArrayOutputStream _buff;
public MemoryPackagePartOutputStream(MemoryPackagePart part) {
this._part = part;
- _buff = new ByteArrayOutputStream();
+ _buff = new UnsynchronizedByteArrayOutputStream();
}
@Override
diff --git a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java
index 0658a03c6d..d6a625baeb 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java
@@ -202,8 +202,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get the category property.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getCategoryProperty()
*/
+ @Override
public Optional<String> getCategoryProperty() {
return category;
}
@@ -211,8 +211,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get content status.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentStatusProperty()
*/
+ @Override
public Optional<String> getContentStatusProperty() {
return contentStatus;
}
@@ -220,8 +220,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get content type.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentTypeProperty()
*/
+ @Override
public Optional<String> getContentTypeProperty() {
return contentType;
}
@@ -229,8 +229,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get created date.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatedProperty()
*/
+ @Override
public Optional<Date> getCreatedProperty() {
return created;
}
@@ -247,8 +247,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get creator.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatorProperty()
*/
+ @Override
public Optional<String> getCreatorProperty() {
return creator;
}
@@ -256,8 +256,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get description.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getDescriptionProperty()
*/
+ @Override
public Optional<String> getDescriptionProperty() {
return description;
}
@@ -265,8 +265,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get identifier.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getIdentifierProperty()
*/
+ @Override
public Optional<String> getIdentifierProperty() {
return identifier;
}
@@ -274,8 +274,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get keywords.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getKeywordsProperty()
*/
+ @Override
public Optional<String> getKeywordsProperty() {
return keywords;
}
@@ -283,8 +283,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get the language.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getLanguageProperty()
*/
+ @Override
public Optional<String> getLanguageProperty() {
return language;
}
@@ -292,8 +292,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get the author of last modifications.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastModifiedByProperty()
*/
+ @Override
public Optional<String> getLastModifiedByProperty() {
return lastModifiedBy;
}
@@ -301,8 +301,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get last printed date.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastPrintedProperty()
*/
+ @Override
public Optional<Date> getLastPrintedProperty() {
return lastPrinted;
}
@@ -319,8 +319,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get modified date.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getModifiedProperty()
*/
+ @Override
public Optional<Date> getModifiedProperty() {
return modified;
}
@@ -340,8 +340,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get revision.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getRevisionProperty()
*/
+ @Override
public Optional<String> getRevisionProperty() {
return revision;
}
@@ -349,8 +349,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get subject.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getSubjectProperty()
*/
+ @Override
public Optional<String> getSubjectProperty() {
return subject;
}
@@ -358,8 +358,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get title.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getTitleProperty()
*/
+ @Override
public Optional<String> getTitleProperty() {
return title;
}
@@ -367,8 +367,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Get version.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#getVersionProperty()
*/
+ @Override
public Optional<String> getVersionProperty() {
return version;
}
@@ -376,8 +376,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the category.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.lang.String)
*/
+ @Override
public void setCategoryProperty(String category) {
this.category = setStringValue(category);
}
@@ -385,15 +385,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the category.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.util.Optional)
*/
+ @Override
public void setCategoryProperty(Optional<String> category) { this.category = category; }
/**
* Set the content status.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.lang.String)
*/
+ @Override
public void setContentStatusProperty(String contentStatus) {
this.contentStatus = setStringValue(contentStatus);
}
@@ -401,15 +401,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the content status.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.util.Optional)
*/
+ @Override
public void setContentStatusProperty(Optional<String> contentStatus) { this.contentStatus = contentStatus; }
/**
* Set the content type.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.lang.String)
*/
+ @Override
public void setContentTypeProperty(String contentType) {
this.contentType = setStringValue(contentType);
}
@@ -417,8 +417,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the content type.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.util.Optional)
*/
+ @Override
public void setContentTypeProperty(Optional<String> contentType) { this.contentType = contentType; }
/**
@@ -426,6 +426,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
*
* @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(java.util.Optional)
*/
+ @Override
public void setCreatedProperty(String created) {
try {
this.created = setDateValue(created);
@@ -437,8 +438,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the created date.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(java.util.Optional)
*/
+ @Override
public void setCreatedProperty(Optional<Date> created) {
if (created.isPresent())
this.created = created;
@@ -447,8 +448,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the creator.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.lang.String)
*/
+ @Override
public void setCreatorProperty(String creator) {
this.creator = setStringValue(creator);
}
@@ -456,15 +457,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the creator.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.util.Optional)
*/
+ @Override
public void setCreatorProperty(Optional<String> creator) { this.creator = creator; }
/**
* Set the description.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.lang.String)
*/
+ @Override
public void setDescriptionProperty(String description) {
this.description = setStringValue(description);
}
@@ -472,15 +473,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set the description.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.util.Optional)
*/
+ @Override
public void setDescriptionProperty(Optional<String> description) { this.description = description; }
/**
* Set identifier.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.lang.String)
*/
+ @Override
public void setIdentifierProperty(String identifier) {
this.identifier = setStringValue(identifier);
}
@@ -488,15 +489,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set identifier.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.util.Optional)
*/
+ @Override
public void setIdentifierProperty(Optional<String> identifier) { this.identifier = identifier; }
/**
* Set keywords.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.lang.String)
*/
+ @Override
public void setKeywordsProperty(String keywords) {
this.keywords = setStringValue(keywords);
}
@@ -504,15 +505,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set keywords.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.util.Optional)
*/
+ @Override
public void setKeywordsProperty(Optional<String> keywords) { this.keywords = keywords; }
/**
* Set language.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.lang.String)
*/
+ @Override
public void setLanguageProperty(String language) {
this.language = setStringValue(language);
}
@@ -520,15 +521,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set language.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.util.Optional)
*/
+ @Override
public void setLanguageProperty(Optional<String> language) { this.language = language; }
/**
* Set last modifications author.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.lang.String)
*/
+ @Override
public void setLastModifiedByProperty(String lastModifiedBy) {
this.lastModifiedBy = setStringValue(lastModifiedBy);
}
@@ -536,8 +537,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set last modifications author.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.util.Optional)
*/
+ @Override
public void setLastModifiedByProperty(Optional<String> lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
@@ -547,6 +548,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
*
* @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(java.util.Optional)
*/
+ @Override
public void setLastPrintedProperty(String lastPrinted) {
try {
this.lastPrinted = setDateValue(lastPrinted);
@@ -559,8 +561,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set last printed date.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(java.util.Optional)
*/
+ @Override
public void setLastPrintedProperty(Optional<Date> lastPrinted) {
if (lastPrinted.isPresent())
this.lastPrinted = lastPrinted;
@@ -571,6 +573,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
*
* @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(java.util.Optional)
*/
+ @Override
public void setModifiedProperty(String modified) {
try {
this.modified = setDateValue(modified);
@@ -583,8 +586,8 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set last modification date.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(java.util.Optional)
*/
+ @Override
public void setModifiedProperty(Optional<Date> modified) {
if (modified.isPresent())
this.modified = modified;
@@ -593,23 +596,23 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set revision.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.util.Optional)
*/
+ @Override
public void setRevisionProperty(Optional<String> revision) { this.revision = revision; }
/**
* Set revision.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.lang.String)
*/
+ @Override
public void setRevisionProperty(String revision) {
this.revision = setStringValue(revision);
}
/**
* Set subject.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.lang.String)
*/
+ @Override
public void setSubjectProperty(String subject) {
this.subject = setStringValue(subject);
}
@@ -617,15 +620,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set subject.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.util.Optional)
*/
+ @Override
public void setSubjectProperty(Optional<String> subject) { this.subject = subject; }
/**
* Set title.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.lang.String)
*/
+ @Override
public void setTitleProperty(String title) {
this.title = setStringValue(title);
}
@@ -633,15 +636,15 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set title.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.util.Optional)
*/
+ @Override
public void setTitleProperty(Optional<String> title) { this.title = title; }
/**
* Set version.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.lang.String)
*/
+ @Override
public void setVersionProperty(String version) {
this.version = setStringValue(version);
}
@@ -649,12 +652,12 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
/**
* Set version.
*
- * @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.util.Optional)
*/
+ @Override
public void setVersionProperty(Optional<String> version) { this.version = version; }
/**
- * Convert a string value into a Optional<String>
+ * Convert a string value into a {@code Optional<String>}
*/
private Optional<String> setStringValue(String s) {
if (s == null || s.isEmpty()) {
@@ -664,7 +667,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
}
/**
- * Convert a string value represented a date into a Optional<Date>.
+ * Convert a string value represented a date into a {@code Optional<Date>}
*
* @throws InvalidFormatException
* Throws if the date format isnot valid.
@@ -707,7 +710,7 @@ public final class PackagePropertiesPart extends PackagePart implements PackageP
}
/**
- * Convert a Optional<Date> into a String.
+ * Convert a {@code Optional<Date>} into a String.
*
* @param d
* The Date to convert.
diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java
index f8ad4a33e5..35e0f4924a 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/DigestOutputStream.java
@@ -17,7 +17,6 @@
package org.apache.poi.poifs.crypt.dsig;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
@@ -26,6 +25,7 @@ import java.security.PrivateKey;
import javax.crypto.Cipher;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.poifs.crypt.ChainingMode;
import org.apache.poi.poifs.crypt.CipherAlgorithm;
@@ -54,7 +54,7 @@ import org.ietf.jgss.Oid;
}
md = CryptoFunctions.getMessageDigest(algo);
}
-
+
@Override
public void write(final int b) throws IOException {
md.update((byte)b);
@@ -66,7 +66,7 @@ import org.ietf.jgss.Oid;
}
public byte[] sign() throws IOException, GeneralSecurityException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
bos.write(getHashMagic());
bos.write(md.digest());
@@ -74,7 +74,7 @@ import org.ietf.jgss.Oid;
, ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1Padding");
return cipher.doFinal(bos.toByteArray());
}
-
+
static boolean isMSCapi(final PrivateKey key) {
return key != null && key.getClass().getName().contains("mscapi");
}
@@ -84,7 +84,7 @@ import org.ietf.jgss.Oid;
* Each digest method has its own ASN1 header
*
* @return the ASN1 header bytes for the signatureValue / digestInfo
- *
+ *
* @see <a href="https://tools.ietf.org/html/rfc2313#section-10.1.2">Data encoding</a>
*/
byte[] getHashMagic() {
@@ -94,7 +94,7 @@ import org.ietf.jgss.Oid;
try {
final byte[] oidBytes = new Oid(algo.rsaOid).getDER();
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
bos.write(0x30);
bos.write(algo.hashSize+oidBytes.length+6);
bos.write(0x30);
@@ -102,7 +102,7 @@ import org.ietf.jgss.Oid;
bos.write(oidBytes);
bos.write(new byte[] {5,0,4});
bos.write(algo.hashSize);
-
+
return bos.toByteArray();
} catch (GSSException|IOException e) {
throw new IllegalStateException(e);
diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
index d38088c68c..ff977fa45a 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
@@ -24,8 +24,6 @@
package org.apache.poi.poifs.crypt.dsig;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
@@ -38,6 +36,7 @@ import javax.xml.crypto.URIReference;
import javax.xml.crypto.URIReferenceException;
import javax.xml.crypto.XMLCryptoContext;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
@@ -60,6 +59,7 @@ public class OOXMLURIDereferencer implements URIDereferencer {
baseUriDereferencer = signatureInfo.getSignatureFactory().getURIDereferencer();
}
+ @Override
public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException {
if (uriReference == null) {
throw new NullPointerException("URIReference cannot be null - call setSignatureInfo(...) before");
@@ -90,12 +90,12 @@ public class OOXMLURIDereferencer implements URIDereferencer {
// although xmlsec has an option to ignore line breaks, currently this
// only affects .rels files, so we only modify these
// http://stackoverflow.com/questions/4728300
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
for (int ch; (ch = dataStream.read()) != -1; ) {
if (ch == 10 || ch == 13) continue;
bos.write(ch);
}
- dataStream = new ByteArrayInputStream(bos.toByteArray());
+ dataStream = bos.toInputStream();
}
} catch (IOException e) {
throw new URIReferenceException("I/O error: " + e.getMessage(), e);
diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java
index 06067ea531..34fc8d30d1 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignatureLine.java
@@ -32,7 +32,6 @@ import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
@@ -46,6 +45,7 @@ import com.microsoft.schemas.vml.CTGroup;
import com.microsoft.schemas.vml.CTImageData;
import com.microsoft.schemas.vml.CTShape;
import com.microsoft.schemas.vml.STExt;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.common.usermodel.PictureType;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.ooxml.POIXMLException;
@@ -290,7 +290,7 @@ public abstract class SignatureLine {
xsl.setSuggestedsigneremail(suggestedSignerEmail);
}
if (setupId == null) {
- setupId = new ClassID("{"+ UUID.randomUUID().toString()+"}");
+ setupId = new ClassID("{"+ UUID.randomUUID() +"}");
}
xsl.setId(setupId.toString());
xsl.setAllowcomments(STTrueFalse.T);
@@ -344,7 +344,7 @@ public abstract class SignatureLine {
rnd.drawImage(gfx, new Rectangle2D.Double(0, 0, defaultWidth, defaultHeight));
gfx.dispose();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
ImageIO.write(bi, "PNG", bos);
return bos.toByteArray();
}
@@ -429,7 +429,7 @@ public abstract class SignatureLine {
gfx.dispose();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
ImageIO.write(bi, "PNG", bos);
return bos.toByteArray();
}
diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
index 3b00748156..5a82f4152c 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
@@ -28,7 +28,6 @@ import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
import static org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet.insertXChild;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CRLException;
@@ -47,6 +46,7 @@ import java.util.UUID;
import javax.xml.crypto.MarshalException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
@@ -104,8 +104,8 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
SignatureConfig signatureConfig = signatureInfo.getSignatureConfig();
- QualifyingPropertiesDocument qualDoc = null;
- QualifyingPropertiesType qualProps = null;
+ QualifyingPropertiesDocument qualDoc;
+ QualifyingPropertiesType qualProps;
// check for XAdES-BES
NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
@@ -289,7 +289,7 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
}
public static byte[] getC14nValue(List<Node> nodeList, String c14nAlgoId) {
- ByteArrayOutputStream c14nValue = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream c14nValue = new UnsynchronizedByteArrayOutputStream();
try {
for (Node node : nodeList) {
/*
diff --git a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java
index e0746f60eb..40b05b483d 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java
@@ -24,7 +24,8 @@
package org.apache.poi.poifs.crypt.dsig.services;
-import java.io.ByteArrayOutputStream;
+import static org.apache.logging.log4j.util.Unbox.box;
+
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
@@ -44,6 +45,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.SimpleMessage;
@@ -72,8 +74,6 @@ import org.bouncycastle.tsp.TimeStampRequestGenerator;
import org.bouncycastle.tsp.TimeStampResponse;
import org.bouncycastle.tsp.TimeStampToken;
-import static org.apache.logging.log4j.util.Unbox.box;
-
/**
* A TSP time-stamp service implementation.
*/
@@ -95,7 +95,8 @@ public class TSPTimeStampService implements TimeStampService {
}
}
- @SuppressWarnings({"unchecked","squid:S2647"})
+ @Override
+ @SuppressWarnings({"squid:S2647"})
public byte[] timeStamp(SignatureInfo signatureInfo, byte[] data, RevocationData revocationData) throws Exception {
SignatureConfig signatureConfig = signatureInfo.getSignatureConfig();
@@ -124,7 +125,7 @@ public class TSPTimeStampService implements TimeStampService {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(host), (port == -1 ? 80 : port)));
}
- ByteArrayOutputStream bos;
+ UnsynchronizedByteArrayOutputStream bos;
String contentType;
HttpURLConnection huc = (HttpURLConnection)new URL(signatureConfig.getTspUrl()).openConnection(proxy);
try {
@@ -163,7 +164,7 @@ public class TSPTimeStampService implements TimeStampService {
throw new RuntimeException("missing Content-Type header");
}
- bos = new ByteArrayOutputStream();
+ bos = new UnsynchronizedByteArrayOutputStream();
IOUtils.copy(huc.getInputStream(), bos);
LOG.atDebug().log(() -> new SimpleMessage("response content: " + HexDump.dump(bos.toByteArray(), 0, 0)));
} finally {
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java
index e6e72058b8..8dba51f77e 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/draw/SVGRenderExtension.java
@@ -43,7 +43,6 @@ import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
@@ -60,6 +59,7 @@ import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGPaintDescriptor;
import org.apache.batik.svggen.SVGTexturePaint;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.sl.draw.BitmapImageRenderer;
import org.apache.poi.sl.draw.DrawTexturePaint;
import org.apache.poi.sl.draw.Drawable;
@@ -274,12 +274,12 @@ public class SVGRenderExtension extends DefaultExtensionHandler {
null, SVG_VIEW_BOX_ATTRIBUTE, x+" "+ y+" "+ w+" "+h
);
- org.apache.poi.sl.usermodel.Shape slShape = fill.getShape();
+ org.apache.poi.sl.usermodel.Shape<?,?> slShape = fill.getShape();
// TODO: the rotation handling is incomplete and the scale handling is missing
// see DrawTexturePaint on how to do it for AWT
if (!fill.isRotatedWithShape() && slShape instanceof SimpleShape) {
- double rot = ((SimpleShape)slShape).getRotation();
+ double rot = ((SimpleShape<?,?>)slShape).getRotation();
if (rot != 0) {
setAttribute(genCtx, patternDef,
null, SVG_PATTERN_TRANSFORM_ATTRIBUTE, "rotate(" + genCtx.doubleString(-rot) + ")");
@@ -311,7 +311,7 @@ public class SVGRenderExtension extends DefaultExtensionHandler {
}
if (imgData == null) {
BufferedImage bi = imgRdr.getImage();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
ImageIO.write(bi, "PNG", bos);
} catch (IOException e) {
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java
index 8ee5017d1f..9b5b9d63dd 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFObjectShape.java
@@ -19,14 +19,14 @@
package org.apache.poi.xslf.usermodel;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
+import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart;
import org.apache.poi.ooxml.POIXMLException;
@@ -68,7 +68,7 @@ public class XSLFObjectShape extends XSLFGraphicFrame implements ObjectShape<XSL
private static final QName[] OLE_OBJ = { new QName(PML_NS, "oleObj") };
private static final QName[] CT_PICTURE = { new QName(PML_NS, "pic") };
- private CTOleObject _oleObject;
+ private final CTOleObject _oleObject;
private XSLFPictureData _data;
/*package*/ XSLFObjectShape(CTGraphicalObjectFrame shape, XSLFSheet sheet){
@@ -193,56 +193,45 @@ public class XSLFObjectShape extends XSLFGraphicFrame implements ObjectShape<XSL
_oleObject.setProgId(md.getProgId());
_oleObject.setName(md.getObjectName());
- return new XSLFObjectOutputStream(rp.getDocumentPart().getPackagePart(),md);
+ return new ByteArrayOutputStream() {
+ @Override
+ public void close() throws IOException {
+ addUpdatedData(rp.getDocumentPart().getPackagePart(),md,this);
+ }
+ };
}
- private static class XSLFObjectOutputStream extends ByteArrayOutputStream {
- final PackagePart objectPart;
- final ObjectMetaData metaData;
- private XSLFObjectOutputStream(final PackagePart objectPart, final ObjectMetaData metaData) {
- super(100000);
- this.objectPart = objectPart;
- this.metaData = metaData;
- }
-
- public void close() throws IOException {
- objectPart.clear();
- try (final OutputStream os = objectPart.getOutputStream()) {
- final ByteArrayInputStream bis = new ByteArrayInputStream(this.buf, 0, size());
- final FileMagic fm = FileMagic.valueOf(this.buf);
+ private void addUpdatedData(PackagePart objectPart, ObjectMetaData metaData, ByteArrayOutputStream baos) throws IOException {
+ objectPart.clear();
+ try (InputStream bis = FileMagic.prepareToCheckMagic(baos.toInputStream());
+ final OutputStream os = objectPart.getOutputStream()) {
+ final FileMagic fm = FileMagic.valueOf(bis);
- if (fm == FileMagic.OLE2) {
- try (final POIFSFileSystem poifs = new POIFSFileSystem(bis)) {
- poifs.getRoot().setStorageClsid(metaData.getClassID());
- poifs.writeFilesystem(os);
- }
- } else if (metaData.getOleEntry() == null) {
- // OLE Name hasn't been specified, pass the input through
- os.write(this.buf, 0, size());
- } else {
- try (final POIFSFileSystem poifs = new POIFSFileSystem()) {
- final ClassID clsId = metaData.getClassID();
- if (clsId != null) {
- poifs.getRoot().setStorageClsid(clsId);
- }
- poifs.createDocument(bis, metaData.getOleEntry());
-
- Ole10Native.createOleMarkerEntry(poifs);
-
- poifs.writeFilesystem(os);
+ if (fm == FileMagic.OLE2) {
+ try (final POIFSFileSystem poifs = new POIFSFileSystem(bis)) {
+ poifs.getRoot().setStorageClsid(metaData.getClassID());
+ poifs.writeFilesystem(os);
+ }
+ } else if (metaData.getOleEntry() == null) {
+ // OLE Name hasn't been specified, pass the input through
+ baos.writeTo(os);
+ } else {
+ try (final POIFSFileSystem poifs = new POIFSFileSystem()) {
+ final ClassID clsId = metaData.getClassID();
+ if (clsId != null) {
+ poifs.getRoot().setStorageClsid(clsId);
}
+ poifs.createDocument(bis, metaData.getOleEntry());
+ Ole10Native.createOleMarkerEntry(poifs);
+ poifs.writeFilesystem(os);
}
}
}
}
-
/**
- *
- *
* @param shapeId 1-based shapeId
* @param picRel relationship to the picture data in the ooxml package
- * @return
*/
static CTGraphicalObjectFrame prototype(int shapeId, String picRel){
CTGraphicalObjectFrame frame = CTGraphicalObjectFrame.Factory.newInstance();
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java
index 9c4fc5902e..21462607d9 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java
@@ -25,8 +25,6 @@ import java.awt.Insets;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
@@ -35,6 +33,7 @@ import javax.imageio.ImageIO;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ooxml.util.POIXMLUnits;
@@ -127,6 +126,7 @@ public class XSLFPictureShape extends XSLFSimpleShape
* Return the data on the (internal) picture.
* For an external linked picture, will return null
*/
+ @Override
public XSLFPictureData getPictureData() {
if(_data == null){
String blipId = getBlipId();
@@ -320,16 +320,16 @@ public class XSLFPictureShape extends XSLFSimpleShape
: new Rectangle2D.Double(0,0, Units.pixelToPoints((int)dim.getWidth()), Units.pixelToPoints((int)dim.getHeight()));
PictureType pt = (previewType != null) ? previewType : PictureType.PNG;
- if (pt != PictureType.JPEG || pt != PictureType.GIF || pt != PictureType.PNG) {
+ if (pt != PictureType.JPEG && pt != PictureType.GIF && pt != PictureType.PNG) {
pt = PictureType.PNG;
}
BufferedImage thmBI = renderer.getImage(dim);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(100000);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(100000);
// use extension instead of enum name, because of "jpeg"
ImageIO.write(thmBI, pt.extension.substring(1), bos);
- XSLFPictureData pngPic = sheet.getSlideShow().addPicture(new ByteArrayInputStream(bos.toByteArray()), pt);
+ XSLFPictureData pngPic = sheet.getSlideShow().addPicture(bos.toInputStream(), pt);
XSLFPictureShape shape = sheet.createPicture(pngPic);
shape.setAnchor(anc);
@@ -375,7 +375,6 @@ public class XSLFPictureShape extends XSLFSimpleShape
if(blip.isSetExtLst()) {
// TODO: check for SVG copying
CTOfficeArtExtensionList extLst = blip.getExtLst();
- //noinspection deprecation
for(CTOfficeArtExtension ext : extLst.getExtArray()){
String xpath = "declare namespace a14='"+ MS_DML_NS +"' $this//a14:imgProps/a14:imgLayer";
XmlObject[] obj = ext.selectPath(xpath);
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java
index f3dfe26d72..c1cf538c8f 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/DummyFormat.java
@@ -18,7 +18,6 @@
package org.apache.poi.xslf.util;
import java.awt.Graphics2D;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -26,14 +25,16 @@ import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+
public class DummyFormat implements OutputFormat {
- private final ByteArrayOutputStream bos;
+ private final UnsynchronizedByteArrayOutputStream bos;
private final DummyGraphics2d dummy2d;
public DummyFormat() {
try {
- bos = new ByteArrayOutputStream();
+ bos = new UnsynchronizedByteArrayOutputStream();
dummy2d = new DummyGraphics2d(new PrintStream(bos, true, StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
@@ -41,7 +42,7 @@ public class DummyFormat implements OutputFormat {
}
@Override
- public Graphics2D addSlide(double width, double height) throws IOException {
+ public Graphics2D addSlide(double width, double height) {
bos.reset();
return dummy2d;
}
@@ -55,7 +56,7 @@ public class DummyFormat implements OutputFormat {
}
@Override
- public void writeDocument(MFProxy proxy, File outFile) throws IOException {
+ public void writeDocument(MFProxy proxy, File outFile) {
}
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java
index 27f053dc85..81fe1f85cc 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xslf/util/PPTX2PNG.java
@@ -121,6 +121,7 @@ public final class PPTX2PNG {
private PPTX2PNG() {
}
+ @SuppressWarnings("AssignmentToForLoopParameter")
private boolean parseCommandLine(String[] args) {
if (args.length == 0) {
usage(null);
@@ -403,6 +404,7 @@ public final class PPTX2PNG {
}
GenericRecord gr = proxy.getRoot();
try (GenericRecordJsonWriter fw = new GenericRecordJsonWriter(dumpfile) {
+ @Override
protected boolean printBytes(String name, Object o) {
return false;
}
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java
index 4cf1ec13a0..6aa3c9f579 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java
@@ -20,13 +20,13 @@ package org.apache.poi.xssf.usermodel;
import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.namespace.QName;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.xmlbeans.XmlException;
@@ -95,7 +95,7 @@ public class XSSFChartSheet extends XSSFSheet {
}
private static byte[] blankWorksheet(){
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
try {
new XSSFSheet().write(out);
} catch (IOException e){
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java
index 16d04085f2..7001c88b5c 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java
@@ -17,7 +17,6 @@
package org.apache.poi.xssf.usermodel;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -68,9 +67,6 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
/**
* Prototype with the default structure of a new auto-shape.
*/
- /**
- * Prototype with the default structure of a new auto-shape.
- */
protected static CTShape prototype() {
final String drawNS = "http://schemas.microsoft.com/office/drawing/2010/main";
@@ -92,7 +88,7 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
cur.insertNamespace("a14", drawNS);
cur.insertAttributeWithValue("spid", "_x0000_s1");
cur.dispose();
-
+
nv.addNewCNvSpPr();
CTShapeProperties sp = shape.addNewSpPr();
@@ -113,16 +109,16 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
return prototype;
}
-
-
-
+
+
+
@Override
public String getOLE2ClassName() {
return getOleObject().getProgId();
}
/**
- * @return the CTOleObject associated with the shape
+ * @return the CTOleObject associated with the shape
*/
public CTOleObject getOleObject() {
if (oleObject == null) {
@@ -134,16 +130,14 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
}
return oleObject;
}
-
+
@Override
public byte[] getObjectData() throws IOException {
- InputStream is = getObjectPart().getInputStream();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- IOUtils.copy(is, bos);
- is.close();
- return bos.toByteArray();
+ try (InputStream is = getObjectPart().getInputStream()) {
+ return IOUtils.toByteArray(is);
+ }
}
-
+
/**
* @return the package part of the object data
*/
@@ -184,7 +178,7 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
public String getFileName() {
return getObjectPart().getPartName().getName();
}
-
+
protected XSSFSheet getSheet() {
return (XSSFSheet)getDrawing().getParent();
}
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
index 45216a8cdd..5255538ef1 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
@@ -21,8 +21,6 @@ import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.setPassword;
import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.validatePassword;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -43,6 +41,7 @@ import javax.xml.namespace.QName;
import org.apache.commons.collections4.ListValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hpsf.ClassIDPredefined;
@@ -485,7 +484,7 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Su
protected static OPCPackage newPackage(XSSFWorkbookType workbookType) {
OPCPackage pkg = null;
try {
- pkg = OPCPackage.create(new ByteArrayOutputStream()); // NOSONAR - we do not want to close this here
+ pkg = OPCPackage.create(new UnsynchronizedByteArrayOutputStream()); // NOSONAR - we do not want to close this here
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName());
// Create main part relationship
@@ -639,9 +638,9 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Su
}
- try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
srcSheet.write(out);
- try (ByteArrayInputStream bis = new ByteArrayInputStream(out.toByteArray())) {
+ try (InputStream bis = out.toInputStream()) {
clonedSheet.read(bis);
}
} catch (IOException e){
@@ -2346,12 +2345,12 @@ public class XSSFWorkbook extends POIXMLDocument implements Workbook, Date1904Su
Ole10Native ole10 = new Ole10Native(label, fileName, command, oleData);
- try (ByteArrayOutputStream bos = new ByteArrayOutputStream(oleData.length+500)) {
+ try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(oleData.length+500)) {
ole10.writeOut(bos);
try (POIFSFileSystem poifs = new POIFSFileSystem()) {
DirectoryNode root = poifs.getRoot();
- root.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray()));
+ root.createDocument(Ole10Native.OLE10_NATIVE, bos.toInputStream());
root.setStorageClsid(ClassIDPredefined.OLE_V1_PACKAGE.getClassID());
// TODO: generate CombObj stream
diff --git a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
index fcf58ed692..eeed142563 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java
@@ -20,7 +20,6 @@ package org.apache.poi.xwpf.usermodel;
import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -36,6 +35,7 @@ import java.util.Map;
import javax.xml.namespace.QName;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ooxml.POIXMLDocument;
@@ -65,19 +65,37 @@ import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STOnOff1;
-import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocument1;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.CommentsDocument;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.DocumentDocument;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.EndnotesDocument;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr;
+import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument;
/**
- * <p>High(ish) level class for working with .docx files.</p>
+ * High(ish) level class for working with .docx files.
* <p>
- * <p>This class tries to hide some of the complexity
+ * This class tries to hide some of the complexity
* of the underlying file format, but as it's not a
* mature and stable API yet, certain parts of the
* XML structure come through. You'll therefore almost
* certainly need to refer to the OOXML specifications
* from
* http://www.ecma-international.org/publications/standards/Ecma-376.htm
- * at some point in your use.</p>
+ * at some point in your use.
*/
@SuppressWarnings("unused")
public class XWPFDocument extends POIXMLDocument implements Document, IBody {
@@ -103,9 +121,9 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Keeps track on all id-values used in this document and included parts, like headers, footers, etc.
*/
- private IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L);
+ private final IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L);
- private FootnoteEndnoteIdManager footnoteIdManager = new FootnoteEndnoteIdManager(this);
+ private final FootnoteEndnoteIdManager footnoteIdManager = new FootnoteEndnoteIdManager(this);
/**
* Handles the joy of different headers/footers for different pages
@@ -137,7 +155,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
protected static OPCPackage newPackage() {
OPCPackage pkg = null;
try {
- pkg = OPCPackage.create(new ByteArrayOutputStream()); // NOSONAR - we do not want to close this here
+ pkg = OPCPackage.create(new UnsynchronizedByteArrayOutputStream()); // NOSONAR - we do not want to close this here
// Main part
PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName());
// Create main part relationship
@@ -306,8 +324,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* returns an Iterator with paragraphs and tables
- *
- * @see IBody#getBodyElements()
*/
@Override
public List<IBodyElement> getBodyElements() {
@@ -318,17 +334,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
return bodyElements.iterator();
}
- /**
- * @see IBody#getParagraphs()
- */
@Override
public List<XWPFParagraph> getParagraphs() {
return Collections.unmodifiableList(paragraphs);
}
- /**
- * @see IBody#getTables()
- */
@Override
public List<XWPFTable> getTables() {
return Collections.unmodifiableList(tables);
@@ -341,9 +351,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
return Collections.unmodifiableList(charts);
}
- /**
- * @see IBody#getTableArray(int)
- */
@Override
public XWPFTable getTableArray(int pos) {
if (pos >= 0 && pos < tables.size()) {
@@ -755,8 +762,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* verifies that cursor is on the right position
- *
- * @param cursor
*/
private boolean isCursorInBody(XmlCursor cursor) {
XmlCursor verify = cursor.newCursor();
@@ -818,9 +823,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Gets the index of the relation we're trying to create
- *
- * @param relation
- * @return i
*/
private int getRelationIndex(XWPFRelation relation) {
int i = 1;
@@ -843,11 +845,11 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
paragraphs.add(p);
return p;
}
-
-
+
+
/**
* Creates an empty comments for the document if one does not already exist
- *
+ *
* @return comments
*/
public XWPFComments createComments() {
@@ -953,7 +955,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* remove a BodyElement from bodyElements array list
*
- * @param pos
* @return true if removing was successfully, else return false
*/
public boolean removeBodyElement(int pos) {
@@ -977,9 +978,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* copies content of a paragraph to a existing paragraph in the list paragraphs at position pos
- *
- * @param paragraph
- * @param pos
*/
public void setParagraph(XWPFParagraph paragraph, int pos) {
paragraphs.set(pos, paragraph);
@@ -1012,10 +1010,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Create an empty table with a number of rows and cols specified
- *
- * @param rows
- * @param cols
- * @return table
*/
public XWPFTable createTable(int rows, int cols) {
XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols);
@@ -1045,9 +1039,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Replace content of table in array tables at position pos with a
- *
- * @param pos
- * @param table
*/
public void setTable(int pos, XWPFTable table) {
tables.set(pos, table);
@@ -1289,7 +1280,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Validates the existing password
*
- * @param password
* @return true, only if password was set and equals, false otherwise
*/
public boolean validateProtectionPassword(String password) {
@@ -1324,7 +1314,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Check if revision tracking is turned on.
*
- * @return <code>true</code> if revision tracking is turned on
+ * @return {@code true} if revision tracking is turned on
*/
public boolean isTrackRevisions() {
return settings.isTrackRevisions();
@@ -1333,7 +1323,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Enable or disable revision tracking.
*
- * @param enable <code>true</code> to turn on revision tracking, <code>false</code> to turn off revision tracking
+ * @param enable {@code true} to turn on revision tracking, {@code false} to turn off revision tracking
*/
public void setTrackRevisions(boolean enable) {
settings.setTrackRevisions(enable);
@@ -1394,9 +1384,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* inserts an existing XWPFTable to the arrays bodyElements and tables
- *
- * @param pos
- * @param table
*/
@Override
public void insertTable(int pos, XWPFTable table) {
@@ -1506,7 +1493,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* get the next free ImageNumber
*
- * @param format
* @return the next free ImageNumber
* @throws InvalidFormatException If the format of the picture is not known.
*/
@@ -1525,7 +1511,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* returns the PictureData by blipID
*
- * @param blipID
* @return XWPFPictureData of a specificID
*/
public XWPFPictureData getPictureDataByID(String blipID) {
@@ -1567,9 +1552,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* get a table by its CTTbl-Object
*
- * @param ctTbl
* @return a table by its CTTbl-Object or null
- * @see IBody#getTable(CTTbl)
*/
@Override
public XWPFTable getTable(CTTbl ctTbl) {
@@ -1591,8 +1574,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* Returns the paragraph that of position pos
- *
- * @see IBody#getParagraphArray(int)
*/
@Override
public XWPFParagraph getParagraphArray(int pos) {
@@ -1606,8 +1587,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* returns the Part, to which the body belongs, which you need for adding relationship to other parts
* Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell
* belongs.
- *
- * @see IBody#getPart()
*/
@Override
public POIXMLDocumentPart getPart() {
@@ -1618,8 +1597,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* get the PartType of the body, for example
* DOCUMENT, HEADER, FOOTER, FOOTNOTE,
- *
- * @see IBody#getPartType()
*/
@Override
public BodyType getPartType() {
@@ -1628,8 +1605,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
/**
* get the TableCell which belongs to the TableCell
- *
- * @param cell
*/
@Override
public XWPFTableCell getTableCell(CTTc cell) {
@@ -1668,8 +1643,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* no need to read MS-Word file and modify charts
*
* @return This method return object of XWPFChart Object with default height and width
- * @throws InvalidFormatException
- * @throws IOException
* @since POI 4.0.0
*/
public XWPFChart createChart() throws InvalidFormatException, IOException {
@@ -1683,8 +1656,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* @param width width of chart in document
* @param height height of chart in document
* @return This method return object of XWPFChart
- * @throws InvalidFormatException
- * @throws IOException
* @since POI 4.0.0
*/
public XWPFChart createChart(int width, int height) throws InvalidFormatException, IOException {
@@ -1697,8 +1668,6 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
* @param width in EMU.
* @param height in EMU.
* @return the new chart.
- * @throws InvalidFormatException
- * @throws IOException
* @since POI 4.1.2
*/
public XWPFChart createChart(XWPFRun run, int width, int height) throws InvalidFormatException, IOException {
@@ -1729,8 +1698,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
public XWPFFootnote createFootnote() {
XWPFFootnotes footnotes = this.createFootnotes();
- XWPFFootnote footnote = footnotes.createFootnote();
- return footnote;
+ return footnotes.createFootnote();
}
/**
@@ -1757,8 +1725,7 @@ public class XWPFDocument extends POIXMLDocument implements Document, IBody {
public XWPFEndnote createEndnote() {
XWPFEndnotes endnotes = this.createEndnotes();
- XWPFEndnote endnote = endnotes.createEndnote();
- return endnote;
+ return endnotes.createEndnote();
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java
index 2104a418a8..ca4d10a135 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/ooxml/TestPOIXMLDocument.java
@@ -17,6 +17,7 @@
package org.apache.poi.ooxml;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -25,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -46,7 +46,6 @@ import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.TempFile;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.usermodel.XSSFRelation;
@@ -142,7 +141,7 @@ public final class TestPOIXMLDocument {
// Should not be able to write a document that has been closed
doc.close();
- IOException e2 = assertThrows(IOException.class, () -> doc.write(new NullOutputStream()),
+ IOException e2 = assertThrows(IOException.class, () -> doc.write(NULL_OUTPUT_STREAM),
"Should not be able to write a document that has been closed.");
assertEquals("Cannot write data, document seems to have been closed already", e2.getMessage());
@@ -292,7 +291,7 @@ public final class TestPOIXMLDocument {
XMLSlideShow ppt = new XMLSlideShow(is)) {
POIXMLDocumentPart doc = ppt.getSlides().get(12).getRelationById("rId3");
assertNotNull(doc);
- assertEquals(POIXMLDocumentPart.class, doc.getClass());
+ assertSame(POIXMLDocumentPart.class, doc.getClass());
}
}
@@ -334,6 +333,7 @@ public final class TestPOIXMLDocument {
private static class UncaughtHandler implements UncaughtExceptionHandler {
Throwable e;
+ @Override
public synchronized void uncaughtException(Thread t, Throwable e) {
this.e = e;
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java
index 1c6b942a58..4068a8e80d 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java
@@ -25,7 +25,7 @@ import java.io.InputStream;
import java.io.IOException;
/**
- * Centralises logic for finding/opening sample files for ooxml4j unit tests
+ * Centralises logic for finding/opening sample files for ooxml4j unit tests
*/
public final class OpenXML4JTestDataSamples {
private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance();
@@ -40,19 +40,13 @@ public final class OpenXML4JTestDataSamples {
public static String getSampleFileName(String sampleFileName) {
return getSampleFile(sampleFileName).getAbsolutePath();
}
-
+
public static File getSampleFile(String sampleFileName) {
return _samples.getFile(sampleFileName);
}
-
- public static File getOutputFile(String outputFileName) throws IOException {
- String suffix = outputFileName.substring(outputFileName.lastIndexOf('.'));
- return TempFile.createTempFile(outputFileName, suffix);
- }
-
- public static InputStream openComplianceSampleStream(String sampleFileName) {
- return _samples.openResourceAsStream(sampleFileName);
+ public static File getOutputFile(String outputFileName) throws IOException {
+ int idx = outputFileName.lastIndexOf('.');
+ return TempFile.createTempFile(outputFileName.substring(0,idx), outputFileName.substring(idx));
}
-
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java
index 9f297f66c6..9e9997d38f 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackage.java
@@ -33,7 +33,6 @@ import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -58,6 +57,8 @@ import com.google.common.io.Files;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
+import org.apache.commons.io.output.CountingOutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.EncryptedDocumentException;
@@ -217,7 +218,7 @@ public final class TestPackage {
*/
@Test
void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
try (OPCPackage pkg = OPCPackage.create(baos)) {
// Add a core document
@@ -675,7 +676,7 @@ public final class TestPackage {
@Test
void zipBombCreateAndHandle()
throws IOException, EncryptedDocumentException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(2500000);
try (ZipFile zipFile = ZipHelper.openZipFile(getSampleFile("sample.xlsx"));
ZipArchiveOutputStream append = new ZipArchiveOutputStream(bos)) {
@@ -693,21 +694,19 @@ public final class TestPackage {
append.putArchiveEntry(eOut);
if (!eOut.isDirectory()) {
try (InputStream is = zipFile.getInputStream(eIn)) {
- if (eOut.getName().equals("[Content_Types].xml")) {
- ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
- IOUtils.copy(is, bos2);
- long size = bos2.size() - "</Types>".length();
- append.write(bos2.toByteArray(), 0, (int) size);
+ if ("[Content_Types].xml".equals(eOut.getName())) {
+ byte[] suffix = "</Types>".getBytes(StandardCharsets.UTF_8);
+ CountingOutputStream cos = new CountingOutputStream(append);
+ IOUtils.copy(is, cos, eOut.getSize() - suffix.length);
+
byte[] spam = new byte[0x7FFF];
Arrays.fill(spam, (byte) ' ');
// 0x7FFF0000 is the maximum for 32-bit zips, but less still works
- while (size < 0x7FFF00) {
- append.write(spam);
- size += spam.length;
+ while (cos.getByteCount() < 0x7FFF00) {
+ cos.write(spam);
}
- append.write("</Types>".getBytes(StandardCharsets.UTF_8));
- size += 8;
- eOut.setSize(size);
+ cos.write(suffix);
+ eOut.setSize(cos.getByteCount());
} else {
IOUtils.copy(is, append);
}
@@ -717,10 +716,7 @@ public final class TestPackage {
}
}
- IOException ex = assertThrows(
- IOException.class,
- () -> WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray()))
- );
+ IOException ex = assertThrows(IOException.class, () -> WorkbookFactory.create(bos.toInputStream()));
assertTrue(ex.getMessage().contains("Zip bomb detected!"));
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java
index 317d1009a0..6dbfcf0dc9 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java
@@ -17,8 +17,17 @@
package org.apache.poi.openxml4j.opc;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
+import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName;
+import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
+import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_DOCUMENT;
+import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES;
+import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.EXTENDED_PROPERTIES;
+import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import java.io.File;
import java.io.InputStream;
import java.text.ParsePosition;
@@ -27,6 +36,7 @@ import java.util.Date;
import java.util.Locale;
import java.util.Optional;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
@@ -36,9 +46,6 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty;
-import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
-import static org.junit.jupiter.api.Assertions.*;
-
public final class TestPackageCoreProperties {
/**
* Test package core properties getters.
@@ -47,7 +54,7 @@ public final class TestPackageCoreProperties {
void testGetProperties() throws Exception {
// Open the package
@SuppressWarnings("resource")
- OPCPackage p = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx"));
+ OPCPackage p = OPCPackage.open(openSampleStream("TestPackageCoreProperiesGetters.docx"));
compareProperties(p);
p.revert();
}
@@ -57,7 +64,7 @@ public final class TestPackageCoreProperties {
*/
@Test
void testSetProperties() throws Exception {
- String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx");
+ String inputPath = getSampleFileName("TestPackageCoreProperiesSetters.docx");
File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx");
@@ -75,28 +82,28 @@ public final class TestPackageCoreProperties {
//test various date formats
props.setCreatedProperty("2007-05-12T08:00:00Z");
- assertEquals(dateToInsert, props.getCreatedProperty().get());
+ assertEquals(dateToInsert, props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z
- assertEquals(dateToInsert, props.getCreatedProperty().get());
+ assertEquals(dateToInsert, props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2007-05-12T08:00:00.123Z");//millis
- assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get());
+ assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2007-05-12T10:00:00+0200");
- assertEquals(dateToInsert, props.getCreatedProperty().get());
+ assertEquals(dateToInsert, props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz
- assertEquals(dateToInsert, props.getCreatedProperty().get());
+ assertEquals(dateToInsert, props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2007-05-12T06:00:00-0200");
- assertEquals(dateToInsert, props.getCreatedProperty().get());
+ assertEquals(dateToInsert, props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2015-07-27");
- assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().get());
+ assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().orElse(null));
props.setCreatedProperty("2007-05-12T10:00:00.123+0200");
- assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().get());
+ assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().orElse(null));
props.setCategoryProperty("MyCategory");
props.setContentStatusProperty("MyContentStatus");
@@ -122,7 +129,7 @@ public final class TestPackageCoreProperties {
OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ);
compareProperties(p2);
p2.revert();
- outputFile.delete();
+ assertTrue(outputFile.delete());
}
private void compareProperties(OPCPackage p) throws InvalidFormatException {
@@ -132,22 +139,22 @@ public final class TestPackageCoreProperties {
// Gets the core properties
PackageProperties props = p.getPackageProperties();
- assertEquals("MyCategory", props.getCategoryProperty().get());
- assertEquals("MyContentStatus", props.getContentStatusProperty().get());
- assertEquals("MyContentType", props.getContentTypeProperty().get());
- assertEquals(expectedDate, props.getCreatedProperty().get());
- assertEquals("MyCreator", props.getCreatorProperty().get());
- assertEquals("MyDescription", props.getDescriptionProperty().get());
- assertEquals("MyIdentifier", props.getIdentifierProperty().get());
- assertEquals("MyKeywords", props.getKeywordsProperty().get());
- assertEquals("MyLanguage", props.getLanguageProperty().get());
- assertEquals("Julien Chable", props.getLastModifiedByProperty().get());
- assertEquals(expectedDate, props.getLastPrintedProperty().get());
- assertEquals(expectedDate, props.getModifiedProperty().get());
- assertEquals("2", props.getRevisionProperty().get());
- assertEquals("MySubject", props.getSubjectProperty().get());
- assertEquals("MyTitle", props.getTitleProperty().get());
- assertEquals("2", props.getVersionProperty().get());
+ assertEquals("MyCategory", props.getCategoryProperty().orElse(null));
+ assertEquals("MyContentStatus", props.getContentStatusProperty().orElse(null));
+ assertEquals("MyContentType", props.getContentTypeProperty().orElse(null));
+ assertEquals(expectedDate, props.getCreatedProperty().orElse(null));
+ assertEquals("MyCreator", props.getCreatorProperty().orElse(null));
+ assertEquals("MyDescription", props.getDescriptionProperty().orElse(null));
+ assertEquals("MyIdentifier", props.getIdentifierProperty().orElse(null));
+ assertEquals("MyKeywords", props.getKeywordsProperty().orElse(null));
+ assertEquals("MyLanguage", props.getLanguageProperty().orElse(null));
+ assertEquals("Julien Chable", props.getLastModifiedByProperty().orElse(null));
+ assertEquals(expectedDate, props.getLastPrintedProperty().orElse(null));
+ assertEquals(expectedDate, props.getModifiedProperty().orElse(null));
+ assertEquals("2", props.getRevisionProperty().orElse(null));
+ assertEquals("MySubject", props.getSubjectProperty().orElse(null));
+ assertEquals("MyTitle", props.getTitleProperty().orElse(null));
+ assertEquals("2", props.getVersionProperty().orElse(null));
}
@Test
@@ -157,90 +164,92 @@ public final class TestPackageCoreProperties {
String strDate = "2007-05-12T08:00:00Z";
Date date = df.parse(strDate);
- OPCPackage pkg = new ZipPackage();
- PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties();
-
- // created
- assertEquals("", props.getCreatedPropertyString());
- assertFalse(props.getCreatedProperty().isPresent());
- props.setCreatedProperty((String)null);
- assertEquals("", props.getCreatedPropertyString());
- assertFalse(props.getCreatedProperty().isPresent());
- props.setCreatedProperty(Optional.empty());
- assertEquals("", props.getCreatedPropertyString());
- assertFalse(props.getCreatedProperty().isPresent());
- props.setCreatedProperty(Optional.of(date));
- assertEquals(strDate, props.getCreatedPropertyString());
- assertEquals(date, props.getCreatedProperty().get());
- props.setCreatedProperty(strDate);
- assertEquals(strDate, props.getCreatedPropertyString());
- assertEquals(date, props.getCreatedProperty().get());
-
- // lastPrinted
- assertEquals("", props.getLastPrintedPropertyString());
- assertFalse(props.getLastPrintedProperty().isPresent());
- props.setLastPrintedProperty((String)null);
- assertEquals("", props.getLastPrintedPropertyString());
- assertFalse(props.getLastPrintedProperty().isPresent());
- props.setLastPrintedProperty(Optional.empty());
- assertEquals("", props.getLastPrintedPropertyString());
- assertFalse(props.getLastPrintedProperty().isPresent());
- props.setLastPrintedProperty(Optional.of(date));
- assertEquals(strDate, props.getLastPrintedPropertyString());
- assertEquals(date, props.getLastPrintedProperty().get());
- props.setLastPrintedProperty(strDate);
- assertEquals(strDate, props.getLastPrintedPropertyString());
- assertEquals(date, props.getLastPrintedProperty().get());
-
- // modified
- assertFalse(props.getModifiedProperty().isPresent());
- props.setModifiedProperty((String)null);
- assertFalse(props.getModifiedProperty().isPresent());
- props.setModifiedProperty(Optional.empty());
- assertFalse(props.getModifiedProperty().isPresent());
- props.setModifiedProperty(Optional.of(date));
- assertEquals(strDate, props.getModifiedPropertyString());
- assertEquals(date, props.getModifiedProperty().get());
- props.setModifiedProperty(strDate);
- assertEquals(strDate, props.getModifiedPropertyString());
- assertEquals(date, props.getModifiedProperty().get());
-
- // Tidy
- pkg.close();
+ try (OPCPackage pkg = new ZipPackage()) {
+ PackagePropertiesPart props = (PackagePropertiesPart) pkg.getPackageProperties();
+
+ // created
+ assertEquals("", props.getCreatedPropertyString());
+ assertFalse(props.getCreatedProperty().isPresent());
+ props.setCreatedProperty((String) null);
+ assertEquals("", props.getCreatedPropertyString());
+ assertFalse(props.getCreatedProperty().isPresent());
+ props.setCreatedProperty(Optional.empty());
+ assertEquals("", props.getCreatedPropertyString());
+ assertFalse(props.getCreatedProperty().isPresent());
+ props.setCreatedProperty(Optional.of(date));
+ assertEquals(strDate, props.getCreatedPropertyString());
+ assertEquals(date, props.getCreatedProperty().get());
+ props.setCreatedProperty(strDate);
+ assertEquals(strDate, props.getCreatedPropertyString());
+ assertEquals(date, props.getCreatedProperty().get());
+
+ // lastPrinted
+ assertEquals("", props.getLastPrintedPropertyString());
+ assertFalse(props.getLastPrintedProperty().isPresent());
+ props.setLastPrintedProperty((String) null);
+ assertEquals("", props.getLastPrintedPropertyString());
+ assertFalse(props.getLastPrintedProperty().isPresent());
+ props.setLastPrintedProperty(Optional.empty());
+ assertEquals("", props.getLastPrintedPropertyString());
+ assertFalse(props.getLastPrintedProperty().isPresent());
+ props.setLastPrintedProperty(Optional.of(date));
+ assertEquals(strDate, props.getLastPrintedPropertyString());
+ assertEquals(date, props.getLastPrintedProperty().get());
+ props.setLastPrintedProperty(strDate);
+ assertEquals(strDate, props.getLastPrintedPropertyString());
+ assertEquals(date, props.getLastPrintedProperty().get());
+
+ // modified
+ assertFalse(props.getModifiedProperty().isPresent());
+ props.setModifiedProperty((String) null);
+ assertFalse(props.getModifiedProperty().isPresent());
+ props.setModifiedProperty(Optional.empty());
+ assertFalse(props.getModifiedProperty().isPresent());
+ props.setModifiedProperty(Optional.of(date));
+ assertEquals(strDate, props.getModifiedPropertyString());
+ assertEquals(date, props.getModifiedProperty().get());
+ props.setModifiedProperty(strDate);
+ assertEquals(strDate, props.getModifiedPropertyString());
+ assertEquals(date, props.getModifiedProperty().get());
+ }
}
@Test
void testGetPropertiesLO() throws Exception {
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
// Open the package
- OPCPackage pkg1 = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("51444.xlsx"));
- PackageProperties props1 = pkg1.getPackageProperties();
- assertFalse(props1.getTitleProperty().isPresent());
- props1.setTitleProperty("Bug 51444 fixed");
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- pkg1.save(out);
- out.close();
- pkg1.close();
-
- OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()));
- PackageProperties props2 = pkg2.getPackageProperties();
- props2.setTitleProperty("Bug 51444 fixed");
- pkg2.close();
+ try (OPCPackage pkg1 = OPCPackage.open(openSampleStream("51444.xlsx"))) {
+ PackageProperties props1 = pkg1.getPackageProperties();
+ assertFalse(props1.getTitleProperty().isPresent());
+ props1.setTitleProperty("Bug 51444 fixed");
+ pkg1.save(out);
+ }
+
+ try (OPCPackage pkg2 = OPCPackage.open(out.toInputStream())) {
+ PackageProperties props2 = pkg2.getPackageProperties();
+ props2.setTitleProperty("Bug 51444 fixed");
+ }
}
@Test
void testEntitiesInCoreProps_56164() throws Exception {
- try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml");
- OPCPackage p = OPCPackage.open(is)) {
+ try (InputStream is = openSampleStream("CorePropertiesHasEntities.ooxml");
+ OPCPackage p = OPCPackage.open(is)) {
// Should have 3 root relationships
boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
for (PackageRelationship pr : p.getRelationships()) {
- if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT))
- foundDocRel = true;
- if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES))
- foundCorePropRel = true;
- if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
- foundExtPropRel = true;
+ switch (pr.getRelationshipType()) {
+ case CORE_DOCUMENT:
+ foundDocRel = true;
+ break;
+ case CORE_PROPERTIES:
+ foundCorePropRel = true;
+ break;
+ case EXTENDED_PROPERTIES:
+ foundExtPropRel = true;
+ break;
+ }
}
assertTrue(foundDocRel, "Core Doc Relationship not found in " + p.getRelationships());
assertTrue(foundCorePropRel, "Core Props Relationship not found in " + p.getRelationships());
@@ -257,67 +266,68 @@ public final class TestPackageCoreProperties {
@Test
void testListOfCustomProperties() throws Exception {
File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm");
- OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ);
- XSSFWorkbook wb = new XSSFWorkbook(pkg);
+ try (OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ);
+ XSSFWorkbook wb = new XSSFWorkbook(pkg)) {
- assertNotNull(wb.getProperties());
- assertNotNull(wb.getProperties().getCustomProperties());
+ assertNotNull(wb.getProperties());
+ assertNotNull(wb.getProperties().getCustomProperties());
- for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) {
- assertNotNull(prop);
+ for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) {
+ assertNotNull(prop);
+ }
}
-
- wb.close();
- pkg.close();
}
@Test
void testAlternateCorePropertyTimezones() throws Exception {
- InputStream is = OpenXML4JTestDataSamples.openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx");
- OPCPackage pkg = OPCPackage.open(is);
- PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties();
- is.close();
-
// We need predictable dates for testing!
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
df.setTimeZone(LocaleUtil.TIMEZONE_UTC);
- // Check text properties first
- assertEquals("Lorem Ipsum", props.getTitleProperty().get());
- assertEquals("Apache POI", props.getCreatorProperty().get());
-
- // Created at has a +3 timezone and milliseconds
- // 2006-10-13T18:06:00.123+03:00
- // = 2006-10-13T15:06:00.123+00:00
- assertEquals("2006-10-13T15:06:00Z", props.getCreatedPropertyString());
- assertEquals("2006-10-13T15:06:00.123Z", df.format(props.getCreatedProperty().get()));
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
+ try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx");
+ OPCPackage pkg1 = OPCPackage.open(is)) {
+ PackagePropertiesPart props1 = (PackagePropertiesPart) pkg1.getPackageProperties();
- // Modified at has a -13 timezone but no milliseconds
- // 2007-06-20T07:59:00-13:00
- // = 2007-06-20T20:59:00-13:00
- assertEquals("2007-06-20T20:59:00Z", props.getModifiedPropertyString());
- assertEquals("2007-06-20T20:59:00.000Z", df.format(props.getModifiedProperty().get()));
+ // Check text properties first
+ assertEquals("Lorem Ipsum", props1.getTitleProperty().orElse(null));
+ assertEquals("Apache POI", props1.getCreatorProperty().orElse(null));
+ // Created at has a +3 timezone and milliseconds
+ // 2006-10-13T18:06:00.123+03:00
+ // = 2006-10-13T15:06:00.123+00:00
+ assertEquals("2006-10-13T15:06:00Z", props1.getCreatedPropertyString());
+ assertEquals("2006-10-13T15:06:00.123Z", df.format(props1.getCreatedProperty().orElse(null)));
- // Ensure we can change them with other timezones and still read back OK
- props.setCreatedProperty("2007-06-20T20:57:00+13:00");
- props.setModifiedProperty("2007-06-20T20:59:00.123-13:00");
+ // Modified at has a -13 timezone but no milliseconds
+ // 2007-06-20T07:59:00-13:00
+ // = 2007-06-20T20:59:00-13:00
+ assertEquals("2007-06-20T20:59:00Z", props1.getModifiedPropertyString());
+ assertEquals("2007-06-20T20:59:00.000Z", df.format(props1.getModifiedProperty().orElse(null)));
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- pkg.save(baos);
- pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()));
- // Check text properties first - should be unchanged
- assertEquals("Lorem Ipsum", props.getTitleProperty().get());
- assertEquals("Apache POI", props.getCreatorProperty().get());
+ // Ensure we can change them with other timezones and still read back OK
+ props1.setCreatedProperty("2007-06-20T20:57:00+13:00");
+ props1.setModifiedProperty("2007-06-20T20:59:00.123-13:00");
- // Check the updated times
- // 2007-06-20T20:57:00+13:00
- // = 2007-06-20T07:57:00Z
- assertEquals("2007-06-20T07:57:00.000Z", df.format(props.getCreatedProperty().get()));
-
- // 2007-06-20T20:59:00.123-13:00
- // = 2007-06-21T09:59:00.123Z
- assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().get()));
+ pkg1.save(baos);
+ }
+ try (OPCPackage pkg2 = OPCPackage.open(baos.toInputStream())) {
+ PackagePropertiesPart props2 = (PackagePropertiesPart) pkg2.getPackageProperties();
+
+ // Check text properties first - should be unchanged
+ assertEquals("Lorem Ipsum", props2.getTitleProperty().orElse(null));
+ assertEquals("Apache POI", props2.getCreatorProperty().orElse(null));
+
+ // Check the updated times
+ // 2007-06-20T20:57:00+13:00
+ // = 2007-06-20T07:57:00Z
+ assertEquals("2007-06-20T07:57:00.000Z", df.format(props2.getCreatedProperty().orElse(null)));
+
+ // 2007-06-20T20:59:00.123-13:00
+ // = 2007-06-21T09:59:00.123Z
+ // CoreProperties are stored as xs:dateTime -> no milliseconds are saved!
+ assertEquals("2007-06-21T09:59:00.000Z", df.format(props2.getModifiedProperty().orElse(null)));
+ }
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java
index d80c88ae12..d6b81c9a54 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/TestRelationships.java
@@ -24,12 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.regex.Pattern;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
@@ -198,18 +197,16 @@ class TestRelationships {
// Write out and re-load
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
pkg.save(baos);
// use revert to not re-write the input file
pkg.revert();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- pkg = OPCPackage.open(bais);
+ pkg = OPCPackage.open(baos.toInputStream());
// Check again
- sheet = pkg.getPart(
- PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
+ sheet = pkg.getPart(PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS));
assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size());
@@ -228,7 +225,7 @@ class TestRelationships {
@Test
void testCreateRelationsFromScratch() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
OPCPackage pkg = OPCPackage.create(baos);
PackagePart partA =
@@ -255,8 +252,7 @@ class TestRelationships {
// Save, and re-load
pkg.close();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- pkg = OPCPackage.open(bais);
+ pkg = OPCPackage.open(baos.toInputStream());
partA = pkg.getPart(PackagingURIHelper.createPartName("/partA"));
partB = pkg.getPart(PackagingURIHelper.createPartName("/partB"));
@@ -297,20 +293,17 @@ class TestRelationships {
@Test
void testTargetWithSpecialChars() throws Exception{
- OPCPackage pkg;
-
String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx");
- pkg = OPCPackage.open(filepath);
+ OPCPackage pkg = OPCPackage.open(filepath);
assert_50154(pkg);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
pkg.save(baos);
// use revert to not re-write the input file
pkg.revert();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- pkg = OPCPackage.open(bais);
+ pkg = OPCPackage.open(baos.toInputStream());
assert_50154(pkg);
}
@@ -359,7 +352,7 @@ class TestRelationships {
@Test
void testSelfRelations_bug51187() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
PackageRelationship rel1;
try (OPCPackage pkg = OPCPackage.create(baos)) {
@@ -374,8 +367,7 @@ class TestRelationships {
// Save, and re-load
}
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- try (OPCPackage pkg = OPCPackage.open(bais)) {
+ try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) {
PackagePart partA = pkg.getPart(PackagingURIHelper.createPartName("/partA"));
@@ -406,11 +398,10 @@ class TestRelationships {
assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString());
assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart());
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
pkg1.save(out);
- out.close();
- try (OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray()))) {
+ try (OPCPackage pkg2 = OPCPackage.open(out.toInputStream())) {
sheetRels = pkg2.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships();
assertEquals(3, sheetRels.size());
rId1 = sheetRels.getRelationshipByID("rId1");
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java
index 598630546b..9b21bb7db0 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/ZipFileAssert.java
@@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -33,6 +32,7 @@ import java.util.TreeMap;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.util.IOUtils;
import org.junit.jupiter.api.Assertions;
import org.xmlunit.builder.DiffBuilder;
@@ -52,15 +52,15 @@ public final class ZipFileAssert {
}
private static void equals(
- TreeMap<String, ByteArrayOutputStream> file1,
- TreeMap<String, ByteArrayOutputStream> file2) {
+ TreeMap<String, UnsynchronizedByteArrayOutputStream> file1,
+ TreeMap<String, UnsynchronizedByteArrayOutputStream> file2) {
Set<String> listFile1 = file1.keySet();
Assertions.assertEquals(listFile1.size(), file2.keySet().size(), "not the same number of files in zip:");
for (String fileName : listFile1) {
// extract the contents for both
- ByteArrayOutputStream contain1 = file1.get(fileName);
- ByteArrayOutputStream contain2 = file2.get(fileName);
+ UnsynchronizedByteArrayOutputStream contain1 = file1.get(fileName);
+ UnsynchronizedByteArrayOutputStream contain2 = file2.get(fileName);
assertNotNull(contain2, fileName + " not found in 2nd zip");
// no need to check for contain1. The key come from it
@@ -84,11 +84,11 @@ public final class ZipFileAssert {
}
}
- private static TreeMap<String, ByteArrayOutputStream> decompress(
+ private static TreeMap<String, UnsynchronizedByteArrayOutputStream> decompress(
File filename) throws IOException {
// store the zip content in memory
// let s assume it is not Go ;-)
- TreeMap<String, ByteArrayOutputStream> zipContent = new TreeMap<>();
+ TreeMap<String, UnsynchronizedByteArrayOutputStream> zipContent = new TreeMap<>();
try (
/* Open file to decompress */
@@ -106,7 +106,7 @@ public final class ZipFileAssert {
while ((entree = zis.getNextEntry()) != null) {
/* Create a array for the current entry */
- ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream byteArray = new UnsynchronizedByteArrayOutputStream();
IOUtils.copy(zis, byteArray);
zipContent.put(entree.getName(), byteArray);
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java
index 3ebd4041a3..b079f00bf3 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java
@@ -17,7 +17,8 @@
package org.apache.poi.openxml4j.opc.compliance;
-import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openComplianceSampleStream;
+import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getOutputFile;
+import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile;
import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -26,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -35,7 +34,7 @@ import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
-import org.apache.poi.POIDataSamples;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.apache.poi.openxml4j.opc.ContentTypes;
@@ -44,7 +43,6 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Test;
/**
@@ -81,13 +79,13 @@ public final class TestOPCComplianceCoreProperties {
@Test
void testCorePropertiesPart() throws IOException {
- try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
+ try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
assertDoesNotThrow(() -> OPCPackage.open(is).close());
}
}
private static String extractInvalidFormatMessage(String sampleNameSuffix) throws IOException {
- try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) {
+ try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix)) {
InvalidFormatException e = assertThrows(InvalidFormatException.class,
() -> OPCPackage.open(is).revert(), "expected OPC compliance exception was not thrown");
return e.getMessage();
@@ -137,7 +135,7 @@ public final class TestOPCComplianceCoreProperties {
*/
@Test
void testOnlyOneCorePropertiesPart_AddRelationship() throws IOException, InvalidFormatException {
- try (InputStream is = openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
+ try (InputStream is = openSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx")) {
OPCPackage pkg = OPCPackage.open(is);
URI partUri = createURI("/docProps/core2.xml");
InvalidOperationException e = assertThrows(InvalidOperationException.class, () ->
@@ -155,7 +153,7 @@ public final class TestOPCComplianceCoreProperties {
@Test
void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException, IOException {
String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
- try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
+ try (OPCPackage pkg = OPCPackage.open(getSampleFile(sampleFileName).getPath())) {
URI partUri = createURI("/docProps/core2.xml");
InvalidOperationException e = assertThrows(InvalidOperationException.class, () ->
@@ -218,9 +216,9 @@ public final class TestOPCComplianceCoreProperties {
@Test
void testNoCoreProperties_saveNew() throws Exception {
String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
- try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
+ try (OPCPackage pkg = OPCPackage.open(getSampleFile(sampleFileName).getPath())) {
// Verify it has empty properties
assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
@@ -232,7 +230,7 @@ public final class TestOPCComplianceCoreProperties {
pkg.revert();
}
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) {
+ try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) {
// An Empty Properties part has been added in the save/load
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
@@ -241,14 +239,14 @@ public final class TestOPCComplianceCoreProperties {
}
// Open a new copy of it
- try (OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath())) {
+ try (OPCPackage pkg = OPCPackage.open(getSampleFile(sampleFileName).getPath())) {
// Save and re-load, without having touched the properties yet
baos.reset();
pkg.save(baos);
pkg.revert();
}
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray()))) {
+ try (OPCPackage pkg = OPCPackage.open(baos.toInputStream())) {
// Check that this too added empty properties without error
assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size());
assertNotNull(pkg.getPackageProperties());
@@ -266,9 +264,9 @@ public final class TestOPCComplianceCoreProperties {
String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx";
// Copy this into a temp file, so we can play with it
- File tmp = TempFile.createTempFile("poi-test", ".opc");
+ File tmp = getOutputFile("poi-test.opc");
try (FileOutputStream out = new FileOutputStream(tmp);
- InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName)) {
+ InputStream in = openSampleStream(sampleFileName)) {
IOUtils.copy(in, out);
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java
index aab917ec63..1fe70833c9 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java
@@ -23,12 +23,11 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
-import org.apache.poi.ooxml.util.POIXMLUnits;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
@@ -40,11 +39,9 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
-import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.XSSFTestDataSamples;
-import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
@@ -53,8 +50,6 @@ import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
-import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor;
public final class TestContentTypeManager {
@@ -137,7 +132,7 @@ public final class TestContentTypeManager {
}
protected byte[] toByteArray(Workbook wb) {
- try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
+ try (UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream()) {
wb.write(os);
return os.toByteArray();
} catch (IOException e) {
diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java
index 3b9b03aed4..40345a029a 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java
@@ -17,16 +17,17 @@
package org.apache.poi.openxml4j.opc.internal.marshallers;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
@@ -38,7 +39,7 @@ class TestZipPackagePropertiesMarshaller {
private final PartMarshaller marshaller = new ZipPackagePropertiesMarshaller();
private boolean marshall() throws OpenXML4JException {
- return marshall(new ZipArchiveOutputStream(new ByteArrayOutputStream()));
+ return marshall(new ZipArchiveOutputStream(new UnsynchronizedByteArrayOutputStream()));
}
private boolean marshall(OutputStream zos) throws OpenXML4JException {
@@ -50,8 +51,7 @@ class TestZipPackagePropertiesMarshaller {
@Test
void nonZipOutputStream() {
- OutputStream notAZipOutputStream = new ByteArrayOutputStream(0);
- assertThrows(IllegalArgumentException.class, () -> marshall(notAZipOutputStream));
+ assertThrows(IllegalArgumentException.class, () -> marshall(NULL_OUTPUT_STREAM));
}
@Test
@@ -61,7 +61,7 @@ class TestZipPackagePropertiesMarshaller {
@Test
void ioException() {
- ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()) {
+ ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new UnsynchronizedByteArrayOutputStream()) {
@Override
public void putArchiveEntry(final ArchiveEntry archiveEntry) throws IOException {
throw new IOException("TestException");
diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
index 52516d0c68..afd498aa12 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
@@ -32,7 +32,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -77,6 +76,7 @@ import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.dom.DOMSignContext;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -160,6 +160,8 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.w3.x2000.x09.xmldsig.ReferenceType;
import org.w3.x2000.x09.xmldsig.SignatureDocument;
import org.w3c.dom.Document;
@@ -210,36 +212,36 @@ class TestSignatureInfo {
@Test
void bug61182() throws Exception {
final String pfxInput =
- "H4sIAAAAAAAAAFXTfzzTeRwH8P2uGRmG6hKSmJh9a2HsuPy60VnHCEU6v86sieZH2Jr2qFl+s+ZHJ5tfUcfKb4uho/OjiFq1qTv5ceFyp0PqEK"+
- "fH4+66++Pz+Dwer9fj8f7r9cRzEd4QMBTPRWxDIM14ZN47NfAWsJgL34Bx4at4Lvwdngvd9b8KqgbjQpGbMXzzgRGovytVFTBEzIXU47kQCd4U"+
- "ofJPvHl8JwyTjRS55hbKoor3UJLDE1i/PcPKCBAIDATjQlKiK67XjVYdcnkZgD2txroiAUb8W9dtn57DvTsbM+3wIsdocXDEN7TdPKgaSl+tU1"+
- "xq9oqiB5yMaZCPho8uUEbFU9U6u3N7lEMLTJGeA0RfX+5FMRrpXPFrbrlJ8uNUCE2H247P28Ckyfqlsy32yeKg/HTbH5JpqUDNw2B32+SaiRw7"+
- "ofRMePUpaAoK7KYgmd5ZIc0rLLYjJBfOWCb28xlrGhbpJvdToFdqt5PXVjEz5YOJ6g7W0fskuKW9/iZP0yLEVpR9XkkHmb6tfpcE8YwCdWNCan"+
- "LvAsco25JdF1j2/FLAMVU79HdOex07main90dy40511OZtTGZ+TdVd3lKZ7D3clEg9hLESHwSNnZ6239X4yLM4xYSElQ/hqSbwdmiozYG9PhF2"+
- "Zf0XaZnxzTK0Iot+rJ3kYoxWTLE8DR9leV62Ywbtlg4mapYOxb3lT7fQ1x4EQ44flh2oFWSPLR8LMbsc6jzJsV6OZ3TrODjHEdw9W+8OD32vd8"+
- "XQ6iCaIHcrSOn6qS0TKLr786234eeSAhvAQbEsVn7vrvc/487Be/O2e/+5Y5zRq2zAtz6pfcNyraJNDqMW1inNkgJ3t3VESbZ3pNzyl3KHILs0"+
- "51dY6msDYSlWhw40TglXxj9rw95O6gFWIuN012W/vhS50jpKXcao4gc1aLaXtJXxirbRkpZ/0e7a0pD6TDa7+GxEdEEML3VGo9udD5YUKhU3y7"+
- "SzWAgN6WIEIglq7LilvCjqIVLIfg8CvVGL9f5iSsCDf5hef4vMxbyvcjINuy06gZu+iPYOWNxjfrwKGYzoqqotK2aywgYVrPMh0JovfkDuN95n"+
- "MdVlYHbN1Mnn4TxAwuv+u3AkBlDZvRUUCwoDMUGxeMNPhTaAgWl60xhhBgCBaEMgAACReMAav7n3x598IDYJ9GxGXRAwaPOT/kfO/1AgPqLQkp"+
- "MiIVaHthnUS4v2y32e2BjdMPyIImUTBW3cV3R5tjVQm0MOm+D2C5+bBW9vHLjLR4lun4toQiY3Ls/v4bES/OJ4EmpZk5xhL9i5ClofYZNEsxFn"+
- "An/q821Tg+Cq9Er4XYGQe8ogjjLJ2b7dUsJ3auFQFNUJF7Ke7yUL2EeYYxl6vz5l4q5u8704mRbFts1E1eWMp6WIy91GPrsVlRGvtuNERfrjfE"+
- "YtzUI3Flcv65zJUbUBEzUnTS0fEYso2XyToAl8kb251mUY2o2lJzv5dp/1htmcjeeP2MjxC+3S45ljx7jd52Pv9XAat+ryiauFOF7YgztkoWWD"+
- "h62tplPH1bzDV+d0NLdaE5AfVJ09HuUYTFS+iggtvT5Euyk+unj4N2XvzW91n+GNjtgWfKOHmkinUPvYRh70Jv+wlPJrVaT8mL7GxJLqDC9jbv"+
- "Gznoiae6es+wQejnk3XjU366MrK/zXxngBYj9J6NnXc9mMiTFLX8WqQ8iTelTAFs2NJzPoDzrBUz4JFIEOa6Dja6dULc68g1jFDTeEHZyra7RZ"+
- "2ElqGDEqcNRo3SNX6feMy9EF1GOyZK0Sa87KwjKw8aM68dpsIYjfLcTXaZ6atg0BKfMnl6axeUGEaIFSP7rzj9wjzumRbG3jgUVp2lX5AK/tsO"+
- "7R4TQX/9/H6RiN34c9KldmPZZGANXzzTajZS9mR2OSvlJ+F4AgSko4htrMAKFTBu51/5SWNsO1vlRaaG48ZRJ+8PzuHQMdvS36gNpRPi7jhF1S"+
- "H3B2ycI4y0VURv6SrqJNUY/X645ZFJQ+eBO+ptG7o8axf1dcqh2beiQk+GRTeZ37LVeUlaeo9vl1/+8tyBfyT2v5lFC5E19WdKIyCuZe7r99Px"+
- "D/Od4Qj0TA92+DQnbCQTCMy/wwse9O4gsEebkkpPIP5GBV3Q0YBsj75XE0uSFQ1tCZSW8bNa9MUJZ/nPBfExohHlgGAAA=";
+ "H4sIAAAAAAAAAFXTfzzTeRwH8P2uGRmG6hKSmJh9a2HsuPy60VnHCEU6v86sieZH2Jr2qFl+s+ZHJ5tfUcfKb4uho/OjiFq1qTv5ceFyp0PqEK"+
+ "fH4+66++Pz+Dwer9fj8f7r9cRzEd4QMBTPRWxDIM14ZN47NfAWsJgL34Bx4at4Lvwdngvd9b8KqgbjQpGbMXzzgRGovytVFTBEzIXU47kQCd4U"+
+ "ofJPvHl8JwyTjRS55hbKoor3UJLDE1i/PcPKCBAIDATjQlKiK67XjVYdcnkZgD2txroiAUb8W9dtn57DvTsbM+3wIsdocXDEN7TdPKgaSl+tU1"+
+ "xq9oqiB5yMaZCPho8uUEbFU9U6u3N7lEMLTJGeA0RfX+5FMRrpXPFrbrlJ8uNUCE2H247P28Ckyfqlsy32yeKg/HTbH5JpqUDNw2B32+SaiRw7"+
+ "ofRMePUpaAoK7KYgmd5ZIc0rLLYjJBfOWCb28xlrGhbpJvdToFdqt5PXVjEz5YOJ6g7W0fskuKW9/iZP0yLEVpR9XkkHmb6tfpcE8YwCdWNCan"+
+ "LvAsco25JdF1j2/FLAMVU79HdOex07main90dy40511OZtTGZ+TdVd3lKZ7D3clEg9hLESHwSNnZ6239X4yLM4xYSElQ/hqSbwdmiozYG9PhF2"+
+ "Zf0XaZnxzTK0Iot+rJ3kYoxWTLE8DR9leV62Ywbtlg4mapYOxb3lT7fQ1x4EQ44flh2oFWSPLR8LMbsc6jzJsV6OZ3TrODjHEdw9W+8OD32vd8"+
+ "XQ6iCaIHcrSOn6qS0TKLr786234eeSAhvAQbEsVn7vrvc/487Be/O2e/+5Y5zRq2zAtz6pfcNyraJNDqMW1inNkgJ3t3VESbZ3pNzyl3KHILs0"+
+ "51dY6msDYSlWhw40TglXxj9rw95O6gFWIuN012W/vhS50jpKXcao4gc1aLaXtJXxirbRkpZ/0e7a0pD6TDa7+GxEdEEML3VGo9udD5YUKhU3y7"+
+ "SzWAgN6WIEIglq7LilvCjqIVLIfg8CvVGL9f5iSsCDf5hef4vMxbyvcjINuy06gZu+iPYOWNxjfrwKGYzoqqotK2aywgYVrPMh0JovfkDuN95n"+
+ "MdVlYHbN1Mnn4TxAwuv+u3AkBlDZvRUUCwoDMUGxeMNPhTaAgWl60xhhBgCBaEMgAACReMAav7n3x598IDYJ9GxGXRAwaPOT/kfO/1AgPqLQkp"+
+ "MiIVaHthnUS4v2y32e2BjdMPyIImUTBW3cV3R5tjVQm0MOm+D2C5+bBW9vHLjLR4lun4toQiY3Ls/v4bES/OJ4EmpZk5xhL9i5ClofYZNEsxFn"+
+ "An/q821Tg+Cq9Er4XYGQe8ogjjLJ2b7dUsJ3auFQFNUJF7Ke7yUL2EeYYxl6vz5l4q5u8704mRbFts1E1eWMp6WIy91GPrsVlRGvtuNERfrjfE"+
+ "YtzUI3Flcv65zJUbUBEzUnTS0fEYso2XyToAl8kb251mUY2o2lJzv5dp/1htmcjeeP2MjxC+3S45ljx7jd52Pv9XAat+ryiauFOF7YgztkoWWD"+
+ "h62tplPH1bzDV+d0NLdaE5AfVJ09HuUYTFS+iggtvT5Euyk+unj4N2XvzW91n+GNjtgWfKOHmkinUPvYRh70Jv+wlPJrVaT8mL7GxJLqDC9jbv"+
+ "Gznoiae6es+wQejnk3XjU366MrK/zXxngBYj9J6NnXc9mMiTFLX8WqQ8iTelTAFs2NJzPoDzrBUz4JFIEOa6Dja6dULc68g1jFDTeEHZyra7RZ"+
+ "2ElqGDEqcNRo3SNX6feMy9EF1GOyZK0Sa87KwjKw8aM68dpsIYjfLcTXaZ6atg0BKfMnl6axeUGEaIFSP7rzj9wjzumRbG3jgUVp2lX5AK/tsO"+
+ "7R4TQX/9/H6RiN34c9KldmPZZGANXzzTajZS9mR2OSvlJ+F4AgSko4htrMAKFTBu51/5SWNsO1vlRaaG48ZRJ+8PzuHQMdvS36gNpRPi7jhF1S"+
+ "H3B2ycI4y0VURv6SrqJNUY/X645ZFJQ+eBO+ptG7o8axf1dcqh2beiQk+GRTeZ37LVeUlaeo9vl1/+8tyBfyT2v5lFC5E19WdKIyCuZe7r99Px"+
+ "D/Od4Qj0TA92+DQnbCQTCMy/wwse9O4gsEebkkpPIP5GBV3Q0YBsj75XE0uSFQ1tCZSW8bNa9MUJZ/nPBfExohHlgGAAA=";
// Unix
final String unixSignExp =
- "QkqTFQZjXagjRAoOWKpAGa8AR0rKqkSfBtfSWqtjBmTgyjarn+t2POHkpySIpheHAbg+90GKSH88ACMtPHbG7q" +
- "FL4gtgAD9Kjew6j16j0IRBwy145UlPrSLFMfF7YF7UlU1k1LBkIlRJ6Fv4MAJl6XspuzZOZIUmHZrWrdxycUQ=";
+ "QkqTFQZjXagjRAoOWKpAGa8AR0rKqkSfBtfSWqtjBmTgyjarn+t2POHkpySIpheHAbg+90GKSH88ACMtPHbG7q" +
+ "FL4gtgAD9Kjew6j16j0IRBwy145UlPrSLFMfF7YF7UlU1k1LBkIlRJ6Fv4MAJl6XspuzZOZIUmHZrWrdxycUQ=";
// Windows
final String winSignExp =
- "GmAlL7+bT1r3FsMHJOp3pKg8betblYieZTjhMIrPZPRBbSzjO7KsYRGNtr0aOE3qr8xzyYJN6/8QdF5X7pUEUc" +
- "2m8ctrm7s5o2vZTkAqk9ENJGDjBPXX7TnuVOiVeL1cJdtjHC2QpjtRwkFR+B54G6b1OXLOFuQpP3vqR3+/XXE=";
+ "GmAlL7+bT1r3FsMHJOp3pKg8betblYieZTjhMIrPZPRBbSzjO7KsYRGNtr0aOE3qr8xzyYJN6/8QdF5X7pUEUc" +
+ "2m8ctrm7s5o2vZTkAqk9ENJGDjBPXX7TnuVOiVeL1cJdtjHC2QpjtRwkFR+B54G6b1OXLOFuQpP3vqR3+/XXE=";
// Mac
final String macSignExp =
@@ -259,13 +261,13 @@ class TestSignatureInfo {
SignatureInfo si = new SignatureInfo();
si.setSignatureConfig(signatureConfig);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(100000);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(100000);
try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
wb1.createSheet().createRow(1).createCell(1).setCellValue("Test");
wb1.write(bos);
}
- try (OPCPackage pkg1 = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (OPCPackage pkg1 = OPCPackage.open(bos.toInputStream())) {
si.setOpcPackage(pkg1);
si.confirmSignature();
assertTrue(si.verifySignature());
@@ -273,7 +275,7 @@ class TestSignatureInfo {
pkg1.save(bos);
}
- try (XSSFWorkbook wb2 = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (XSSFWorkbook wb2 = new XSSFWorkbook(bos.toInputStream())) {
assertEquals("Test", wb2.getSheetAt(0).getRow(1).getCell(1).getStringCellValue());
OPCPackage pkg2 = wb2.getPackage();
si.setOpcPackage(pkg2);
@@ -306,71 +308,65 @@ class TestSignatureInfo {
}
}
- @Test
- void getSignerUnsigned() throws Exception {
- String[] testFiles = {
- "hello-world-unsigned.docx",
- "hello-world-unsigned.pptx",
- "hello-world-unsigned.xlsx",
- "hello-world-office-2010-technical-preview-unsigned.docx"
- };
-
- for (String testFile : testFiles) {
- List<X509Certificate> result = new ArrayList<>();
- try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) {
- SignatureConfig sic = new SignatureConfig();
- SignatureInfo si = new SignatureInfo();
- si.setOpcPackage(pkg);
- si.setSignatureConfig(sic);
- for (SignaturePart sp : si.getSignatureParts()) {
- if (sp.validate()) {
- result.add(sp.getSigner());
- }
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "hello-world-unsigned.docx",
+ "hello-world-unsigned.pptx",
+ "hello-world-unsigned.xlsx",
+ "hello-world-office-2010-technical-preview-unsigned.docx"
+ })
+ void getSignerUnsigned(String testFile) throws Exception {
+ List<X509Certificate> result = new ArrayList<>();
+ try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) {
+ SignatureConfig sic = new SignatureConfig();
+ SignatureInfo si = new SignatureInfo();
+ si.setOpcPackage(pkg);
+ si.setSignatureConfig(sic);
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
}
- pkg.revert();
}
- assertNotNull(result);
- assertTrue(result.isEmpty());
+ pkg.revert();
}
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
}
- @Test
- void getSigner() throws Exception {
- String[] testFiles = {
- "hyperlink-example-signed.docx",
- "hello-world-signed.docx",
- "hello-world-signed.pptx",
- "hello-world-signed.xlsx",
- "hello-world-office-2010-technical-preview.docx",
- "ms-office-2010-signed.docx",
- "ms-office-2010-signed.pptx",
- "ms-office-2010-signed.xlsx",
- "Office2010-SP1-XAdES-X-L.docx",
- "signed.docx"
- };
-
- for (String testFile : testFiles) {
- try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) {
- SignatureConfig sic = new SignatureConfig();
- SignatureInfo si = new SignatureInfo();
- si.setOpcPackage(pkg);
- si.setSignatureConfig(sic);
- List<X509Certificate> result = new ArrayList<>();
- for (SignaturePart sp : si.getSignatureParts()) {
- if (sp.validate()) {
- result.add(sp.getSigner());
- }
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "hyperlink-example-signed.docx",
+ "hello-world-signed.docx",
+ "hello-world-signed.pptx",
+ "hello-world-signed.xlsx",
+ "hello-world-office-2010-technical-preview.docx",
+ "ms-office-2010-signed.docx",
+ "ms-office-2010-signed.pptx",
+ "ms-office-2010-signed.xlsx",
+ "Office2010-SP1-XAdES-X-L.docx",
+ "signed.docx"
+ })
+ void getSigner(String testFile) throws Exception {
+ try (OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ)) {
+ SignatureConfig sic = new SignatureConfig();
+ SignatureInfo si = new SignatureInfo();
+ si.setOpcPackage(pkg);
+ si.setSignatureConfig(sic);
+ List<X509Certificate> result = new ArrayList<>();
+ for (SignaturePart sp : si.getSignatureParts()) {
+ if (sp.validate()) {
+ result.add(sp.getSigner());
}
+ }
- assertNotNull(result);
- assertEquals(1, result.size(), "test-file: " + testFile);
- X509Certificate signer = result.get(0);
- LOG.atDebug().log("signer: {}", signer.getSubjectX500Principal());
+ assertNotNull(result);
+ assertEquals(1, result.size(), "test-file: " + testFile);
+ X509Certificate signer = result.get(0);
+ LOG.atDebug().log("signer: {}", signer.getSubjectX500Principal());
- boolean b = si.verifySignature();
- assertTrue(b, "test-file: " + testFile);
- pkg.revert();
- }
+ boolean b = si.verifySignature();
+ assertTrue(b, "test-file: " + testFile);
+ pkg.revert();
}
}
@@ -474,7 +470,7 @@ class TestSignatureInfo {
void testSignEnvelopingDocument() throws Exception {
String testFile = "hello-world-unsigned.xlsx";
File sigCopy = testdata.getFile(testFile);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(50000);
final String execTimestr;
@@ -613,7 +609,7 @@ class TestSignatureInfo {
pkg.save(bos);
}
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) {
SignatureConfig signatureConfig = new SignatureConfig();
signatureConfig.setUpdateConfigOnValidate(true);
@@ -752,7 +748,7 @@ class TestSignatureInfo {
void bug65214() throws Exception {
initKeyPair();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (XWPFDocument doc = new XWPFDocument()) {
XWPFHyperlinkRun r = doc.createParagraph().createHyperlinkRun("http://poi.apache.org");
r.setText("Hyperlink");
@@ -765,7 +761,7 @@ class TestSignatureInfo {
signatureConfig.setKey(keyPair.getPrivate());
signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
signatureConfig.setDigestAlgo(HashAlgorithm.sha256);
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) {
SignatureInfo si = new SignatureInfo();
si.setOpcPackage(pkg);
si.setSignatureConfig(signatureConfig);
@@ -776,7 +772,7 @@ class TestSignatureInfo {
assumeTrue(e.getMessage().startsWith("Export Restrictions"));
}
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) {
SignatureInfo si = new SignatureInfo();
si.setOpcPackage(pkg);
si.setSignatureConfig(signatureConfig);
@@ -793,10 +789,10 @@ class TestSignatureInfo {
try (SXSSFWorkbook wb1 = new SXSSFWorkbook((XSSFWorkbook)WorkbookFactory.create(tpl), 10)) {
wb1.setCompressTempFiles(true);
wb1.removeSheetAt(0);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
wb1.write(os);
- try (OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(os.toByteArray()))) {
+ try (OPCPackage pkg = OPCPackage.open(os.toInputStream())) {
initKeyPair();
SignatureConfig signatureConfig = new SignatureConfig();
signatureConfig.setKey(keyPair.getPrivate());
diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java
index 14e6debbf4..27930ce1d0 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestAgileEncryptionParameters.java
@@ -20,8 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
@@ -30,6 +28,7 @@ import java.util.stream.Stream;
import javax.crypto.Cipher;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.poifs.crypt.ChainingMode;
import org.apache.poi.poifs.crypt.CipherAlgorithm;
@@ -79,7 +78,7 @@ class TestAgileEncryptionParameters {
int maxKeyLen = Cipher.getMaxAllowedKeyLength(ca.jceId);
assumeTrue(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files");
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
POIFSFileSystem fsEnc = new POIFSFileSystem();
EncryptionInfo infoEnc = new EncryptionInfo(EncryptionMode.agile, ca, ha, -1, -1, cm);
@@ -92,7 +91,7 @@ class TestAgileEncryptionParameters {
fsEnc.writeFilesystem(bos);
fsEnc.close();
- POIFSFileSystem fsDec = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
+ POIFSFileSystem fsDec = new POIFSFileSystem(bos.toInputStream());
EncryptionInfo infoDec = new EncryptionInfo(fsDec);
Decryptor dec = infoDec.getDecryptor();
boolean passed = dec.verifyPassword("foobaa");
diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java
index fed15e2f3c..4be8a9b674 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestDecryptor.java
@@ -22,7 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -34,6 +33,7 @@ import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.crypt.Decryptor;
@@ -142,7 +142,7 @@ class TestDecryptor {
Decryptor d = Decryptor.getInstance(info);
d.verifyPassword("pwd123");
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
+ final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(10000);
try (final ZipArchiveInputStream zis = new ZipArchiveInputStream(d.getDataStream(fs))) {
int[] sizes = { 3711, 1155, 445, 9376, 450, 588, 1337, 2593, 304, 7910 };
for (int size : sizes) {
diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java
index ed2ee87e02..4cd6e0e1fd 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestEncryptor.java
@@ -16,6 +16,7 @@
==================================================================== */
package org.apache.poi.poifs.crypt.tests;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -24,8 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -39,6 +38,7 @@ import java.util.Random;
import javax.crypto.Cipher;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.OPCPackage;
@@ -59,7 +59,6 @@ import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.filesystem.TempFilePOIFSFileSystem;
import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.TempFile;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
@@ -78,7 +77,7 @@ class TestEncryptor {
payloadExpected = IOUtils.toByteArray(is);
}
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4);
Encryptor enc = ei.getEncryptor();
@@ -92,7 +91,7 @@ class TestEncryptor {
}
final byte[] payloadActual;
- try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (POIFSFileSystem fs = new POIFSFileSystem(bos.toInputStream())) {
EncryptionInfo ei = new EncryptionInfo(fs);
Decryptor dec = ei.getDecryptor();
boolean b = dec.verifyPassword(password);
@@ -115,7 +114,7 @@ class TestEncryptor {
payloadExpected = IOUtils.toByteArray(is);
}
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (POIFSFileSystem fs = new TempFilePOIFSFileSystem()) {
EncryptionInfo ei = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = ei.getEncryptor();
@@ -129,7 +128,7 @@ class TestEncryptor {
}
final byte[] payloadActual;
- try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (POIFSFileSystem fs = new POIFSFileSystem(bos.toInputStream())) {
EncryptionInfo ei = new EncryptionInfo(fs);
Decryptor dec = ei.getDecryptor();
boolean b = dec.verifyPassword(password);
@@ -202,7 +201,7 @@ class TestEncryptor {
Encryptor e = Encryptor.getInstance(infoActual);
e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (POIFSFileSystem fs = new POIFSFileSystem()) {
try (OutputStream os = e.getDataStream(fs)) {
os.write(payloadExpected);
@@ -213,7 +212,7 @@ class TestEncryptor {
final EncryptionInfo infoActual2;
final byte[] payloadActual, encPackActual;
final long decPackLenActual;
- try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (POIFSFileSystem nfs = new POIFSFileSystem(bos.toInputStream())) {
infoActual2 = new EncryptionInfo(nfs.getRoot());
Decryptor decActual = Decryptor.getInstance(infoActual2);
boolean passed = decActual.verifyPassword(pass);
@@ -289,7 +288,7 @@ class TestEncryptor {
// now we use a newly generated salt/verifier and check
// if the file content is still the same
- final byte[] encBytes;
+ final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(50000);
try (POIFSFileSystem fs = new POIFSFileSystem()) {
final EncryptionInfo infoActual2 = new EncryptionInfo(
@@ -308,13 +307,11 @@ class TestEncryptor {
os.write(payloadExpected);
}
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
fs.writeFilesystem(bos);
- encBytes = bos.toByteArray();
}
final byte[] payloadActual;
- try (POIFSFileSystem nfs = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) {
+ try (POIFSFileSystem nfs = new POIFSFileSystem(bos.toInputStream())) {
final EncryptionInfo ei = new EncryptionInfo(nfs);
Decryptor d2 = Decryptor.getInstance(ei);
assertTrue(d2.verifyPassword(pass), "Unable to process: document is encrypted");
@@ -336,7 +333,7 @@ class TestEncryptor {
@Test
void encryptPackageWithoutCoreProperties() throws Exception {
// Open our file without core properties
- final byte[] encBytes;
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
try (InputStream is = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("OPCCompliance_NoCoreProperties.xlsx");
OPCPackage pkg = OPCPackage.open(is)) {
@@ -358,14 +355,12 @@ class TestEncryptor {
}
// Save the resulting OLE2 document, and re-open it
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
fs.writeFilesystem(baos);
- encBytes = baos.toByteArray();
}
}
- try (POIFSFileSystem inpFS = new POIFSFileSystem(new ByteArrayInputStream(encBytes))) {
+ try (POIFSFileSystem inpFS = new POIFSFileSystem(baos.toInputStream())) {
// Check we can decrypt it
EncryptionInfo info = new EncryptionInfo(inpFS);
Decryptor d = Decryptor.getInstance(info);
@@ -539,10 +534,10 @@ class TestEncryptor {
os.write(zipInput);
}
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
fsNew.writeFilesystem(bos);
- try (POIFSFileSystem fsReload = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (POIFSFileSystem fsReload = new POIFSFileSystem(bos.toInputStream())) {
infoReload = new EncryptionInfo(fsReload);
try (InputStream epReload = fsReload.getRoot().createDocumentInputStream("EncryptedPackage")) {
epNewBytes = IOUtils.toByteArray(epReload, 9400);
@@ -633,9 +628,8 @@ class TestEncryptor {
assertTrue(passOk);
try (InputStream is = dec.getDataStream(poifs);
- DigestInputStream dis = new DigestInputStream(is, md);
- NullOutputStream nos = new NullOutputStream()) {
- IOUtils.copy(dis, nos);
+ DigestInputStream dis = new DigestInputStream(is, md)) {
+ IOUtils.copy(dis, NULL_OUTPUT_STREAM);
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java
index bf5aebb590..6f4f27c486 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/tests/TestHxxFEncryption.java
@@ -26,28 +26,20 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
-import org.apache.poi.hssf.model.WorkbookRecordList;
-import org.apache.poi.hssf.record.FilePassRecord;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POIDocument;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.extractor.POITextExtractor;
-import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
-import org.apache.poi.poifs.crypt.binaryrc4.BinaryRC4EncryptionHeader;
import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader;
import org.apache.poi.poifs.storage.RawDataUtil;
import org.junit.jupiter.api.Test;
@@ -110,14 +102,13 @@ class TestHxxFEncryption {
private void newPassword(String newPass, POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
File f = sampleDir.getFile(file);
Biff8EncryptionKey.setCurrentUserPassword(password);
- try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) {
+ try (POITextExtractor te1 = ExtractorFactory.createExtractor(f);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
Biff8EncryptionKey.setCurrentUserPassword(newPass);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (POIDocument doc = (POIDocument) te1.getDocument()) {
doc.write(bos);
}
- ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
- try (POITextExtractor te2 = ExtractorFactory.createExtractor(bis)) {
+ try (POITextExtractor te2 = ExtractorFactory.createExtractor(bos.toInputStream())) {
String actual = te2.getText().trim();
assertEquals(expected, actual);
}
@@ -131,9 +122,9 @@ class TestHxxFEncryption {
@MethodSource("data")
void changeEncryption(POIDataSamples sampleDir, String file, String password, String expected) throws IOException {
File f = sampleDir.getFile(file);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
Biff8EncryptionKey.setCurrentUserPassword(password);
- try (POITextExtractor te1 = ExtractorFactory.createExtractor(f)) {
+ try (POITextExtractor te1 = ExtractorFactory.createExtractor(f);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
// first remove encryption
Biff8EncryptionKey.setCurrentUserPassword(null);
try (POIDocument doc = (POIDocument) te1.getDocument()) {
@@ -141,7 +132,7 @@ class TestHxxFEncryption {
}
// then use default setting, which is cryptoapi
String newPass = "newPass";
- try (POITextExtractor te2 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (POITextExtractor te2 = ExtractorFactory.createExtractor(bos.toInputStream())) {
Biff8EncryptionKey.setCurrentUserPassword(newPass);
try (POIDocument doc = (POIDocument) te2.getDocument()) {
bos.reset();
@@ -149,7 +140,7 @@ class TestHxxFEncryption {
}
}
// and finally update cryptoapi setting
- try (POITextExtractor te3 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
+ try (POITextExtractor te3 = ExtractorFactory.createExtractor(bos.toInputStream());
POIDocument doc = (POIDocument) te3.getDocument()) {
// need to cache data (i.e. read all data) before changing the key size
Class<?> clazz = doc.getClass();
@@ -167,7 +158,7 @@ class TestHxxFEncryption {
doc.write(bos);
}
// check the setting
- try (POITextExtractor te4 = ExtractorFactory.createExtractor(new ByteArrayInputStream(bos.toByteArray()));
+ try (POITextExtractor te4 = ExtractorFactory.createExtractor(bos.toInputStream());
POIDocument doc = (POIDocument) te4.getDocument()) {
EncryptionInfo ei = doc.getEncryptionInfo();
assertNotNull(ei);
@@ -181,7 +172,7 @@ class TestHxxFEncryption {
@Test
public void changeEncryptionMode() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(10_000);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(10_000);
try (HSSFWorkbook wb = new HSSFWorkbook()) {
wb.createSheet().createRow(1).createCell(1).setCellValue("Test");
@@ -189,7 +180,7 @@ class TestHxxFEncryption {
wb.write(bos);
}
- try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (HSSFWorkbook wb = new HSSFWorkbook(bos.toInputStream())) {
assertEquals(EncryptionMode.cryptoAPI, wb.getEncryptionMode());
wb.setEncryptionMode(EncryptionMode.binaryRC4);
Biff8EncryptionKey.setCurrentUserPassword("test2");
@@ -197,7 +188,7 @@ class TestHxxFEncryption {
wb.write(bos);
}
- try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (HSSFWorkbook wb = new HSSFWorkbook(bos.toInputStream())) {
assertEquals(EncryptionMode.binaryRC4, wb.getEncryptionMode());
wb.setEncryptionMode(null);
bos.reset();
@@ -206,7 +197,7 @@ class TestHxxFEncryption {
assertNull(Biff8EncryptionKey.getCurrentUserPassword());
- try (HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (HSSFWorkbook wb = new HSSFWorkbook(bos.toInputStream())) {
assertNull(wb.getEncryptionMode());
wb.setEncryptionMode(null);
assertEquals("Test", wb.getSheetAt(0).getRow(1).getCell(1).getStringCellValue());
diff --git a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java
index bda636d2ad..8352e0061c 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestOleShape.java
@@ -29,8 +29,6 @@ import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -39,6 +37,7 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.stream.Stream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POIDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -114,7 +113,7 @@ class TestOleShape {
@ParameterizedTest
@MethodSource("data")
void embedData(Api api, ObjectMetaData.Application app) throws IOException, ReflectiveOperationException {
- final ByteArrayInputStream pptBytes;
+ final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(50000);
try (SlideShow<?,?> ppt = createSlideShow(api)) {
final PictureData picData = ppt.addPicture(pictureFile, PictureType.EMF);
final Slide<?,?> slide = ppt.createSlide();
@@ -123,11 +122,9 @@ class TestOleShape {
try (OutputStream os = oleShape.updateObjectData(app, null)) {
fillOleData(app, os);
}
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
ppt.write(bos);
- pptBytes = new ByteArrayInputStream(bos.toByteArray());
}
- try (SlideShow<?,?> ppt = SlideShowFactory.create(pptBytes)) {
+ try (SlideShow<?,?> ppt = SlideShowFactory.create(bos.toInputStream())) {
final ObjectShape<?,?> oleShape = (ObjectShape<?,?>)ppt.getSlides().get(0).getShapes().get(0);
try (InputStream bis = oleShape.readObjectData()) {
validateOleData(app, bis);
diff --git a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java
index eb066e4688..06c358a459 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestSlide.java
@@ -24,11 +24,10 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
@@ -56,10 +55,10 @@ class TestSlide {
ppt1.createSlide().setHidden(true);
ppt1.createSlide();
- try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
+ try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
ppt1.write(bos);
- try (InputStream is = new ByteArrayInputStream(bos.toByteArray());
+ try (InputStream is = bos.toInputStream();
SlideShow<?, ?> ppt2 = SlideShowFactory.create(is)) {
Boolean[] hiddenState = ppt2.getSlides().stream().map(Slide::isHidden).toArray(Boolean[]::new);
diff --git a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java
index cedb11eed0..ccd6d86aa5 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/sl/tests/TestTable.java
@@ -29,11 +29,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
@@ -42,6 +40,8 @@ import org.apache.poi.sl.usermodel.TableShape;
import org.apache.poi.sl.usermodel.TextShape.TextDirection;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
class TestTable {
@@ -51,26 +51,23 @@ class TestTable {
// Test of table dimensions of same slideshow saved as ppt/x
// to check if both return similar (points) value
- SlideShow<?,?> ppt = openSampleSlideshow("table_test.ppt");
- TableShape<?,?> ts = (TableShape<?,?>)ppt.getSlides().get(0).getShapes().get(0);
-
- SlideShow<?,?> pptx = openSampleSlideshow("table_test.pptx");
- TableShape<?,?> tsx = (TableShape<?,?>)pptx.getSlides().get(0).getShapes().get(0);
-
- // assume table shape should be equal to itself
- confirmTableShapeEqual(ts, ts);
- confirmTableShapeEqual(tsx, tsx);
-
- // assert ppt and pptx versions of the same table have the same shape
- confirmTableShapeEqual(ts, tsx);
-
- // change row height and validate again
- tsx.setRowHeight(1, 50);
- ts.setRowHeight(1, 50);
- confirmTableShapeEqual(ts, tsx);
-
- pptx.close();
- ppt.close();
+ try (SlideShow<?,?> ppt = openSampleSlideshow("table_test.ppt");
+ SlideShow<?,?> pptx = openSampleSlideshow("table_test.pptx")) {
+ TableShape<?, ?> ts = (TableShape<?, ?>) ppt.getSlides().get(0).getShapes().get(0);
+ TableShape<?, ?> tsx = (TableShape<?, ?>) pptx.getSlides().get(0).getShapes().get(0);
+
+ // assume table shape should be equal to itself
+ confirmTableShapeEqual(ts, ts);
+ confirmTableShapeEqual(tsx, tsx);
+
+ // assert ppt and pptx versions of the same table have the same shape
+ confirmTableShapeEqual(ts, tsx);
+
+ // change row height and validate again
+ tsx.setRowHeight(1, 50);
+ ts.setRowHeight(1, 50);
+ confirmTableShapeEqual(ts, tsx);
+ }
}
private void confirmTableShapeEqual(TableShape<?,?> tableA, TableShape<?,?> tableB) {
@@ -95,16 +92,16 @@ class TestTable {
@Test
void directionHSLF() throws IOException {
assumeFalse(xslfOnly());
- SlideShow<?,?> ppt1 = SlideShowFactory.create(false);
- testTextDirection(ppt1);
- ppt1.close();
+ try (SlideShow<?,?> ppt1 = SlideShowFactory.create(false)) {
+ testTextDirection(ppt1);
+ }
}
@Test
void directionXSLF() throws IOException {
- SlideShow<?,?> ppt1 = new XMLSlideShow();
- testTextDirection(ppt1);
- ppt1.close();
+ try (SlideShow<?,?> ppt1 = new XMLSlideShow()) {
+ testTextDirection(ppt1);
+ }
}
private void testTextDirection(SlideShow<?,?> ppt1) throws IOException {
@@ -128,27 +125,26 @@ class TestTable {
}
}
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
ppt1.write(bos);
- ppt1.close();
- InputStream is = new ByteArrayInputStream(bos.toByteArray());
- SlideShow<?,?> ppt2 = SlideShowFactory.create(is);
- TableShape<?,?> tbl2 = (TableShape<?,?>)ppt2.getSlides().get(0).getShapes().get(0);
+ try (SlideShow<?,?> ppt2 = SlideShowFactory.create(bos.toInputStream())) {
+ TableShape<?, ?> tbl2 = (TableShape<?, ?>) ppt2.getSlides().get(0).getShapes().get(0);
- col = 0;
- for (TextDirection td : tds) {
- TableCell<?,?> c = tbl2.getCell(0, col++);
- assertEquals(td, c.getTextDirection());
+ col = 0;
+ for (TextDirection td : tds) {
+ TableCell<?, ?> c = tbl2.getCell(0, col++);
+ assertEquals(td, c.getTextDirection());
+ }
}
- ppt2.close();
}
- @Test
- void tableSpan() throws IOException {
- String[] files = (xslfOnly()) ? new String[]{"bug60993.pptx"} : new String[]{"bug60993.pptx", "bug60993.ppt"};
- for (String f : files) {
- SlideShow<?,?> ppt = openSampleSlideshow(f);
+ @ParameterizedTest
+ @ValueSource(strings = {"bug60993.pptx", "bug60993.ppt"})
+ void tableSpan(String file) throws IOException {
+ assumeFalse(file.endsWith("ppt") && xslfOnly());
+
+ try (SlideShow<?,?> ppt = openSampleSlideshow(file)) {
Slide<?,?> slide = ppt.getSlides().get(0);
TableShape<?,?> ts = (TableShape<?,?>)slide.getShapes().get(0);
int cols = ts.getNumberOfColumns();
@@ -157,11 +153,11 @@ class TestTable {
for (int c=0; c<cols; c++) {
TableCell<?,?> tc = ts.getCell(r, c);
int rc = r*10+c;
- String msg = f+" (r"+r+",c"+c+")";
+ String msg = file+" (r"+r+",c"+c+")";
switch (rc) {
case 22:
case 51:
- if (f.endsWith("ppt")) {
+ if (file.endsWith("ppt")) {
assertNull(tc, msg);
} else {
assertNotNull(tc, msg);
@@ -189,7 +185,6 @@ class TestTable {
}
}
}
- ppt.close();
}
}
} \ No newline at end of file
diff --git a/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java b/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java
index 001ea8ebce..4c085df879 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/ss/tests/usermodel/TestEmbedOLEPackage.java
@@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
@@ -35,6 +34,7 @@ import java.util.List;
import java.util.Locale;
import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.ClassIDPredefined;
import org.apache.poi.hssf.HSSFTestDataSamples;
@@ -121,9 +121,9 @@ class TestEmbedOLEPackage {
try (POIFSFileSystem scratchFS = new POIFSFileSystem();
POIFSFileSystem ole1FS = new POIFSFileSystem(new ByteArrayInputStream(oleShapes.get(0).getObjectData()))) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
scratch.writeOut(bos);
- scratchFS.createDocument(new ByteArrayInputStream(bos.toByteArray()), Ole10Native.OLE10_NATIVE);
+ scratchFS.createDocument(bos.toInputStream(), Ole10Native.OLE10_NATIVE);
scratchFS.getRoot().setStorageClsid(ClassIDPredefined.OLE_V1_PACKAGE.getClassID());
assertTrue(EntryUtils.areDirectoriesIdentical(ole1FS.getRoot(), scratchFS.getRoot()));
}
@@ -220,7 +220,7 @@ class TestEmbedOLEPackage {
sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200));
sh1.setFillColor(java.awt.Color.red);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
ppt.write(bos);
ppt.close();
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java
index 08250192ac..5b239a8ad6 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java
@@ -20,6 +20,7 @@ import static org.apache.poi.POITestCase.assertContains;
import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_HREF;
import static org.apache.poi.sl.draw.DrawTextParagraph.HYPERLINK_LABEL;
import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument;
+import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -32,7 +33,6 @@ import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
@@ -76,13 +76,15 @@ import org.apache.poi.sl.usermodel.TextRun;
import org.apache.poi.sl.usermodel.TextShape;
import org.apache.poi.sl.usermodel.VerticalAlignment;
import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xslf.util.DummyGraphics2d;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.ThrowingSupplier;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect;
import org.openxmlformats.schemas.presentationml.x2006.main.CTShape;
@@ -121,89 +123,87 @@ class TestXSLFBugs {
@Test
void bug62736() throws Exception {
- XMLSlideShow ss1 = openSampleDocument("bug62736.pptx");
-
- assertEquals(1, ss1.getSlides().size());
+ try (XMLSlideShow ss1 = openSampleDocument("bug62736.pptx")) {
+ assertEquals(1, ss1.getSlides().size());
- XSLFSlide slide0 = ss1.getSlides().get(0);
+ XSLFSlide slide0 = ss1.getSlides().get(0);
- assertEquals(slide0.getShapes().size(), 4);
+ assertEquals(slide0.getShapes().size(), 4);
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
- assertRelation(slide0, "/ppt/media/image1.png", "rId2");
- assertEquals(slide0.getRelations().size(), 2);
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
+ assertRelation(slide0, "/ppt/media/image1.png", "rId2");
+ assertEquals(slide0.getRelations().size(), 2);
- List<XSLFPictureShape> pictures = new ArrayList<>();
- for (XSLFShape shape : slide0.getShapes()) {
- if (shape instanceof XSLFPictureShape) {
- pictures.add((XSLFPictureShape) shape);
+ List<XSLFPictureShape> pictures = new ArrayList<>();
+ for (XSLFShape shape : slide0.getShapes()) {
+ if (shape instanceof XSLFPictureShape) {
+ pictures.add((XSLFPictureShape) shape);
+ }
}
- }
- assertEquals(pictures.size(), 2);
- assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png");
- assertEquals(pictures.get(1).getPictureData().getFileName(), "image1.png");
- // blipId is rId2 of both pictures
+ assertEquals(pictures.size(), 2);
+ assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png");
+ assertEquals(pictures.get(1).getPictureData().getFileName(), "image1.png");
+ // blipId is rId2 of both pictures
- // remove just the first picture
- slide0.removeShape(pictures.get(0));
+ // remove just the first picture
+ slide0.removeShape(pictures.get(0));
- assertEquals(slide0.getShapes().size(), 3);
+ assertEquals(slide0.getShapes().size(), 3);
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
- // the bug is that the following relation is gone
- assertRelation(slide0, "/ppt/media/image1.png", "rId2");
- assertEquals(slide0.getRelations().size(), 2);
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
+ // the bug is that the following relation is gone
+ assertRelation(slide0, "/ppt/media/image1.png", "rId2");
+ assertEquals(slide0.getRelations().size(), 2);
- // Save and re-load
- XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1);
- ss1.close();
- assertEquals(1, ss2.getSlides().size());
+ // Save and re-load
+ try (XMLSlideShow ss2 = writeOutAndReadBack(ss1)) {
+ assertEquals(1, ss2.getSlides().size());
- slide0 = ss2.getSlides().get(0);
+ slide0 = ss2.getSlides().get(0);
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
- assertRelation(slide0, "/ppt/media/image1.png", "rId2");
- assertEquals(slide0.getRelations().size(), 2);
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
+ assertRelation(slide0, "/ppt/media/image1.png", "rId2");
+ assertEquals(slide0.getRelations().size(), 2);
- pictures.clear();
- for (XSLFShape shape : slide0.getShapes()) {
- if (shape instanceof XSLFPictureShape) {
- pictures.add((XSLFPictureShape) shape);
- }
- }
+ pictures.clear();
+ for (XSLFShape shape : slide0.getShapes()) {
+ if (shape instanceof XSLFPictureShape) {
+ pictures.add((XSLFPictureShape) shape);
+ }
+ }
- assertEquals(pictures.size(), 1);
- assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png");
+ assertEquals(pictures.size(), 1);
+ assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png");
- slide0.removeShape(pictures.get(0));
+ slide0.removeShape(pictures.get(0));
- assertEquals(slide0.getShapes().size(), 2);
+ assertEquals(slide0.getShapes().size(), 2);
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
- assertNull(slide0.getRelationById("rId2"));
- assertEquals(slide0.getRelations().size(), 1);
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
+ assertNull(slide0.getRelationById("rId2"));
+ assertEquals(slide0.getRelations().size(), 1);
- // Save and re-load
- XMLSlideShow ss3 = XSLFTestDataSamples.writeOutAndReadBack(ss2);
- ss2.close();
- assertEquals(1, ss3.getSlides().size());
+ // Save and re-load
+ try (XMLSlideShow ss3 = writeOutAndReadBack(ss2)) {
+ assertEquals(1, ss3.getSlides().size());
- slide0 = ss3.getSlides().get(0);
+ slide0 = ss3.getSlides().get(0);
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
- assertEquals(slide0.getShapes().size(), 2);
- ss3.close();
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1");
+ assertEquals(slide0.getShapes().size(), 2);
+ }
+ }
+ }
}
@Test
void bug61589() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (XMLSlideShow src = new XMLSlideShow();
XMLSlideShow dest = new XMLSlideShow()) {
XSLFSlide slide = src.createSlide();
@@ -229,71 +229,65 @@ class TestXSLFBugs {
dest.createSlide().importContent(slide);
dest.createSlide().importContent(slide2);
- dest.write(bos);
+ try (XMLSlideShow ppt3 = writeOutAndReadBack(dest)) {
+ XSLFSlide slide3 = ppt3.getSlides().get(0);
+ XSLFTextBox shape3 = (XSLFTextBox) slide3.getShapes().get(0);
+ XSLFTextParagraph p3 = shape3.getTextParagraphs().get(1);
+ XSLFHyperlink h1 = p3.getTextRuns().get(0).getHyperlink();
+ assertNotNull(h1);
+ assertEquals("https://poi.apache.org", h1.getAddress());
+ XSLFHyperlink h2 = p3.getTextRuns().get(2).getHyperlink();
+ assertNotNull(h2);
+ // relative url will be resolved to an absolute url, therefore this doesn't equals to "slide2.xml"
+ assertEquals("/ppt/slides/slide2.xml", h2.getAddress());
+ RelationPart sldRef = slide3.getRelationPartById(h2.getXmlObject().getId());
+ assertTrue(sldRef.getDocumentPart() instanceof XSLFSlide);
+ }
}
- try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) {
- XSLFSlide slide = ppt.getSlides().get(0);
- XSLFTextBox shape = (XSLFTextBox) slide.getShapes().get(0);
- XSLFTextParagraph p = shape.getTextParagraphs().get(1);
- XSLFHyperlink h1 = p.getTextRuns().get(0).getHyperlink();
- assertNotNull(h1);
- assertEquals("https://poi.apache.org", h1.getAddress());
- XSLFHyperlink h2 = p.getTextRuns().get(2).getHyperlink();
- assertNotNull(h2);
- // relative url will be resolved to an absolute url, therefore this doesn't equals to "slide2.xml"
- assertEquals("/ppt/slides/slide2.xml", h2.getAddress());
- RelationPart sldRef = slide.getRelationPartById(h2.getXmlObject().getId());
- assertTrue(sldRef.getDocumentPart() instanceof XSLFSlide);
- }
}
@Test
void bug62587() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try (XMLSlideShow ppt = new XMLSlideShow()) {
- Slide<?, ?> slide = ppt.createSlide();
- XSLFPictureData pd = ppt.addPicture(slTests.getFile("wrench.emf"), PictureType.EMF);
- PictureShape<?, ?> ps = slide.createPicture(pd);
- ps.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
- ppt.write(bos);
- }
-
Object[][] pics = {
{"santa.wmf", PictureType.WMF, XSLFRelation.IMAGE_WMF},
{"tomcat.png", PictureType.PNG, XSLFRelation.IMAGE_PNG},
{"clock.jpg", PictureType.JPEG, XSLFRelation.IMAGE_JPEG}
};
- try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) {
- XSLFSlide s1 = ppt.getSlides().get(0);
-
- for (Object[] p : pics) {
- XSLFSlide s2 = ppt.createSlide();
- s2.importContent(s1);
-
- XSLFPictureData pd = ppt.addPicture(slTests.getFile((String) p[0]), (PictureType) p[1]);
- XSLFPictureShape ps = (XSLFPictureShape) s2.getShapes().get(0);
- Rectangle2D anchor = ps.getAnchor();
- s2.removeShape(ps);
- ps = s2.createPicture(pd);
- ps.setAnchor(anchor);
- }
-
- bos.reset();
- ppt.write(bos);
- }
+ try (XMLSlideShow ppt1 = new XMLSlideShow()) {
+ Slide<?, ?> slide = ppt1.createSlide();
+ XSLFPictureData pd1 = ppt1.addPicture(slTests.getFile("wrench.emf"), PictureType.EMF);
+ PictureShape<?, ?> ps1 = slide.createPicture(pd1);
+ ps1.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
+
+ try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ XSLFSlide s1 = ppt2.getSlides().get(0);
+
+ for (Object[] p : pics) {
+ XSLFSlide s2 = ppt2.createSlide();
+ s2.importContent(s1);
+
+ XSLFPictureData pd2 = ppt2.addPicture(slTests.getFile((String) p[0]), (PictureType) p[1]);
+ XSLFPictureShape ps2 = (XSLFPictureShape) s2.getShapes().get(0);
+ Rectangle2D anchor2 = ps2.getAnchor();
+ s2.removeShape(ps2);
+ ps2 = s2.createPicture(pd2);
+ ps2.setAnchor(anchor2);
+ }
- try (XMLSlideShow ppt = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()))) {
- for (XSLFSlide sl : ppt.getSlides()) {
- List<RelationPart> rels = sl.getRelationParts();
- assertEquals(2, rels.size());
- RelationPart rel0 = rels.get(0);
- assertEquals("rId1", rel0.getRelationship().getId());
- assertEquals(XSLFRelation.SLIDE_LAYOUT.getRelation(), rel0.getRelationship().getRelationshipType());
- RelationPart rel1 = rels.get(1);
- assertEquals("rId2", rel1.getRelationship().getId());
- assertEquals(XSLFRelation.IMAGES.getRelation(), rel1.getRelationship().getRelationshipType());
+ try (XMLSlideShow ppt3 = writeOutAndReadBack(ppt2)) {
+ for (XSLFSlide sl : ppt3.getSlides()) {
+ List<RelationPart> rels = sl.getRelationParts();
+ assertEquals(2, rels.size());
+ RelationPart rel0 = rels.get(0);
+ assertEquals("rId1", rel0.getRelationship().getId());
+ assertEquals(XSLFRelation.SLIDE_LAYOUT.getRelation(), rel0.getRelationship().getRelationshipType());
+ RelationPart rel1 = rels.get(1);
+ assertEquals("rId2", rel1.getRelationship().getId());
+ assertEquals(XSLFRelation.IMAGES.getRelation(), rel1.getRelationship().getRelationshipType());
+ }
+ }
}
}
}
@@ -301,78 +295,73 @@ class TestXSLFBugs {
@Test
void bug60499() throws IOException, InvalidFormatException {
- InputStream is = slTests.openResourceAsStream("bug60499.pptx");
- byte[] buf = IOUtils.toByteArray(is);
- is.close();
-
PackagePartName ppn = PackagingURIHelper.createPartName("/ppt/media/image1.png");
- XMLSlideShow ppt1 = new XMLSlideShow(new ByteArrayInputStream(buf));
- XSLFSlide slide1 = ppt1.getSlides().get(0);
-
- Optional<XSLFShape> shapeToDelete1 =
- slide1.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).findFirst();
-
- assertTrue(shapeToDelete1.isPresent());
- slide1.removeShape(shapeToDelete1.get());
- assertTrue(slide1.getRelationParts().stream()
- .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId())));
-
- assertNotNull(ppt1.getPackage().getPart(ppn));
- ppt1.close();
-
- XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(buf));
- XSLFSlide slide2 = ppt2.getSlides().get(0);
-
- Optional<XSLFShape> shapeToDelete2 =
- slide2.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).skip(1).findFirst();
- assertTrue(shapeToDelete2.isPresent());
- slide2.removeShape(shapeToDelete2.get());
- assertTrue(slide2.getRelationParts().stream()
- .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId())));
- assertNotNull(ppt2.getPackage().getPart(ppn));
- ppt2.close();
-
- XMLSlideShow ppt3 = new XMLSlideShow(new ByteArrayInputStream(buf));
- XSLFSlide slide3 = ppt3.getSlides().get(0);
- slide3.getShapes().stream()
- .filter(s -> s instanceof XSLFPictureShape)
- .collect(Collectors.toList())
- .forEach(slide3::removeShape);
- assertNull(ppt3.getPackage().getPart(ppn));
- ppt3.close();
+ try (XMLSlideShow ppt1 = openSampleDocument("bug60499.pptx")) {
+ XSLFSlide slide1 = ppt1.getSlides().get(0);
+
+ Optional<XSLFShape> shapeToDelete1 =
+ slide1.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).findFirst();
+
+ assertTrue(shapeToDelete1.isPresent());
+ slide1.removeShape(shapeToDelete1.get());
+ assertTrue(slide1.getRelationParts().stream()
+ .allMatch(rp -> "rId1,rId3".contains(rp.getRelationship().getId())));
+
+ assertNotNull(ppt1.getPackage().getPart(ppn));
+ }
+
+ try (XMLSlideShow ppt2 = openSampleDocument("bug60499.pptx")) {
+ XSLFSlide slide2 = ppt2.getSlides().get(0);
+ Optional<XSLFShape> shapeToDelete2 =
+ slide2.getShapes().stream().filter(s -> s instanceof XSLFPictureShape).skip(1).findFirst();
+ assertTrue(shapeToDelete2.isPresent());
+ slide2.removeShape(shapeToDelete2.get());
+ assertTrue(slide2.getRelationParts().stream()
+ .allMatch(rp -> "rId1,rId2".contains(rp.getRelationship().getId())));
+ assertNotNull(ppt2.getPackage().getPart(ppn));
+ }
+
+ try (XMLSlideShow ppt3 = openSampleDocument("bug60499.pptx")) {
+ XSLFSlide slide3 = ppt3.getSlides().get(0);
+ slide3.getShapes().stream()
+ .filter(s -> s instanceof XSLFPictureShape)
+ .collect(Collectors.toList())
+ .forEach(slide3::removeShape);
+ assertNull(ppt3.getPackage().getPart(ppn));
+ }
}
@Test
void bug51187() throws Exception {
- XMLSlideShow ss1 = openSampleDocument("51187.pptx");
-
- assertEquals(1, ss1.getSlides().size());
-
- // Check the relations on it
- // Note - rId3 is a self reference
- XSLFSlide slide0 = ss1.getSlides().get(0);
-
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1");
- assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2");
- assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3");
- assertRelation(slide0, "/ppt/media/image1.png", "rId4");
-
- // Save and re-load
- XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1);
- ss1.close();
- assertEquals(1, ss2.getSlides().size());
-
- slide0 = ss2.getSlides().get(0);
- assertRelation(slide0, "/ppt/slides/slide1.xml", null);
- assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1");
- assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2");
- // TODO Fix this
- assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3");
- assertRelation(slide0, "/ppt/media/image1.png", "rId4");
-
- ss2.close();
+ try (XMLSlideShow ss1 = openSampleDocument("51187.pptx")) {
+
+ assertEquals(1, ss1.getSlides().size());
+
+ // Check the relations on it
+ // Note - rId3 is a self reference
+ XSLFSlide slide0 = ss1.getSlides().get(0);
+
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1");
+ assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2");
+ assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3");
+ assertRelation(slide0, "/ppt/media/image1.png", "rId4");
+
+ // Save and re-load
+ try (XMLSlideShow ss2 = writeOutAndReadBack(ss1)) {
+ assertEquals(1, ss2.getSlides().size());
+
+ slide0 = ss2.getSlides().get(0);
+ assertRelation(slide0, "/ppt/slides/slide1.xml", null);
+ assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1");
+ assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2");
+ // TODO Fix this
+ assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3");
+ assertRelation(slide0, "/ppt/media/image1.png", "rId4");
+
+ }
+ }
}
private static void assertRelation(XSLFSlide slide, String exp, String rId) {
@@ -386,41 +375,40 @@ class TestXSLFBugs {
*/
@Test
void tika705() throws Exception {
- XMLSlideShow ss = openSampleDocument("with_japanese.pptx");
-
- // Should have one slide
- assertEquals(1, ss.getSlides().size());
- XSLFSlide slide = ss.getSlides().get(0);
-
- // Check the relations from this
- Collection<RelationPart> rels = slide.getRelationParts();
-
- // Should have 6 relations:
- // 1 external hyperlink (skipped from list)
- // 4 internal hyperlinks
- // 1 slide layout
- assertEquals(5, rels.size());
- int layouts = 0;
- int hyperlinks = 0;
- for (RelationPart p : rels) {
- if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) {
- hyperlinks++;
- } else if (p.getDocumentPart() instanceof XSLFSlideLayout) {
- layouts++;
+ try (XMLSlideShow ss = openSampleDocument("with_japanese.pptx")) {
+ // Should have one slide
+ assertEquals(1, ss.getSlides().size());
+ XSLFSlide slide = ss.getSlides().get(0);
+
+ // Check the relations from this
+ Collection<RelationPart> rels = slide.getRelationParts();
+
+ // Should have 6 relations:
+ // 1 external hyperlink (skipped from list)
+ // 4 internal hyperlinks
+ // 1 slide layout
+ assertEquals(5, rels.size());
+ int layouts = 0;
+ int hyperlinks = 0;
+ for (RelationPart p : rels) {
+ if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) {
+ hyperlinks++;
+ } else if (p.getDocumentPart() instanceof XSLFSlideLayout) {
+ layouts++;
+ }
}
- }
- assertEquals(1, layouts);
- assertEquals(4, hyperlinks);
-
- // Hyperlinks should all be to #_ftn1 or #ftnref1
- for (RelationPart p : rels) {
- if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) {
- URI target = p.getRelationship().getTargetURI();
- String frag = target.getFragment();
- assertTrue(frag.equals("_ftn1") || frag.equals("_ftnref1"), "Invalid target " + frag + " on " + target);
+ assertEquals(1, layouts);
+ assertEquals(4, hyperlinks);
+
+ // Hyperlinks should all be to #_ftn1 or #ftnref1
+ for (RelationPart p : rels) {
+ if (p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) {
+ URI target = p.getRelationship().getTargetURI();
+ String frag = target.getFragment();
+ assertTrue(frag.equals("_ftn1") || frag.equals("_ftnref1"), "Invalid target " + frag + " on " + target);
+ }
}
}
- ss.close();
}
/**
@@ -459,34 +447,34 @@ class TestXSLFBugs {
*/
@Test
void bug56812() throws Exception {
- XMLSlideShow ppt = openSampleDocument("56812.pptx");
-
- int internalPictures = 0;
- int externalPictures = 0;
- for (XSLFSlide slide : ppt.getSlides()) {
- for (XSLFShape shape : slide.getShapes()) {
- assertNotNull(shape);
-
- if (shape instanceof XSLFPictureShape) {
- XSLFPictureShape picture = (XSLFPictureShape) shape;
- if (picture.isExternalLinkedPicture()) {
- externalPictures++;
-
- assertNotNull(picture.getPictureLink());
- } else {
- internalPictures++;
-
- XSLFPictureData data = picture.getPictureData();
- assertNotNull(data);
- assertNotNull(data.getFileName());
+ try (XMLSlideShow ppt = openSampleDocument("56812.pptx")) {
+
+ int internalPictures = 0;
+ int externalPictures = 0;
+ for (XSLFSlide slide : ppt.getSlides()) {
+ for (XSLFShape shape : slide.getShapes()) {
+ assertNotNull(shape);
+
+ if (shape instanceof XSLFPictureShape) {
+ XSLFPictureShape picture = (XSLFPictureShape) shape;
+ if (picture.isExternalLinkedPicture()) {
+ externalPictures++;
+
+ assertNotNull(picture.getPictureLink());
+ } else {
+ internalPictures++;
+
+ XSLFPictureData data = picture.getPictureData();
+ assertNotNull(data);
+ assertNotNull(data.getFileName());
+ }
}
}
}
- }
- assertEquals(2, internalPictures);
- assertEquals(1, externalPictures);
- ppt.close();
+ assertEquals(2, internalPictures);
+ assertEquals(1, externalPictures);
+ }
}
private String getSlideText(XMLSlideShow ppt, XSLFSlide slide) throws IOException {
@@ -502,29 +490,29 @@ class TestXSLFBugs {
@Test
void bug57250() throws Exception {
- XMLSlideShow ss = new XMLSlideShow();
- for (String s : new String[]{"Slide1", "Slide2"}) {
- ss.createSlide().createTextBox().setText(s);
- }
- validateSlides(ss, false, "Slide1", "Slide2");
+ try (XMLSlideShow ss = new XMLSlideShow()) {
+ for (String s : new String[]{"Slide1", "Slide2"}) {
+ ss.createSlide().createTextBox().setText(s);
+ }
+ validateSlides(ss, false, "Slide1", "Slide2");
- XSLFSlide slide = ss.createSlide();
- slide.createTextBox().setText("New slide");
- validateSlides(ss, true, "Slide1", "Slide2", "New slide");
+ XSLFSlide slide = ss.createSlide();
+ slide.createTextBox().setText("New slide");
+ validateSlides(ss, true, "Slide1", "Slide2", "New slide");
- // Move backward
- ss.setSlideOrder(slide, 0);
- validateSlides(ss, true, "New slide", "Slide1", "Slide2");
+ // Move backward
+ ss.setSlideOrder(slide, 0);
+ validateSlides(ss, true, "New slide", "Slide1", "Slide2");
- // Move forward
- ss.setSlideOrder(slide, 1);
- validateSlides(ss, true, "Slide1", "New slide", "Slide2");
+ // Move forward
+ ss.setSlideOrder(slide, 1);
+ validateSlides(ss, true, "Slide1", "New slide", "Slide2");
- // Move to end
- ss.setSlideOrder(slide, 0);
- ss.setSlideOrder(slide, 2);
- validateSlides(ss, true, "Slide1", "Slide2", "New slide");
- ss.close();
+ // Move to end
+ ss.setSlideOrder(slide, 0);
+ ss.setSlideOrder(slide, 2);
+ validateSlides(ss, true, "Slide1", "Slide2", "New slide");
+ }
}
/**
@@ -533,89 +521,88 @@ class TestXSLFBugs {
*/
@Test
void test57552() throws Exception {
- XMLSlideShow ss = new XMLSlideShow();
- for (String s : new String[]{"Slide1", "Slide2"}) {
- ss.createSlide().createTextBox().setText(s);
- }
+ try (XMLSlideShow ss = new XMLSlideShow()) {
+ for (String s : new String[]{"Slide1", "Slide2"}) {
+ ss.createSlide().createTextBox().setText(s);
+ }
- // Slide starts with just layout relation
- XSLFSlide slide = ss.getSlides().get(0);
- assertEquals(0, ss.getPictureData().size());
- assertEquals(1, slide.getShapes().size());
+ // Slide starts with just layout relation
+ XSLFSlide slide = ss.getSlides().get(0);
+ assertEquals(0, ss.getPictureData().size());
+ assertEquals(1, slide.getShapes().size());
- assertEquals(1, slide.getRelations().size());
+ assertEquals(1, slide.getRelations().size());
- final XSLFRelation expected = XSLFRelation.SLIDE_LAYOUT;
- final POIXMLDocumentPart relation = slide.getRelations().get(0);
+ final XSLFRelation expected = XSLFRelation.SLIDE_LAYOUT;
+ final POIXMLDocumentPart relation = slide.getRelations().get(0);
- assertEquals(expected.getContentType(), relation.getPackagePart().getContentType());
- assertEquals(expected.getFileName(expected.getFileNameIndex(relation)), relation.getPackagePart().getPartName().getName());
+ assertEquals(expected.getContentType(), relation.getPackagePart().getContentType());
+ assertEquals(expected.getFileName(expected.getFileNameIndex(relation)), relation.getPackagePart().getPartName().getName());
- // Some dummy pictures
- byte[][] pics = new byte[15][3];
- for (int i = 0; i < pics.length; i++) {
- Arrays.fill(pics[i], (byte) i);
- }
-
- // Add a few pictures
- addPictures(ss, slide, pics, 0, 10);
+ // Some dummy pictures
+ byte[][] pics = new byte[15][3];
+ for (int i = 0; i < pics.length; i++) {
+ Arrays.fill(pics[i], (byte) i);
+ }
- // Re-fetch the pictures and check
- for (int i = 0; i < 10; i++) {
- XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1);
- assertNotNull(shape.getPictureData());
- assertArrayEquals(pics[i], shape.getPictureData().getData());
- }
+ // Add a few pictures
+ addPictures(ss, slide, pics, 0, 10);
- // Add past 10
- addPictures(ss, slide, pics, 10, 15);
+ // Re-fetch the pictures and check
+ for (int i = 0; i < 10; i++) {
+ XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1);
+ assertNotNull(shape.getPictureData());
+ assertArrayEquals(pics[i], shape.getPictureData().getData());
+ }
- // Check all pictures
- for (int i = 0; i < 15; i++) {
- XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1);
- assertNotNull(shape.getPictureData());
- assertArrayEquals(pics[i], shape.getPictureData().getData());
- }
+ // Add past 10
+ addPictures(ss, slide, pics, 10, 15);
- // Add a duplicate, check the right one is picked
- XSLFPictureData data = ss.addPicture(pics[3], PictureType.JPEG);
- assertEquals(3, data.getIndex());
- assertEquals(15, ss.getPictureData().size());
+ // Check all pictures
+ for (int i = 0; i < 15; i++) {
+ XSLFPictureShape shape = (XSLFPictureShape) slide.getShapes().get(i + 1);
+ assertNotNull(shape.getPictureData());
+ assertArrayEquals(pics[i], shape.getPictureData().getData());
+ }
- XSLFPictureShape shape = slide.createPicture(data);
- assertNotNull(shape.getPictureData());
- assertArrayEquals(pics[3], shape.getPictureData().getData());
- assertEquals(17, slide.getShapes().size());
+ // Add a duplicate, check the right one is picked
+ XSLFPictureData data = ss.addPicture(pics[3], PictureType.JPEG);
+ assertEquals(3, data.getIndex());
+ assertEquals(15, ss.getPictureData().size());
+ XSLFPictureShape shape = slide.createPicture(data);
+ assertNotNull(shape.getPictureData());
+ assertArrayEquals(pics[3], shape.getPictureData().getData());
+ assertEquals(17, slide.getShapes().size());
- // Save and re-load
- XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss);
- slide = ss2.getSlides().get(0);
- // Check the 15 individual ones added
- for (int i = 0; i < 15; i++) {
- shape = (XSLFPictureShape) slide.getShapes().get(i + 1);
- assertNotNull(shape.getPictureData());
- assertArrayEquals(pics[i], shape.getPictureData().getData());
- }
+ // Save and re-load
+ try (XMLSlideShow ss2 = writeOutAndReadBack(ss)) {
+ slide = ss2.getSlides().get(0);
- // Check the duplicate
- shape = (XSLFPictureShape) slide.getShapes().get(16);
- assertNotNull(shape.getPictureData());
- assertArrayEquals(pics[3], shape.getPictureData().getData());
+ // Check the 15 individual ones added
+ for (int i = 0; i < 15; i++) {
+ shape = (XSLFPictureShape) slide.getShapes().get(i + 1);
+ assertNotNull(shape.getPictureData());
+ assertArrayEquals(pics[i], shape.getPictureData().getData());
+ }
- // Add another duplicate
- data = ss2.addPicture(pics[5], PictureType.JPEG);
- assertEquals(5, data.getIndex());
- assertEquals(15, ss2.getPictureData().size());
+ // Check the duplicate
+ shape = (XSLFPictureShape) slide.getShapes().get(16);
+ assertNotNull(shape.getPictureData());
+ assertArrayEquals(pics[3], shape.getPictureData().getData());
- shape = slide.createPicture(data);
- assertNotNull(shape.getPictureData());
- assertArrayEquals(pics[5], shape.getPictureData().getData());
- assertEquals(18, slide.getShapes().size());
+ // Add another duplicate
+ data = ss2.addPicture(pics[5], PictureType.JPEG);
+ assertEquals(5, data.getIndex());
+ assertEquals(15, ss2.getPictureData().size());
- ss2.close();
- ss.close();
+ shape = slide.createPicture(data);
+ assertNotNull(shape.getPictureData());
+ assertArrayEquals(pics[5], shape.getPictureData().getData());
+ assertEquals(18, slide.getShapes().size());
+ }
+ }
}
private void addPictures(XMLSlideShow ss, XSLFSlide slide, byte[][] pics, int start, int end) {
@@ -633,9 +620,9 @@ class TestXSLFBugs {
private void validateSlides(XMLSlideShow ss, boolean saveAndReload, String... slideTexts) throws IOException {
if (saveAndReload) {
- XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss);
- validateSlides(ss, slideTexts);
- ss2.close();
+ try (XMLSlideShow ss2 = writeOutAndReadBack(ss)) {
+ validateSlides(ss2, slideTexts);
+ }
} else {
validateSlides(ss, slideTexts);
}
@@ -652,69 +639,57 @@ class TestXSLFBugs {
@Test
void bug58205() throws IOException {
- XMLSlideShow ss = openSampleDocument("themes.pptx");
-
- int i = 1;
- for (XSLFSlideMaster sm : ss.getSlideMasters()) {
- assertEquals("rId" + (i++), ss.getRelationId(sm));
+ try (XMLSlideShow ss = openSampleDocument("themes.pptx")) {
+ int i = 1;
+ for (XSLFSlideMaster sm : ss.getSlideMasters()) {
+ assertEquals("rId" + (i++), ss.getRelationId(sm));
+ }
}
-
- ss.close();
}
- @Test
- void bug55791a() throws IOException {
- XMLSlideShow ppt = openSampleDocument("45541_Footer.pptx");
- removeAndCreateSlide(ppt);
- ppt.close();
- }
-
- @Test
- void bug55791b() throws IOException {
- XMLSlideShow ppt = openSampleDocument("SampleShow.pptx");
- removeAndCreateSlide(ppt);
- ppt.close();
- }
-
- private void removeAndCreateSlide(XMLSlideShow ppt) {
- assertTrue(ppt.getSlides().size() > 1);
- ppt.removeSlide(1);
- assertNotNull(ppt.createSlide());
+ @ParameterizedTest
+ @ValueSource(strings = {"45541_Footer.pptx", "SampleShow.pptx"})
+ void bug55791(String fileName) throws IOException {
+ try (XMLSlideShow ppt = openSampleDocument(fileName)) {
+ assertTrue(ppt.getSlides().size() > 1);
+ ppt.removeSlide(1);
+ assertNotNull(ppt.createSlide());
+ }
}
@Test
void blibFillAlternateContent() throws IOException {
- XMLSlideShow ppt = openSampleDocument("2411-Performance_Up.pptx");
- XSLFPictureShape ps = (XSLFPictureShape) ppt.getSlides().get(4).getShapes().get(0);
- assertNotNull(ps.getPictureData());
- ppt.close();
+ try (XMLSlideShow ppt = openSampleDocument("2411-Performance_Up.pptx")) {
+ XSLFPictureShape ps = (XSLFPictureShape) ppt.getSlides().get(4).getShapes().get(0);
+ assertNotNull(ps.getPictureData());
+ }
}
@Test
void bug59434() throws IOException {
String url1 = "https://poi.apache.org/changes.html";
String url2 = "https://poi.apache.org/faq.html";
- XMLSlideShow ppt1 = new XMLSlideShow();
- PictureData pd1 = ppt1.addPicture(slTests.readFile("tomcat.png"), PictureType.PNG);
- PictureData pd2 = ppt1.addPicture(slTests.readFile("santa.wmf"), PictureType.WMF);
- XSLFSlide slide = ppt1.createSlide();
- XSLFPictureShape ps1 = slide.createPicture(pd1);
- ps1.setAnchor(new Rectangle2D.Double(20, 20, 100, 100));
- XSLFHyperlink hl1 = ps1.createHyperlink();
- hl1.linkToUrl(url1);
- XSLFPictureShape ps2 = slide.createPicture(pd2);
- ps2.setAnchor(new Rectangle2D.Double(120, 120, 100, 100));
- XSLFHyperlink hl2 = ps2.createHyperlink();
- hl2.linkToUrl(url2);
- XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1);
- ppt1.close();
- slide = ppt2.getSlides().get(0);
- ps1 = (XSLFPictureShape) slide.getShapes().get(0);
- ps2 = (XSLFPictureShape) slide.getShapes().get(1);
- assertEquals(url1, ps1.getHyperlink().getAddress());
- assertEquals(url2, ps2.getHyperlink().getAddress());
-
- ppt2.close();
+ try (XMLSlideShow ppt1 = new XMLSlideShow()) {
+ PictureData pd1 = ppt1.addPicture(slTests.readFile("tomcat.png"), PictureType.PNG);
+ PictureData pd2 = ppt1.addPicture(slTests.readFile("santa.wmf"), PictureType.WMF);
+ XSLFSlide slide = ppt1.createSlide();
+ XSLFPictureShape ps1 = slide.createPicture(pd1);
+ ps1.setAnchor(new Rectangle2D.Double(20, 20, 100, 100));
+ XSLFHyperlink hl1 = ps1.createHyperlink();
+ hl1.linkToUrl(url1);
+ XSLFPictureShape ps2 = slide.createPicture(pd2);
+ ps2.setAnchor(new Rectangle2D.Double(120, 120, 100, 100));
+ XSLFHyperlink hl2 = ps2.createHyperlink();
+ hl2.linkToUrl(url2);
+
+ try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ slide = ppt2.getSlides().get(0);
+ ps1 = (XSLFPictureShape) slide.getShapes().get(0);
+ ps2 = (XSLFPictureShape) slide.getShapes().get(1);
+ assertEquals(url1, ps1.getHyperlink().getAddress());
+ assertEquals(url2, ps2.getHyperlink().getAddress());
+ }
+ }
}
@Test
@@ -723,27 +698,27 @@ class TestXSLFBugs {
Color lineColor = new Color(25.3f / 255f, 1f, 0f, 0.4f);
Color textColor = new Color(1f, 1f, 0f, 0.6f);
- XMLSlideShow ppt1 = new XMLSlideShow();
- XSLFSlide sl = ppt1.createSlide();
- XSLFAutoShape as = sl.createAutoShape();
- as.setShapeType(ShapeType.STAR_10);
- as.setAnchor(new Rectangle2D.Double(100, 100, 300, 300));
- as.setFillColor(fillColor);
- as.setLineColor(lineColor);
- as.setText("Alpha");
- as.setVerticalAlignment(VerticalAlignment.MIDDLE);
- as.setHorizontalCentered(true);
- XSLFTextRun tr = as.getTextParagraphs().get(0).getTextRuns().get(0);
- tr.setFontSize(32d);
- tr.setFontColor(textColor);
- XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1);
- ppt1.close();
- sl = ppt2.getSlides().get(0);
- as = (XSLFAutoShape) sl.getShapes().get(0);
- checkColor(fillColor, as.getFillStyle().getPaint());
- checkColor(lineColor, as.getStrokeStyle().getPaint());
- checkColor(textColor, as.getTextParagraphs().get(0).getTextRuns().get(0).getFontColor());
- ppt2.close();
+ try (XMLSlideShow ppt1 = new XMLSlideShow()) {
+ XSLFSlide sl = ppt1.createSlide();
+ XSLFAutoShape as = sl.createAutoShape();
+ as.setShapeType(ShapeType.STAR_10);
+ as.setAnchor(new Rectangle2D.Double(100, 100, 300, 300));
+ as.setFillColor(fillColor);
+ as.setLineColor(lineColor);
+ as.setText("Alpha");
+ as.setVerticalAlignment(VerticalAlignment.MIDDLE);
+ as.setHorizontalCentered(true);
+ XSLFTextRun tr = as.getTextParagraphs().get(0).getTextRuns().get(0);
+ tr.setFontSize(32d);
+ tr.setFontColor(textColor);
+ try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ sl = ppt2.getSlides().get(0);
+ as = (XSLFAutoShape) sl.getShapes().get(0);
+ checkColor(fillColor, as.getFillStyle().getPaint());
+ checkColor(lineColor, as.getStrokeStyle().getPaint());
+ checkColor(textColor, as.getTextParagraphs().get(0).getTextRuns().get(0).getFontColor());
+ }
+ }
}
private static void checkColor(Color expected, PaintStyle actualStyle) {
@@ -757,64 +732,60 @@ class TestXSLFBugs {
@Test
void bug55714() throws IOException {
- XMLSlideShow srcPptx = openSampleDocument("pptx2svg.pptx");
- XMLSlideShow newPptx = new XMLSlideShow();
- XSLFSlide srcSlide = srcPptx.getSlides().get(0);
- XSLFSlide newSlide = newPptx.createSlide();
-
- XSLFSlideLayout srcSlideLayout = srcSlide.getSlideLayout();
- XSLFSlideLayout newSlideLayout = newSlide.getSlideLayout();
- newSlideLayout.importContent(srcSlideLayout);
-
- XSLFSlideMaster srcSlideMaster = srcSlide.getSlideMaster();
- XSLFSlideMaster newSlideMaster = newSlide.getSlideMaster();
- newSlideMaster.importContent(srcSlideMaster);
-
- newSlide.importContent(srcSlide);
- XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(newPptx);
-
- PaintStyle ps = rwPptx.getSlides().get(0).getBackground().getFillStyle().getPaint();
- assertTrue(ps instanceof TexturePaint);
-
- rwPptx.close();
- newPptx.close();
- srcPptx.close();
+ try (XMLSlideShow srcPptx = openSampleDocument("pptx2svg.pptx");
+ XMLSlideShow newPptx = new XMLSlideShow()) {
+ XSLFSlide srcSlide = srcPptx.getSlides().get(0);
+ XSLFSlide newSlide = newPptx.createSlide();
+
+ XSLFSlideLayout srcSlideLayout = srcSlide.getSlideLayout();
+ XSLFSlideLayout newSlideLayout = newSlide.getSlideLayout();
+ newSlideLayout.importContent(srcSlideLayout);
+
+ XSLFSlideMaster srcSlideMaster = srcSlide.getSlideMaster();
+ XSLFSlideMaster newSlideMaster = newSlide.getSlideMaster();
+ newSlideMaster.importContent(srcSlideMaster);
+
+ newSlide.importContent(srcSlide);
+ try (XMLSlideShow rwPptx = writeOutAndReadBack(newPptx)) {
+ PaintStyle ps = rwPptx.getSlides().get(0).getBackground().getFillStyle().getPaint();
+ assertTrue(ps instanceof TexturePaint);
+ }
+ }
}
@Test
void bug59273() throws IOException {
- XMLSlideShow ppt = openSampleDocument("bug59273.potx");
- ppt.getPackage().replaceContentType(
- XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType(),
- XSLFRelation.MAIN.getContentType()
- );
-
- XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(ppt);
- OPCPackage pkg = rwPptx.getPackage();
- int size = pkg.getPartsByContentType(XSLFRelation.MAIN.getContentType()).size();
- assertEquals(1, size);
- size = pkg.getPartsByContentType(XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType()).size();
- assertEquals(0, size);
-
- rwPptx.close();
- ppt.close();
+ try (XMLSlideShow ppt = openSampleDocument("bug59273.potx")) {
+ ppt.getPackage().replaceContentType(
+ XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType(),
+ XSLFRelation.MAIN.getContentType()
+ );
+
+ try (XMLSlideShow rwPptx = writeOutAndReadBack(ppt)) {
+ OPCPackage pkg = rwPptx.getPackage();
+ int size = pkg.getPartsByContentType(XSLFRelation.MAIN.getContentType()).size();
+ assertEquals(1, size);
+ size = pkg.getPartsByContentType(XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType()).size();
+ assertEquals(0, size);
+ }
+ }
}
@Test
void bug60373() throws IOException {
- XMLSlideShow ppt = new XMLSlideShow();
- XSLFSlide sl = ppt.createSlide();
- XSLFTable t = sl.createTable();
- XSLFTableRow r = t.addRow();
- bug60373_addCell(r);
- bug60373_addCell(r);
- r = t.addRow();
- XSLFTableCell c = bug60373_addCell(r);
- // call getTextHeight, when table is not fully populated
- double th = c.getTextHeight();
- assertTrue(th > 10);
- ppt.close();
+ try (XMLSlideShow ppt = new XMLSlideShow()) {
+ XSLFSlide sl = ppt.createSlide();
+ XSLFTable t = sl.createTable();
+ XSLFTableRow r = t.addRow();
+ bug60373_addCell(r);
+ bug60373_addCell(r);
+ r = t.addRow();
+ XSLFTableCell c = bug60373_addCell(r);
+ // call getTextHeight, when table is not fully populated
+ double th = c.getTextHeight();
+ assertTrue(th > 10);
+ }
}
private static XSLFTableCell bug60373_addCell(XSLFTableRow r) {
@@ -834,42 +805,39 @@ class TestXSLFBugs {
@Test
void bug60662() throws IOException {
- XMLSlideShow src = new XMLSlideShow();
- XSLFSlide sl = src.createSlide();
- XSLFGroupShape gs = sl.createGroup();
- gs.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
- gs.setInteriorAnchor(new Rectangle2D.Double(0, 0, 100, 100));
- XSLFAutoShape as = gs.createAutoShape();
- as.setAnchor(new Rectangle2D.Double(0, 0, 100, 100));
- as.setShapeType(ShapeType.STAR_24);
- as.setFillColor(Color.YELLOW);
- CTShape csh = (CTShape) as.getXmlObject();
- CTOuterShadowEffect shadow = csh.getSpPr().addNewEffectLst().addNewOuterShdw();
- shadow.setDir(270000);
- shadow.setDist(100000);
- shadow.addNewSrgbClr().setVal(new byte[]{0x00, (byte) 0xFF, 0x00});
-
- XMLSlideShow dst = new XMLSlideShow();
- XSLFSlide sl2 = dst.createSlide();
- sl2.importContent(sl);
- XSLFGroupShape gs2 = (XSLFGroupShape) sl2.getShapes().get(0);
- XSLFAutoShape as2 = (XSLFAutoShape) gs2.getShapes().get(0);
- CTShape csh2 = (CTShape) as2.getXmlObject();
- assertTrue(csh2.getSpPr().isSetEffectLst());
-
- dst.close();
- src.close();
+ try (XMLSlideShow src = new XMLSlideShow();
+ XMLSlideShow dst = new XMLSlideShow()) {
+ XSLFSlide sl = src.createSlide();
+ XSLFGroupShape gs = sl.createGroup();
+ gs.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
+ gs.setInteriorAnchor(new Rectangle2D.Double(0, 0, 100, 100));
+ XSLFAutoShape as = gs.createAutoShape();
+ as.setAnchor(new Rectangle2D.Double(0, 0, 100, 100));
+ as.setShapeType(ShapeType.STAR_24);
+ as.setFillColor(Color.YELLOW);
+ CTShape csh = (CTShape) as.getXmlObject();
+ CTOuterShadowEffect shadow = csh.getSpPr().addNewEffectLst().addNewOuterShdw();
+ shadow.setDir(270000);
+ shadow.setDist(100000);
+ shadow.addNewSrgbClr().setVal(new byte[]{0x00, (byte) 0xFF, 0x00});
+
+ XSLFSlide sl2 = dst.createSlide();
+ sl2.importContent(sl);
+ XSLFGroupShape gs2 = (XSLFGroupShape) sl2.getShapes().get(0);
+ XSLFAutoShape as2 = (XSLFAutoShape) gs2.getShapes().get(0);
+ CTShape csh2 = (CTShape) as2.getXmlObject();
+ assertTrue(csh2.getSpPr().isSetEffectLst());
+ }
}
@Test
void test60810() throws IOException {
- XMLSlideShow ppt = openSampleDocument("60810.pptx");
- for (XSLFSlide slide : ppt.getSlides()) {
- XSLFNotes notesSlide = ppt.getNotesSlide(slide);
- assertNotNull(notesSlide);
+ try (XMLSlideShow ppt = openSampleDocument("60810.pptx")) {
+ for (XSLFSlide slide : ppt.getSlides()) {
+ XSLFNotes notesSlide = ppt.getNotesSlide(slide);
+ assertNotNull(notesSlide);
+ }
}
-
- ppt.close();
}
@Test
@@ -886,7 +854,7 @@ class TestXSLFBugs {
try (XMLSlideShow ppt = openSampleDocument("61515.pptx")) {
ppt.removeSlide(0);
assertEquals(1, ppt.createSlide().getRelations().size());
- try (XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) {
+ try (XMLSlideShow saved = writeOutAndReadBack(ppt)) {
assertEquals(1, saved.getSlides().size());
XSLFSlide slide = saved.getSlides().get(0);
assertEquals(1, slide.getRelations().size());
@@ -897,7 +865,7 @@ class TestXSLFBugs {
@Test
void testAptia() throws IOException {
try (XMLSlideShow ppt = openSampleDocument("aptia.pptx");
- XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) {
+ XMLSlideShow saved = writeOutAndReadBack(ppt)) {
assertEquals(ppt.getSlides().size(), saved.getSlides().size());
}
}
@@ -906,7 +874,7 @@ class TestXSLFBugs {
@Test
void testDivinoRevelado() throws IOException {
try (XMLSlideShow ppt = openSampleDocument("Divino_Revelado.pptx");
- XMLSlideShow saved = XSLFTestDataSamples.writeOutAndReadBack(ppt)) {
+ XMLSlideShow saved = writeOutAndReadBack(ppt)) {
assertEquals(ppt.getSlides().size(), saved.getSlides().size());
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java
index d902c12714..897fcd1d27 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/XSLFTestDataSamples.java
@@ -16,54 +16,32 @@
==================================================================== */
package org.apache.poi.xslf;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
public class XSLFTestDataSamples {
public static XMLSlideShow openSampleDocument(String sampleName) {
- InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream(sampleName);
- try {
+ try (InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream(sampleName)) {
return new XMLSlideShow(OPCPackage.open(is));
} catch (Exception e) {
throw new RuntimeException(e);
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
}
}
public static XMLSlideShow writeOutAndReadBack(XMLSlideShow doc) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
- try {
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) {
doc.write(baos);
+ try (InputStream bais = baos.toInputStream()) {
+ return new XMLSlideShow(bais);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
-
- InputStream bais;
- bais = new ByteArrayInputStream(baos.toByteArray());
- try {
- return new XMLSlideShow(OPCPackage.open(bais));
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- try {
- baos.close();
- bais.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java
index 520f62fb04..295767a75c 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java
@@ -16,14 +16,14 @@
==================================================================== */
package org.apache.poi.xslf.usermodel;
+import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument;
+import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.opc.OPCPackage;
@@ -69,133 +69,119 @@ class TestXMLSlideShow extends BaseTestSlideShow<XSLFShape, XSLFTextParagraph> {
@Test
void testOpen() throws Exception {
// With the finalised uri, should be fine
- XMLSlideShow xml = new XMLSlideShow(pack);
- // Check the core
- assertNotNull(xml.getCTPresentation());
+ try (XMLSlideShow xml = new XMLSlideShow(pack)) {
+ // Check the core
+ assertNotNull(xml.getCTPresentation());
- // Check it has some slides
- assertFalse(xml.getSlides().isEmpty());
- assertFalse(xml.getSlideMasters().isEmpty());
-
- xml.close();
+ // Check it has some slides
+ assertFalse(xml.getSlides().isEmpty());
+ assertFalse(xml.getSlideMasters().isEmpty());
+ }
}
- @SuppressWarnings("deprecation")
@Test
void testSlideBasics() throws IOException {
- XMLSlideShow xml = new XMLSlideShow(pack);
+ try (XMLSlideShow xml = new XMLSlideShow(pack)) {
- // Should have 1 master
- assertEquals(1, xml.getSlideMasters().size());
+ // Should have 1 master
+ assertEquals(1, xml.getSlideMasters().size());
- // Should have two sheets
- assertEquals(2, xml.getSlides().size());
+ // Should have two sheets
+ assertEquals(2, xml.getSlides().size());
- // Check they're as expected
- CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray();
+ // Check they're as expected
+ CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray();
- assertEquals(256, slides[0].getId());
- assertEquals(257, slides[1].getId());
- assertEquals("rId2", slides[0].getId2());
- assertEquals("rId3", slides[1].getId2());
+ assertEquals(256, slides[0].getId());
+ assertEquals(257, slides[1].getId());
+ assertEquals("rId2", slides[0].getId2());
+ assertEquals("rId3", slides[1].getId2());
- // Now get those objects
- assertNotNull(xml.getSlides().get(0));
- assertNotNull(xml.getSlides().get(1));
+ // Now get those objects
+ assertNotNull(xml.getSlides().get(0));
+ assertNotNull(xml.getSlides().get(1));
- // And check they have notes as expected
- assertNotNull(xml.getSlides().get(0).getNotes());
- assertNotNull(xml.getSlides().get(1).getNotes());
+ // And check they have notes as expected
+ assertNotNull(xml.getSlides().get(0).getNotes());
+ assertNotNull(xml.getSlides().get(1).getNotes());
- // Next up look for the slide master
- CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray();
+ // Next up look for the slide master
+ CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray();
- // see SlideAtom.USES_MASTER_SLIDE_ID
- assertEquals(0x80000000L, masters[0].getId());
- assertEquals("rId1", masters[0].getId2());
- assertNotNull(xml.getSlideMasters().get(0));
+ // see SlideAtom.USES_MASTER_SLIDE_ID
+ assertEquals(0x80000000L, masters[0].getId());
+ assertEquals("rId1", masters[0].getId2());
+ assertNotNull(xml.getSlideMasters().get(0));
- // Finally look for the notes master
- CTNotesMasterIdListEntry notesMaster =
- xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId();
- assertNotNull(notesMaster);
+ // Finally look for the notes master
+ CTNotesMasterIdListEntry notesMaster =
+ xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId();
+ assertNotNull(notesMaster);
- assertNotNull(xml.getNotesMaster());
-
- xml.close();
+ assertNotNull(xml.getNotesMaster());
+ }
}
@Test
void testMetadataBasics() throws IOException {
- XMLSlideShow xml = new XMLSlideShow(pack);
+ try (XMLSlideShow xml = new XMLSlideShow(pack)) {
- assertNotNull(xml.getProperties().getCoreProperties());
- assertNotNull(xml.getProperties().getExtendedProperties());
+ assertNotNull(xml.getProperties().getCoreProperties());
+ assertNotNull(xml.getProperties().getExtendedProperties());
- assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication());
- assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters());
- assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines());
+ assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication());
+ assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters());
+ assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines());
- assertNull(xml.getProperties().getCoreProperties().getTitle());
- assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent());
-
- xml.close();
+ assertNull(xml.getProperties().getCoreProperties().getTitle());
+ assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent());
+ }
}
@Test
void testComments() throws Exception {
// Default sample file has none
- XMLSlideShow xml = new XMLSlideShow(pack);
-
- assertNull(xml.getCommentAuthors());
+ try (XMLSlideShow xml = new XMLSlideShow(pack)) {
+ assertNull(xml.getCommentAuthors());
- for (XSLFSlide slide : xml.getSlides()) {
- assertTrue(slide.getComments().isEmpty());
+ for (XSLFSlide slide : xml.getSlides()) {
+ assertTrue(slide.getComments().isEmpty());
+ }
}
// Try another with comments
- XMLSlideShow xmlComments = new XMLSlideShow(slTests.openResourceAsStream("45545_Comment.pptx"));
-
- // Has one author
- assertNotNull(xmlComments.getCommentAuthors());
- assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray());
- assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName());
-
- // First two slides have comments
- int i = -1;
- for (XSLFSlide slide : xmlComments.getSlides()) {
- i++;
-
- if (i == 0) {
- assertNotNull(slide.getCommentsPart());
- assertEquals(1, slide.getCommentsPart().getNumberOfComments());
- assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText());
- assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId());
- } else if (i == 1) {
- assertNotNull(slide.getComments());
- assertEquals(1, slide.getCommentsPart().getNumberOfComments());
- assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText());
- assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId());
- } else {
- assertNull(slide.getCommentsPart());
- assertTrue(slide.getComments().isEmpty());
+ try (XMLSlideShow xmlComments = openSampleDocument("45545_Comment.pptx")) {
+
+ // Has one author
+ assertNotNull(xmlComments.getCommentAuthors());
+ assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray());
+ assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName());
+
+ // First two slides have comments
+ int i = -1;
+ for (XSLFSlide slide : xmlComments.getSlides()) {
+ i++;
+
+ if (i == 0) {
+ assertNotNull(slide.getCommentsPart());
+ assertEquals(1, slide.getCommentsPart().getNumberOfComments());
+ assertEquals("testdoc", slide.getCommentsPart().getCommentAt(0).getText());
+ assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId());
+ } else if (i == 1) {
+ assertNotNull(slide.getComments());
+ assertEquals(1, slide.getCommentsPart().getNumberOfComments());
+ assertEquals("test phrase", slide.getCommentsPart().getCommentAt(0).getText());
+ assertEquals(0, slide.getCommentsPart().getCommentAt(0).getAuthorId());
+ } else {
+ assertNull(slide.getCommentsPart());
+ assertTrue(slide.getComments().isEmpty());
+ }
}
}
-
- xmlComments.close();
- xml.close();
}
@Override
public XMLSlideShow reopen(SlideShow<XSLFShape, XSLFTextParagraph> show) throws IOException {
- BufAccessBAOS bos = new BufAccessBAOS();
- show.write(bos);
- return new XMLSlideShow(new ByteArrayInputStream(bos.getBuf()));
- }
-
- private static class BufAccessBAOS extends ByteArrayOutputStream {
- byte[] getBuf() {
- return buf;
- }
+ return writeOutAndReadBack((XMLSlideShow) show);
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java
index 02640c0efe..78ae286f7e 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFExamples.java
@@ -21,12 +21,10 @@ import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERT
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Rectangle;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.List;
import javax.xml.namespace.QName;
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java
index 0df21b2720..37fb3318be 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java
@@ -16,6 +16,8 @@
==================================================================== */
package org.apache.poi.xslf.usermodel;
+import static org.apache.poi.xslf.XSLFTestDataSamples.openSampleDocument;
+import static org.apache.poi.xslf.XSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -25,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -41,7 +41,6 @@ import org.apache.poi.POIDataSamples;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
-import org.apache.poi.xslf.XSLFTestDataSamples;
import org.apache.poi.xslf.util.PPTX2PNG;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture;
@@ -51,245 +50,240 @@ class TestXSLFPictureShape {
@Test
void testCreate() throws Exception {
- XMLSlideShow ppt1 = new XMLSlideShow();
- assertEquals(0, ppt1.getPictureData().size());
- byte[] data1 = new byte[100];
- for(int i = 0;i < 100;i++) { data1[i] = (byte)i; }
- XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG);
- assertEquals(0, pdata1.getIndex());
- assertEquals(1, ppt1.getPictureData().size());
-
- XSLFSlide slide = ppt1.createSlide();
- XSLFPictureShape shape1 = slide.createPicture(pdata1);
- assertNotNull(shape1.getPictureData());
- assertArrayEquals(data1, shape1.getPictureData().getData());
-
- byte[] data2 = new byte[200];
- for(int i = 0;i < 200;i++) { data2[i] = (byte)i; }
- XSLFPictureData pdata2 = ppt1.addPicture(data2, PictureType.PNG);
- XSLFPictureShape shape2 = slide.createPicture(pdata2);
- assertNotNull(shape2.getPictureData());
- assertEquals(1, pdata2.getIndex());
- assertEquals(2, ppt1.getPictureData().size());
- assertArrayEquals(data2, shape2.getPictureData().getData());
-
- XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1);
- ppt1.close();
- List<XSLFPictureData> pics = ppt2.getPictureData();
- assertEquals(2, pics.size());
- assertArrayEquals(data1, pics.get(0).getData());
- assertArrayEquals(data2, pics.get(1).getData());
-
- List<XSLFShape> shapes = ppt2.getSlides().get(0).getShapes();
- assertArrayEquals(data1, ((XSLFPictureShape) shapes.get(0)).getPictureData().getData());
- assertArrayEquals(data2, ((XSLFPictureShape) shapes.get(1)).getPictureData().getData());
- ppt2.close();
+ try (XMLSlideShow ppt1 = new XMLSlideShow()) {
+ assertEquals(0, ppt1.getPictureData().size());
+ byte[] data1 = new byte[100];
+ for (int i = 0; i < 100; i++) {
+ data1[i] = (byte) i;
+ }
+ XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG);
+ assertEquals(0, pdata1.getIndex());
+ assertEquals(1, ppt1.getPictureData().size());
+
+ XSLFSlide slide = ppt1.createSlide();
+ XSLFPictureShape shape1 = slide.createPicture(pdata1);
+ assertNotNull(shape1.getPictureData());
+ assertArrayEquals(data1, shape1.getPictureData().getData());
+
+ byte[] data2 = new byte[200];
+ for (int i = 0; i < 200; i++) {
+ data2[i] = (byte) i;
+ }
+ XSLFPictureData pdata2 = ppt1.addPicture(data2, PictureType.PNG);
+ XSLFPictureShape shape2 = slide.createPicture(pdata2);
+ assertNotNull(shape2.getPictureData());
+ assertEquals(1, pdata2.getIndex());
+ assertEquals(2, ppt1.getPictureData().size());
+ assertArrayEquals(data2, shape2.getPictureData().getData());
+
+ try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ List<XSLFPictureData> pics = ppt2.getPictureData();
+ assertEquals(2, pics.size());
+ assertArrayEquals(data1, pics.get(0).getData());
+ assertArrayEquals(data2, pics.get(1).getData());
+
+ List<XSLFShape> shapes = ppt2.getSlides().get(0).getShapes();
+ assertArrayEquals(data1, ((XSLFPictureShape) shapes.get(0)).getPictureData().getData());
+ assertArrayEquals(data2, ((XSLFPictureShape) shapes.get(1)).getPictureData().getData());
+ }
+ }
}
@Test
void testCreateMultiplePictures() throws Exception {
- XMLSlideShow ppt1 = new XMLSlideShow();
- XSLFSlide slide1 = ppt1.createSlide();
- XSLFGroupShape group1 = slide1.createGroup();
-
-
- int pictureIndex = 0;
- // first add 20 images to the slide
- for (int i = 0; i < 20; i++, pictureIndex++) {
- byte[] data = new byte[]{(byte)pictureIndex};
- XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG);
- assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19
- XSLFPictureShape picture = slide1.createPicture(elementData);
- // POI saves images as image1.png, image2.png, etc.
- String fileName = "image" + (elementData.getIndex()+1) + ".png";
- assertEquals(fileName, picture.getPictureData().getFileName());
- assertArrayEquals(data, picture.getPictureData().getData());
- }
-
- // and then add next 20 images to a group
- for (int i = 0; i < 20; i++, pictureIndex++) {
- byte[] data = new byte[]{(byte)pictureIndex};
- XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG);
- XSLFPictureShape picture = group1.createPicture(elementData);
- // POI saves images as image1.png, image2.png, etc.
- assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19
- String fileName = "image" + (pictureIndex + 1) + ".png";
- assertEquals(fileName, picture.getPictureData().getFileName());
- assertArrayEquals(data, picture.getPictureData().getData());
- }
+ try (XMLSlideShow ppt1 = new XMLSlideShow()) {
+ XSLFSlide slide1 = ppt1.createSlide();
+ XSLFGroupShape group1 = slide1.createGroup();
+
+
+ int pictureIndex = 0;
+ // first add 20 images to the slide
+ for (int i = 0; i < 20; i++, pictureIndex++) {
+ byte[] data = new byte[]{(byte) pictureIndex};
+ XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG);
+ assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19
+ XSLFPictureShape picture = slide1.createPicture(elementData);
+ // POI saves images as image1.png, image2.png, etc.
+ String fileName = "image" + (elementData.getIndex() + 1) + ".png";
+ assertEquals(fileName, picture.getPictureData().getFileName());
+ assertArrayEquals(data, picture.getPictureData().getData());
+ }
- // serialize, read back and check that all images are there
+ // and then add next 20 images to a group
+ for (int i = 0; i < 20; i++, pictureIndex++) {
+ byte[] data = new byte[]{(byte) pictureIndex};
+ XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG);
+ XSLFPictureShape picture = group1.createPicture(elementData);
+ // POI saves images as image1.png, image2.png, etc.
+ assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19
+ String fileName = "image" + (pictureIndex + 1) + ".png";
+ assertEquals(fileName, picture.getPictureData().getFileName());
+ assertArrayEquals(data, picture.getPictureData().getData());
+ }
- XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1);
- ppt1.close();
- // pictures keyed by file name
- Map<String, XSLFPictureData> pics = new HashMap<>();
- for(XSLFPictureData p : ppt2.getPictureData()){
- pics.put(p.getFileName(), p);
- }
- assertEquals(40, pics.size());
- for (int i = 0; i < 40; i++) {
- byte[] data1 = new byte[]{(byte)i};
- String fileName = "image" + (i + 1) + ".png";
- XSLFPictureData data = pics.get(fileName);
- assertNotNull(data);
- assertEquals(fileName, data.getFileName());
- assertArrayEquals(data1, data.getData());
+ // serialize, read back and check that all images are there
+
+ try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ // pictures keyed by file name
+ Map<String, XSLFPictureData> pics = new HashMap<>();
+ for (XSLFPictureData p : ppt2.getPictureData()) {
+ pics.put(p.getFileName(), p);
+ }
+ assertEquals(40, pics.size());
+ for (int i = 0; i < 40; i++) {
+ byte[] data1 = new byte[]{(byte) i};
+ String fileName = "image" + (i + 1) + ".png";
+ XSLFPictureData data = pics.get(fileName);
+ assertNotNull(data);
+ assertEquals(fileName, data.getFileName());
+ assertArrayEquals(data1, data.getData());
+ }
+ }
}
- ppt2.close();
}
@Test
void testImageCaching() throws Exception {
- XMLSlideShow ppt = new XMLSlideShow();
- byte[] img1 = new byte[]{1,2,3};
- byte[] img2 = new byte[]{3,4,5};
- XSLFPictureData pdata1 = ppt.addPicture(img1, PictureType.PNG);
- assertEquals(0, pdata1.getIndex());
- assertEquals(0, ppt.addPicture(img1, PictureType.PNG).getIndex());
-
- XSLFPictureData idx2 = ppt.addPicture(img2, PictureType.PNG);
- assertEquals(1, idx2.getIndex());
- assertEquals(1, ppt.addPicture(img2, PictureType.PNG).getIndex());
-
- XSLFSlide slide1 = ppt.createSlide();
- assertNotNull(slide1);
- XSLFSlide slide2 = ppt.createSlide();
- assertNotNull(slide2);
-
- ppt.close();
+ try (XMLSlideShow ppt = new XMLSlideShow()) {
+ byte[] img1 = new byte[]{1, 2, 3};
+ byte[] img2 = new byte[]{3, 4, 5};
+ XSLFPictureData pdata1 = ppt.addPicture(img1, PictureType.PNG);
+ assertEquals(0, pdata1.getIndex());
+ assertEquals(0, ppt.addPicture(img1, PictureType.PNG).getIndex());
+
+ XSLFPictureData idx2 = ppt.addPicture(img2, PictureType.PNG);
+ assertEquals(1, idx2.getIndex());
+ assertEquals(1, ppt.addPicture(img2, PictureType.PNG).getIndex());
+
+ XSLFSlide slide1 = ppt.createSlide();
+ assertNotNull(slide1);
+ XSLFSlide slide2 = ppt.createSlide();
+ assertNotNull(slide2);
+ }
}
@Test
void testMerge() throws Exception {
- XMLSlideShow ppt1 = new XMLSlideShow();
- byte[] data1 = new byte[100];
- XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG);
+ try (XMLSlideShow ppt1 = new XMLSlideShow()) {
+ byte[] data1 = new byte[100];
+ XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG);
- XSLFSlide slide1 = ppt1.createSlide();
- XSLFPictureShape shape1 = slide1.createPicture(pdata1);
- CTPicture ctPic1 = (CTPicture)shape1.getXmlObject();
- ctPic1.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99");
+ XSLFSlide slide1 = ppt1.createSlide();
+ XSLFPictureShape shape1 = slide1.createPicture(pdata1);
+ CTPicture ctPic1 = (CTPicture) shape1.getXmlObject();
+ ctPic1.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99");
- XSLFPictureShape shape2 = slide1.createPicture(pdata1);
- CTPicture ctPic2 = (CTPicture)shape2.getXmlObject();
- ctPic2.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99");
+ XSLFPictureShape shape2 = slide1.createPicture(pdata1);
+ CTPicture ctPic2 = (CTPicture) shape2.getXmlObject();
+ ctPic2.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99");
- differentShapeName(shape1, shape2);
+ differentShapeName(shape1, shape2);
- XSLFGroupShape group = slide1.createGroup();
- XSLFTextBox tb1 = group.createTextBox();
- XSLFTextBox tb2 = group.createTextBox();
+ XSLFGroupShape group = slide1.createGroup();
+ XSLFTextBox tb1 = group.createTextBox();
+ XSLFTextBox tb2 = group.createTextBox();
- assertNotEquals("We should have different names now, but had: " + tb1.getShapeName() + " for both", tb1.getShapeName(), tb2.getShapeName());
+ differentShapeName(tb1, tb2);
- XMLSlideShow pptCopy = new XMLSlideShow();
+ try (XMLSlideShow pptCopy = new XMLSlideShow()) {
+ XSLFSlide slideCopy = pptCopy.createSlide().importContent(slide1);
+ XSLFPictureShape shapeCopy1 = (XSLFPictureShape) slideCopy.getShapes().get(0);
- XSLFSlide slideCopy = pptCopy.createSlide().importContent(slide1);
- XSLFPictureShape shapeCopy1 = (XSLFPictureShape)slideCopy.getShapes().get(0);
+ assertArrayEquals(data1, shapeCopy1.getPictureData().getData());
+ assertEquals(shape1.getShapeName(), shapeCopy1.getShapeName());
- assertArrayEquals(data1, shapeCopy1.getPictureData().getData());
- assertEquals(shape1.getShapeName(), shapeCopy1.getShapeName());
+ CTPicture ctPicCopy1 = (CTPicture) shapeCopy1.getXmlObject();
+ assertFalse(ctPicCopy1.getNvPicPr().getNvPr().isSetCustDataLst());
- CTPicture ctPicCopy1 = (CTPicture)shapeCopy1.getXmlObject();
- assertFalse(ctPicCopy1.getNvPicPr().getNvPr().isSetCustDataLst());
+ XSLFPictureShape shapeCopy2 = (XSLFPictureShape) slideCopy.getShapes().get(1);
- XSLFPictureShape shapeCopy2 = (XSLFPictureShape)slideCopy.getShapes().get(1);
+ assertArrayEquals(data1, shapeCopy2.getPictureData().getData());
+ assertEquals(shape2.getShapeName(), shapeCopy2.getShapeName());
- assertArrayEquals(data1, shapeCopy2.getPictureData().getData());
- assertEquals(shape2.getShapeName(), shapeCopy2.getShapeName());
+ CTPicture ctPicCopy2 = (CTPicture) shapeCopy2.getXmlObject();
+ assertFalse(ctPicCopy2.getNvPicPr().getNvPr().isSetCustDataLst());
- CTPicture ctPicCopy2 = (CTPicture)shapeCopy2.getXmlObject();
- assertFalse(ctPicCopy2.getNvPicPr().getNvPr().isSetCustDataLst());
+ differentShapeName(shapeCopy1, shapeCopy2);
- differentShapeName(shapeCopy1, shapeCopy2);
+ XSLFGroupShape groupCopy = (XSLFGroupShape) slideCopy.getShapes().get(2);
+ XSLFTextBox tbCopy1 = (XSLFTextBox) groupCopy.getShapes().get(0);
+ XSLFTextBox tbCopy2 = (XSLFTextBox) groupCopy.getShapes().get(1);
- XSLFGroupShape groupCopy = (XSLFGroupShape) slideCopy.getShapes().get(2);
- XSLFTextBox tbCopy1 = (XSLFTextBox) groupCopy.getShapes().get(0);
- XSLFTextBox tbCopy2 = (XSLFTextBox) groupCopy.getShapes().get(1);
+ assertEquals(group.getShapeName(), groupCopy.getShapeName());
+ assertEquals(tb1.getShapeName(), tbCopy1.getShapeName());
+ assertEquals(tb2.getShapeName(), tbCopy2.getShapeName());
- assertEquals(group.getShapeName(), groupCopy.getShapeName());
- assertEquals(tb1.getShapeName(), tbCopy1.getShapeName());
- assertEquals(tb2.getShapeName(), tbCopy2.getShapeName());
-
- differentShapeName(tb1, tb2);
-
- ppt1.close();
- pptCopy.close();
+ differentShapeName(tb1, tb2);
+ }
+ }
}
private void differentShapeName(XSLFShape shape1, XSLFShape shape2) {
- assertNotEquals("We should have different names now, but had: " + shape1.getShapeName() + " for both", shape1.getShapeName(), shape2.getShapeName());
+ assertNotEquals(shape1.getShapeName(), shape2.getShapeName(),
+ "We should have different names now, but had: " + shape1.getShapeName() + " for both");
}
@Test
void bug58663() throws IOException {
- InputStream is = _slTests.openResourceAsStream("shapes.pptx");
- XMLSlideShow ppt = new XMLSlideShow(is);
- is.close();
-
- XSLFSlide slide = ppt.getSlides().get(0);
- XSLFPictureShape ps = (XSLFPictureShape)slide.getShapes().get(3);
- slide.removeShape(ps);
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ppt.write(bos);
- ppt.close();
+ try (XMLSlideShow ppt = openSampleDocument("shapes.pptx")) {
+ XSLFSlide slide = ppt.getSlides().get(0);
+ XSLFPictureShape ps = (XSLFPictureShape) slide.getShapes().get(3);
+ slide.removeShape(ps);
- XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray()));
- assertTrue(ppt2.getPictureData().isEmpty());
- ppt2.close();
+ try (XMLSlideShow ppt2 = writeOutAndReadBack(ppt)) {
+ assertTrue(ppt2.getPictureData().isEmpty());
+ }
+ }
}
@Test
void testTiffImageBug59742() throws Exception {
- XMLSlideShow slideShow = new XMLSlideShow();
- final InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif");
- final byte[] pictureData = IOUtils.toByteArray(tiffStream);
- IOUtils.closeQuietly(tiffStream);
-
- XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF);
- assertEquals("image/tiff", pic.getContentType());
- assertEquals("image1.tiff", pic.getFileName());
+ try (XMLSlideShow slideShow = new XMLSlideShow();
+ InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif")) {
+ final byte[] pictureData = IOUtils.toByteArray(tiffStream);
- slideShow.close();
+ XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF);
+ assertEquals("image/tiff", pic.getContentType());
+ assertEquals("image1.tiff", pic.getFileName());
+ }
}
@Test
void renderSvgImage() throws Exception {
- XMLSlideShow ppt = new XMLSlideShow();
- XSLFSlide slide = ppt.createSlide();
+ try (XMLSlideShow ppt = new XMLSlideShow()) {
+ XSLFSlide slide = ppt.createSlide();
- try {
- XSLFPictureData svgPic = ppt.addPicture(POIDataSamples.getDocumentInstance().getFile("../project-header.svg"), PictureType.SVG);
- XSLFPictureShape shape = XSLFPictureShape.addSvgImage(slide, svgPic, PictureType.JPEG, null);
+ try {
+ XSLFPictureData svgPic = ppt.addPicture(POIDataSamples.getDocumentInstance().getFile("../project-header.svg"), PictureType.SVG);
+ XSLFPictureShape shape = XSLFPictureShape.addSvgImage(slide, svgPic, PictureType.JPEG, null);
- Rectangle2D anchor = shape.getAnchor();
- anchor.setRect(100, 100, anchor.getWidth(), anchor.getHeight());
- shape.setAnchor(anchor);
+ Rectangle2D anchor = shape.getAnchor();
+ anchor.setRect(100, 100, anchor.getWidth(), anchor.getHeight());
+ shape.setAnchor(anchor);
- assertNotNull(shape.getSvgImage());
+ assertNotNull(shape.getSvgImage());
- final File tmpFile = TempFile.createTempFile("svgtest", ".pptx");
- System.out.println(tmpFile);
- try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
- ppt.write(fos);
- }
+ final File tmpFile = TempFile.createTempFile("svgtest", ".pptx");
+ System.out.println(tmpFile);
+ try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
+ ppt.write(fos);
+ }
- String[] args = {
+ String[] args = {
"-format", "png", // png,gif,jpg or null for test
"-slide", "-1", // -1 for all
"-outdir", tmpFile.getParentFile().getCanonicalPath(),
"-quiet",
tmpFile.getAbsolutePath()
- };
- PPTX2PNG.main(args);
- } catch (IIOException ignore) {
- // Ignore all ImageIO related exceptions like "Can't create output stream!"
- // which fail often in maven builds because of missing/wrong temp directory
- } catch (NoClassDefFoundError ignore) {
- assumeFalse(true, "Batik doesn't work on th module-path");
+ };
+ PPTX2PNG.main(args);
+ } catch (IIOException ignored) {
+ // Ignore all ImageIO related exceptions like "Can't create output stream!"
+ // which fail often in maven builds because of missing/wrong temp directory
+ } catch (NoClassDefFoundError ignored) {
+ assumeFalse(true, "Batik doesn't work on th module-path");
+ }
}
}
} \ No newline at end of file
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java
index 56c5efda1f..c35db12765 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/DeferredSXSSFITestDataProvider.java
@@ -19,6 +19,12 @@
package org.apache.poi.xssf;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.SpreadsheetVersion;
@@ -31,13 +37,6 @@ import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-
public final class DeferredSXSSFITestDataProvider implements ITestDataProvider {
public static final DeferredSXSSFITestDataProvider instance = new DeferredSXSSFITestDataProvider();
@@ -69,16 +68,14 @@ public final class DeferredSXSSFITestDataProvider implements ITestDataProvider {
throw new IllegalArgumentException("Expected an instance of XSSFWorkbook");
}
- XSSFWorkbook result;
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
wb.write(baos);
- InputStream is = new ByteArrayInputStream(baos.toByteArray());
- result = new XSSFWorkbook(is);
+ try (InputStream is = baos.toInputStream()) {
+ return new XSSFWorkbook(is);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
- return result;
}
@Override
@@ -87,7 +84,7 @@ public final class DeferredSXSSFITestDataProvider implements ITestDataProvider {
instances.add(wb);
return wb;
}
-
+
//************ SXSSF-specific methods ***************//
@Override
public DeferredSXSSFWorkbook createWorkbook(int rowAccessWindowSize) {
@@ -95,13 +92,13 @@ public final class DeferredSXSSFITestDataProvider implements ITestDataProvider {
instances.add(wb);
return wb;
}
-
+
@Override
public void trackAllColumnsForAutosizing(Sheet sheet) {
((DeferredSXSSFSheet)sheet).trackAllColumnsForAutoSizing();
}
//************ End SXSSF-specific methods ***************//
-
+
@Override
public FormulaEvaluator createFormulaEvaluator(Workbook wb) {
return new XSSFFormulaEvaluator(((DeferredSXSSFWorkbook) wb).getXSSFWorkbook());
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java
index 744b02beb0..8c722151ee 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/SXSSFITestDataProvider.java
@@ -19,13 +19,12 @@
package org.apache.poi.xssf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ss.ITestDataProvider;
import org.apache.poi.ss.SpreadsheetVersion;
@@ -68,16 +67,14 @@ public final class SXSSFITestDataProvider implements ITestDataProvider {
throw new IllegalArgumentException("Expected an instance of SXSSFWorkbook");
}
- XSSFWorkbook result;
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
wb.write(baos);
- InputStream is = new ByteArrayInputStream(baos.toByteArray());
- result = new XSSFWorkbook(is);
+ try (InputStream is = baos.toInputStream()) {
+ return new XSSFWorkbook(is);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
- return result;
}
@Override
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java
index bb9859998c..3b35c52ac9 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/TestXSSFMemoryLeak.java
@@ -21,13 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ooxml.POIXMLException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
@@ -72,7 +72,7 @@ public class TestXSSFMemoryLeak {
// not freed until we free up the Cell itself
//verifier.addObject(ctCell);
- try (OutputStream out = new ByteArrayOutputStream(8192)) {
+ try (OutputStream out = new UnsynchronizedByteArrayOutputStream(8192)) {
wb.write(out);
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java
index 6beb153bd2..3a0ed9d4c3 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/XSSFTestDataSamples.java
@@ -17,14 +17,13 @@
package org.apache.poi.xssf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Workbook;
@@ -62,8 +61,8 @@ public class XSSFTestDataSamples {
}
/**
- * Write out workbook <code>wb</code> to {@link #TEST_OUTPUT_DIR}/testName.xlsx
- * (or create a temporary file if <code>TEST_OUTPUT_DIR</code> is not defined).
+ * Write out workbook {@code wb} to {@link #TEST_OUTPUT_DIR}/testName.xlsx
+ * (or create a temporary file if {@code TEST_OUTPUT_DIR} is not defined).
*
* @param wb the workbook to write
* @param testName a fragment of the filename
@@ -93,7 +92,7 @@ public class XSSFTestDataSamples {
final File file;
if (testOutputDir != null) {
// In case user provided testName with a file extension, don't repeat the file extension a second time
- final String testNameWithExtension = testName.endsWith(".xlsx") ? testName : testName + ".xlsx";
+ final String testNameWithExtension = (testName.endsWith(".xlsx") || testName.endsWith(".xlsxm")) ? testName : testName + ".xlsx";
// FIXME: may want to defer to the TempFile with a persistent file creation strategy to the test output dir
// This would add the random value in the middle of the filename so that test runs wouldn't overwrite files
file = new File(testOutputDir, testNameWithExtension);
@@ -110,14 +109,14 @@ public class XSSFTestDataSamples {
}
/**
- * Write out workbook <code>wb</code> to a memory buffer
+ * Write out workbook {@code wb} to a memory buffer
*
* @param wb the workbook to write
* @return the memory buffer
* @throws IOException If writing the file fails
*/
- public static <R extends Workbook> ByteArrayOutputStream writeOut(R wb) throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
+ public static <R extends Workbook> UnsynchronizedByteArrayOutputStream writeOut(R wb) throws IOException {
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(8192);
wb.write(out);
return out;
}
@@ -130,10 +129,10 @@ public class XSSFTestDataSamples {
* Make sure there are no references to any objects in the workbook
* so that garbage collection may free the workbook.
*
- * After calling this method, null the reference to <code>wb</code>,
+ * After calling this method, null the reference to {@code wb},
* then call {@link #readBack(File)} or {@link #readBackAndDelete(File)} to re-read the file.
*
- * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream
+ * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a UnsynchronizedByteArrayOutputStream/ByteArrayInputStream
* to avoid creating a temporary file. However, this may complicate the calling
* code to avoid having the workbook, BAOS, and BAIS open at the same time.
*
@@ -156,15 +155,15 @@ public class XSSFTestDataSamples {
/**
- * Write out workbook <code>wb</code> to a memory buffer,
+ * Write out workbook {@code wb} to a memory buffer,
* then close the workbook
*
* @param wb the workbook to write
* @return the memory buffer
* @throws RuntimeException If writing the file fails
*/
- public static <R extends Workbook> ByteArrayOutputStream writeOutAndClose(R wb) throws IOException {
- ByteArrayOutputStream out = writeOut(wb);
+ public static <R extends Workbook> UnsynchronizedByteArrayOutputStream writeOutAndClose(R wb) throws IOException {
+ UnsynchronizedByteArrayOutputStream out = writeOut(wb);
// Do not close the workbook if there was a problem writing the workbook
wb.close();
return out;
@@ -211,8 +210,8 @@ public class XSSFTestDataSamples {
* @return the read back workbook
* @throws IOException If reading the file fails
*/
- public static XSSFWorkbook readBack(ByteArrayOutputStream out) throws IOException {
- try (InputStream is = new ByteArrayInputStream(out.toByteArray())) {
+ public static XSSFWorkbook readBack(UnsynchronizedByteArrayOutputStream out) throws IOException {
+ try (InputStream is = out.toInputStream()) {
out.close();
return new XSSFWorkbook(is);
}
@@ -226,12 +225,12 @@ public class XSSFTestDataSamples {
* Workbook wb = new XSSFWorkbook();
* String testName = "example";
*
- * <code>
+ * {@code
* File file = writeOutAndClose(wb, testName);
* // clear all references that would prevent the workbook from getting garbage collected
* wb = null;
* Workbook wbBack = readBackAndDelete(file);
- * </code>
+ * }
*
* @param wb the workbook to write out
* @return the read back workbook
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java
index e85998cb12..5672564fd0 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java
@@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
@@ -34,6 +33,7 @@ import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ooxml.util.DocumentHelper;
import org.apache.poi.ss.usermodel.Cell;
@@ -66,7 +66,7 @@ public final class TestXSSFExportToXML {
XSSFMap map = mapInfo.getXSSFMapById(1);
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xml = os.toString("UTF-8");
@@ -114,7 +114,7 @@ public final class TestXSSFExportToXML {
XSSFMap map = mapInfo.getXSSFMapById(1);
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xml = os.toString("UTF-8");
@@ -187,7 +187,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map);
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xml = os.toString("UTF-8");
@@ -223,7 +223,7 @@ public final class TestXSSFExportToXML {
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
}
}
@@ -246,7 +246,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -290,7 +290,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -325,7 +325,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -364,7 +364,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -390,7 +390,7 @@ public final class TestXSSFExportToXML {
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -468,7 +468,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -546,7 +546,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -577,7 +577,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, false);
String xmlData = os.toString("UTF-8");
@@ -609,7 +609,7 @@ public final class TestXSSFExportToXML {
assertNotNull(map, "XSSFMap is null");
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, true);
String xmlData = os.toString("UTF-8");
@@ -635,7 +635,7 @@ public final class TestXSSFExportToXML {
for (XSSFMap map : mappings) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream os = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(os, false);
assertNotNull(os.toString("UTF-8"));
}
@@ -647,9 +647,9 @@ public final class TestXSSFExportToXML {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61281.xlsx")) {
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
exporter.exportToXML(bos, true);
- assertNotNull(DocumentHelper.readDocument(new ByteArrayInputStream(bos.toByteArray())));
+ assertNotNull(DocumentHelper.readDocument(bos.toInputStream()));
String exportedXml = bos.toString("UTF-8");
assertEquals("<Test><Test>1</Test></Test>", exportedXml.replaceAll("\\s+", ""));
}
@@ -661,7 +661,7 @@ public final class TestXSSFExportToXML {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("xxe_in_schema.xlsx")) {
for (XSSFMap map : wb.getCustomXMLMappings()) {
XSSFExportToXml exporter = new XSSFExportToXml(map);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
assertThrows(SAXParseException.class, () -> exporter.exportToXML(bos, true));
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java
index e065b26adb..17c4eec074 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java
@@ -19,6 +19,7 @@
package org.apache.poi.xssf.streaming;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.apache.poi.POITestCase.assertEndsWith;
import static org.apache.poi.POITestCase.assertStartsWith;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -29,14 +30,13 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
@@ -48,7 +48,6 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellReference;
-import org.apache.poi.util.NullOutputStream;
import org.apache.poi.xssf.SXSSFITestDataProvider;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.SharedStringsTable;
@@ -74,7 +73,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
@Override
@Test
protected void cloneSheet() throws IOException {
- RuntimeException e = assertThrows(RuntimeException.class, () -> super.cloneSheet());
+ RuntimeException e = assertThrows(RuntimeException.class, super::cloneSheet);
assertEquals("Not Implemented", e.getMessage());
}
@@ -84,7 +83,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
@Override
@Test
protected void sheetClone() {
- RuntimeException e = assertThrows(RuntimeException.class, () -> super.sheetClone());
+ RuntimeException e = assertThrows(RuntimeException.class, super::sheetClone);
assertEquals("Not Implemented", e.getMessage());
}
@@ -407,8 +406,8 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
private static void saveTwice(Workbook wb) throws Exception {
for (int i = 0; i < 2; i++) {
- try (NullOutputStream out = new NullOutputStream()) {
- wb.write(out);
+ try {
+ wb.write(NULL_OUTPUT_STREAM);
} catch (Exception e) {
throw new Exception("ERROR: failed on " + (i + 1)
+ "th time calling " + wb.getClass().getName()
@@ -471,7 +470,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
}
}
- assertDoesNotThrow(() -> swb.write(new NullOutputStream()));
+ assertDoesNotThrow(() -> swb.write(NULL_OUTPUT_STREAM));
swb.dispose();
}
}
@@ -489,7 +488,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
File input = XSSFTestDataSamples.getSampleFile("sample.xlsx");
try (OPCPackage pkg = OPCPackage.open(input, PackageAccess.READ)) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (XSSFWorkbook xssf = new XSSFWorkbook(pkg)) {
try (SXSSFWorkbook wb = new SXSSFWorkbook(xssf, 2)) {
Sheet s = wb.createSheet(sheetName);
@@ -506,7 +505,7 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
}
}
- try (XSSFWorkbook xssf = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
+ try (XSSFWorkbook xssf = new XSSFWorkbook(bos.toInputStream())) {
Sheet s = xssf.getSheet(sheetName);
assertEquals(10, s.getLastRowNum());
assertTrue(s.getRow(0).getCell(0).getBooleanCellValue());
@@ -518,20 +517,17 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
@Test
void test56557() throws IOException {
- Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56557.xlsx");
-
- // Using streaming XSSFWorkbook makes the output file invalid
- wb = new SXSSFWorkbook(((XSSFWorkbook) wb));
-
- // Should not throw POIXMLException: java.io.IOException: Unable to parse xml bean when reading back
- Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
- assertNotNull(wbBack);
- wbBack.close();
-
- wb.close();
+ try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56557.xlsx");
+ // Using streaming XSSFWorkbook makes the output file invalid
+ Workbook wb2 = new SXSSFWorkbook(wb);
+ // Should not throw POIXMLException: java.io.IOException: Unable to parse xml bean when reading back
+ Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb2)
+ ) {
+ assertNotNull(wbBack);
+ }
}
+ @Disabled("not implemented")
void changeSheetNameWithSharedFormulas() {
- /* not implemented */
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java
index b1fa40fe69..d5afe8ea15 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java
@@ -20,12 +20,11 @@
package org.apache.poi.xssf.streaming;
import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -33,6 +32,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.util.ZipEntrySource;
@@ -58,38 +58,40 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource {
// write an unencrypted workbook to disk, but any temporary files are encrypted
@Test
void customZipEntrySource() throws IOException {
- SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource();
- SXSSFSheet sheet1 = workbook.createSheet(sheetName);
- SXSSFRow row1 = sheet1.createRow(1);
- SXSSFCell cell1 = row1.createCell(1);
- cell1.setCellValue(cellValue);
- ByteArrayOutputStream os = new ByteArrayOutputStream(8192);
- workbook.write(os);
- workbook.close();
- workbook.dispose();
- XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(os.toByteArray()));
- XSSFSheet xs1 = xwb.getSheetAt(0);
- assertEquals(sheetName, xs1.getSheetName());
- XSSFRow xr1 = xs1.getRow(1);
- XSSFCell xc1 = xr1.getCell(1);
- assertEquals(cellValue, xc1.getStringCellValue());
- xwb.close();
+ UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(8192);
+ try (SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource()) {
+ SXSSFSheet sheet1 = workbook.createSheet(sheetName);
+ SXSSFRow row1 = sheet1.createRow(1);
+ SXSSFCell cell1 = row1.createCell(1);
+ cell1.setCellValue(cellValue);
+ workbook.write(os);
+ workbook.close();
+ workbook.dispose();
+ }
+ try (XSSFWorkbook xwb = new XSSFWorkbook(os.toInputStream())) {
+ XSSFSheet xs1 = xwb.getSheetAt(0);
+ assertEquals(sheetName, xs1.getSheetName());
+ XSSFRow xr1 = xs1.getRow(1);
+ XSSFCell xc1 = xr1.getCell(1);
+ assertEquals(cellValue, xc1.getStringCellValue());
+ }
}
// write an encrypted workbook to disk, and encrypt any temporary files as well
@Test
void customZipEntrySourceForWriteAndRead() throws IOException, InvalidFormatException {
- SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource();
- SXSSFSheet sheet1 = workbook.createSheet(sheetName);
- SXSSFRow row1 = sheet1.createRow(1);
- SXSSFCell cell1 = row1.createCell(1);
- cell1.setCellValue(cellValue);
EncryptedTempData tempData = new EncryptedTempData();
- try (OutputStream os = tempData.getOutputStream()) {
- workbook.write(os);
+ try (SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource()) {
+ SXSSFSheet sheet1 = workbook.createSheet(sheetName);
+ SXSSFRow row1 = sheet1.createRow(1);
+ SXSSFCell cell1 = row1.createCell(1);
+ cell1.setCellValue(cellValue);
+ try (OutputStream os = tempData.getOutputStream()) {
+ workbook.write(os);
+ }
+ workbook.close();
+ workbook.dispose();
}
- workbook.close();
- workbook.dispose();
try (InputStream is = tempData.getInputStream();
ZipEntrySource zipEntrySource = AesZipFileZipEntrySource.createZipEntrySource(is)) {
tempData.dispose();
@@ -111,8 +113,7 @@ public final class TestSXSSFWorkbookWithCustomZipEntrySource {
SXSSFRow row1 = sheet1.createRow(1);
SXSSFCell cell1 = row1.createCell(1);
cell1.setCellValue(cellValue);
- ByteArrayOutputStream os = new ByteArrayOutputStream(8192);
- workbook.write(os);
+ workbook.write(NULL_OUTPUT_STREAM);
workbook.close();
List<File> tempFiles = workbook.getTempFiles();
assertEquals(1, tempFiles.size());
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java
index 679c3c60bf..0b307277f5 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java
@@ -17,6 +17,7 @@
package org.apache.poi.xssf.usermodel;
+import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -24,13 +25,13 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ss.formula.OperationEvaluationContext;
import org.apache.poi.ss.formula.eval.NumberEval;
import org.apache.poi.ss.formula.eval.ValueEval;
@@ -242,7 +243,7 @@ public final class TestUnfixedBugs {
checkRows57423(testSheet);
- Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
+ Workbook wbBack = writeOutAndReadBack(wb);
/* XSSFTestDataSamples.writeOut(wb, "bug 57423 for manual review"); */
wb.close();
@@ -277,12 +278,8 @@ public final class TestUnfixedBugs {
checkRow57423(testSheet, 17, "17");
checkRow57423(testSheet, 18, "18");
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- try {
- ((XSSFSheet)testSheet).write(stream);
- } finally {
- stream.close();
- }
+ UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream();
+ ((XSSFSheet)testSheet).write(stream);
// verify that the resulting XML has the rows in correct order as required by Excel
String xml = new String(stream.toByteArray(), StandardCharsets.UTF_8);
@@ -310,27 +307,21 @@ public final class TestUnfixedBugs {
@Test
void bug57423_shiftRowsByLargeOffset() throws IOException {
- try (
- XSSFWorkbook wb = new XSSFWorkbook()
- //OutputStream out = new FileOutputStream("/tmp/57423." + wb.getClass().getName() + ".xlsx"));
- ) {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
Sheet sh = wb.createSheet();
sh.createRow(0).createCell(0).setCellValue("a");
sh.createRow(1).createCell(0).setCellValue("b");
sh.createRow(2).createCell(0).setCellValue("c");
sh.shiftRows(0, 1, 3);
- XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
-
- assertThatRowsInAscendingOrder(wb);
- assertThatRowsInAscendingOrder(wbBack);
-
- //wbBack.write(out);
- // Excel reports that the workbook is corrupt because the rows are not in ascending order
- // LibreOffice doesn't complain when rows are not in ascending order
-
- wbBack.close();
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) {
+ assertThatRowsInAscendingOrder(wb);
+ assertThatRowsInAscendingOrder(wbBack);
+ //wbBack.write(out);
+ // Excel reports that the workbook is corrupt because the rows are not in ascending order
+ // LibreOffice doesn't complain when rows are not in ascending order
+ }
fail("Excel reports that the workbook is corrupt, LibreOffice can read it");
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java
index d0d97e91de..508362e820 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFBugs.java
@@ -19,20 +19,20 @@ package org.apache.poi.xssf.usermodel;
import static java.time.Duration.between;
import static java.time.Instant.now;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.apache.logging.log4j.util.Unbox.box;
import static org.apache.poi.extractor.ExtractorFactory.OOXML_PACKAGE;
import static org.apache.poi.openxml4j.opc.TestContentType.isOldXercesActive;
+import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook;
+import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
@@ -47,6 +47,7 @@ import java.util.TreeMap;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.POIDataSamples;
@@ -99,7 +100,7 @@ import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.util.NullOutputStream;
+import org.apache.commons.io.output.NullOutputStream;
import org.apache.poi.util.TempFile;
import org.apache.poi.util.XMLHelper;
import org.apache.poi.xssf.SXSSFITestDataProvider;
@@ -115,6 +116,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName;
@@ -140,7 +142,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug45430() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("45430.xlsx")) {
assertFalse(wb.isMacroEnabled());
assertEquals(3, wb.getNumberOfNames());
@@ -160,7 +162,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
assertEquals("SheetC", wb.getName("SheetCA1").getSheetName());
// Save and re-load, still there
- try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (XSSFWorkbook nwb = writeOutAndReadBack(wb)) {
assertEquals(3, nwb.getNumberOfNames());
assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula());
}
@@ -172,79 +174,74 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug45431() throws IOException, InvalidFormatException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm");
- OPCPackage pkg1 = wb1.getPackage();
- assertTrue(wb1.isMacroEnabled());
+ try (XSSFWorkbook wb1 = openSampleWorkbook("45431.xlsm");
+ OPCPackage pkg1 = wb1.getPackage()) {
+ assertTrue(wb1.isMacroEnabled());
- // Check the various macro related bits can be found
- PackagePart vba = pkg1.getPart(
+ // Check the various macro related bits can be found
+ PackagePart vba = pkg1.getPart(
PackagingURIHelper.createPartName("/xl/vbaProject.bin")
- );
- assertNotNull(vba);
- // And the drawing bit
- PackagePart drw = pkg1.getPart(
+ );
+ assertNotNull(vba);
+ // And the drawing bit
+ PackagePart drw = pkg1.getPart(
PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
- );
- assertNotNull(drw);
-
-
- // Save and re-open, both still there
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- pkg1.close();
- wb1.close();
-
- OPCPackage pkg2 = wb2.getPackage();
- assertTrue(wb2.isMacroEnabled());
-
- vba = pkg2.getPart(
- PackagingURIHelper.createPartName("/xl/vbaProject.bin")
- );
- assertNotNull(vba);
- drw = pkg2.getPart(
- PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
- );
- assertNotNull(drw);
-
- // And again, just to be sure
- XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
- pkg2.close();
- wb2.close();
- OPCPackage pkg3 = wb3.getPackage();
- assertTrue(wb3.isMacroEnabled());
-
- vba = pkg3.getPart(
- PackagingURIHelper.createPartName("/xl/vbaProject.bin")
- );
- assertNotNull(vba);
- drw = pkg3.getPart(
- PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
- );
- assertNotNull(drw);
-
- pkg3.close();
- wb3.close();
+ );
+ assertNotNull(drw);
+
+
+ // Save and re-open, both still there
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1);
+ OPCPackage pkg2 = wb2.getPackage()) {
+ assertTrue(wb2.isMacroEnabled());
+
+ vba = pkg2.getPart(
+ PackagingURIHelper.createPartName("/xl/vbaProject.bin")
+ );
+ assertNotNull(vba);
+ drw = pkg2.getPart(
+ PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
+ );
+ assertNotNull(drw);
+
+ // And again, just to be sure
+ try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2);
+ OPCPackage pkg3 = wb3.getPackage()) {
+ assertTrue(wb3.isMacroEnabled());
+
+ vba = pkg3.getPart(
+ PackagingURIHelper.createPartName("/xl/vbaProject.bin")
+ );
+ assertNotNull(vba);
+ drw = pkg3.getPart(
+ PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml")
+ );
+ assertNotNull(drw);
+ }
+ }
+ }
}
@Test
void bug47504() throws IOException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx");
- assertEquals(1, wb1.getNumberOfSheets());
- XSSFSheet sh = wb1.getSheetAt(0);
- XSSFDrawing drawing = sh.createDrawingPatriarch();
- List<RelationPart> rels = drawing.getRelationParts();
- assertEquals(1, rels.size());
- assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment());
-
- // And again, just to be sure
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- assertEquals(1, wb2.getNumberOfSheets());
- sh = wb2.getSheetAt(0);
- drawing = sh.createDrawingPatriarch();
- rels = drawing.getRelationParts();
- assertEquals(1, rels.size());
- assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment());
- wb2.close();
+ try (XSSFWorkbook wb1 = openSampleWorkbook("47504.xlsx")) {
+ assertEquals(1, wb1.getNumberOfSheets());
+ XSSFSheet sh = wb1.getSheetAt(0);
+ XSSFDrawing drawing = sh.createDrawingPatriarch();
+ List<RelationPart> rels = drawing.getRelationParts();
+ assertEquals(1, rels.size());
+ assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment());
+
+ // And again, just to be sure
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ assertEquals(1, wb2.getNumberOfSheets());
+ sh = wb2.getSheetAt(0);
+ drawing = sh.createDrawingPatriarch();
+ rels = drawing.getRelationParts();
+ assertEquals(1, rels.size());
+ assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment());
+ }
+ }
}
/**
@@ -255,7 +252,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49020() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("BrNotClosed.xlsx")) {
assertNotNull(wb);
}
}
@@ -265,7 +262,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49325() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("49325.xlsx")) {
CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet();
assertNotNull(sh.getPhoneticPr());
}
@@ -277,7 +274,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug48923() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("48923.xlsx")) {
assertEquals(4, wb.getNumberOfNames());
Name b1 = wb.getName("NameB1");
@@ -321,7 +318,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug48539() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("48539.xlsx")) {
assertEquals(3, wb.getNumberOfSheets());
assertEquals(0, wb.getNumberOfNames());
@@ -358,7 +355,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug48779() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("48779.xlsx")) {
XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0);
XSSFCellStyle cs = cell.getCellStyle();
@@ -396,7 +393,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug47490() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("GeneralFormatTests.xlsx")) {
Sheet s = wb.getSheetAt(1);
Row r;
DataFormatter df = new DataFormatter();
@@ -434,7 +431,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49609() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("49609.xlsx")) {
assertEquals("FAM", wb.getSheetName(0));
assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue());
}
@@ -443,7 +440,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug49783() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("49783.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Cell cell;
@@ -476,78 +473,77 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49941() throws IOException {
- XSSFWorkbook wb1 = new XSSFWorkbook();
- XSSFSheet s = wb1.createSheet();
- XSSFRow r = s.createRow(0);
- XSSFCell c = r.createCell(0);
+ try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
+ XSSFSheet s = wb1.createSheet();
+ XSSFRow r = s.createRow(0);
+ XSSFCell c = r.createCell(0);
- // First without fonts
- c.setCellValue(
+ // First without fonts
+ c.setCellValue(
new XSSFRichTextString(" with spaces ")
- );
- assertEquals(" with spaces ", c.getRichStringCellValue().toString());
- assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
- assertTrue(c.getRichStringCellValue().getCTRst().isSetT());
- // Should have the preserve set
- assertEquals(
+ );
+ assertEquals(" with spaces ", c.getRichStringCellValue().toString());
+ assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
+ assertTrue(c.getRichStringCellValue().getCTRst().isSetT());
+ // Should have the preserve set
+ assertEquals(
1,
c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
- );
- assertEquals(
+ );
+ assertEquals(
"preserve",
c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().item(0).getNodeValue()
- );
-
- // Save and check
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- s = wb2.getSheetAt(0);
- r = s.getRow(0);
- c = r.getCell(0);
- assertEquals(" with spaces ", c.getRichStringCellValue().toString());
- assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
- assertTrue(c.getRichStringCellValue().getCTRst().isSetT());
-
- // Change the string
- c.setCellValue(
- new XSSFRichTextString("hello world")
- );
- assertEquals("hello world", c.getRichStringCellValue().toString());
- // Won't have preserve
- assertEquals(
- 0,
- c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
- );
-
- // Apply a font
- XSSFFont f = wb2.createFont();
- f.setBold(true);
- c.getRichStringCellValue().applyFont(0, 5, f);
- assertEquals("hello world", c.getRichStringCellValue().toString());
- // Does need preserving on the 2nd part
- assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
- assertEquals(
- 0,
- c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
- );
- assertEquals(
- 1,
- c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
- );
- assertEquals(
- "preserve",
- c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
- );
-
- // Save and check
- XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
+ );
- s = wb3.getSheetAt(0);
- r = s.getRow(0);
- c = r.getCell(0);
- assertEquals("hello world", c.getRichStringCellValue().toString());
- wb3.close();
+ // Save and check
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ s = wb2.getSheetAt(0);
+ r = s.getRow(0);
+ c = r.getCell(0);
+ assertEquals(" with spaces ", c.getRichStringCellValue().toString());
+ assertEquals(0, c.getRichStringCellValue().getCTRst().sizeOfRArray());
+ assertTrue(c.getRichStringCellValue().getCTRst().isSetT());
+
+ // Change the string
+ c.setCellValue(
+ new XSSFRichTextString("hello world")
+ );
+ assertEquals("hello world", c.getRichStringCellValue().toString());
+ // Won't have preserve
+ assertEquals(
+ 0,
+ c.getRichStringCellValue().getCTRst().xgetT().getDomNode().getAttributes().getLength()
+ );
+
+ // Apply a font
+ XSSFFont f = wb2.createFont();
+ f.setBold(true);
+ c.getRichStringCellValue().applyFont(0, 5, f);
+ assertEquals("hello world", c.getRichStringCellValue().toString());
+ // Does need preserving on the 2nd part
+ assertEquals(2, c.getRichStringCellValue().getCTRst().sizeOfRArray());
+ assertEquals(
+ 0,
+ c.getRichStringCellValue().getCTRst().getRArray(0).xgetT().getDomNode().getAttributes().getLength()
+ );
+ assertEquals(
+ 1,
+ c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().getLength()
+ );
+ assertEquals(
+ "preserve",
+ c.getRichStringCellValue().getCTRst().getRArray(1).xgetT().getDomNode().getAttributes().item(0).getNodeValue()
+ );
+
+ // Save and check
+ try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
+ s = wb3.getSheetAt(0);
+ r = s.getRow(0);
+ c = r.getCell(0);
+ assertEquals("hello world", c.getRichStringCellValue().toString());
+ }
+ }
+ }
}
/**
@@ -555,25 +551,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49940() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("styles.xlsx")) {
assertEquals(3, wb.getNumberOfSheets());
assertEquals(10, wb.getStylesSource().getNumCellStyles());
- ByteArrayOutputStream b1 = new ByteArrayOutputStream();
- ByteArrayOutputStream b2 = new ByteArrayOutputStream();
- ByteArrayOutputStream b3 = new ByteArrayOutputStream();
- wb.write(b1);
- wb.write(b2);
- wb.write(b3);
-
- for (byte[] data : new byte[][]{
- b1.toByteArray(), b2.toByteArray(), b3.toByteArray()
- }) {
- ByteArrayInputStream bais = new ByteArrayInputStream(data);
- XSSFWorkbook wb2 = new XSSFWorkbook(bais);
- assertEquals(3, wb2.getNumberOfSheets());
- assertEquals(10, wb2.getStylesSource().getNumCellStyles());
- wb2.close();
+ for (int i=0; i<3; i++) {
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb)) {
+ assertEquals(3, wb2.getNumberOfSheets());
+ assertEquals(10, wb2.getStylesSource().getNumCellStyles());
+ }
}
}
}
@@ -584,11 +570,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49966() throws IOException {
- try (XSSFWorkbook wb1 = XSSFTestDataSamples
- .openSampleWorkbook("shared_formulas.xlsx")) {
+ try (XSSFWorkbook wb1 = openSampleWorkbook("shared_formulas.xlsx")) {
XSSFSheet sheet = wb1.getSheetAt(0);
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
// CalcChain has lots of entries
CalculationChain cc = wb1.getCalculationChain();
@@ -601,7 +586,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR());
assertEquals(40, cc.getCTCalcChain().sizeOfCArray());
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
// Try various ways of changing the formulas
// If it stays a formula, chain entry should remain
@@ -609,25 +594,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay
sheet.getRow(2).getCell(0).setCellFormula(null); // go
sheet.getRow(3).getCell(0).setCellFormula("14"); // stay
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
sheet.getRow(4).getCell(0).setBlank(); // go
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
validateCells(sheet);
sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go
validateCells(sheet);
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
sheet.getRow(6).getCell(0).setBlank(); // go
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
sheet.getRow(7).getCell(0).setCellValue((String) null); // go
- XSSFTestDataSamples.writeOutAndReadBack(wb1).close();
+ writeOutAndReadBack(wb1).close();
// Save and check
- try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) {
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
wb1.close();
assertEquals(35, cc.getCTCalcChain().sizeOfCArray());
@@ -641,8 +626,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug49966Row() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples
- .openSampleWorkbook("shared_formulas.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("shared_formulas.xlsx")) {
XSSFSheet sheet = wb.getSheetAt(0);
validateCells(sheet);
@@ -660,7 +644,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug49156() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("49156.xlsx")) {
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.getSheetAt(0);
@@ -680,7 +664,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50440And51875() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("NewlineInFormulas.xlsx")) {
Sheet s = wb.getSheetAt(0);
Cell c = s.getRow(0).getCell(0);
@@ -706,58 +690,55 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50795() throws IOException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50795.xlsx");
- XSSFSheet sheet = wb1.getSheetAt(0);
- XSSFRow row = sheet.getRow(0);
-
- XSSFCell cellWith = row.getCell(0);
- XSSFCell cellWithoutComment = row.getCell(1);
-
- assertNotNull(cellWith.getCellComment());
- assertNull(cellWithoutComment.getCellComment());
-
- String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
- XSSFComment comment = cellWith.getCellComment();
- assertEquals(exp, comment.getString().getString());
+ try (XSSFWorkbook wb1 = openSampleWorkbook("50795.xlsx")) {
+ XSSFSheet sheet = wb1.getSheetAt(0);
+ XSSFRow row = sheet.getRow(0);
+ XSSFCell cellWith = row.getCell(0);
+ XSSFCell cellWithoutComment = row.getCell(1);
- // Check we can write it out and read it back as-is
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
+ assertNotNull(cellWith.getCellComment());
+ assertNull(cellWithoutComment.getCellComment());
- sheet = wb2.getSheetAt(0);
- row = sheet.getRow(0);
- cellWith = row.getCell(0);
- cellWithoutComment = row.getCell(1);
+ String exp = "\u0410\u0432\u0442\u043e\u0440:\ncomment";
+ XSSFComment comment = cellWith.getCellComment();
+ assertEquals(exp, comment.getString().getString());
- // Double check things are as expected
- assertNotNull(cellWith.getCellComment());
- assertNull(cellWithoutComment.getCellComment());
- comment = cellWith.getCellComment();
- assertEquals(exp, comment.getString().getString());
+ // Check we can write it out and read it back as-is
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ sheet = wb2.getSheetAt(0);
+ row = sheet.getRow(0);
+ cellWith = row.getCell(0);
+ cellWithoutComment = row.getCell(1);
- // Move the comment
- cellWithoutComment.setCellComment(comment);
+ // Double check things are as expected
+ assertNotNull(cellWith.getCellComment());
+ assertNull(cellWithoutComment.getCellComment());
+ comment = cellWith.getCellComment();
+ assertEquals(exp, comment.getString().getString());
- // Write out and re-check
- XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
+ // Move the comment
+ cellWithoutComment.setCellComment(comment);
- sheet = wb3.getSheetAt(0);
- row = sheet.getRow(0);
- // Ensure it swapped over
- cellWith = row.getCell(0);
- cellWithoutComment = row.getCell(1);
- assertNull(cellWith.getCellComment());
- assertNotNull(cellWithoutComment.getCellComment());
+ // Write out and re-check
+ try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
+ sheet = wb3.getSheetAt(0);
+ row = sheet.getRow(0);
- comment = cellWithoutComment.getCellComment();
- assertEquals(exp, comment.getString().getString());
+ // Ensure it swapped over
+ cellWith = row.getCell(0);
+ cellWithoutComment = row.getCell(1);
+ assertNull(cellWith.getCellComment());
+ assertNotNull(cellWithoutComment.getCellComment());
- wb3.close();
+ comment = cellWithoutComment.getCellComment();
+ assertEquals(exp, comment.getString().getString());
+ }
+ }
+ }
}
/**
@@ -768,7 +749,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50299() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("50299.xlsx")) {
// Check all the colours
for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) {
@@ -799,7 +780,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50786() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("50786-indexed_colours.xlsx")) {
XSSFSheet s = wb.getSheetAt(0);
XSSFRow r = s.getRow(2);
@@ -822,7 +803,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50846() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("50846-border_colours.xlsx")) {
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = sheet.getRow(0);
@@ -852,7 +833,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50784() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("50784-font_theme_colours.xlsx")) {
XSSFSheet s = wb.getSheetAt(0);
XSSFRow r = s.getRow(0);
@@ -886,69 +867,65 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
String text = "Use \n with word wrap on to create a new line.\n" +
"This line finishes with two trailing spaces. ";
- XSSFWorkbook wb1 = new XSSFWorkbook();
- XSSFSheet sheet = wb1.createSheet();
+ try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
+ XSSFSheet sheet = wb1.createSheet();
- Font font1 = wb1.createFont();
- font1.setColor((short) 20);
- Font font2 = wb1.createFont();
- font2.setColor(Font.COLOR_RED);
- Font font3 = wb1.getFontAt(0);
+ Font font1 = wb1.createFont();
+ font1.setColor((short) 20);
+ Font font2 = wb1.createFont();
+ font2.setColor(Font.COLOR_RED);
+ Font font3 = wb1.getFontAt(0);
- XSSFRow row = sheet.createRow(2);
- XSSFCell cell = row.createCell(2);
+ XSSFRow row = sheet.createRow(2);
+ XSSFCell cell = row.createCell(2);
- XSSFRichTextString richTextString =
+ XSSFRichTextString richTextString =
wb1.getCreationHelper().createRichTextString(text);
- // Check the text has the newline
- assertEquals(text, richTextString.getString());
-
- // Apply the font
- richTextString.applyFont(font3);
- richTextString.applyFont(0, 3, font1);
- cell.setCellValue(richTextString);
+ // Check the text has the newline
+ assertEquals(text, richTextString.getString());
- // To enable newlines you need set a cell styles with wrap=true
- CellStyle cs = wb1.createCellStyle();
- cs.setWrapText(true);
- cell.setCellStyle(cs);
+ // Apply the font
+ richTextString.applyFont(font3);
+ richTextString.applyFont(0, 3, font1);
+ cell.setCellValue(richTextString);
- // Check the text has the
- assertEquals(text, cell.getStringCellValue());
+ // To enable newlines you need set a cell styles with wrap=true
+ CellStyle cs = wb1.createCellStyle();
+ cs.setWrapText(true);
+ cell.setCellStyle(cs);
- // Save the file and re-read it
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- row = sheet.getRow(2);
- cell = row.getCell(2);
- assertEquals(text, cell.getStringCellValue());
+ // Check the text has the
+ assertEquals(text, cell.getStringCellValue());
- // Now add a 2nd, and check again
- int fontAt = text.indexOf('\n', 6);
- cell.getRichStringCellValue().applyFont(10, fontAt + 1, font2);
- assertEquals(text, cell.getStringCellValue());
+ // Save the file and re-read it
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ sheet = wb2.getSheetAt(0);
+ row = sheet.getRow(2);
+ cell = row.getCell(2);
+ assertEquals(text, cell.getStringCellValue());
- assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
- assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT());
+ // Now add a 2nd, and check again
+ int fontAt = text.indexOf('\n', 6);
+ cell.getRichStringCellValue().applyFont(10, fontAt + 1, font2);
+ assertEquals(text, cell.getStringCellValue());
- String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT();
- assertEquals("line.\n", r3.substring(r3.length() - 6));
+ assertEquals(4, cell.getRichStringCellValue().numFormattingRuns());
+ assertEquals("Use", cell.getRichStringCellValue().getCTRst().getRArray(0).getT());
- // Save and re-check
- XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
+ String r3 = cell.getRichStringCellValue().getCTRst().getRArray(2).getT();
+ assertEquals("line.\n", r3.substring(r3.length() - 6));
- sheet = wb3.getSheetAt(0);
- row = sheet.getRow(2);
- cell = row.getCell(2);
- assertEquals(text, cell.getStringCellValue());
- wb3.close();
+ // Save and re-check
+ try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
- // FileOutputStream out = new FileOutputStream("/tmp/test48877.xlsx");
- // wb.write(out);
- // out.close();
+ sheet = wb3.getSheetAt(0);
+ row = sheet.getRow(2);
+ cell = row.getCell(2);
+ assertEquals(text, cell.getStringCellValue());
+ }
+ }
+ }
}
/**
@@ -956,119 +933,118 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug50867() throws IOException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("50867_with_table.xlsx");
- assertEquals(3, wb1.getNumberOfSheets());
-
- XSSFSheet s1 = wb1.getSheetAt(0);
- XSSFSheet s2 = wb1.getSheetAt(1);
- XSSFSheet s3 = wb1.getSheetAt(2);
- assertEquals(1, s1.getTables().size());
- assertEquals(0, s2.getTables().size());
- assertEquals(0, s3.getTables().size());
-
- XSSFTable t = s1.getTables().get(0);
- assertEquals("Tabella1", t.getName());
- assertEquals("Tabella1", t.getDisplayName());
- assertEquals("A1:C3", t.getCTTable().getRef());
-
- // Add a sheet and re-order
- XSSFSheet s4 = wb1.createSheet("NewSheet");
- wb1.setSheetOrder(s4.getSheetName(), 0);
-
- // Check on tables
- assertEquals(1, s1.getTables().size());
- assertEquals(0, s2.getTables().size());
- assertEquals(0, s3.getTables().size());
- assertEquals(0, s4.getTables().size());
-
- // Refetch to get the new order
- s1 = wb1.getSheetAt(0);
- s2 = wb1.getSheetAt(1);
- s3 = wb1.getSheetAt(2);
- s4 = wb1.getSheetAt(3);
- assertEquals(0, s1.getTables().size());
- assertEquals(1, s2.getTables().size());
- assertEquals(0, s3.getTables().size());
- assertEquals(0, s4.getTables().size());
-
- // Save and re-load
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
-
- s1 = wb2.getSheetAt(0);
- s2 = wb2.getSheetAt(1);
- s3 = wb2.getSheetAt(2);
- s4 = wb2.getSheetAt(3);
- assertEquals(0, s1.getTables().size());
- assertEquals(1, s2.getTables().size());
- assertEquals(0, s3.getTables().size());
- assertEquals(0, s4.getTables().size());
-
- t = s2.getTables().get(0);
- assertEquals("Tabella1", t.getName());
- assertEquals("Tabella1", t.getDisplayName());
- assertEquals("A1:C3", t.getCTTable().getRef());
-
-
- // Add some more tables, and check
- t = s2.createTable(null);
- t.setName("New 2");
- t.setDisplayName("New 2");
- t = s3.createTable(null);
- t.setName("New 3");
- t.setDisplayName("New 3");
-
- XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- s1 = wb3.getSheetAt(0);
- s2 = wb3.getSheetAt(1);
- s3 = wb3.getSheetAt(2);
- s4 = wb3.getSheetAt(3);
- assertEquals(0, s1.getTables().size());
- assertEquals(2, s2.getTables().size());
- assertEquals(1, s3.getTables().size());
- assertEquals(0, s4.getTables().size());
-
- t = s2.getTables().get(0);
- assertEquals("Tabella1", t.getName());
- assertEquals("Tabella1", t.getDisplayName());
- assertEquals("A1:C3", t.getCTTable().getRef());
-
- t = s2.getTables().get(1);
- assertEquals("New 2", t.getName());
- assertEquals("New 2", t.getDisplayName());
-
- t = s3.getTables().get(0);
- assertEquals("New 3", t.getName());
- assertEquals("New 3", t.getDisplayName());
-
- // Check the relationships
- assertEquals(0, s1.getRelations().size());
- assertEquals(3, s2.getRelations().size());
- assertEquals(1, s3.getRelations().size());
- assertEquals(0, s4.getRelations().size());
-
- assertEquals(
- XSSFRelation.PRINTER_SETTINGS.getContentType(),
- s2.getRelations().get(0).getPackagePart().getContentType()
- );
- assertEquals(
- XSSFRelation.TABLE.getContentType(),
- s2.getRelations().get(1).getPackagePart().getContentType()
- );
- assertEquals(
- XSSFRelation.TABLE.getContentType(),
- s2.getRelations().get(2).getPackagePart().getContentType()
- );
- assertEquals(
- XSSFRelation.TABLE.getContentType(),
- s3.getRelations().get(0).getPackagePart().getContentType()
- );
- assertEquals(
- "/xl/tables/table3.xml",
- s3.getRelations().get(0).getPackagePart().getPartName().toString()
- );
- wb3.close();
+ try (XSSFWorkbook wb1 = openSampleWorkbook("50867_with_table.xlsx")) {
+ assertEquals(3, wb1.getNumberOfSheets());
+
+ XSSFSheet s1 = wb1.getSheetAt(0);
+ XSSFSheet s2 = wb1.getSheetAt(1);
+ XSSFSheet s3 = wb1.getSheetAt(2);
+ assertEquals(1, s1.getTables().size());
+ assertEquals(0, s2.getTables().size());
+ assertEquals(0, s3.getTables().size());
+
+ XSSFTable t = s1.getTables().get(0);
+ assertEquals("Tabella1", t.getName());
+ assertEquals("Tabella1", t.getDisplayName());
+ assertEquals("A1:C3", t.getCTTable().getRef());
+
+ // Add a sheet and re-order
+ XSSFSheet s4 = wb1.createSheet("NewSheet");
+ wb1.setSheetOrder(s4.getSheetName(), 0);
+
+ // Check on tables
+ assertEquals(1, s1.getTables().size());
+ assertEquals(0, s2.getTables().size());
+ assertEquals(0, s3.getTables().size());
+ assertEquals(0, s4.getTables().size());
+
+ // Refetch to get the new order
+ s1 = wb1.getSheetAt(0);
+ s2 = wb1.getSheetAt(1);
+ s3 = wb1.getSheetAt(2);
+ s4 = wb1.getSheetAt(3);
+ assertEquals(0, s1.getTables().size());
+ assertEquals(1, s2.getTables().size());
+ assertEquals(0, s3.getTables().size());
+ assertEquals(0, s4.getTables().size());
+
+ // Save and re-load
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ s1 = wb2.getSheetAt(0);
+ s2 = wb2.getSheetAt(1);
+ s3 = wb2.getSheetAt(2);
+ s4 = wb2.getSheetAt(3);
+ assertEquals(0, s1.getTables().size());
+ assertEquals(1, s2.getTables().size());
+ assertEquals(0, s3.getTables().size());
+ assertEquals(0, s4.getTables().size());
+
+ t = s2.getTables().get(0);
+ assertEquals("Tabella1", t.getName());
+ assertEquals("Tabella1", t.getDisplayName());
+ assertEquals("A1:C3", t.getCTTable().getRef());
+
+
+ // Add some more tables, and check
+ t = s2.createTable(null);
+ t.setName("New 2");
+ t.setDisplayName("New 2");
+ t = s3.createTable(null);
+ t.setName("New 3");
+ t.setDisplayName("New 3");
+
+ try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
+ s1 = wb3.getSheetAt(0);
+ s2 = wb3.getSheetAt(1);
+ s3 = wb3.getSheetAt(2);
+ s4 = wb3.getSheetAt(3);
+ assertEquals(0, s1.getTables().size());
+ assertEquals(2, s2.getTables().size());
+ assertEquals(1, s3.getTables().size());
+ assertEquals(0, s4.getTables().size());
+
+ t = s2.getTables().get(0);
+ assertEquals("Tabella1", t.getName());
+ assertEquals("Tabella1", t.getDisplayName());
+ assertEquals("A1:C3", t.getCTTable().getRef());
+
+ t = s2.getTables().get(1);
+ assertEquals("New 2", t.getName());
+ assertEquals("New 2", t.getDisplayName());
+
+ t = s3.getTables().get(0);
+ assertEquals("New 3", t.getName());
+ assertEquals("New 3", t.getDisplayName());
+
+ // Check the relationships
+ assertEquals(0, s1.getRelations().size());
+ assertEquals(3, s2.getRelations().size());
+ assertEquals(1, s3.getRelations().size());
+ assertEquals(0, s4.getRelations().size());
+
+ assertEquals(
+ XSSFRelation.PRINTER_SETTINGS.getContentType(),
+ s2.getRelations().get(0).getPackagePart().getContentType()
+ );
+ assertEquals(
+ XSSFRelation.TABLE.getContentType(),
+ s2.getRelations().get(1).getPackagePart().getContentType()
+ );
+ assertEquals(
+ XSSFRelation.TABLE.getContentType(),
+ s2.getRelations().get(2).getPackagePart().getContentType()
+ );
+ assertEquals(
+ XSSFRelation.TABLE.getContentType(),
+ s3.getRelations().get(0).getPackagePart().getContentType()
+ );
+ assertEquals(
+ "/xl/tables/table3.xml",
+ s3.getRelations().get(0).getPackagePart().getPartName().toString()
+ );
+ }
+ }
+ }
}
/**
@@ -1077,45 +1053,43 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug49253() throws IOException {
- XSSFWorkbook wb1 = new XSSFWorkbook();
- XSSFWorkbook wb2 = new XSSFWorkbook();
- CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3");
-
- // No print settings before repeating
- XSSFSheet s1 = wb1.createSheet();
- assertFalse(s1.getCTWorksheet().isSetPageSetup());
- assertTrue(s1.getCTWorksheet().isSetPageMargins());
- s1.setRepeatingColumns(cra);
- s1.setRepeatingRows(cra);
+ try (XSSFWorkbook wb1 = new XSSFWorkbook();
+ XSSFWorkbook wb2 = new XSSFWorkbook()) {
+ CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3");
- assertTrue(s1.getCTWorksheet().isSetPageSetup());
- assertTrue(s1.getCTWorksheet().isSetPageMargins());
+ // No print settings before repeating
+ XSSFSheet s1 = wb1.createSheet();
+ assertFalse(s1.getCTWorksheet().isSetPageSetup());
+ assertTrue(s1.getCTWorksheet().isSetPageMargins());
+ s1.setRepeatingColumns(cra);
+ s1.setRepeatingRows(cra);
- PrintSetup ps1 = s1.getPrintSetup();
- assertFalse(ps1.getValidSettings());
- assertFalse(ps1.getLandscape());
+ assertTrue(s1.getCTWorksheet().isSetPageSetup());
+ assertTrue(s1.getCTWorksheet().isSetPageMargins());
+ PrintSetup ps1 = s1.getPrintSetup();
+ assertFalse(ps1.getValidSettings());
+ assertFalse(ps1.getLandscape());
- // Had valid print settings before repeating
- XSSFSheet s2 = wb2.createSheet();
- PrintSetup ps2 = s2.getPrintSetup();
- assertTrue(s2.getCTWorksheet().isSetPageSetup());
- assertTrue(s2.getCTWorksheet().isSetPageMargins());
- ps2.setLandscape(false);
- assertTrue(ps2.getValidSettings());
- assertFalse(ps2.getLandscape());
- s2.setRepeatingColumns(cra);
- s2.setRepeatingRows(cra);
+ // Had valid print settings before repeating
+ XSSFSheet s2 = wb2.createSheet();
+ PrintSetup ps2 = s2.getPrintSetup();
+ assertTrue(s2.getCTWorksheet().isSetPageSetup());
+ assertTrue(s2.getCTWorksheet().isSetPageMargins());
- ps2 = s2.getPrintSetup();
- assertTrue(s2.getCTWorksheet().isSetPageSetup());
- assertTrue(s2.getCTWorksheet().isSetPageMargins());
- assertTrue(ps2.getValidSettings());
- assertFalse(ps2.getLandscape());
+ ps2.setLandscape(false);
+ assertTrue(ps2.getValidSettings());
+ assertFalse(ps2.getLandscape());
+ s2.setRepeatingColumns(cra);
+ s2.setRepeatingRows(cra);
- wb1.close();
- wb2.close();
+ ps2 = s2.getPrintSetup();
+ assertTrue(s2.getCTWorksheet().isSetPageSetup());
+ assertTrue(s2.getCTWorksheet().isSetPageMargins());
+ assertTrue(ps2.getValidSettings());
+ assertFalse(ps2.getLandscape());
+ }
}
/**
@@ -1123,77 +1097,77 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug51037() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet s = wb.createSheet();
-
- CellStyle defaultStyle = wb.getCellStyleAt((short) 0);
- assertEquals(0, defaultStyle.getIndex());
-
- CellStyle blueStyle = wb.createCellStyle();
- blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
- blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
- assertEquals(1, blueStyle.getIndex());
-
- CellStyle pinkStyle = wb.createCellStyle();
- pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
- pinkStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
- assertEquals(2, pinkStyle.getIndex());
-
- // Starts empty
- assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
- CTCols cols = s.getCTWorksheet().getColsArray(0);
- assertEquals(0, cols.sizeOfColArray());
-
- // Add some rows and columns
- XSSFRow r1 = s.createRow(0);
- XSSFRow r2 = s.createRow(1);
- r1.createCell(0);
- r1.createCell(2);
- r2.createCell(0);
- r2.createCell(3);
-
- // Check no style is there
- assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
- assertEquals(0, cols.sizeOfColArray());
-
- assertEquals(defaultStyle, s.getColumnStyle(0));
- assertEquals(defaultStyle, s.getColumnStyle(2));
- assertEquals(defaultStyle, s.getColumnStyle(3));
-
-
- // Apply the styles
- s.setDefaultColumnStyle(0, pinkStyle);
- s.setDefaultColumnStyle(3, blueStyle);
-
- // Check
- assertEquals(pinkStyle, s.getColumnStyle(0));
- assertEquals(defaultStyle, s.getColumnStyle(2));
- assertEquals(blueStyle, s.getColumnStyle(3));
-
- assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
- assertEquals(2, cols.sizeOfColArray());
-
- assertEquals(1, cols.getColArray(0).getMin());
- assertEquals(1, cols.getColArray(0).getMax());
- assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
-
- assertEquals(4, cols.getColArray(1).getMin());
- assertEquals(4, cols.getColArray(1).getMax());
- assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
-
-
- // Save, re-load and re-check
- XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
- wb.close();
- s = wbBack.getSheetAt(0);
- defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex());
- blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex());
- pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex());
-
- assertEquals(pinkStyle, s.getColumnStyle(0));
- assertEquals(defaultStyle, s.getColumnStyle(2));
- assertEquals(blueStyle, s.getColumnStyle(3));
- wbBack.close();
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet s = wb.createSheet();
+
+ CellStyle defaultStyle = wb.getCellStyleAt((short) 0);
+ assertEquals(0, defaultStyle.getIndex());
+
+ CellStyle blueStyle = wb.createCellStyle();
+ blueStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
+ blueStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+ assertEquals(1, blueStyle.getIndex());
+
+ CellStyle pinkStyle = wb.createCellStyle();
+ pinkStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
+ pinkStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+ assertEquals(2, pinkStyle.getIndex());
+
+ // Starts empty
+ assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
+ CTCols cols = s.getCTWorksheet().getColsArray(0);
+ assertEquals(0, cols.sizeOfColArray());
+
+ // Add some rows and columns
+ XSSFRow r1 = s.createRow(0);
+ XSSFRow r2 = s.createRow(1);
+ r1.createCell(0);
+ r1.createCell(2);
+ r2.createCell(0);
+ r2.createCell(3);
+
+ // Check no style is there
+ assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
+ assertEquals(0, cols.sizeOfColArray());
+
+ assertEquals(defaultStyle, s.getColumnStyle(0));
+ assertEquals(defaultStyle, s.getColumnStyle(2));
+ assertEquals(defaultStyle, s.getColumnStyle(3));
+
+
+ // Apply the styles
+ s.setDefaultColumnStyle(0, pinkStyle);
+ s.setDefaultColumnStyle(3, blueStyle);
+
+ // Check
+ assertEquals(pinkStyle, s.getColumnStyle(0));
+ assertEquals(defaultStyle, s.getColumnStyle(2));
+ assertEquals(blueStyle, s.getColumnStyle(3));
+
+ assertEquals(1, s.getCTWorksheet().sizeOfColsArray());
+ assertEquals(2, cols.sizeOfColArray());
+
+ assertEquals(1, cols.getColArray(0).getMin());
+ assertEquals(1, cols.getColArray(0).getMax());
+ assertEquals(pinkStyle.getIndex(), cols.getColArray(0).getStyle());
+
+ assertEquals(4, cols.getColArray(1).getMin());
+ assertEquals(4, cols.getColArray(1).getMax());
+ assertEquals(blueStyle.getIndex(), cols.getColArray(1).getStyle());
+
+
+ // Save, re-load and re-check
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) {
+ s = wbBack.getSheetAt(0);
+ defaultStyle = wbBack.getCellStyleAt(defaultStyle.getIndex());
+ blueStyle = wbBack.getCellStyleAt(blueStyle.getIndex());
+ pinkStyle = wbBack.getCellStyleAt(pinkStyle.getIndex());
+
+ assertEquals(pinkStyle, s.getColumnStyle(0));
+ assertEquals(defaultStyle, s.getColumnStyle(2));
+ assertEquals(blueStyle, s.getColumnStyle(3));
+ }
+ }
}
/**
@@ -1203,9 +1177,9 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug46662() throws IOException {
for (int i=0; i<2; i++) {
- try (XSSFWorkbook wb1 = (i == 0) ? new XSSFWorkbook() : XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) {
+ try (XSSFWorkbook wb1 = (i == 0) ? new XSSFWorkbook() : openSampleWorkbook("sample.xlsx")) {
for (int j=0; j<3; j++) {
- try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) {
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
assertEquals(wb1.getNumberOfSheets(), wb2.getNumberOfSheets());
}
}
@@ -1220,7 +1194,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug51222() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("51222.xlsx")) {
XSSFSheet s = wb.getSheetAt(0);
XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0);
@@ -1260,7 +1234,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug51470() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("51470.xlsx")) {
XSSFSheet sh0 = wb.getSheetAt(0);
XSSFSheet sh1 = wb.cloneSheet(0);
List<RelationPart> rels0 = sh0.getRelationParts();
@@ -1286,64 +1260,64 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug51850() throws IOException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx");
- XSSFSheet sh1 = wb1.getSheetAt(0);
- XSSFSheet sh2 = wb1.getSheetAt(1);
+ try (XSSFWorkbook wb1 = openSampleWorkbook("51850.xlsx")) {
+ XSSFSheet sh1 = wb1.getSheetAt(0);
+ XSSFSheet sh2 = wb1.getSheetAt(1);
- // Sheet 2 has comments
- assertNotNull(sh2.getCommentsTable(false));
- assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
+ // Sheet 2 has comments
+ assertNotNull(sh2.getCommentsTable(false));
+ assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
- // Sheet 1 doesn't (yet)
- assertNull(sh1.getCommentsTable(false));
+ // Sheet 1 doesn't (yet)
+ assertNull(sh1.getCommentsTable(false));
- // Try to add comments to Sheet 1
- CreationHelper factory = wb1.getCreationHelper();
- Drawing<?> drawing = sh1.createDrawingPatriarch();
+ // Try to add comments to Sheet 1
+ CreationHelper factory = wb1.getCreationHelper();
+ Drawing<?> drawing = sh1.createDrawingPatriarch();
- ClientAnchor anchor = factory.createClientAnchor();
- anchor.setCol1(0);
- anchor.setCol2(4);
- anchor.setRow1(0);
- anchor.setRow2(1);
+ ClientAnchor anchor = factory.createClientAnchor();
+ anchor.setCol1(0);
+ anchor.setCol2(4);
+ anchor.setRow1(0);
+ anchor.setRow2(1);
- Comment comment1 = drawing.createCellComment(anchor);
- comment1.setString(
+ Comment comment1 = drawing.createCellComment(anchor);
+ comment1.setString(
factory.createRichTextString("I like this cell. It's my favourite."));
- comment1.setAuthor("Bob T. Fish");
-
- anchor = factory.createClientAnchor();
- anchor.setCol1(0);
- anchor.setCol2(4);
- anchor.setRow1(1);
- anchor.setRow2(1);
- Comment comment2 = drawing.createCellComment(anchor);
- comment2.setString(
+ comment1.setAuthor("Bob T. Fish");
+
+ anchor = factory.createClientAnchor();
+ anchor.setCol1(0);
+ anchor.setCol2(4);
+ anchor.setRow1(1);
+ anchor.setRow2(1);
+ Comment comment2 = drawing.createCellComment(anchor);
+ comment2.setString(
factory.createRichTextString("This is much less fun..."));
- comment2.setAuthor("Bob T. Fish");
+ comment2.setAuthor("Bob T. Fish");
- Cell c1 = sh1.getRow(0).createCell(4);
- c1.setCellValue(2.3);
- c1.setCellComment(comment1);
+ Cell c1 = sh1.getRow(0).createCell(4);
+ c1.setCellValue(2.3);
+ c1.setCellComment(comment1);
- Cell c2 = sh1.getRow(0).createCell(5);
- c2.setCellValue(2.1);
- c2.setCellComment(comment2);
+ Cell c2 = sh1.getRow(0).createCell(5);
+ c2.setCellValue(2.1);
+ c2.setCellComment(comment2);
- // Save and re-load
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sh1 = wb2.getSheetAt(0);
- sh2 = wb2.getSheetAt(1);
+ // Save and re-load
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ sh1 = wb2.getSheetAt(0);
+ sh2 = wb2.getSheetAt(1);
- // Check the comments
- assertNotNull(sh2.getCommentsTable(false));
- assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
+ // Check the comments
+ assertNotNull(sh2.getCommentsTable(false));
+ assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments());
- assertNotNull(sh1.getCommentsTable(false));
- assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
- wb2.close();
+ assertNotNull(sh1.getCommentsTable(false));
+ assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments());
+ }
+ }
}
/**
@@ -1351,7 +1325,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug51963() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("51963.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
assertEquals("Abc,1", sheet.getSheetName());
@@ -1372,7 +1346,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug48703() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("48703.xlsx")) {
XSSFSheet sheet = wb.getSheetAt(0);
// Contains two forms, one with a range and one a list
@@ -1402,7 +1376,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug51710() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("51710.xlsx")) {
final String[] columns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"};
final int rowMax = 500; // bug triggers on row index 59
@@ -1434,7 +1408,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug5301() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("53101.xlsx")) {
FormulaEvaluator evaluator =
wb.getCreationHelper().createFormulaEvaluator();
// A1: SUM(B1: IZ1)
@@ -1455,7 +1429,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug54436() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("54436.xlsx")) {
if (!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")) {
Function func = (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA;
@@ -1507,7 +1481,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug53282() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("53282b.xlsx")) {
Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
assertEquals("#@_#", c.getStringCellValue());
assertEquals("http://invalid.uri", c.getHyperlink().getAddress());
@@ -1521,11 +1495,11 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug56278() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("56278.xlsx")) {
assertEquals(0, wb.getSheetIndex("Market Rates"));
// Save and re-check
- Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb);
+ Workbook nwb = writeOutAndReadBack(wb);
assertEquals(0, nwb.getSheetIndex("Market Rates"));
nwb.close();
}
@@ -1533,7 +1507,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug56315() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("56315.xlsx")) {
Cell c = wb.getSheetAt(0).getRow(1).getCell(0);
CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c);
double rounded = cv.getNumberValue();
@@ -1558,7 +1532,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
Thread.sleep(10);
}
- ByteArrayOutputStream bos = new ByteArrayOutputStream(8096);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(8096);
wb.write(bos);
byte[] firstSave = bos.toByteArray();
bos.reset();
@@ -1578,17 +1552,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
void bug54034() throws IOException {
TimeZone tz = LocaleUtil.getUserTimeZone();
LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET"));
- try {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx")) {
- Sheet sheet = wb.getSheet("Sheet1");
- Row row = sheet.getRow(1);
- Cell cell = row.getCell(2);
- assertTrue(DateUtil.isCellDateFormatted(cell));
-
- DataFormatter fmt = new DataFormatter();
- assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
- assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
- }
+ try (Workbook wb = openSampleWorkbook("54034.xlsx")) {
+ Sheet sheet = wb.getSheet("Sheet1");
+ Row row = sheet.getRow(1);
+ Cell cell = row.getCell(2);
+ assertTrue(DateUtil.isCellDateFormatted(cell));
+
+ DataFormatter fmt = new DataFormatter();
+ assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString());
+ assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell));
} finally {
LocaleUtil.setUserTimeZone(tz);
}
@@ -1597,7 +1569,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void testBug53798XLSX() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) {
File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
bug53798Work(wb, xlsOutput);
}
@@ -1606,7 +1578,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Disabled("Shifting rows is not yet implemented in SXSSFSheet")
@Test
void testBug53798XLSXStream() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) {
File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx");
SXSSFWorkbook wb2 = new SXSSFWorkbook(wb);
bug53798Work(wb2, xlsOutput);
@@ -1616,10 +1588,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void testBug53798XLS() throws IOException {
- Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls");
- File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
- bug53798Work(wb, xlsOutput);
- wb.close();
+ try (Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls")) {
+ File xlsOutput = TempFile.createTempFile("testBug53798", ".xls");
+ bug53798Work(wb, xlsOutput);
+ }
}
/**
@@ -1627,7 +1599,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void testBug56420SumIfNPE() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("56420.xlsx")) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
@@ -1689,7 +1661,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug56702() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("56702.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
@@ -1718,7 +1690,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug56737() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("56737.xlsx")) {
// Check the named range definitions
Name nSheetScope = wb.getName("NR_To_A1");
@@ -1787,38 +1759,32 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
}
}
- @Test
- void testBug56688_1() throws IOException {
- XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx");
- checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
- excel.close();
- }
-
- @Test
- void testBug56688_2() throws IOException {
- XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx");
- checkValue(excel, "#VALUE!");
- excel.close();
- }
+ @ParameterizedTest
+ @CsvSource({
+ /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */
+ "56688_1.xlsx, -1.0",
+ "56688_2.xlsx, #VALUE!",
+ "56688_3.xlsx, #VALUE!",
+ "56688_4.xlsx, date"
+ })
+ void testBug56688(String fileName, String expect) throws IOException {
+ if ("date".equals(expect)) {
+ Calendar calendar = LocaleUtil.getLocaleCalendar();
+ calendar.add(Calendar.MONTH, 2);
+ double excelDate = DateUtil.getExcelDate(calendar.getTime());
+ NumberEval eval = new NumberEval(Math.floor(excelDate));
+ expect = eval.getStringValue() + ".0";
+ }
- @Test
- void testBug56688_3() throws IOException {
- XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx");
- checkValue(excel, "#VALUE!");
- excel.close();
- }
+ try (XSSFWorkbook excel = openSampleWorkbook(fileName)) {
+ XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
+ evaluator.evaluateAll();
- @Test
- void testBug56688_4() throws IOException {
- XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx");
-
- Calendar calendar = LocaleUtil.getLocaleCalendar();
- calendar.add(Calendar.MONTH, 2);
- double excelDate = DateUtil.getExcelDate(calendar.getTime());
- NumberEval eval = new NumberEval(Math.floor(excelDate));
- checkValue(excel, eval.getStringValue() + ".0");
+ XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
+ CellValue value = evaluator.evaluate(cell);
- excel.close();
+ assertEquals(expect, value.formatAsString());
+ }
}
/**
@@ -1827,33 +1793,33 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void testBug56527() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sheet = wb.createSheet();
- XSSFCreationHelper creationHelper = wb.getCreationHelper();
- XSSFHyperlink hyperlink;
-
- // Try with a cell reference
- hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
- sheet.addHyperlink(hyperlink);
- hyperlink.setAddress("http://myurl");
- hyperlink.setCellReference("B4");
- assertEquals(3, hyperlink.getFirstRow());
- assertEquals(1, hyperlink.getFirstColumn());
- assertEquals(3, hyperlink.getLastRow());
- assertEquals(1, hyperlink.getLastColumn());
-
- // Try with explicit rows / columns
- hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
- sheet.addHyperlink(hyperlink);
- hyperlink.setAddress("http://myurl");
- hyperlink.setFirstRow(5);
- hyperlink.setFirstColumn(3);
-
- assertEquals(5, hyperlink.getFirstRow());
- assertEquals(3, hyperlink.getFirstColumn());
- assertEquals(5, hyperlink.getLastRow());
- assertEquals(3, hyperlink.getLastColumn());
- wb.close();
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sheet = wb.createSheet();
+ XSSFCreationHelper creationHelper = wb.getCreationHelper();
+ XSSFHyperlink hyperlink;
+
+ // Try with a cell reference
+ hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
+ sheet.addHyperlink(hyperlink);
+ hyperlink.setAddress("http://myurl");
+ hyperlink.setCellReference("B4");
+ assertEquals(3, hyperlink.getFirstRow());
+ assertEquals(1, hyperlink.getFirstColumn());
+ assertEquals(3, hyperlink.getLastRow());
+ assertEquals(1, hyperlink.getLastColumn());
+
+ // Try with explicit rows / columns
+ hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
+ sheet.addHyperlink(hyperlink);
+ hyperlink.setAddress("http://myurl");
+ hyperlink.setFirstRow(5);
+ hyperlink.setFirstColumn(3);
+
+ assertEquals(5, hyperlink.getFirstRow());
+ assertEquals(3, hyperlink.getFirstColumn());
+ assertEquals(5, hyperlink.getLastRow());
+ assertEquals(3, hyperlink.getLastColumn());
+ }
}
/**
@@ -1862,7 +1828,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug56502() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("56502.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
Cell cFunc = sheet.getRow(3).getCell(0);
@@ -1900,7 +1866,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
"Should fail as too much expansion occurs");
// Check we can still parse valid files after all that
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("sample.xlsx")) {
assertEquals(3, wb.getNumberOfSheets());
}
}
@@ -1936,7 +1902,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug57176() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("57176.xlsx")) {
CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames();
List<CTDefinedName> definedNameList = definedNames.getDefinedNameList();
for (CTDefinedName defName : definedNameList) {
@@ -1967,19 +1933,9 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
assertThrows(XLSBUnsupportedException.class, () -> WorkbookFactory.create(xlsbFile), ".xlsb files not supported");
}
- private void checkValue(XSSFWorkbook excel, String expect) {
- XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel);
- evaluator.evaluateAll();
-
- XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1);
- CellValue value = evaluator.evaluate(cell);
-
- assertEquals(expect, value.formatAsString());
- }
-
@Test
void testBug57196() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("57196.xlsx")) {
Sheet sheet = wb.getSheet("Feuil1");
Row mod = sheet.getRow(1);
mod.getCell(1).setCellValue(3);
@@ -1992,30 +1948,30 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test57196_Detail() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sheet = wb.createSheet("Sheet1");
- XSSFRow row = sheet.createRow(0);
- XSSFCell cell = row.createCell(0);
- cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
- XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
- CellValue cv = fe.evaluate(cell);
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sheet = wb.createSheet("Sheet1");
+ XSSFRow row = sheet.createRow(0);
+ XSSFCell cell = row.createCell(0);
+ cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)");
+ XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
+ CellValue cv = fe.evaluate(cell);
- assertNotNull(cv);
- wb.close();
+ assertNotNull(cv);
+ }
}
@Test
void test57196_Detail2() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet sheet = wb.createSheet("Sheet1");
- XSSFRow row = sheet.createRow(0);
- XSSFCell cell = row.createCell(0);
- cell.setCellFormula("DEC2HEX(O2+D2)");
- XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
- CellValue cv = fe.evaluate(cell);
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet sheet = wb.createSheet("Sheet1");
+ XSSFRow row = sheet.createRow(0);
+ XSSFCell cell = row.createCell(0);
+ cell.setCellFormula("DEC2HEX(O2+D2)");
+ XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb);
+ CellValue cv = fe.evaluate(cell);
- assertNotNull(cv);
- wb.close();
+ assertNotNull(cv);
+ }
}
@ParameterizedTest
@@ -2081,7 +2037,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
// Try to write-out and read again, should only work
// in read-write mode, not read-only mode
- try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) {
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
if (access == PackageAccess.READ) {
fail("Shouln't be able to write from read-only mode");
}
@@ -2110,7 +2066,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug57535() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("57535.xlsx")) {
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
evaluator.clearAllCachedResultValues();
@@ -2130,13 +2086,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test57165() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("57171_57163_57165.xlsx")) {
removeAllSheetsBut(3, wb);
// Throws exception here
assertDoesNotThrow(() -> wb.cloneSheet(0));
wb.setSheetName(1, "New Sheet");
- try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) {
assertNotNull(wbBack.getSheet("New Sheet"));
}
}
@@ -2144,13 +2100,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test57165_create() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("57171_57163_57165.xlsx")) {
removeAllSheetsBut(3, wb);
// Throws exception here
assertDoesNotThrow(() -> wb.createSheet("newsheet"));
wb.setSheetName(1, "New Sheet");
- try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) {
assertNotNull(wbBack.getSheet("New Sheet"));
}
}
@@ -2235,7 +2191,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test56467() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("picture.xlsx")) {
Sheet orig = wb.getSheetAt(0);
assertNotNull(orig);
@@ -2258,12 +2214,12 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
@Disabled("XMLBeans namespace mis-match on ooxml-strict files")
void test57699() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("sample.strict.xlsx")) {
assertEquals(3, wb.getNumberOfSheets());
// TODO Check sheet contents
// TODO Check formula evaluation
- try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) {
assertEquals(3, wbBack.getNumberOfSheets());
// TODO Re-check sheet contents
// TODO Re-check formula evaluation
@@ -2273,13 +2229,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void testBug56295_MergeXlslsWithStyles() throws IOException {
- XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx");
- XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0);
- XSSFRow srcRow = sheet.getRow(0);
- XSSFCell oldCell = srcRow.getCell(0);
- XSSFCellStyle cellStyle = oldCell.getCellStyle();
+ try (XSSFWorkbook xlsToAppendWorkbook = openSampleWorkbook("56295.xlsx");
+ XSSFWorkbook targetWorkbook = new XSSFWorkbook()) {
+ XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0);
+ XSSFRow srcRow = sheet.getRow(0);
+ XSSFCell oldCell = srcRow.getCell(0);
+ XSSFCellStyle cellStyle = oldCell.getCellStyle();
- checkStyle(cellStyle);
+ checkStyle(cellStyle);
// StylesTable table = xlsToAppendWorkbook.getStylesSource();
// List<XSSFCellFill> fills = table.getFills();
@@ -2287,33 +2244,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
// for(XSSFCellFill fill : fills) {
// System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor());
// }
- xlsToAppendWorkbook.close();
-
- XSSFWorkbook targetWorkbook = new XSSFWorkbook();
- XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName());
- XSSFRow destRow = newSheet.createRow(0);
- XSSFCell newCell = destRow.createCell(0);
-
- //newCell.getCellStyle().cloneStyleFrom(cellStyle);
- CellStyle newCellStyle = targetWorkbook.createCellStyle();
- newCellStyle.cloneStyleFrom(cellStyle);
- newCell.setCellStyle(newCellStyle);
- checkStyle(newCell.getCellStyle());
- newCell.setCellValue(oldCell.getStringCellValue());
-
-// OutputStream os = new FileOutputStream("output.xlsm");
-// try {
-// targetWorkbook.write(os);
-// } finally {
-// os.close();
-// }
+ xlsToAppendWorkbook.close();
+
+ XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName());
+ XSSFRow destRow = newSheet.createRow(0);
+ XSSFCell newCell = destRow.createCell(0);
- XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook);
- XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
- checkStyle(styleBack);
+ //newCell.getCellStyle().cloneStyleFrom(cellStyle);
+ CellStyle newCellStyle = targetWorkbook.createCellStyle();
+ newCellStyle.cloneStyleFrom(cellStyle);
+ newCell.setCellStyle(newCellStyle);
+ checkStyle(newCell.getCellStyle());
+ newCell.setCellValue(oldCell.getStringCellValue());
- targetWorkbook.close();
- wbBack.close();
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(targetWorkbook)) {
+ XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
+ checkStyle(styleBack);
+
+ }
+ }
}
/**
@@ -2323,27 +2272,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void testBug57826() throws IOException {
- XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx");
-
- assertTrue(workbook.getNumberOfSheets() >= 1, "no sheets in workbook");
- XSSFSheet sheet = workbook.getSheetAt(0);
+ try (XSSFWorkbook workbook = openSampleWorkbook("57826.xlsx")) {
+ assertTrue(workbook.getNumberOfSheets() >= 1, "no sheets in workbook");
+ XSSFSheet sheet = workbook.getSheetAt(0);
- XSSFDrawing drawing = sheet.getDrawingPatriarch();
- assertNotNull(drawing);
+ XSSFDrawing drawing = sheet.getDrawingPatriarch();
+ assertNotNull(drawing);
- List<XSSFShape> shapes = drawing.getShapes();
- assertEquals(1, shapes.size());
- assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
+ List<XSSFShape> shapes = drawing.getShapes();
+ assertEquals(1, shapes.size());
+ assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
- XSSFSimpleShape shape = (XSSFSimpleShape) shapes.get(0);
+ XSSFSimpleShape shape = (XSSFSimpleShape) shapes.get(0);
- // Used to throw a NPE
- String text = shape.getText();
+ // Used to throw a NPE
+ String text = shape.getText();
- // No bulleting info included
- assertEquals("test ok", text);
-
- workbook.close();
+ // No bulleting info included
+ assertEquals("test ok", text);
+ }
}
private void checkStyle(XSSFCellStyle cellStyle) {
@@ -2363,20 +2310,19 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug57642() throws IOException {
- XSSFWorkbook wb = new XSSFWorkbook();
- XSSFSheet s = wb.createSheet("TestSheet");
- XSSFCell c = s.createRow(0).createCell(0);
- c.setCellFormula("ISERROR(TestSheet!A1)");
- c = s.createRow(1).createCell(1);
- c.setCellFormula("ISERROR(B2)");
-
- wb.setSheetName(0, "CSN");
- c = s.getRow(0).getCell(0);
- assertEquals("ISERROR(CSN!A1)", c.getCellFormula());
- c = s.getRow(1).getCell(1);
- assertEquals("ISERROR(B2)", c.getCellFormula());
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ XSSFSheet s = wb.createSheet("TestSheet");
+ XSSFCell c = s.createRow(0).createCell(0);
+ c.setCellFormula("ISERROR(TestSheet!A1)");
+ c = s.createRow(1).createCell(1);
+ c.setCellFormula("ISERROR(B2)");
- wb.close();
+ wb.setSheetName(0, "CSN");
+ c = s.getRow(0).getCell(0);
+ assertEquals("ISERROR(CSN!A1)", c.getCellFormula());
+ c = s.getRow(1).getCell(1);
+ assertEquals("ISERROR(B2)", c.getCellFormula());
+ }
}
/**
@@ -2386,47 +2332,42 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void bug57880() throws IOException {
int numStyles = 33000;
- XSSFWorkbook wb = new XSSFWorkbook();
- for (int i = 1; i < numStyles; i++) {
- // Create a style and use it
- XSSFCellStyle style = wb.createCellStyle();
- assertEquals(i, style.getUIndex());
- }
- assertEquals(numStyles, wb.getNumCellStyles());
+ File file;
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ for (int i = 1; i < numStyles; i++) {
+ // Create a style and use it
+ XSSFCellStyle style = wb.createCellStyle();
+ assertEquals(i, style.getUIndex());
+ }
+ assertEquals(numStyles, wb.getNumCellStyles());
- // avoid OOM in Gump run
- File file = XSSFTestDataSamples.writeOutAndClose(wb, "bug57880");
- //noinspection UnusedAssignment
- wb = null;
- // Garbage collection may happen here
+ // avoid OOM in Gump run
+ file = XSSFTestDataSamples.writeOutAndClose(wb, "bug57880");
+ }
// avoid zip bomb detection
double ratio = ZipSecureFile.getMinInflateRatio();
ZipSecureFile.setMinInflateRatio(0.00005);
- wb = XSSFTestDataSamples.readBackAndDelete(file);
- ZipSecureFile.setMinInflateRatio(ratio);
-
- //Assume identical cell styles aren't consolidated
- //If XSSFWorkbooks ever implicitly optimize/consolidate cell styles (such as when the workbook is written to disk)
- //then this unit test should be updated
- assertEquals(numStyles, wb.getNumCellStyles());
- for (int i = 1; i < numStyles; i++) {
- XSSFCellStyle style = wb.getCellStyleAt(i);
- assertNotNull(style);
- assertEquals(i, style.getUIndex());
+ try (XSSFWorkbook wb = XSSFTestDataSamples.readBackAndDelete(file)) {
+ ZipSecureFile.setMinInflateRatio(ratio);
+
+ //Assume identical cell styles aren't consolidated
+ //If XSSFWorkbooks ever implicitly optimize/consolidate cell styles (such as when the workbook is written to disk)
+ //then this unit test should be updated
+ assertEquals(numStyles, wb.getNumCellStyles());
+ for (int i = 1; i < numStyles; i++) {
+ XSSFCellStyle style = wb.getCellStyleAt(i);
+ assertNotNull(style);
+ assertEquals(i, style.getUIndex());
+ }
}
- wb.close();
}
- @Test
- void test56574() throws IOException {
- runTest56574(false);
- runTest56574(true);
- }
-
- private void runTest56574(boolean createRow) throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx")) {
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true})
+ void test56574(boolean createRow) throws IOException {
+ try (XSSFWorkbook wb = openSampleWorkbook("56574.xlsx")) {
Sheet sheet = wb.getSheet("Func");
assertNotNull(sheet);
@@ -2475,14 +2416,13 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
CalculationChain chain = wb.getCalculationChain();
checkCellsAreGone(chain);
- XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
- Sheet sheetBack = wbBack.getSheet("Func");
- assertNotNull(sheetBack);
-
- chain = wbBack.getCalculationChain();
- checkCellsAreGone(chain);
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(wb)) {
+ Sheet sheetBack = wbBack.getSheet("Func");
+ assertNotNull(sheetBack);
- wbBack.close();
+ chain = wbBack.getCalculationChain();
+ checkCellsAreGone(chain);
+ }
}
}
@@ -2502,14 +2442,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void bug57181() throws IOException {
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("57181.xlsm")) {
assertEquals(9, wb.getNumberOfSheets());
}
}
@Test
void bug52111() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("Intersection-52111-xssf.xlsx")) {
Sheet s = wb.getSheetAt(0);
assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0");
assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0");
@@ -2519,7 +2459,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test48962() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("48962.xlsx")) {
Sheet sh = wb.getSheetAt(0);
Row row = sh.getRow(1);
Cell cell = row.getCell(0);
@@ -2544,7 +2484,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test50755_workday_formula_example() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("50755_workday_formula_example.xlsx")) {
Sheet sheet = wb.getSheet("Sheet1");
for (Row aRow : sheet) {
Cell cell = aRow.getCell(1);
@@ -2559,25 +2499,17 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
}
}
- @Test
- void test51626() throws IOException {
- Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51626.xlsx");
- assertNotNull(wb);
- wb.close();
-
- InputStream stream = HSSFTestDataSamples.openSampleFileStream("51626.xlsx");
- wb = WorkbookFactory.create(stream);
- stream.close();
- wb.close();
-
- wb = XSSFTestDataSamples.openSampleWorkbook("51626_contact.xlsx");
- assertNotNull(wb);
- wb.close();
+ @ParameterizedTest
+ @ValueSource(strings = { "51626.xlsx", "51626_contact.xlsx"})
+ void test51626(String fileName) throws IOException {
+ try (Workbook wb = openSampleWorkbook(fileName)) {
+ assertNotNull(wb);
+ }
- stream = HSSFTestDataSamples.openSampleFileStream("51626_contact.xlsx");
- wb = WorkbookFactory.create(stream);
- stream.close();
- wb.close();
+ try (InputStream stream = HSSFTestDataSamples.openSampleFileStream(fileName);
+ Workbook wb = WorkbookFactory.create(stream)) {
+ assertNotNull(wb);
+ }
}
@Disabled("this test is only for manual verification, as we can't test if the cell is visible in Excel")
@@ -2599,7 +2531,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test53105() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("53105.xlsx")) {
assertNotNull(wb);
@@ -2616,7 +2548,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test58315() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("58315.xlsx")) {
Cell cell = wb.getSheetAt(0).getRow(0).getCell(0);
assertNotNull(cell);
StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue());
@@ -2635,7 +2567,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test55406() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
Cell cellA1 = sheet.getRow(0).getCell(0);
Cell cellA2 = sheet.getRow(1).getCell(0);
@@ -2662,45 +2594,43 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test51998() throws IOException {
- Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51998.xlsx");
+ try (Workbook wb = openSampleWorkbook("51998.xlsx")) {
+ Set<String> sheetNames = new HashSet<>();
- Set<String> sheetNames = new HashSet<>();
+ for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
+ sheetNames.add(wb.getSheetName(sheetNum));
+ }
- for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
- sheetNames.add(wb.getSheetName(sheetNum));
- }
+ for (String sheetName : sheetNames) {
+ int sheetIndex = wb.getSheetIndex(sheetName);
- for (String sheetName : sheetNames) {
- int sheetIndex = wb.getSheetIndex(sheetName);
+ wb.removeSheetAt(sheetIndex);
- wb.removeSheetAt(sheetIndex);
+ Sheet newSheet = wb.createSheet();
+ //Sheet newSheet = wb.createSheet(sheetName);
+ int newSheetIndex = wb.getSheetIndex(newSheet);
+ wb.setSheetName(newSheetIndex, sheetName);
+ wb.setSheetOrder(sheetName, sheetIndex);
+ }
- Sheet newSheet = wb.createSheet();
- //Sheet newSheet = wb.createSheet(sheetName);
- int newSheetIndex = wb.getSheetIndex(newSheet);
- wb.setSheetName(newSheetIndex, sheetName);
- wb.setSheetOrder(sheetName, sheetIndex);
+ try (Workbook wbBack = writeOutAndReadBack(wb)) {
+ assertNotNull(wbBack);
+ }
}
-
- Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
- wb.close();
-
- assertNotNull(wbBack);
- wbBack.close();
}
@Test
void test58731() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx")) {
+ Object[][] bookData = {
+ {"Head First Java", "Kathy Serria", 79},
+ {"Effective Java", "Joshua Bloch", 36},
+ {"Clean Code", "Robert martin", 42},
+ {"Thinking in Java", "Bruce Eckel", 35},
+ };
+
+ try (Workbook wb = openSampleWorkbook("58731.xlsx")) {
Sheet sheet = wb.createSheet("Java Books");
- Object[][] bookData = {
- {"Head First Java", "Kathy Serria", 79},
- {"Effective Java", "Joshua Bloch", 36},
- {"Clean Code", "Robert martin", 42},
- {"Thinking in Java", "Bruce Eckel", 35},
- };
-
int rowCount = 0;
for (Object[] aBook : bookData) {
Row row = sheet.createRow(rowCount++);
@@ -2716,7 +2646,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
}
}
- try (Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (Workbook wb2 = writeOutAndReadBack(wb)) {
sheet = wb2.getSheet("Java Books");
assertNotNull(sheet.getRow(0));
assertNotNull(sheet.getRow(0).getCell(0));
@@ -2733,14 +2663,14 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void test58760() throws IOException {
- Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("58760.xlsx");
- assertEquals(1, wb1.getNumberOfSheets());
- assertEquals("Sheet1", wb1.getSheetName(0));
- Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- assertEquals(1, wb2.getNumberOfSheets());
- assertEquals("Sheet1", wb2.getSheetName(0));
- wb2.close();
- wb1.close();
+ try (Workbook wb1 = openSampleWorkbook("58760.xlsx")) {
+ assertEquals(1, wb1.getNumberOfSheets());
+ assertEquals("Sheet1", wb1.getSheetName(0));
+ try (Workbook wb2 = writeOutAndReadBack(wb1)) {
+ assertEquals(1, wb2.getNumberOfSheets());
+ assertEquals("Sheet1", wb2.getSheetName(0));
+ }
+ }
}
@Test
@@ -2755,7 +2685,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
DataFormatter formatter = new DataFormatter(true);
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("57236.xlsx")) {
for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
Sheet sheet = wb.getSheetAt(sheetNum);
for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum(); rowNum++) {
@@ -2771,41 +2701,27 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
}
}
- /**
- * helper function for {@link #test58043()}
- * Side-effects: closes the provided workbook!
- *
- * @param workbook the workbook to save for manual checking
- * @param outputFile the output file location to save the workbook to
- */
- private void saveRotatedTextExample(Workbook workbook, File outputFile) throws IOException {
- Sheet sheet = workbook.createSheet();
- Row row = sheet.createRow((short) 0);
-
- Cell cell = row.createCell(0);
-
- cell.setCellValue("Unsuccessful rotated text.");
-
- CellStyle style = workbook.createCellStyle();
- style.setRotation((short) -90);
-
- cell.setCellStyle(style);
+ @ParameterizedTest()
+ @CsvSource({ "false, rotated.xls", "true, rotated.xlsx" })
+ @Disabled("Creates files for checking results manually, actual values are tested in Test*CellStyle")
+ void test58043(boolean xssf, String fileName) throws IOException {
+ try (Workbook wb = WorkbookFactory.create(xssf)) {
+ Sheet sheet = wb.createSheet();
+ Row row = sheet.createRow((short) 0);
+ Cell cell = row.createCell(0);
+ cell.setCellValue("Unsuccessful rotated text.");
- OutputStream fos = new FileOutputStream(outputFile);
- workbook.write(fos);
- fos.close();
- workbook.close();
- }
+ CellStyle style = wb.createCellStyle();
+ style.setRotation((short) -90);
+ cell.setCellStyle(style);
- @Disabled("Creates files for checking results manually, actual values are tested in Test*CellStyle")
- void test58043() throws IOException {
- saveRotatedTextExample(new HSSFWorkbook(), TempFile.createTempFile("rotated", ".xls"));
- saveRotatedTextExample(new XSSFWorkbook(), TempFile.createTempFile("rotated", ".xlsx"));
+ XSSFTestDataSamples.writeOut(wb, fileName);
+ }
}
@Test
void test59132() throws IOException {
- try (Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("59132.xlsx")) {
+ try (Workbook workbook = openSampleWorkbook("59132.xlsx")) {
Sheet worksheet = workbook.getSheet("sheet1");
// B3
@@ -2848,51 +2764,51 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Disabled("bug 59442")
@Test
void testSetRGBBackgroundColor() throws IOException {
- XSSFWorkbook workbook = new XSSFWorkbook();
- XSSFCell cell = workbook.createSheet().createRow(0).createCell(0);
-
- XSSFColor color = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors());
- XSSFCellStyle style = workbook.createCellStyle();
- style.setFillForegroundColor(color);
- style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
- cell.setCellStyle(style);
-
- // Everything is fine at this point, cell is red
- XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor();
- assertNull(actual);
- actual = cell.getCellStyle().getFillForegroundColorColor();
- assertNotNull(actual);
- assertEquals(color.getARGBHex(), actual.getARGBHex());
-
- Map<String, Object> properties = new HashMap<>();
- properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN);
- CellUtil.setCellStyleProperties(cell, properties);
-
- // Now the cell is all black
- actual = cell.getCellStyle().getFillBackgroundColorColor();
- assertNotNull(actual);
- assertNull(actual.getARGBHex());
- actual = cell.getCellStyle().getFillForegroundColorColor();
- assertNotNull(actual);
- assertEquals(color.getARGBHex(), actual.getARGBHex());
-
- XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(workbook);
- workbook.close();
- XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0);
- XSSFColor ncolor = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors());
-
- // Now the cell is all black
- XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor();
- assertNotNull(nactual);
- assertEquals(ncolor.getARGBHex(), nactual.getARGBHex());
-
- nwb.close();
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
+ XSSFCell cell = workbook.createSheet().createRow(0).createCell(0);
+
+ XSSFColor color = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors());
+ XSSFCellStyle style = workbook.createCellStyle();
+ style.setFillForegroundColor(color);
+ style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+ cell.setCellStyle(style);
+
+ // Everything is fine at this point, cell is red
+ XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor();
+ assertNull(actual);
+ actual = cell.getCellStyle().getFillForegroundColorColor();
+ assertNotNull(actual);
+ assertEquals(color.getARGBHex(), actual.getARGBHex());
+
+ Map<String, Object> properties = new HashMap<>();
+ properties.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN);
+ CellUtil.setCellStyleProperties(cell, properties);
+
+ // Now the cell is all black
+ actual = cell.getCellStyle().getFillBackgroundColorColor();
+ assertNotNull(actual);
+ assertNull(actual.getARGBHex());
+ actual = cell.getCellStyle().getFillForegroundColorColor();
+ assertNotNull(actual);
+ assertEquals(color.getARGBHex(), actual.getARGBHex());
+
+ try (XSSFWorkbook nwb = writeOutAndReadBack(workbook)) {
+ XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0);
+ XSSFColor ncolor = new XSSFColor(java.awt.Color.RED, workbook.getStylesSource().getIndexedColors());
+
+ // Now the cell is all black
+ XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor();
+ assertNotNull(nactual);
+ assertEquals(ncolor.getARGBHex(), nactual.getARGBHex());
+
+ }
+ }
}
@Disabled("currently fails on POI 3.15 beta 2")
@Test
void test55273() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("ExcelTables.xlsx")) {
Sheet sheet = wb.getSheet("ExcelTable");
Name name = wb.getName("TableAsRangeName");
@@ -2910,7 +2826,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test57523() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("57523.xlsx")) {
Sheet sheet = wb.getSheet("Attribute Master");
Row row = sheet.getRow(15);
@@ -2930,7 +2846,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void noRowNumbers59746() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("59746_NoRowNums.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
assertTrue(sheet.getLastRowNum() > 20, "Last row num: " + sheet.getLastRowNum());
assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue());
@@ -2944,7 +2860,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void testWorkdayFunction() throws IOException {
- try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx")) {
+ try (XSSFWorkbook workbook = openSampleWorkbook("59106.xlsx")) {
XSSFSheet sheet = workbook.getSheet("Test");
Row row = sheet.getRow(1);
Cell cell = row.getCell(0);
@@ -3003,7 +2919,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
*/
@Test
void drawingNumbersAlreadyTaken_60255() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("60255_extra_drawingparts.xlsx")) {
assertEquals(4, wb.getNumberOfSheets());
// Sheet 3 starts with a drawing
@@ -3023,7 +2939,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
assertNotNull(sheet.getDrawingPatriarch());
// Save and check
- Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
+ Workbook wbBack = writeOutAndReadBack(wb);
assertEquals(5, wbBack.getNumberOfSheets());
// Sheets 3 and 5 now
@@ -3042,52 +2958,50 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test53611() throws IOException {
- Workbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("test");
- Row row = sheet.createRow(1);
- Cell cell = row.createCell(1);
- cell.setCellValue("blabla");
-
- //0 1 2 3 4 5 6 7
- //A B C D E F G H
- row = sheet.createRow(4);
- cell = row.createCell(7);
- cell.setCellValue("blabla");
+ try (Workbook wb = new XSSFWorkbook()) {
+ Sheet sheet = wb.createSheet("test");
+ Row row = sheet.createRow(1);
+ Cell cell = row.createCell(1);
+ cell.setCellValue("blabla");
- // we currently only populate the dimension during writing out
- // to avoid having to iterate all rows/cells in each add/remove of a row or cell
- wb.write(new NullOutputStream());
+ //0 1 2 3 4 5 6 7
+ //A B C D E F G H
+ row = sheet.createRow(4);
+ cell = row.createCell(7);
+ cell.setCellValue("blabla");
- assertEquals("B2:H5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef());
+ // we currently only populate the dimension during writing out
+ // to avoid having to iterate all rows/cells in each add/remove of a row or cell
+ wb.write(NULL_OUTPUT_STREAM);
- wb.close();
+ assertEquals("B2:H5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef());
+ }
}
@Test
void test61798() throws IOException {
- Workbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("test");
- Row row = sheet.createRow(1);
- Cell cell = row.createCell(1);
- cell.setCellValue("blabla");
-
- row = sheet.createRow(4);
- // Allowable column range for EXCEL2007 is (0..16383) or ('A'..'XDF')
- cell = row.createCell(16383);
- cell.setCellValue("blabla");
+ try (Workbook wb = new XSSFWorkbook()) {
+ Sheet sheet = wb.createSheet("test");
+ Row row = sheet.createRow(1);
+ Cell cell = row.createCell(1);
+ cell.setCellValue("blabla");
- // we currently only populate the dimension during writing out
- // to avoid having to iterate all rows/cells in each add/remove of a row or cell
- wb.write(new NullOutputStream());
+ row = sheet.createRow(4);
+ // Allowable column range for EXCEL2007 is (0..16383) or ('A'..'XDF')
+ cell = row.createCell(16383);
+ cell.setCellValue("blabla");
- assertEquals("B2:XFD5", ((XSSFSheet)sheet).getCTWorksheet().getDimension().getRef());
+ // we currently only populate the dimension during writing out
+ // to avoid having to iterate all rows/cells in each add/remove of a row or cell
+ wb.write(NULL_OUTPUT_STREAM);
- wb.close();
+ assertEquals("B2:XFD5", ((XSSFSheet) sheet).getCTWorksheet().getDimension().getRef());
+ }
}
@Test
void bug61063() throws Exception {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61063.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("61063.xlsx")) {
FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator();
Sheet s = wb.getSheetAt(0);
@@ -3107,59 +3021,59 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
final String initialFormula = "A1";
final String expectedFormula = "#REF!"; // from ms excel
- XSSFWorkbook wb = new XSSFWorkbook();
- Sheet sheet = wb.createSheet("sheet1");
- sheet.createRow(0).createCell(0).setCellValue(1); // A1 = 1
-
- {
- Cell c3 = sheet.createRow(2).createCell(2);
- c3.setCellFormula(initialFormula); // C3 = =A1
- FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
- CellValue cellValue = evaluator.evaluate(c3);
- assertEquals(1, cellValue.getNumberValue(), 0.0001);
- }
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ Sheet sheet = wb.createSheet("sheet1");
+ sheet.createRow(0).createCell(0).setCellValue(1); // A1 = 1
+
+ {
+ Cell c3 = sheet.createRow(2).createCell(2);
+ c3.setCellFormula(initialFormula); // C3 = =A1
+ FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
+ CellValue cellValue = evaluator.evaluate(c3);
+ assertEquals(1, cellValue.getNumberValue(), 0.0001);
+ }
- {
- FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/
+ {
+ FormulaShifter formulaShifter = FormulaShifter.createForRowCopy(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/
, -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up
- XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
- Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1]
- formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A]
- String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A
- //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla));
- assertEquals(expectedFormula, shiftedFmla,
- "On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF");
- }
+ XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
+ Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1]
+ formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A]
+ String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A
+ //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla));
+ assertEquals(expectedFormula, shiftedFmla,
+ "On copy we expect the formula to be adjusted, in this case it would point to row -1, which is an invalid REF");
+ }
- {
- FormulaShifter formulaShifter = FormulaShifter.createForRowShift(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/
+ {
+ FormulaShifter formulaShifter = FormulaShifter.createForRowShift(0, "sheet1", 2/*firstRowToShift*/, 2/*lastRowToShift*/
, -1/*step*/, SpreadsheetVersion.EXCEL2007); // parameters 2, 2, -1 should mean : move row range [2-2] one level up
- XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
- Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1]
- formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A]
- String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A
- //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla));
- assertEquals(initialFormula, shiftedFmla,
- "On move we expect the formula to stay the same, thus expecting the initial formula A1 here");
- }
+ XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb);
+ Ptg[] ptgs = FormulaParser.parse(initialFormula, fpb, FormulaType.CELL, 0); // [A1]
+ formulaShifter.adjustFormula(ptgs, 0); // adjusted to [A]
+ String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); //A
+ //System.out.println(String.format("initial formula : A1; expected formula value after shifting up : #REF!; actual formula value : %s", shiftedFmla));
+ assertEquals(initialFormula, shiftedFmla,
+ "On move we expect the formula to stay the same, thus expecting the initial formula A1 here");
+ }
- sheet.shiftRows(2, 2, -1);
- {
- Cell c2 = sheet.getRow(1).getCell(2);
- assertNotNull(c2, "cell C2 needs to exist now");
- assertEquals(CellType.FORMULA, c2.getCellType());
- assertEquals(initialFormula, c2.getCellFormula());
- FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
- CellValue cellValue = evaluator.evaluate(c2);
- assertEquals(1, cellValue.getNumberValue(), 0.0001);
- }
+ sheet.shiftRows(2, 2, -1);
+ {
+ Cell c2 = sheet.getRow(1).getCell(2);
+ assertNotNull(c2, "cell C2 needs to exist now");
+ assertEquals(CellType.FORMULA, c2.getCellType());
+ assertEquals(initialFormula, c2.getCellFormula());
+ FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
+ CellValue cellValue = evaluator.evaluate(c2);
+ assertEquals(1, cellValue.getNumberValue(), 0.0001);
+ }
- wb.close();
+ }
}
@Test
void test61652() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61652.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("61652.xlsx")) {
Sheet sheet = wb.getSheet("IRPPCalc");
Row row = sheet.getRow(11);
Cell cell = row.getCell(18);
@@ -3240,52 +3154,41 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
}
}
- @Test
- void test61905xlsx() throws IOException {
- try (Workbook wb = new XSSFWorkbook()) {
- checkActiveSheet(wb, XSSFITestDataProvider.instance);
- }
- }
-
- @Test
- void test61905xls() throws IOException {
- try (Workbook wb = new HSSFWorkbook()) {
- checkActiveSheet(wb, HSSFITestDataProvider.instance);
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void test61905(boolean xssf) throws IOException {
+ ITestDataProvider instance = xssf ? XSSFITestDataProvider.instance : HSSFITestDataProvider.instance;
+ try (Workbook wb = instance.createWorkbook()) {
+ Sheet sheet = wb.createSheet("new sheet");
+ sheet.setActiveCell(new CellAddress("E11"));
+ assertEquals("E11", sheet.getActiveCell().formatAsString());
+
+ try (Workbook wbBack = instance.writeOutAndReadBack(wb)) {
+ sheet = wbBack.getSheetAt(0);
+ assertEquals("E11", sheet.getActiveCell().formatAsString());
+ }
}
}
- private void checkActiveSheet(Workbook wb, ITestDataProvider instance) throws IOException {
- Sheet sheet = wb.createSheet("new sheet");
- sheet.setActiveCell(new CellAddress("E11"));
- assertEquals("E11", sheet.getActiveCell().formatAsString());
-
- Workbook wbBack = instance.writeOutAndReadBack(wb);
- sheet = wbBack.getSheetAt(0);
- assertEquals("E11", sheet.getActiveCell().formatAsString());
- wbBack.close();
- }
-
@Test
void testBug54084Unicode() throws IOException {
// sample XLSX with the same text-contents as the text-file above
- try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("54084 - Greek - beyond BMP.xlsx")) {
+ try (XSSFWorkbook wb = openSampleWorkbook("54084 - Greek - beyond BMP.xlsx")) {
verifyBug54084Unicode(wb);
//XSSFTestDataSamples.writeOut(wb, "bug 54084 for manual review");
// now write the file and read it back in
- XSSFWorkbook wbWritten = XSSFTestDataSamples.writeOutAndReadBack(wb);
- verifyBug54084Unicode(wbWritten);
+ try (XSSFWorkbook wbWritten = writeOutAndReadBack(wb)) {
+ verifyBug54084Unicode(wbWritten);
+ }
// finally also write it out via the streaming interface and verify that we still can read it back in
- SXSSFWorkbook swb = new SXSSFWorkbook(wb);
- Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb);
- verifyBug54084Unicode(wbStreamingWritten);
-
- wbWritten.close();
- swb.close();
- wbStreamingWritten.close();
+ try (SXSSFWorkbook swb = new SXSSFWorkbook(wb);
+ Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb)) {
+ verifyBug54084Unicode(wbStreamingWritten);
+ }
}
}
@@ -3309,29 +3212,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
void bug63371() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
-
CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2);
assertEquals(0, sheet.addMergedRegion(region));
- //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index));
-
- final List<CellRangeAddress> ranges = sheet.getMergedRegions();
- final int numMergedRegions = sheet.getNumMergedRegions();
- final CTWorksheet ctSheet = sheet.getCTWorksheet();
- final CTMergeCells ctMergeCells = ctSheet.getMergeCells();
- final List<CTMergeCell> ctMergeCellList = ctMergeCells.getMergeCellList();
- final long ctMergeCellCount = ctMergeCells.getCount();
- final int ctMergeCellListSize = ctMergeCellList.size();
-
- /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region"));
- System.out.println(String.format("ranges.size=%d", ranges.size()));
- System.out.println(String.format("numMergedRegions=%d", numMergedRegions));
- System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount));
- System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/
- assertEquals(1, ranges.size());
- assertEquals(1, numMergedRegions);
- assertEquals(1, ctMergeCellCount);
- assertEquals(1, ctMergeCellListSize);
+ final CTMergeCells ctMergeCells = sheet.getCTWorksheet().getMergeCells();
+
+ assertEquals(1, sheet.getMergedRegions().size());
+ assertEquals(1, sheet.getNumMergedRegions());
+ assertEquals(1, ctMergeCells.getCount());
+ assertEquals(1, ctMergeCells.getMergeCellList().size());
}
}
@@ -3343,7 +3232,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
CellRangeAddress region = new CellRangeAddress(1, 1, 1, 2);
assertEquals(0, sheet.addMergedRegion(region));
- //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index));
List<CellRangeAddress> ranges = sheet.getMergedRegions();
int numMergedRegions = sheet.getNumMergedRegions();
@@ -3353,12 +3241,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
long ctMergeCellCount = ctMergeCells.getCount();
int ctMergeCellListSize = ctMergeCellList.size();
- /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region"));
- System.out.println(String.format("ranges.size=%d", ranges.size()));
- System.out.println(String.format("numMergedRegions=%d", numMergedRegions));
- System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount));
- System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize)); */
-
assertEquals(1, ranges.size());
assertEquals(1, numMergedRegions);
assertEquals(1, ctMergeCellCount);
@@ -3366,7 +3248,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
CellRangeAddress region2 = new CellRangeAddress(1, 2, 4, 6);
assertEquals(1, sheet.addMergedRegion(region2));
- //System.out.println(String.format("%s: index=%d", "testAddMergedRegion", index));
ranges = sheet.getMergedRegions();
numMergedRegions = sheet.getNumMergedRegions();
@@ -3376,12 +3257,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
ctMergeCellCount = ctMergeCells.getCount();
ctMergeCellListSize = ctMergeCellList.size();
- /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding second region"));
- System.out.println(String.format("ranges.size=%d", ranges.size()));
- System.out.println(String.format("numMergedRegions=%d", numMergedRegions));
- System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount));
- System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/
-
assertEquals(2, ranges.size());
assertEquals(2, numMergedRegions);
assertEquals(2, ctMergeCellCount);
@@ -3420,7 +3295,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test58896WithFile() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58896.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("58896.xlsx")) {
Sheet sheet = wb.getSheetAt(0);
Instant start = now();
@@ -3455,7 +3330,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
assertNull(((XSSFCell) cell).getCTCell().getV(),
"Element 'v' should not be set for formulas unless the value was calculated");
- try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (Workbook wbBack = writeOutAndReadBack(wb)) {
Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(0);
assertNull(((XSSFCell) cellBack).getCTCell().getV(),
"Element 'v' should not be set for formulas unless the value was calculated");
@@ -3484,7 +3359,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
row.createCell(1).setCellValue(5);
row.createCell(2).setCellFormula("A1+B1");
- try (Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ try (Workbook wbBack = writeOutAndReadBack(wb)) {
Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(2);
assertNull(((XSSFCell) cellBack).getCTCell().getV(),
@@ -3533,7 +3408,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void testBug64508() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64508.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("64508.xlsx")) {
int activeSheet = wb.getActiveSheetIndex();
Sheet sheet1 = wb.getSheetAt(activeSheet);
Row row = sheet1.getRow(1);
@@ -3547,7 +3422,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void testBug64667() throws IOException {
//test that an NPE isn't thrown on opening
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64667.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("64667.xlsx")) {
int activeSheet = wb.getActiveSheetIndex();
assertEquals(0, activeSheet);
assertNotNull(wb.getSheetAt(activeSheet));
@@ -3602,32 +3477,33 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
}
@Test
- void test64986() {
- XSSFWorkbook w = new XSSFWorkbook();
- XSSFSheet s = w.createSheet();
- XSSFRow r = s.createRow(0);
- XSSFCell c = r.createCell(0);
- c.setCellFormula("MATCH(\"VAL\",B1:B11,)");
+ void test64986() throws IOException {
+ try (XSSFWorkbook w = new XSSFWorkbook()) {
+ XSSFSheet s = w.createSheet();
+ XSSFRow r = s.createRow(0);
+ XSSFCell c = r.createCell(0);
+ c.setCellFormula("MATCH(\"VAL\",B1:B11,)");
- FormulaEvaluator evaluator = w.getCreationHelper().createFormulaEvaluator();
- CellValue value = evaluator.evaluate(c);
- assertEquals(CellType.ERROR, value.getCellType());
- assertEquals(ErrorEval.NA.getErrorCode(), value.getErrorValue());
+ FormulaEvaluator evaluator = w.getCreationHelper().createFormulaEvaluator();
+ CellValue value = evaluator.evaluate(c);
+ assertEquals(CellType.ERROR, value.getCellType());
+ assertEquals(ErrorEval.NA.getErrorCode(), value.getErrorValue());
- // put a value in place so the match should find something
- Cell val = r.createCell(1);
- val.setCellValue("VAL");
+ // put a value in place so the match should find something
+ Cell val = r.createCell(1);
+ val.setCellValue("VAL");
- // clear and check that now we find a match
- evaluator.clearAllCachedResultValues();
- value = evaluator.evaluate(c);
- assertEquals(CellType.NUMERIC, value.getCellType());
- assertEquals(1, value.getNumberValue(), 0.01);
+ // clear and check that now we find a match
+ evaluator.clearAllCachedResultValues();
+ value = evaluator.evaluate(c);
+ assertEquals(CellType.NUMERIC, value.getCellType());
+ assertEquals(1, value.getNumberValue(), 0.01);
+ }
}
@Test
void test64750() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64750.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("64750.xlsx")) {
Sheet sheet = wb.getSheet("Sheet1");
assertEquals(1, sheet.getDataValidations().size());
}
@@ -3635,7 +3511,7 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
@Test
void test64450() throws IOException {
- try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("64450.xlsx")) {
+ try (Workbook wb = openSampleWorkbook("64450.xlsx")) {
assertNotNull(wb);
}
}
@@ -3664,10 +3540,6 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues {
cellLeft.setCellValue("L");
cellLeft.setCellStyle(styleLeft);
- /*try (OutputStream out = new FileOutputStream("/tmp/64494.xlsx")) {
- wb.write(out);
- }*/
-
assertEquals(HorizontalAlignment.RIGHT, cellRight.getCellStyle().getAlignment());
assertEquals(HorizontalAlignment.LEFT, cellLeft.getCellStyle().getAlignment());
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java
index b544f916ac..064d2d83c1 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFPicture.java
@@ -20,6 +20,7 @@ package org.apache.poi.xssf.usermodel;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import java.io.IOException;
import java.util.List;
@@ -41,6 +42,7 @@ public final class TestXSSFPicture extends BaseTestPicture {
super(XSSFITestDataProvider.instance);
}
+ @Override
protected Picture getPictureShape(Drawing<?> pat, int picIdx) {
return (Picture)((XSSFDrawing)pat).getShapes().get(picIdx);
}
@@ -73,7 +75,7 @@ public final class TestXSSFPicture extends BaseTestPicture {
CTTwoCellAnchor ctShapeHolder = drawing.getCTDrawing().getTwoCellAnchorArray(0);
// STEditAs.ABSOLUTE corresponds to ClientAnchor.DONT_MOVE_AND_RESIZE
- assertEquals(STEditAs.ABSOLUTE, ctShapeHolder.getEditAs());
+ assertSame(STEditAs.ABSOLUTE, ctShapeHolder.getEditAs());
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
index 3bd3012ef5..4ee8a83d3c 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java
@@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
@@ -45,6 +44,7 @@ import com.microsoft.schemas.vml.CTShapetype;
import com.microsoft.schemas.vml.STExt;
import com.microsoft.schemas.vml.STStrokeJoinStyle;
import com.microsoft.schemas.vml.impl.CTShapetypeImpl;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
@@ -62,8 +62,8 @@ class TestXSSFVMLDrawing {
assertEquals(2, items.size());
assertTrue(items.get(0) instanceof CTShapeLayout);
CTShapeLayout layout = (CTShapeLayout)items.get(0);
- assertEquals(STExt.EDIT, layout.getExt());
- assertEquals(STExt.EDIT, layout.getIdmap().getExt());
+ assertSame(STExt.EDIT, layout.getExt());
+ assertSame(STExt.EDIT, layout.getIdmap().getExt());
assertEquals("1", layout.getIdmap().getData());
assertTrue(items.get(1) instanceof CTShapetype);
@@ -72,8 +72,8 @@ class TestXSSFVMLDrawing {
assertEquals(202.0f, type.getSpt(), 0);
assertEquals("m,l,21600r21600,l21600,xe", type.getPath2());
assertEquals("_x0000_t202", type.getId());
- assertEquals(STTrueFalse.T, type.getPathArray(0).getGradientshapeok());
- assertEquals(STConnectType.RECT, type.getPathArray(0).getConnecttype());
+ assertSame(STTrueFalse.T, type.getPathArray(0).getGradientshapeok());
+ assertSame(STConnectType.RECT, type.getPathArray(0).getConnecttype());
CTShape shape = vml.newCommentShape();
items = vml.getItems();
@@ -82,16 +82,16 @@ class TestXSSFVMLDrawing {
assertEquals("#_x0000_t202", shape.getType());
assertEquals("position:absolute; visibility:hidden", shape.getStyle());
assertEquals("#ffffe1", shape.getFillcolor());
- assertEquals(STInsetMode.AUTO, shape.getInsetmode());
+ assertSame(STInsetMode.AUTO, shape.getInsetmode());
assertEquals("#ffffe1", shape.getFillArray(0).getColor());
CTShadow shadow = shape.getShadowArray(0);
- assertEquals(STTrueFalse.T, shadow.getOn());
+ assertSame(STTrueFalse.T, shadow.getOn());
assertEquals("black", shadow.getColor());
- assertEquals(STTrueFalse.T, shadow.getObscured());
- assertEquals(STConnectType.NONE, shape.getPathArray(0).getConnecttype());
+ assertSame(STTrueFalse.T, shadow.getObscured());
+ assertSame(STConnectType.NONE, shape.getPathArray(0).getConnecttype());
assertEquals("mso-direction-alt:auto", shape.getTextboxArray(0).getStyle());
CTClientData cldata = shape.getClientDataArray(0);
- assertEquals(STObjectType.NOTE, cldata.getObjectType());
+ assertSame(STObjectType.NOTE, cldata.getObjectType());
assertEquals(1, cldata.sizeOfMoveWithCellsArray());
assertEquals(1, cldata.sizeOfSizeWithCellsArray());
assertEquals("1, 15, 0, 2, 3, 15, 3, 16", cldata.getAnchorArray(0));
@@ -103,11 +103,11 @@ class TestXSSFVMLDrawing {
assertEquals("[True]", cldata.getVisibleList().toString());
//serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
vml.write(out);
XSSFVMLDrawing vml2 = new XSSFVMLDrawing();
- vml2.read(new ByteArrayInputStream(out.toByteArray()));
+ vml2.read(out.toInputStream());
List<XmlObject> items2 = vml2.getItems();
assertEquals(3, items2.size());
assertTrue(items2.get(0) instanceof CTShapeLayout);
@@ -208,6 +208,6 @@ class TestXSSFVMLDrawing {
XmlObject xst = objs.get(0);
assertTrue(xst instanceof CTShapetypeImpl);
CTShapetype st = (CTShapetype)xst;
- assertEquals(STStrokeJoinStyle.MITER, st.getStrokeArray(0).getJoinstyle());
+ assertSame(STStrokeJoinStyle.MITER, st.getStrokeArray(0).getJoinstyle());
}
} \ No newline at end of file
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java
index 78563bc32e..ef17baa8e7 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java
@@ -17,6 +17,11 @@
package org.apache.poi.xssf.usermodel;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
+import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleFileStream;
+import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook;
+import static org.apache.poi.xssf.XSSFTestDataSamples.writeOut;
+import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -27,12 +32,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Iterator;
@@ -72,7 +75,6 @@ import org.apache.poi.util.TempFile;
import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
import org.apache.poi.xddf.usermodel.chart.XDDFChartData;
import org.apache.poi.xssf.XSSFITestDataProvider;
-import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.model.StylesTable;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr;
@@ -92,94 +94,87 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
*/
@Test
void saveLoadNew() throws IOException, InvalidFormatException {
- XSSFWorkbook wb1 = new XSSFWorkbook();
+ File file;
+ try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
- //check that the default date system is set to 1900
- CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr();
- assertNotNull(pr);
- assertTrue(pr.isSetDate1904());
- assertFalse(pr.getDate1904(), "XSSF must use the 1900 date system");
+ //check that the default date system is set to 1900
+ CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr();
+ assertNotNull(pr);
+ assertTrue(pr.isSetDate1904());
+ assertFalse(pr.getDate1904(), "XSSF must use the 1900 date system");
- Sheet sheet1 = wb1.createSheet("sheet1");
- Sheet sheet2 = wb1.createSheet("sheet2");
- wb1.createSheet("sheet3");
+ Sheet sheet1 = wb1.createSheet("sheet1");
+ Sheet sheet2 = wb1.createSheet("sheet2");
+ wb1.createSheet("sheet3");
- RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world");
+ RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world");
- sheet1.createRow(0).createCell((short)0).setCellValue(1.2);
- sheet1.createRow(1).createCell((short)0).setCellValue(rts);
- sheet2.createRow(0);
+ sheet1.createRow(0).createCell((short) 0).setCellValue(1.2);
+ sheet1.createRow(1).createCell((short) 0).setCellValue(rts);
+ sheet2.createRow(0);
- assertEquals(0, wb1.getSheetAt(0).getFirstRowNum());
- assertEquals(1, wb1.getSheetAt(0).getLastRowNum());
- assertEquals(0, wb1.getSheetAt(1).getFirstRowNum());
- assertEquals(0, wb1.getSheetAt(1).getLastRowNum());
- assertEquals(-1, wb1.getSheetAt(2).getFirstRowNum());
- assertEquals(-1, wb1.getSheetAt(2).getLastRowNum());
+ assertEquals(0, wb1.getSheetAt(0).getFirstRowNum());
+ assertEquals(1, wb1.getSheetAt(0).getLastRowNum());
+ assertEquals(0, wb1.getSheetAt(1).getFirstRowNum());
+ assertEquals(0, wb1.getSheetAt(1).getLastRowNum());
+ assertEquals(-1, wb1.getSheetAt(2).getFirstRowNum());
+ assertEquals(-1, wb1.getSheetAt(2).getLastRowNum());
- File file = TempFile.createTempFile("poi-", ".xlsx");
- OutputStream out = new FileOutputStream(file);
- wb1.write(out);
- out.close();
+ file = writeOut(wb1, "poi-.xlsx");
+ }
// Check the package contains what we'd expect it to
- OPCPackage pkg = OPCPackage.open(file.toString());
- PackagePart wbRelPart =
- pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels"));
- assertNotNull(wbRelPart);
- assertTrue(wbRelPart.isRelationshipPart());
- assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType());
-
- PackagePart wbPart =
- pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
- // Links to the three sheets, shared strings and styles
- assertTrue(wbPart.hasRelationships());
- assertEquals(5, wbPart.getRelationships().size());
- wb1.close();
-
- // Load back the XSSFWorkbook
- @SuppressWarnings("resource")
- XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
- assertEquals(3, wb2.getNumberOfSheets());
- assertNotNull(wb2.getSheetAt(0));
- assertNotNull(wb2.getSheetAt(1));
- assertNotNull(wb2.getSheetAt(2));
-
- assertNotNull(wb2.getSharedStringSource());
- assertNotNull(wb2.getStylesSource());
-
- assertEquals(0, wb2.getSheetAt(0).getFirstRowNum());
- assertEquals(1, wb2.getSheetAt(0).getLastRowNum());
- assertEquals(0, wb2.getSheetAt(1).getFirstRowNum());
- assertEquals(0, wb2.getSheetAt(1).getLastRowNum());
- assertEquals(-1, wb2.getSheetAt(2).getFirstRowNum());
- assertEquals(-1, wb2.getSheetAt(2).getLastRowNum());
-
- sheet1 = wb2.getSheetAt(0);
- assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001);
- assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString());
-
- pkg.close();
+ try (OPCPackage pkg = OPCPackage.open(file.toString())) {
+ PackagePart wbRelPart =
+ pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels"));
+ assertNotNull(wbRelPart);
+ assertTrue(wbRelPart.isRelationshipPart());
+ assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType());
+
+ PackagePart wbPart =
+ pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
+ // Links to the three sheets, shared strings and styles
+ assertTrue(wbPart.hasRelationships());
+ assertEquals(5, wbPart.getRelationships().size());
+
+ // Load back the XSSFWorkbook
+ try (XSSFWorkbook wb2 = new XSSFWorkbook(pkg)) {
+ assertEquals(3, wb2.getNumberOfSheets());
+ assertNotNull(wb2.getSheetAt(0));
+ assertNotNull(wb2.getSheetAt(1));
+ assertNotNull(wb2.getSheetAt(2));
+
+ assertNotNull(wb2.getSharedStringSource());
+ assertNotNull(wb2.getStylesSource());
+
+ assertEquals(0, wb2.getSheetAt(0).getFirstRowNum());
+ assertEquals(1, wb2.getSheetAt(0).getLastRowNum());
+ assertEquals(0, wb2.getSheetAt(1).getFirstRowNum());
+ assertEquals(0, wb2.getSheetAt(1).getLastRowNum());
+ assertEquals(-1, wb2.getSheetAt(2).getFirstRowNum());
+ assertEquals(-1, wb2.getSheetAt(2).getLastRowNum());
+
+ Sheet sheet1 = wb2.getSheetAt(0);
+ assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001);
+ assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString());
+ }
+ }
}
@Test
void existing() throws Exception {
+ try (XSSFWorkbook workbook = openSampleWorkbook("Formatting.xlsx");
+ OPCPackage pkg = OPCPackage.open(openSampleFileStream("Formatting.xlsx"))) {
+ assertNotNull(workbook.getSharedStringSource());
+ assertNotNull(workbook.getStylesSource());
- XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
- assertNotNull(workbook.getSharedStringSource());
- assertNotNull(workbook.getStylesSource());
-
- // And check a few low level bits too
- OPCPackage pkg = OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx"));
- PackagePart wbPart =
- pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
-
- // Links to the three sheets, shared, styles and themes
- assertTrue(wbPart.hasRelationships());
- assertEquals(6, wbPart.getRelationships().size());
+ // And check a few low level bits too
+ PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
- pkg.close();
- workbook.close();
+ // Links to the three sheets, shared, styles and themes
+ assertTrue(wbPart.hasRelationships());
+ assertEquals(6, wbPart.getRelationships().size());
+ }
}
@Test
@@ -230,7 +225,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
void loadSave() throws IOException {
- XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
+ XSSFWorkbook workbook = openSampleWorkbook("Formatting.xlsx");
assertEquals(3, workbook.getNumberOfSheets());
assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString());
assertNotNull(workbook.getSharedStringSource());
@@ -238,7 +233,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
// Write out, and check
// Load up again, check all still there
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook);
+ XSSFWorkbook wb2 = writeOutAndReadBack(workbook);
assertEquals(3, wb2.getNumberOfSheets());
assertNotNull(wb2.getSheetAt(0));
assertNotNull(wb2.getSheetAt(1));
@@ -257,43 +252,41 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
void styles() throws IOException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx");
-
- StylesTable ss = wb1.getStylesSource();
- assertNotNull(ss);
- StylesTable st = ss;
-
- // Has 8 number formats
- assertEquals(8, st.getNumDataFormats());
- // Has 2 fonts
- assertEquals(2, st.getFonts().size());
- // Has 2 fills
- assertEquals(2, st.getFills().size());
- // Has 1 border
- assertEquals(1, st.getBorders().size());
-
- // Add two more styles
- assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
+ try (XSSFWorkbook wb1 = openSampleWorkbook("Formatting.xlsx")) {
+ StylesTable ss = wb1.getStylesSource();
+ assertNotNull(ss);
+ StylesTable st = ss;
+
+ // Has 8 number formats
+ assertEquals(8, st.getNumDataFormats());
+ // Has 2 fonts
+ assertEquals(2, st.getFonts().size());
+ // Has 2 fills
+ assertEquals(2, st.getFills().size());
+ // Has 1 border
+ assertEquals(1, st.getBorders().size());
+
+ // Add two more styles
+ assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
st.putNumberFormat("testFORMAT"));
- assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
+ assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8,
st.putNumberFormat("testFORMAT"));
- assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9,
+ assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9,
st.putNumberFormat("testFORMAT2"));
- assertEquals(10, st.getNumDataFormats());
-
+ assertEquals(10, st.getNumDataFormats());
- // Save, load back in again, and check
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- ss = wb2.getStylesSource();
- assertNotNull(ss);
+ // Save, load back in again, and check
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ ss = wb2.getStylesSource();
+ assertNotNull(ss);
- assertEquals(10, st.getNumDataFormats());
- assertEquals(2, st.getFonts().size());
- assertEquals(2, st.getFills().size());
- assertEquals(1, st.getBorders().size());
- wb2.close();
+ assertEquals(10, st.getNumDataFormats());
+ assertEquals(2, st.getFonts().size());
+ assertEquals(2, st.getFills().size());
+ assertEquals(1, st.getBorders().size());
+ }
+ }
}
@Test
@@ -305,7 +298,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertEquals(2, sheetId);
//test file with gaps in the sheetId sequence
- try (XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm")) {
+ try (XSSFWorkbook wbBack = openSampleWorkbook("47089.xlsm")) {
int lastSheetId = (int) wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId();
sheetId = (int) wbBack.createSheet().sheet.getSheetId();
assertEquals(lastSheetId + 1, sheetId);
@@ -328,15 +321,15 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertNotNull(opcProps);
opcProps.setTitleProperty("Testing Bugzilla #47460");
- assertEquals("Apache POI", opcProps.getCreatorProperty().get());
+ assertEquals("Apache POI", opcProps.getCreatorProperty().orElse(""));
opcProps.setCreatorProperty("poi-dev@poi.apache.org");
- XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook);
- assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication());
- opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties();
- assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().get());
- assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().get());
- wbBack.close();
+ try (XSSFWorkbook wbBack = writeOutAndReadBack(workbook)) {
+ assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication());
+ opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties();
+ assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().orElse(""));
+ assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().orElse(""));
+ }
}
}
@@ -346,36 +339,36 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
*/
@Test
void bug47668() throws Exception {
- XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("47668.xlsx");
- List<XSSFPictureData> allPictures = workbook.getAllPictures();
- assertEquals(1, allPictures.size());
+ try (XSSFWorkbook workbook = openSampleWorkbook("47668.xlsx")) {
+ List<XSSFPictureData> allPictures = workbook.getAllPictures();
+ assertEquals(1, allPictures.size());
- PackagePartName imagePartName = PackagingURIHelper
+ PackagePartName imagePartName = PackagingURIHelper
.createPartName("/xl/media/image1.jpeg");
- PackagePart imagePart = workbook.getPackage().getPart(imagePartName);
- assertNotNull(imagePart);
+ PackagePart imagePart = workbook.getPackage().getPart(imagePartName);
+ assertNotNull(imagePart);
- for (XSSFPictureData pictureData : allPictures) {
- PackagePart picturePart = pictureData.getPackagePart();
- assertSame(imagePart, picturePart);
- }
+ for (XSSFPictureData pictureData : allPictures) {
+ PackagePart picturePart = pictureData.getPackagePart();
+ assertSame(imagePart, picturePart);
+ }
- XSSFSheet sheet0 = workbook.getSheetAt(0);
- XSSFDrawing drawing0 = sheet0.createDrawingPatriarch();
- XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0);
- byte[] data0 = pictureData0.getData();
- CRC32 crc0 = new CRC32();
- crc0.update(data0);
-
- XSSFSheet sheet1 = workbook.getSheetAt(1);
- XSSFDrawing drawing1 = sheet1.createDrawingPatriarch();
- XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0);
- byte[] data1 = pictureData1.getData();
- CRC32 crc1 = new CRC32();
- crc1.update(data1);
-
- assertEquals(crc0.getValue(), crc1.getValue());
- workbook.close();
+ XSSFSheet sheet0 = workbook.getSheetAt(0);
+ XSSFDrawing drawing0 = sheet0.createDrawingPatriarch();
+ XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0);
+ byte[] data0 = pictureData0.getData();
+ CRC32 crc0 = new CRC32();
+ crc0.update(data0);
+
+ XSSFSheet sheet1 = workbook.getSheetAt(1);
+ XSSFDrawing drawing1 = sheet1.createDrawingPatriarch();
+ XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0);
+ byte[] data1 = pictureData1.getData();
+ CRC32 crc1 = new CRC32();
+ crc1.update(data1);
+
+ assertEquals(crc0.getValue(), crc1.getValue());
+ }
}
/**
@@ -384,27 +377,26 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@SuppressWarnings("deprecation")
@Test
void bug47737() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx");
- assertEquals(2, wb.getNumberOfNames());
- assertNotNull(wb.getCalculationChain());
-
- XSSFName nm0 = wb.getNameAt(0);
- assertTrue(nm0.getCTName().isSetLocalSheetId());
- assertEquals(0, nm0.getCTName().getLocalSheetId());
-
- XSSFName nm1 = wb.getNameAt(1);
- assertTrue(nm1.getCTName().isSetLocalSheetId());
- assertEquals(1, nm1.getCTName().getLocalSheetId());
-
- wb.removeSheetAt(0);
- assertEquals(1, wb.getNumberOfNames());
- XSSFName nm2 = wb.getNameAt(0);
- assertTrue(nm2.getCTName().isSetLocalSheetId());
- assertEquals(0, nm2.getCTName().getLocalSheetId());
- //calculation chain is removed as well
- assertNull(wb.getCalculationChain());
- wb.close();
-
+ try (XSSFWorkbook wb = openSampleWorkbook("47737.xlsx")) {
+ assertEquals(2, wb.getNumberOfNames());
+ assertNotNull(wb.getCalculationChain());
+
+ XSSFName nm0 = wb.getNameAt(0);
+ assertTrue(nm0.getCTName().isSetLocalSheetId());
+ assertEquals(0, nm0.getCTName().getLocalSheetId());
+
+ XSSFName nm1 = wb.getNameAt(1);
+ assertTrue(nm1.getCTName().isSetLocalSheetId());
+ assertEquals(1, nm1.getCTName().getLocalSheetId());
+
+ wb.removeSheetAt(0);
+ assertEquals(1, wb.getNumberOfNames());
+ XSSFName nm2 = wb.getNameAt(0);
+ assertTrue(nm2.getCTName().isSetLocalSheetId());
+ assertEquals(0, nm2.getCTName().getLocalSheetId());
+ //calculation chain is removed as well
+ assertNull(wb.getCalculationChain());
+ }
}
/**
@@ -412,28 +404,28 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
*/
@Test
void bug47813() throws IOException {
- XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx");
- assertEquals(3, wb1.getNumberOfSheets());
- assertNotNull(wb1.getCalculationChain());
-
- assertEquals("Numbers", wb1.getSheetName(0));
- //the second sheet is of type 'chartsheet'
- assertEquals("Chart", wb1.getSheetName(1));
- assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet);
- assertEquals("SomeJunk", wb1.getSheetName(2));
-
- wb1.removeSheetAt(2);
- assertEquals(2, wb1.getNumberOfSheets());
- assertNull(wb1.getCalculationChain());
-
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- assertEquals(2, wb2.getNumberOfSheets());
- assertNull(wb2.getCalculationChain());
-
- assertEquals("Numbers", wb2.getSheetName(0));
- assertEquals("Chart", wb2.getSheetName(1));
- wb2.close();
- wb1.close();
+ try (XSSFWorkbook wb1 = openSampleWorkbook("47813.xlsx")) {
+ assertEquals(3, wb1.getNumberOfSheets());
+ assertNotNull(wb1.getCalculationChain());
+
+ assertEquals("Numbers", wb1.getSheetName(0));
+ //the second sheet is of type 'chartsheet'
+ assertEquals("Chart", wb1.getSheetName(1));
+ assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet);
+ assertEquals("SomeJunk", wb1.getSheetName(2));
+
+ wb1.removeSheetAt(2);
+ assertEquals(2, wb1.getNumberOfSheets());
+ assertNull(wb1.getCalculationChain());
+
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ assertEquals(2, wb2.getNumberOfSheets());
+ assertNull(wb2.getCalculationChain());
+
+ assertEquals("Numbers", wb2.getSheetName(0));
+ assertEquals("Chart", wb2.getSheetName(1));
+ }
+ }
}
/**
@@ -461,14 +453,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertNull(wb1.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist");
// Save and reload
- try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1)) {
+ try (XSSFWorkbook nwb = writeOutAndReadBack(wb1)) {
assertEquals(2, nwb.getNumCellStyles());
nwb.getCellStyleAt((short) 0);
nwb.getCellStyleAt((short) 1);
assertNull(nwb.getCellStyleAt((short) 2), "Shouldn't be able to get style at 2 that doesn't exist");
// Now with an existing file
- try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) {
+ try (XSSFWorkbook wb2 = openSampleWorkbook("sample.xlsx")) {
assertEquals(3, wb2.getNumCellStyles());
wb2.getCellStyleAt((short) 0);
wb2.getCellStyleAt((short) 1);
@@ -501,7 +493,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
// calcMode="manual" is unset when forceFormulaRecalculation=true
calcPr.setCalcMode(STCalcMode.MANUAL);
wb.setForceFormulaRecalculation(true);
- assertEquals(STCalcMode.AUTO, calcPr.getCalcMode());
+ assertSame(STCalcMode.AUTO, calcPr.getCalcMode());
assertTrue(wb.getForceFormulaRecalculation());
wb.setForceFormulaRecalculation(false);
@@ -514,26 +506,22 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
void columnWidthPOI52233() throws Exception {
- XSSFWorkbook workbook = new XSSFWorkbook();
- XSSFSheet sheet = workbook.createSheet();
- XSSFRow row = sheet.createRow(0);
- XSSFCell cell = row.createCell(0);
- cell.setCellValue("hello world");
-
- sheet = workbook.createSheet();
- sheet.setColumnWidth(4, 5000);
- sheet.setColumnWidth(5, 5000);
+ try (XSSFWorkbook workbook = new XSSFWorkbook()) {
+ XSSFSheet sheet = workbook.createSheet();
+ XSSFRow row = sheet.createRow(0);
+ XSSFCell cell = row.createCell(0);
+ cell.setCellValue("hello world");
- sheet.groupColumn((short) 4, (short) 5);
+ sheet = workbook.createSheet();
+ sheet.setColumnWidth(4, 5000);
+ sheet.setColumnWidth(5, 5000);
- accessWorkbook(workbook);
+ sheet.groupColumn((short) 4, (short) 5);
- try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
- workbook.write(stream);
+ accessWorkbook(workbook);
+ workbook.write(NULL_OUTPUT_STREAM);
+ accessWorkbook(workbook);
}
-
- accessWorkbook(workbook);
- workbook.close();
}
private void accessWorkbook(XSSFWorkbook workbook) {
@@ -546,136 +534,128 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
void bug48495() throws IOException {
- Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx");
+ try (Workbook wb = openSampleWorkbook("48495.xlsx")) {
+ assertSheetOrder(wb, "Sheet1");
+
+ Sheet sheet = wb.getSheetAt(0);
+ sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false);
+ Row newRow = sheet.getRow(2);
+ if (newRow == null) {
+ newRow = sheet.createRow(2);
+ }
+ newRow.createCell(0).setCellValue(" Another Header");
+ wb.cloneSheet(0);
- assertSheetOrder(wb, "Sheet1");
+ assertSheetOrder(wb, "Sheet1", "Sheet1 (2)");
- Sheet sheet = wb.getSheetAt(0);
- sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false);
- Row newRow = sheet.getRow(2);
- if (newRow == null) {
- newRow = sheet.createRow(2);
+ try (Workbook read = writeOutAndReadBack(wb)) {
+ assertNotNull(read);
+ assertSheetOrder(read, "Sheet1", "Sheet1 (2)");
+ }
}
- newRow.createCell(0).setCellValue(" Another Header");
- wb.cloneSheet(0);
-
- assertSheetOrder(wb, "Sheet1", "Sheet1 (2)");
-
- // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx");
-// try {
-// wb.write(fileOut);
-// } finally {
-// fileOut.close();
-// }
-
- Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
- assertNotNull(read);
- assertSheetOrder(read, "Sheet1", "Sheet1 (2)");
- read.close();
- wb.close();
}
@Test
void bug47090a() throws IOException {
- Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
- assertSheetOrder(workbook, "Sheet1", "Sheet2");
- workbook.removeSheetAt(0);
- assertSheetOrder(workbook, "Sheet2");
- workbook.createSheet();
- assertSheetOrder(workbook, "Sheet2", "Sheet1");
- Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
- assertSheetOrder(read, "Sheet2", "Sheet1");
- read.close();
- workbook.close();
+ try (Workbook workbook = openSampleWorkbook("47090.xlsx")) {
+ assertSheetOrder(workbook, "Sheet1", "Sheet2");
+ workbook.removeSheetAt(0);
+ assertSheetOrder(workbook, "Sheet2");
+ workbook.createSheet();
+ assertSheetOrder(workbook, "Sheet2", "Sheet1");
+ try (Workbook read = writeOutAndReadBack(workbook)) {
+ assertSheetOrder(read, "Sheet2", "Sheet1");
+ }
+ }
}
@Test
void bug47090b() throws IOException {
- Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
- assertSheetOrder(workbook, "Sheet1", "Sheet2");
- workbook.removeSheetAt(1);
- assertSheetOrder(workbook, "Sheet1");
- workbook.createSheet();
- assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point!
- Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
- assertSheetOrder(read, "Sheet1", "Sheet0");
- read.close();
- workbook.close();
+ try (Workbook workbook = openSampleWorkbook("47090.xlsx")) {
+ assertSheetOrder(workbook, "Sheet1", "Sheet2");
+ workbook.removeSheetAt(1);
+ assertSheetOrder(workbook, "Sheet1");
+ workbook.createSheet();
+ assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point!
+ try (Workbook read = writeOutAndReadBack(workbook)) {
+ assertSheetOrder(read, "Sheet1", "Sheet0");
+ }
+ }
}
@Test
void bug47090c() throws IOException {
- Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
- assertSheetOrder(workbook, "Sheet1", "Sheet2");
- workbook.removeSheetAt(0);
- assertSheetOrder(workbook, "Sheet2");
- workbook.cloneSheet(0);
- assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)");
- Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
- assertSheetOrder(read, "Sheet2", "Sheet2 (2)");
- read.close();
- workbook.close();
+ try (Workbook workbook = openSampleWorkbook("47090.xlsx")) {
+ assertSheetOrder(workbook, "Sheet1", "Sheet2");
+ workbook.removeSheetAt(0);
+ assertSheetOrder(workbook, "Sheet2");
+ workbook.cloneSheet(0);
+ assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)");
+ try (Workbook read = writeOutAndReadBack(workbook)) {
+ assertSheetOrder(read, "Sheet2", "Sheet2 (2)");
+ }
+ }
}
@Test
void bug47090d() throws IOException {
- Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx");
- assertSheetOrder(workbook, "Sheet1", "Sheet2");
- workbook.createSheet();
- assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0");
- workbook.removeSheetAt(0);
- assertSheetOrder(workbook, "Sheet2", "Sheet0");
- workbook.createSheet();
- assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1");
- Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook);
- assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1");
- read.close();
- workbook.close();
+ try (Workbook workbook = openSampleWorkbook("47090.xlsx")) {
+ assertSheetOrder(workbook, "Sheet1", "Sheet2");
+ workbook.createSheet();
+ assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0");
+ workbook.removeSheetAt(0);
+ assertSheetOrder(workbook, "Sheet2", "Sheet0");
+ workbook.createSheet();
+ assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1");
+ try (Workbook read = writeOutAndReadBack(workbook)) {
+ assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1");
+ }
+ }
}
@Test
void bug51158() throws IOException {
// create a workbook
- final XSSFWorkbook wb1 = new XSSFWorkbook();
- XSSFSheet sheet = wb1.createSheet("Test Sheet");
- XSSFRow row = sheet.createRow(2);
- XSSFCell cell = row.createCell(3);
- cell.setCellValue("test1");
+ try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
+ XSSFSheet sheet = wb1.createSheet("Test Sheet");
+ XSSFRow row = sheet.createRow(2);
+ XSSFCell cell = row.createCell(3);
+ cell.setCellValue("test1");
- //XSSFCreationHelper helper = workbook.getCreationHelper();
- //cell.setHyperlink(helper.createHyperlink(0));
+ //XSSFCreationHelper helper = workbook.getCreationHelper();
+ //cell.setHyperlink(helper.createHyperlink(0));
- XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor());
- assertNotNull(comment);
- comment.setString("some comment");
+ XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor());
+ assertNotNull(comment);
+ comment.setString("some comment");
// CellStyle cs = workbook.createCellStyle();
// cs.setShrinkToFit(false);
// row.createCell(0).setCellStyle(cs);
- // write the first excel file
- XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
- assertNotNull(wb2);
- sheet = wb2.getSheetAt(0);
- row = sheet.getRow(2);
- assertEquals("test1", row.getCell(3).getStringCellValue());
- assertNull(row.getCell(4));
-
- // add a new cell to the sheet
- cell = row.createCell(4);
- cell.setCellValue("test2");
-
- // write the second excel file
- XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2);
- assertNotNull(wb3);
- sheet = wb3.getSheetAt(0);
- row = sheet.getRow(2);
-
- assertEquals("test1", row.getCell(3).getStringCellValue());
- assertEquals("test2", row.getCell(4).getStringCellValue());
- wb3.close();
- wb2.close();
- wb1.close();
+ // write the first excel file
+ try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) {
+ assertNotNull(wb2);
+ sheet = wb2.getSheetAt(0);
+ row = sheet.getRow(2);
+ assertEquals("test1", row.getCell(3).getStringCellValue());
+ assertNull(row.getCell(4));
+
+ // add a new cell to the sheet
+ cell = row.createCell(4);
+ cell.setCellValue("test2");
+
+ // write the second excel file
+ try (XSSFWorkbook wb3 = writeOutAndReadBack(wb2)) {
+ assertNotNull(wb3);
+ sheet = wb3.getSheetAt(0);
+ row = sheet.getRow(2);
+
+ assertEquals("test1", row.getCell(3).getStringCellValue());
+ assertEquals("test2", row.getCell(4).getStringCellValue());
+ }
+ }
+ }
}
@Test
@@ -704,20 +684,20 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
@Test
void bug60509() throws Exception {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60509.xlsx");
- assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3");
- int sheetIndex = wb.getSheetIndex("Sheet1");
- wb.setSheetName(sheetIndex, "Sheet1-Renamed");
- Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb);
- assertNotNull(read);
- assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3");
- XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed");
- XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries(0);
- assertTrue(series instanceof XDDFBarChartData.Series, "should be a bar chart data series");
- String formula = series.getCategoryData().getFormula();
- assertTrue(formula.startsWith("'Sheet1-Renamed'!"), "should contain new sheet name");
- read.close();
- wb.close();
+ try (XSSFWorkbook wb = openSampleWorkbook("60509.xlsx")) {
+ assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3");
+ int sheetIndex = wb.getSheetIndex("Sheet1");
+ wb.setSheetName(sheetIndex, "Sheet1-Renamed");
+ try (Workbook read = writeOutAndReadBack(wb)) {
+ assertNotNull(read);
+ assertSheetOrder(read, "Sheet1-Renamed", "Sheet2", "Sheet3");
+ XSSFSheet sheet = (XSSFSheet) read.getSheet("Sheet1-Renamed");
+ XDDFChartData.Series series = sheet.getDrawingPatriarch().getCharts().get(0).getChartSeries().get(0).getSeries(0);
+ assertTrue(series instanceof XDDFBarChartData.Series, "should be a bar chart data series");
+ String formula = series.getCategoryData().getFormula();
+ assertTrue(formula.startsWith("'Sheet1-Renamed'!"), "should contain new sheet name");
+ }
+ }
}
private static final int INDEX_NOT_FOUND = -1;
@@ -850,15 +830,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertEquals(idx2, wb.getFirstVisibleTab());
assertEquals(idx3, wb.getActiveSheetIndex());
- Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb);
-
- sheet2 = wbBack.getSheetAt(idx2);
- assertNotNull(sheet2);
- sheet3 = wbBack.getSheetAt(idx3);
- assertNotNull(sheet3);
- assertEquals(idx2, wb.getFirstVisibleTab());
- assertEquals(idx3, wb.getActiveSheetIndex());
- wbBack.close();
+ try (Workbook wbBack = writeOutAndReadBack(wb)) {
+ sheet2 = wbBack.getSheetAt(idx2);
+ assertNotNull(sheet2);
+ sheet3 = wbBack.getSheetAt(idx3);
+ assertNotNull(sheet3);
+ assertEquals(idx2, wb.getFirstVisibleTab());
+ assertEquals(idx3, wb.getActiveSheetIndex());
+ }
}
}
@@ -873,42 +852,39 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
allBytes[i] = (byte) (i - 128);
}
- XSSFWorkbook wb1 = new XSSFWorkbook();
- wb1.createSheet();
- wb1.setVBAProject(new ByteArrayInputStream(allBytes));
- file = TempFile.createTempFile("poi-", ".xlsm");
- OutputStream out = new FileOutputStream(file);
- wb1.write(out);
- out.close();
- wb1.close();
+ try (XSSFWorkbook wb1 = new XSSFWorkbook()) {
+ wb1.createSheet();
+ wb1.setVBAProject(new ByteArrayInputStream(allBytes));
+ file = writeOut(wb1, "ooi-.xlsm");
+ }
// Check the package contains what we'd expect it to
- OPCPackage pkg = OPCPackage.open(file.toString());
- PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
- assertTrue(wbPart.hasRelationships());
- final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation());
- assertEquals(1, relationships.size());
- PackageRelationship relationship = relationships.getRelationship(0);
- assertNotNull(relationship);
- assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationship.getTargetURI().toString());
- PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName()));
- assertNotNull(vbaPart);
- assertFalse(vbaPart.isRelationshipPart());
- assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType());
- final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream());
- assertArrayEquals(allBytes, fromFile);
-
- // Load back the XSSFWorkbook just to check nothing explodes
- @SuppressWarnings("resource")
- XSSFWorkbook wb2 = new XSSFWorkbook(pkg);
- assertEquals(1, wb2.getNumberOfSheets());
- assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType());
- pkg.close();
+ try (OPCPackage pkg = OPCPackage.open(file.toString())) {
+ PackagePart wbPart = pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml"));
+ assertTrue(wbPart.hasRelationships());
+ final PackageRelationshipCollection relationships = wbPart.getRelationships().getRelationships(XSSFRelation.VBA_MACROS.getRelation());
+ assertEquals(1, relationships.size());
+ PackageRelationship relationship = relationships.getRelationship(0);
+ assertNotNull(relationship);
+ assertEquals(XSSFRelation.VBA_MACROS.getDefaultFileName(), relationship.getTargetURI().toString());
+ PackagePart vbaPart = pkg.getPart(PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName()));
+ assertNotNull(vbaPart);
+ assertFalse(vbaPart.isRelationshipPart());
+ assertEquals(XSSFRelation.VBA_MACROS.getContentType(), vbaPart.getContentType());
+ final byte[] fromFile = IOUtils.toByteArray(vbaPart.getInputStream());
+ assertArrayEquals(allBytes, fromFile);
+
+ // Load back the XSSFWorkbook just to check nothing explodes
+ try (XSSFWorkbook wb2 = new XSSFWorkbook(pkg)) {
+ assertEquals(1, wb2.getNumberOfSheets());
+ assertEquals(XSSFWorkbookType.XLSM, wb2.getWorkbookType());
+ }
+ }
}
@Test
void testBug54399() throws IOException {
- try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54399.xlsx")) {
+ try (XSSFWorkbook workbook = openSampleWorkbook("54399.xlsx")) {
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
String name = "SheetRenamed" + (i + 1);
@@ -920,14 +896,14 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
}
/**
- * Iterator<XSSFSheet> XSSFWorkbook.iterator was committed in r700472 on 2008-09-30
- * and has been replaced with Iterator<Sheet> XSSFWorkbook.iterator
+ * {@code Iterator<XSSFSheet> XSSFWorkbook.iterator} was committed in r700472 on 2008-09-30
+ * and has been replaced with {@code Iterator<Sheet> XSSFWorkbook.iterator}
*
* In order to make code for looping over sheets in workbooks standard, regardless
* of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously
- * available Iterator<XSSFSheet> iterator and Iterator<XSSFSheet> sheetIterator
- * have been replaced with Iterator<Sheet> {@link Sheet#iterator} and
- * Iterator<Sheet> {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook
+ * available {@code Iterator<XSSFSheet> iterator} and {@code Iterator<XSSFSheet> sheetIterator}
+ * have been replaced with {@code Iterator<Sheet>} {@link Sheet#iterator} and
+ * {@code Iterator<Sheet>} {@link Workbook#sheetIterator}. This makes iterating over sheets in a workbook
* similar to iterating over rows in a sheet and cells in a row.
*
* Note: this breaks backwards compatibility! Existing codebases will need to
@@ -1054,7 +1030,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
assertThrows(IOException.class, () -> {
try {
- XSSFTestDataSamples.writeOutAndReadBack(wb);
+ writeOutAndReadBack(wb);
} catch (RuntimeException e) {
throw e.getCause();
}
@@ -1067,7 +1043,7 @@ public final class TestXSSFWorkbook extends BaseTestXWorkbook {
*/
@Test
void getTable() throws IOException {
- XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx");
+ XSSFWorkbook wb = openSampleWorkbook("WithTable.xlsx");
XSSFTable table1 = wb.getTable("Tabella1");
assertNotNull(table1, "Tabella1 was not found in workbook");
assertEquals("Tabella1", table1.getName(), "Table name");
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java
index 77a7e8be08..ec2b4cc5e6 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java
@@ -20,10 +20,10 @@ package org.apache.poi.xssf.util;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.ReplacingInputStream;
import org.junit.jupiter.api.Test;
@@ -68,23 +68,20 @@ public final class TestEvilUnclosedBRFixingInputStream {
// Vary the buffer size, so that we can end up with the br in the
// overflow or only part in the buffer
for(int i=5; i<orig.length; i++) {
- EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig);
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- boolean going = true;
- while(going) {
- byte[] b = new byte[i];
- int r = inp.read(b);
- if(r > 0) {
+ try (EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig);
+ UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream()) {
+ for (;;) {
+ byte[] b = new byte[i];
+ int r = inp.read(b);
+ if (r <= 0) {
+ break;
+ }
bout.write(b, 0, r);
- } else {
- going = false;
}
- }
- byte[] result = bout.toByteArray();
- assertArrayEquals(fixed, result);
- inp.close();
+ byte[] result = bout.toByteArray();
+ assertArrayEquals(fixed, result);
+ }
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java
index b24d0bf46c..e38b5b1e2d 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/XWPFTestDataSamples.java
@@ -16,11 +16,10 @@
==================================================================== */
package org.apache.poi.xwpf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
@@ -33,10 +32,9 @@ public class XWPFTestDataSamples {
}
public static XWPFDocument writeOutAndReadBack(XWPFDocument doc) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096);
doc.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- return new XWPFDocument(bais);
+ return new XWPFDocument(baos.toInputStream());
}
public static byte[] getImage(String filename) throws IOException {
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java
index 39673c3bba..0b74bfa5f1 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestChangeTracking.java
@@ -19,9 +19,9 @@ package org.apache.poi.xwpf.usermodel;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.xwpf.XWPFTestDataSamples;
import org.junit.jupiter.api.Test;
@@ -58,14 +58,14 @@ class TestChangeTracking {
r1.setText("Lorem ipsum dolor sit amet.");
doc.setTrackRevisions(true);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- doc.write(out);
+ try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
+ doc.write(out);
- ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray());
- XWPFDocument document = new XWPFDocument(inputStream);
- inputStream.close();
-
- assertTrue(document.isTrackRevisions());
+ try (InputStream inputStream = out.toInputStream()) {
+ XWPFDocument document = new XWPFDocument(inputStream);
+ assertTrue(document.isTrackRevisions());
+ }
+ }
}
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java
index 2974c879dc..10c8fca9e7 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java
@@ -16,6 +16,7 @@
==================================================================== */
package org.apache.poi.xwpf.usermodel;
+import static org.apache.poi.xwpf.XWPFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -23,8 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
@@ -170,15 +169,11 @@ class TestXWPFBugs {
@Test
void test59378() throws IOException {
try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("59378.docx")) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- doc.write(out);
- out.close();
-
- try (XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()))) {
+ try (XWPFDocument doc2 = writeOutAndReadBack(doc)) {
assertNotNull(doc2);
}
- try (XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc)) {
+ try (XWPFDocument docBack = writeOutAndReadBack(doc)) {
assertNotNull(docBack);
}
}
diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java
index 856fcd9be3..dc614470ea 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFRun.java
@@ -16,15 +16,17 @@
==================================================================== */
package org.apache.poi.xwpf.usermodel;
+import static org.apache.poi.xwpf.XWPFTestDataSamples.openSampleDocument;
+import static org.apache.poi.xwpf.XWPFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
@@ -296,7 +298,7 @@ class TestXWPFRun {
*/
@Test
void testExisting() throws IOException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
+ XWPFDocument doc = openSampleDocument("TestDocument.docx");
XWPFParagraph p;
XWPFRun run;
@@ -430,7 +432,7 @@ class TestXWPFRun {
@Test
void testPictureInHeader() throws IOException {
- XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx");
+ XWPFDocument sampleDoc = openSampleDocument("headerPic.docx");
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
XWPFHeader header = policy.getDefaultHeader();
@@ -486,7 +488,7 @@ class TestXWPFRun {
@Test
void testAddPicture() throws Exception {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
+ XWPFDocument doc = openSampleDocument("TestDocument.docx");
XWPFParagraph p = doc.getParagraphArray(2);
XWPFRun r = p.getRuns().get(0);
@@ -498,7 +500,7 @@ class TestXWPFRun {
assertEquals(1, doc.getAllPictures().size());
assertEquals(1, r.getEmbeddedPictures().size());
- XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
+ XWPFDocument docBack = writeOutAndReadBack(doc);
XWPFParagraph pBack = docBack.getParagraphArray(2);
XWPFRun rBack = pBack.getRuns().get(0);
@@ -513,39 +515,39 @@ class TestXWPFRun {
*/
@Test
void testAddPictureInHeader() throws IOException, InvalidFormatException {
- XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx");
- XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
- XWPFParagraph p = hdr.createParagraph();
- XWPFRun r = p.createRun();
+ try (XWPFDocument doc = openSampleDocument("TestDocument.docx")) {
+ XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
+ XWPFParagraph p = hdr.createParagraph();
+ XWPFRun r = p.createRun();
- assertEquals(0, hdr.getAllPictures().size());
- assertEquals(0, r.getEmbeddedPictures().size());
+ assertEquals(0, hdr.getAllPictures().size());
+ assertEquals(0, r.getEmbeddedPictures().size());
- r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);
+ r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32);
- assertEquals(1, hdr.getAllPictures().size());
- assertEquals(1, r.getEmbeddedPictures().size());
+ assertEquals(1, hdr.getAllPictures().size());
+ assertEquals(1, r.getEmbeddedPictures().size());
- XWPFPicture pic = r.getEmbeddedPictures().get(0);
- CTPicture ctPic = pic.getCTPicture();
- CTBlipFillProperties ctBlipFill = ctPic.getBlipFill();
+ XWPFPicture pic = r.getEmbeddedPictures().get(0);
+ CTPicture ctPic = pic.getCTPicture();
+ CTBlipFillProperties ctBlipFill = ctPic.getBlipFill();
- assertNotNull(ctBlipFill);
+ assertNotNull(ctBlipFill);
- CTBlip ctBlip = ctBlipFill.getBlip();
+ CTBlip ctBlip = ctBlipFill.getBlip();
- assertNotNull(ctBlip);
- assertEquals("rId1", ctBlip.getEmbed());
+ assertNotNull(ctBlip);
+ assertEquals("rId1", ctBlip.getEmbed());
- XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc);
- XWPFHeader hdrBack = docBack.getHeaderArray(0);
- XWPFParagraph pBack = hdrBack.getParagraphArray(0);
- XWPFRun rBack = pBack.getRuns().get(0);
+ try (XWPFDocument docBack = writeOutAndReadBack(doc)) {
+ XWPFHeader hdrBack = docBack.getHeaderArray(0);
+ XWPFParagraph pBack = hdrBack.getParagraphArray(0);
+ XWPFRun rBack = pBack.getRuns().get(0);
- assertEquals(1, hdrBack.getAllPictures().size());
- assertEquals(1, rBack.getEmbeddedPictures().size());
- docBack.close();
- doc.close();
+ assertEquals(1, hdrBack.getAllPictures().size());
+ assertEquals(1, rBack.getEmbeddedPictures().size());
+ }
+ }
}
/**
@@ -554,7 +556,7 @@ class TestXWPFRun {
*/
@Test
void testSetFontFamily_52288() throws IOException {
- try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx")) {
+ try (XWPFDocument doc = openSampleDocument("52288.docx")) {
doc.getParagraphs().stream()
.flatMap(p -> p.getRuns().stream())
.filter(p -> p != null && p.getText(0) != null)
@@ -565,157 +567,148 @@ class TestXWPFRun {
@Test
void testBug55476() throws IOException, InvalidFormatException {
byte[] image = XWPFTestDataSamples.getImage("abstract1.jpg");
- XWPFDocument document = new XWPFDocument();
+ try (XWPFDocument document = new XWPFDocument()) {
- document.createParagraph().createRun().addPicture(
+ document.createParagraph().createRun().addPicture(
new ByteArrayInputStream(image), Document.PICTURE_TYPE_JPEG, "test.jpg", Units.toEMU(300), Units.toEMU(100));
- XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(document);
- List<XWPFPicture> pictures = docBack.getParagraphArray(0).getRuns().get(0).getEmbeddedPictures();
- assertEquals(1, pictures.size());
- docBack.close();
-
- /*OutputStream stream = new FileOutputStream("c:\\temp\\55476.docx");
- try {
- document.write(stream);
- } finally {
- stream.close();
- }*/
-
- document.close();
+ try (XWPFDocument docBack = writeOutAndReadBack(document)) {
+ List<XWPFPicture> pictures = docBack.getParagraphArray(0).getRuns().get(0).getEmbeddedPictures();
+ assertEquals(1, pictures.size());
+ }
+ }
}
@Test
void testBug58922() throws IOException {
- XWPFDocument document = new XWPFDocument();
-
- final XWPFRun run = document.createParagraph().createRun();
+ try (XWPFDocument document = new XWPFDocument()) {
+ final XWPFRun run = document.createParagraph().createRun();
- assertEquals(-1, run.getFontSize());
- run.setFontSize(10);
- assertEquals(10, run.getFontSize());
+ assertEquals(-1, run.getFontSize());
- run.setFontSize(Short.MAX_VALUE-1);
- assertEquals(Short.MAX_VALUE-1, run.getFontSize());
+ run.setFontSize(10);
+ assertEquals(10, run.getFontSize());
- run.setFontSize(Short.MAX_VALUE);
- assertEquals(Short.MAX_VALUE, run.getFontSize());
+ run.setFontSize(Short.MAX_VALUE - 1);
+ assertEquals(Short.MAX_VALUE - 1, run.getFontSize());
- run.setFontSize(Short.MAX_VALUE+1);
- assertEquals(Short.MAX_VALUE+1, run.getFontSize());
+ run.setFontSize(Short.MAX_VALUE);
+ assertEquals(Short.MAX_VALUE, run.getFontSize());
- run.setFontSize(Integer.MAX_VALUE-1);
- assertEquals(Integer.MAX_VALUE-1, run.getFontSize());
+ run.setFontSize(Short.MAX_VALUE + 1);
+ assertEquals(Short.MAX_VALUE + 1, run.getFontSize());
- run.setFontSize(Integer.MAX_VALUE);
- assertEquals(Integer.MAX_VALUE, run.getFontSize());
+ run.setFontSize(Integer.MAX_VALUE - 1);
+ assertEquals(Integer.MAX_VALUE - 1, run.getFontSize());
- run.setFontSize(-1);
- assertEquals(-1, run.getFontSize());
+ run.setFontSize(Integer.MAX_VALUE);
+ assertEquals(Integer.MAX_VALUE, run.getFontSize());
+ run.setFontSize(-1);
+ assertEquals(-1, run.getFontSize());
- assertEquals(-1, run.getTextPosition());
- run.setTextPosition(10);
- assertEquals(10, run.getTextPosition());
+ assertEquals(-1, run.getTextPosition());
- run.setTextPosition(Short.MAX_VALUE-1);
- assertEquals(Short.MAX_VALUE-1, run.getTextPosition());
+ run.setTextPosition(10);
+ assertEquals(10, run.getTextPosition());
- run.setTextPosition(Short.MAX_VALUE);
- assertEquals(Short.MAX_VALUE, run.getTextPosition());
+ run.setTextPosition(Short.MAX_VALUE - 1);
+ assertEquals(Short.MAX_VALUE - 1, run.getTextPosition());
- run.setTextPosition(Short.MAX_VALUE+1);
- assertEquals(Short.MAX_VALUE+1, run.getTextPosition());
+ run.setTextPosition(Short.MAX_VALUE);
+ assertEquals(Short.MAX_VALUE, run.getTextPosition());
- run.setTextPosition(Short.MAX_VALUE+1);
- assertEquals(Short.MAX_VALUE+1, run.getTextPosition());
+ run.setTextPosition(Short.MAX_VALUE + 1);
+ assertEquals(Short.MAX_VALUE + 1, run.getTextPosition());
- run.setTextPosition(Integer.MAX_VALUE-1);
- assertEquals(Integer.MAX_VALUE-1, run.getTextPosition());
+ run.setTextPosition(Short.MAX_VALUE + 1);
+ assertEquals(Short.MAX_VALUE + 1, run.getTextPosition());
- run.setTextPosition(Integer.MAX_VALUE);
- assertEquals(Integer.MAX_VALUE, run.getTextPosition());
+ run.setTextPosition(Integer.MAX_VALUE - 1);
+ assertEquals(Integer.MAX_VALUE - 1, run.getTextPosition());
- run.setTextPosition(-1);
- assertEquals(-1, run.getTextPosition());
+ run.setTextPosition(Integer.MAX_VALUE);
+ assertEquals(Integer.MAX_VALUE, run.getTextPosition());
- document.close();
+ run.setTextPosition(-1);
+ assertEquals(-1, run.getTextPosition());
+ }
}
@Test
- void testSetters() {
- XWPFDocument document = new XWPFDocument();
- final XWPFRun run = document.createParagraph().createRun();
-
- // at least trigger some of the setters to ensure classes are included in
- // the poi-ooxml-lite
- run.setBold(true);
- run.setCapitalized(true);
- run.setCharacterSpacing(2);
- assertEquals(2, run.getCharacterSpacing());
- run.setColor("000000");
- run.setDoubleStrikethrough(true);
- run.setEmbossed(true);
- run.setFontFamily("Calibri");
- assertEquals("Calibri", run.getFontFamily());
- run.setFontSize(10);
- assertEquals(10, run.getFontSize());
- run.setImprinted(true);
- run.setItalic(true);
+ void testSetters() throws IOException {
+ try (XWPFDocument document = new XWPFDocument()) {
+ final XWPFRun run = document.createParagraph().createRun();
+
+ // at least trigger some of the setters to ensure classes are included in
+ // the poi-ooxml-lite
+ run.setBold(true);
+ run.setCapitalized(true);
+ run.setCharacterSpacing(2);
+ assertEquals(2, run.getCharacterSpacing());
+ run.setColor("000000");
+ run.setDoubleStrikethrough(true);
+ run.setEmbossed(true);
+ run.setFontFamily("Calibri");
+ assertEquals("Calibri", run.getFontFamily());
+ run.setFontSize(10);
+ assertEquals(10, run.getFontSize());
+ run.setImprinted(true);
+ run.setItalic(true);
+ }
}
@Test
void testSetGetTextScale() throws IOException {
- XWPFDocument document = new XWPFDocument();
- final XWPFRun run = document.createParagraph().createRun();
- assertEquals(100, run.getTextScale());
- run.setTextScale(200);
- assertEquals(200, run.getTextScale());
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ final XWPFRun run = document.createParagraph().createRun();
+ assertEquals(100, run.getTextScale());
+ run.setTextScale(200);
+ assertEquals(200, run.getTextScale());
+ }
}
@Test
void testSetGetTextHighlightColor() throws IOException {
- XWPFDocument document = new XWPFDocument();
- final XWPFRun run = document.createParagraph().createRun();
- assertEquals(STHighlightColor.NONE, run.getTextHightlightColor());
- assertFalse(run.isHighlighted());
- run.setTextHighlightColor("darkGreen"); // See 17.18.40 ST_HighlightColor (Text Highlight Colors)
- assertEquals(STHighlightColor.DARK_GREEN, run.getTextHightlightColor());
- assertTrue(run.isHighlighted());
- run.setTextHighlightColor("none");
- assertFalse(run.isHighlighted());
-
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ final XWPFRun run = document.createParagraph().createRun();
+ assertSame(STHighlightColor.NONE, run.getTextHightlightColor());
+ assertFalse(run.isHighlighted());
+ run.setTextHighlightColor("darkGreen"); // See 17.18.40 ST_HighlightColor (Text Highlight Colors)
+ assertSame(STHighlightColor.DARK_GREEN, run.getTextHightlightColor());
+ assertTrue(run.isHighlighted());
+ run.setTextHighlightColor("none");
+ assertFalse(run.isHighlighted());
+ }
}
@Test
void testSetGetVanish() throws IOException {
- XWPFDocument document = new XWPFDocument();
- final XWPFRun run = document.createParagraph().createRun();
- assertFalse(run.isVanish());
- run.setVanish(true);
- assertTrue(run.isVanish());
- run.setVanish(false);
- assertFalse(run.isVanish());
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ final XWPFRun run = document.createParagraph().createRun();
+ assertFalse(run.isVanish());
+ run.setVanish(true);
+ assertTrue(run.isVanish());
+ run.setVanish(false);
+ assertFalse(run.isVanish());
+ }
}
@Test
void testSetGetVerticalAlignment() throws IOException {
- XWPFDocument document = new XWPFDocument();
- XWPFRun run = document.createParagraph().createRun();
- assertEquals(STVerticalAlignRun.BASELINE, run.getVerticalAlignment());
- // Reset to a fresh run so we test case of run not having vertical alignment at all
- run = document.createParagraph().createRun();
- run.setVerticalAlignment("subscript");
- assertEquals(STVerticalAlignRun.SUBSCRIPT, run.getVerticalAlignment());
- run.setVerticalAlignment("superscript");
- assertEquals(STVerticalAlignRun.SUPERSCRIPT, run.getVerticalAlignment());
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ XWPFRun run = document.createParagraph().createRun();
+ assertSame(STVerticalAlignRun.BASELINE, run.getVerticalAlignment());
+ // Reset to a fresh run so we test case of run not having vertical alignment at all
+ run = document.createParagraph().createRun();
+ run.setVerticalAlignment("subscript");
+ assertSame(STVerticalAlignRun.SUBSCRIPT, run.getVerticalAlignment());
+ run.setVerticalAlignment("superscript");
+ assertSame(STVerticalAlignRun.SUPERSCRIPT, run.getVerticalAlignment());
+ }
}
@Test
@@ -726,82 +719,81 @@ class TestXWPFRun {
XWPFRun run = new XWPFRun(ctRun, irb);
run.setSubscript(VerticalAlign.BASELINE);
- assertEquals(STVerticalAlignRun.BASELINE, rpr.getVertAlignArray(0).getVal());
+ assertSame(STVerticalAlignRun.BASELINE, rpr.getVertAlignArray(0).getVal());
}
@Test
void testSetGetEmphasisMark() throws IOException {
- XWPFDocument document = new XWPFDocument();
- XWPFRun run = document.createParagraph().createRun();
- assertEquals(STEm.NONE, run.getEmphasisMark());
- // Reset to a fresh run so we test case of run not having property at all
- run = document.createParagraph().createRun();
- run.setEmphasisMark("dot");
- assertEquals(STEm.DOT, run.getEmphasisMark());
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ XWPFRun run = document.createParagraph().createRun();
+ assertSame(STEm.NONE, run.getEmphasisMark());
+ // Reset to a fresh run so we test case of run not having property at all
+ run = document.createParagraph().createRun();
+ run.setEmphasisMark("dot");
+ assertSame(STEm.DOT, run.getEmphasisMark());
+ }
}
@Test
void testSetGetUnderlineColor() throws IOException {
- XWPFDocument document = new XWPFDocument();
- XWPFRun run = document.createParagraph().createRun();
- assertEquals("auto", run.getUnderlineColor());
- // Reset to a fresh run so we test case of run not having property at all
- run = document.createParagraph().createRun();
- String colorRgb = "C0F1a2";
- run.setUnderlineColor(colorRgb);
- assertEquals(colorRgb.toUpperCase(LocaleUtil.getUserLocale()), run.getUnderlineColor());
- run.setUnderlineColor("auto");
- assertEquals("auto", run.getUnderlineColor());
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ XWPFRun run = document.createParagraph().createRun();
+ assertEquals("auto", run.getUnderlineColor());
+ // Reset to a fresh run so we test case of run not having property at all
+ run = document.createParagraph().createRun();
+ String colorRgb = "C0F1a2";
+ run.setUnderlineColor(colorRgb);
+ assertEquals(colorRgb.toUpperCase(LocaleUtil.getUserLocale()), run.getUnderlineColor());
+ run.setUnderlineColor("auto");
+ assertEquals("auto", run.getUnderlineColor());
+ }
}
@Test
void testSetGetUnderlineThemeColor() throws IOException {
- XWPFDocument document = new XWPFDocument();
- XWPFRun run = document.createParagraph().createRun();
- assertEquals(STThemeColor.NONE, run.getUnderlineThemeColor());
- // Reset to a fresh run so we test case of run not having property at all
- run = document.createParagraph().createRun();
- String colorName = "accent4";
- run.setUnderlineThemeColor(colorName);
- assertEquals(STThemeColor.Enum.forString(colorName), run.getUnderlineThemeColor());
- run.setUnderlineThemeColor("none");
- assertEquals(STThemeColor.NONE, run.getUnderlineThemeColor());
- document.close();
+ try (XWPFDocument document = new XWPFDocument()) {
+ XWPFRun run = document.createParagraph().createRun();
+ assertSame(STThemeColor.NONE, run.getUnderlineThemeColor());
+ // Reset to a fresh run so we test case of run not having property at all
+ run = document.createParagraph().createRun();
+ String colorName = "accent4";
+ run.setUnderlineThemeColor(colorName);
+ assertSame(STThemeColor.Enum.forString(colorName), run.getUnderlineThemeColor());
+ run.setUnderlineThemeColor("none");
+ assertSame(STThemeColor.NONE, run.getUnderlineThemeColor());
+ }
}
@Test
void testSetStyleId() throws IOException {
- XWPFDocument document = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx");
- final XWPFRun run = document.createParagraph().createRun();
-
- String styleId = "bolditalic";
- run.setStyle(styleId);
- String candStyleId = run.getCTR().getRPr().getRStyleArray(0).getVal();
- assertNotNull( candStyleId, "Expected to find a run style ID" );
- assertEquals(styleId, candStyleId);
+ try (XWPFDocument document = openSampleDocument("SampleDoc.docx")) {
+ final XWPFRun run = document.createParagraph().createRun();
- assertEquals(styleId, run.getStyle());
+ String styleId = "bolditalic";
+ run.setStyle(styleId);
+ String candStyleId = run.getCTR().getRPr().getRStyleArray(0).getVal();
+ assertNotNull(candStyleId, "Expected to find a run style ID");
+ assertEquals(styleId, candStyleId);
- document.close();
+ assertEquals(styleId, run.getStyle());
+ }
}
@Test
void testGetEmptyStyle() throws IOException {
- XWPFDocument document = new XWPFDocument();
- final XWPFRun run = document.createParagraph().createRun();
- assertEquals("", run.getStyle());
+ try (XWPFDocument document = new XWPFDocument()) {
+ final XWPFRun run = document.createParagraph().createRun();
+ assertEquals("", run.getStyle());
- run.getCTR().addNewRPr();
- assertEquals("", run.getStyle());
- document.close();
+ run.getCTR().addNewRPr();
+ assertEquals("", run.getStyle());
+ }
}
@Test
void testGetDepthWidth() throws IOException, InvalidFormatException {
- try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) {
+ try (XWPFDocument doc = openSampleDocument("TestDocument.docx")) {
XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT);
XWPFParagraph p = hdr.createParagraph();
XWPFRun r = p.createRun();
@@ -827,35 +819,28 @@ class TestXWPFRun {
" The quick brown fox",
"\t\tjumped over the lazy dog"
};
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try (XWPFDocument doc = new XWPFDocument();) {
+ try (XWPFDocument doc1 = new XWPFDocument()) {
for(String s : text) {
- XWPFParagraph p1 = doc.createParagraph();
+ XWPFParagraph p1 = doc1.createParagraph();
XWPFRun r1 = p1.createRun();
r1.setText(s);
}
- doc.write(bos);
- bos.flush();
- }
-
- try (
- ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
- XWPFDocument doc = new XWPFDocument(bis)
- ) {
- List<XWPFParagraph> paragraphs = doc.getParagraphs();
- assertEquals(2, paragraphs.size());
- for (int i = 0; i < text.length; i++) {
- XWPFParagraph p1 = paragraphs.get(i);
- String expected = text[i];
- assertEquals(expected, p1.getText());
- CTP ctp = p1.getCTP();
- CTR ctr = ctp.getRArray(0);
- CTText ctText = ctr.getTArray(0);
- // if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set
- // <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
- boolean isWhitespace = Character.isWhitespace(expected.charAt(0));
- assertEquals(isWhitespace, ctText.isSetSpace());
+ try (XWPFDocument doc2 = writeOutAndReadBack(doc1)) {
+ List<XWPFParagraph> paragraphs = doc2.getParagraphs();
+ assertEquals(2, paragraphs.size());
+ for (int i = 0; i < text.length; i++) {
+ XWPFParagraph p1 = paragraphs.get(i);
+ String expected = text[i];
+ assertEquals(expected, p1.getText());
+ CTP ctp = p1.getCTP();
+ CTR ctr = ctp.getRArray(0);
+ CTText ctText = ctr.getTArray(0);
+ // if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set
+ // <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ boolean isWhitespace = Character.isWhitespace(expected.charAt(0));
+ assertEquals(isWhitespace, ctText.isSetSpace());
+ }
}
}
}