- * This will fail (with an {@link IllegalStateException} if the
+ * This will fail (with an {@link IllegalStateException} if the
* slideshow was opened read-only, opened from an {@link InputStream}
* instead of a File, or if this is not the root document. For those cases,
* you must use {@link #write(OutputStream)} or {@link #write(File)} to
@@ -686,7 +689,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
* of this class.
*
This will write out only the common OLE2 streams. If you require all
* streams to be written out, use {@link #write(File, boolean)}
- * with preserveNodes
set to true
.
+ * with {@code preserveNodes} set to {@code true}.
*
* @param newFile The File to write to.
* @throws IOException If there is an unexpected IOException from writing to the File
@@ -701,7 +704,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
* Writes out the slideshow file the is represented by an instance
* of this class.
* If you require all streams to be written out (eg Marcos, embeded
- * documents), then set preserveNodes
set to true
+ * documents), then set {@code preserveNodes} set to {@code true}
*
* @param newFile The File to write to.
* @param preserveNodes Should all OLE2 streams be written back out, or only the common ones?
@@ -724,7 +727,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
* of this class.
*
This will write out only the common OLE2 streams. If you require all
* streams to be written out, use {@link #write(OutputStream, boolean)}
- * with preserveNodes
set to true
.
+ * with {@code preserveNodes} set to {@code true}.
*
* @param out The OutputStream to write to.
* @throws IOException If there is an unexpected IOException from
@@ -740,7 +743,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
* Writes out the slideshow file the is represented by an instance
* of this class.
* If you require all streams to be written out (eg Marcos, embeded
- * documents), then set preserveNodes
set to true
+ * documents), then set {@code preserveNodes} set to {@code true}
*
* @param out The OutputStream to write to.
* @param preserveNodes Should all OLE2 streams be written back out, or only the common ones?
@@ -776,16 +779,16 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
// Write out the Property Streams
writeProperties(outFS, writtenEntries);
- BufAccessBAOS baos = new BufAccessBAOS();
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
- // For position dependent records, hold where they were and now are
- // As we go along, update, and hand over, to any Position Dependent
- // records we happen across
- updateAndWriteDependantRecords(baos, null);
+ // For position dependent records, hold where they were and now are
+ // As we go along, update, and hand over, to any Position Dependent
+ // records we happen across
+ updateAndWriteDependantRecords(baos, null);
- // Update our cached copy of the bytes that make up the PPT stream
- _docstream = baos.toByteArray();
- baos.close();
+ // Update our cached copy of the bytes that make up the PPT stream
+ _docstream = baos.toByteArray();
+ }
// Write the PPT stream into the POIFS layer
ByteArrayInputStream bais = new ByteArrayInputStream(_docstream);
@@ -796,20 +799,18 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
currentUser.writeToFS(outFS);
writtenEntries.add("Current User");
- if (_pictures.size() > 0) {
- BufAccessBAOS pict = new BufAccessBAOS();
- for (HSLFPictureData p : _pictures) {
- int offset = pict.size();
- p.write(pict);
- encryptedSS.encryptPicture(pict.getBuf(), offset);
- }
- outFS.createOrUpdateDocument(
- new ByteArrayInputStream(pict.getBuf(), 0, pict.size()), "Pictures"
+ if (!_pictures.isEmpty()) {
+ Enumeration pictEnum = IteratorUtils.asEnumeration(
+ _pictures.stream().map(data -> encryptOnePicture(encryptedSS, data)).iterator()
);
- writtenEntries.add("Pictures");
- pict.close();
- }
+ try (SequenceInputStream sis = new SequenceInputStream(pictEnum)) {
+ outFS.createOrUpdateDocument(sis, "Pictures");
+ writtenEntries.add("Pictures");
+ } catch (IllegalStateException e) {
+ throw (IOException)e.getCause();
+ }
+ }
}
// If requested, copy over any other streams we spot, eg Macros
@@ -818,6 +819,17 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
}
}
+ private static InputStream encryptOnePicture(HSLFSlideShowEncrypted encryptedSS, HSLFPictureData data) {
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
+ data.write(baos);
+ byte[] pictBytes = baos.toByteArray();
+ encryptedSS.encryptPicture(pictBytes, 0);
+ return new ByteArrayInputStream(pictBytes);
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
@Override
public EncryptionInfo getEncryptionInfo() {
@@ -1017,12 +1029,6 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
super.replaceDirectory(newDirectory);
}
- private static class BufAccessBAOS extends ByteArrayOutputStream {
- public byte[] getBuf() {
- return buf;
- }
- }
-
private static class CountingOS extends OutputStream {
int count;
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java b/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java
index 6cf92111a6..7915ca5c66 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java
@@ -17,8 +17,9 @@
package org.apache.poi.hsmf.datatypes;
+import static org.apache.logging.log4j.util.Unbox.box;
+
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -30,6 +31,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hsmf.datatypes.PropertyValue.BooleanPropertyValue;
@@ -47,8 +49,6 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndian.BufferUnderrunException;
-import static org.apache.logging.log4j.util.Unbox.box;
-
/**
*
* A Chunk which holds (single) fixed-length properties, and pointer to the
@@ -76,13 +76,13 @@ public abstract class PropertiesChunk extends Chunk {
* Holds properties, indexed by type. If a property is multi-valued, or
* variable length, it will be held via a {@link ChunkBasedPropertyValue}.
*/
- private Map properties = new HashMap<>();
+ private final Map properties = new HashMap<>();
/**
* The ChunkGroup that these properties apply to. Used when matching chunks
* to variable sized and multi-valued properties
*/
- private ChunkGroup parentGroup;
+ private final ChunkGroup parentGroup;
/**
* Creates a Properties Chunk.
@@ -254,7 +254,7 @@ public abstract class PropertiesChunk extends Chunk {
}
// Wrap and store
- PropertyValue propVal = null;
+ PropertyValue propVal;
if (isPointer) {
// We'll match up the chunk later
propVal = new ChunkBasedPropertyValue(prop, flags, data, type);
@@ -302,16 +302,17 @@ public abstract class PropertiesChunk extends Chunk {
* If an I/O error occurs.
*/
public void writeProperties(DirectoryEntry directory) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- List values = writeProperties(baos);
- baos.close();
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
+ List values = writeProperties(baos);
- // write the header data with the properties declaration
- directory.createDocument(PropertiesChunk.NAME,
- new ByteArrayInputStream(baos.toByteArray()));
+ // write the header data with the properties declaration
+ try (InputStream is = baos.toInputStream()) {
+ directory.createDocument(PropertiesChunk.NAME, is);
+ }
- // write the property values
- writeNodeData(directory, values);
+ // write the property values
+ writeNodeData(directory, values);
+ }
}
/**
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java
index 82baf52036..c56ae3f17f 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java
@@ -190,7 +190,7 @@ public class HwmfEscape implements HwmfRecord {
}
public interface HwmfEscapeData {
- public int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException;
+ int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException;
}
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java
index 19fda80509..fb24af7cb4 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java
@@ -17,13 +17,13 @@
package org.apache.poi.hwmf.usermodel;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hwmf.record.HwmfEscape;
import org.apache.poi.hwmf.record.HwmfEscape.EscapeFunction;
import org.apache.poi.hwmf.record.HwmfEscape.WmfEscapeEMF;
@@ -120,7 +120,7 @@ public class HwmfEmbeddedIterator implements Iterator {
final HwmfEmbedded emb = new HwmfEmbedded();
emb.setEmbeddedType(HwmfEmbeddedType.EMF);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
for (;;) {
bos.write(img.getEmfData());
@@ -132,8 +132,8 @@ public class HwmfEmbeddedIterator implements Iterator {
return emb;
}
}
- } catch (IOException e) {
- // ByteArrayOutputStream doesn't throw IOException
+ } catch (IOException ignored) {
+ // UnsynchronizedByteArrayOutputStream doesn't throw IOException
return null;
} finally {
emb.setData(bos.toByteArray());
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java
index 8fb9055bc5..71079c3b1b 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java
@@ -17,8 +17,6 @@
package org.apache.poi.hwpf.dev;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -31,6 +29,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.HWPFOldDocument;
@@ -262,12 +261,11 @@ public final class HWPFLister {
private static HWPFDocumentCore writeOutAndReadBack(
HWPFDocumentCore original ) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream( 4096 );
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
original.write( baos );
- ByteArrayInputStream bais = new ByteArrayInputStream(
- baos.toByteArray() );
- return loadDoc( bais );
+ try (InputStream is = baos.toInputStream()) {
+ return loadDoc(is);
+ }
}
catch ( IOException e ) {
throw new RuntimeException( e );
@@ -388,7 +386,7 @@ public final class HWPFLister {
}
}
- public void dumpFileSystem() throws Exception {
+ public void dumpFileSystem() {
System.out.println( dumpFileSystem( _doc.getDirectory() ) );
}
@@ -439,8 +437,7 @@ public final class HWPFLister {
}
}
- public void dumpPapx( boolean withProperties, boolean withSprms )
- throws Exception {
+ public void dumpPapx( boolean withProperties, boolean withSprms ) {
if ( _doc instanceof HWPFDocument ) {
System.out.println( "binary PAP pages " );
@@ -514,8 +511,8 @@ public final class HWPFLister {
if ( dumpAssotiatedPapx ) {
boolean hasAssotiatedPapx = false;
for ( PAPX papx : _doc.getParagraphTable().getParagraphs() ) {
- if ( papx.getStart() <= endOfParagraphCharOffset.intValue()
- && endOfParagraphCharOffset.intValue() < papx
+ if ( papx.getStart() <= endOfParagraphCharOffset
+ && endOfParagraphCharOffset < papx
.getEnd() ) {
hasAssotiatedPapx = true;
System.out.println( "* " + papx );
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java
index 913b4950ae..d4283a612b 100644
--- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java
+++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java
@@ -18,13 +18,13 @@
package org.apache.poi.hwpf.usermodel;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.zip.InflaterInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ddf.EscherBSERecord;
@@ -37,6 +37,7 @@ import org.apache.poi.ddf.EscherRecord;
import org.apache.poi.hwpf.model.PICF;
import org.apache.poi.hwpf.model.PICFAndOfficeArtData;
import org.apache.poi.sl.image.ImageHeaderPNG;
+import org.apache.poi.util.IOUtils;
import org.apache.poi.util.StringUtil;
/**
@@ -120,10 +121,10 @@ public final class Picture {
}
}
- private void fillImageContent()
- {
- if ( content != null && content.length > 0 )
+ private void fillImageContent() {
+ if ( content != null && content.length > 0 ) {
return;
+ }
byte[] rawContent = getRawContent();
@@ -134,33 +135,21 @@ public final class Picture {
* similarity in the data block contents.
*/
if ( matchSignature( rawContent, COMPRESSED1, 32 )
- || matchSignature( rawContent, COMPRESSED2, 32 ) )
- {
- try
- {
- InflaterInputStream in = new InflaterInputStream(
- new ByteArrayInputStream( rawContent, 33,
- rawContent.length - 33 ) );
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buf = new byte[4096];
- int readBytes;
- while ( ( readBytes = in.read( buf ) ) > 0 )
- {
- out.write( buf, 0, readBytes );
- }
+ || matchSignature( rawContent, COMPRESSED2, 32 ) ) {
+ try (ByteArrayInputStream bis = new ByteArrayInputStream( rawContent, 33, rawContent.length - 33 );
+ InflaterInputStream in = new InflaterInputStream(bis);
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
+
+ IOUtils.copy(in, out);
content = out.toByteArray();
- }
- catch ( IOException e )
- {
+ } catch (IOException e) {
/*
* Problems reading from the actual ByteArrayInputStream should
* never happen so this will only ever be a ZipException.
*/
LOGGER.atInfo().withThrowable(e).log("Possibly corrupt compression or non-compressed data");
}
- }
- else
- {
+ } else {
// Raw data is not compressed.
content = new ImageHeaderPNG(rawContent).extractPNG();
}
@@ -186,8 +175,8 @@ public final class Picture {
byte[] jpegContent = getContent();
int pointer = 2;
- int firstByte = jpegContent[pointer];
- int secondByte = jpegContent[pointer + 1];
+ int firstByte;
+ int secondByte;
int endOfPicture = jpegContent.length;
while ( pointer < endOfPicture - 1 )
{
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java b/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java
index 302eacc928..6a1a830a0b 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java
@@ -26,7 +26,7 @@ import java.io.File;
import java.io.PrintStream;
import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.Test;
public class TestVSDDumper {
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java b/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java
index 6d39586729..d52873779c 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java
@@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.geom.Point2D;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -34,6 +33,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hemf.record.emf.HemfComment;
import org.apache.poi.hemf.record.emf.HemfComment.EmfComment;
@@ -52,7 +52,6 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.util.RecordFormatException;
import org.junit.jupiter.api.Test;
-@SuppressWarnings("StatementWithEmptyBody")
public class TestHemfPicture {
private static final POIDataSamples ss_samples = POIDataSamples.getSpreadSheetInstance();
@@ -286,10 +285,10 @@ public class TestHemfPicture {
@Test
void testInfiniteLoopOnByteArray() throws Exception {
try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
IOUtils.copy(is, bos);
- HemfPicture pic = new HemfPicture(new ByteArrayInputStream(bos.toByteArray()));
+ HemfPicture pic = new HemfPicture(bos.toInputStream());
assertThrows(RecordFormatException.class, () -> pic.forEach(r -> {}));
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java
index d0359a6d2e..5717e5157d 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java
@@ -21,15 +21,16 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hmef.attribute.MAPIAttribute;
import org.apache.poi.hmef.attribute.MAPIRtfAttribute;
@@ -83,10 +84,10 @@ public final class TestHMEFMessage {
assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_MAPIPROPERTIES));
// Check the order
- assertEquals(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty());
- assertEquals(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty());
- assertEquals(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty());
- assertEquals(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty());
+ assertSame(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty());
+ assertSame(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty());
+ assertSame(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty());
+ assertSame(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty());
// Check some that aren't there
assertNull(msg.getMessageAttribute(TNEFProperty.ID_AIDOWNER));
@@ -168,7 +169,7 @@ public final class TestHMEFMessage {
@Test
void testNoData() throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
// Header
LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out);
@@ -176,16 +177,14 @@ public final class TestHMEFMessage {
// field
LittleEndian.putUShort(0, out);
- byte[] bytes = out.toByteArray();
- InputStream str = new ByteArrayInputStream(bytes);
- HMEFMessage msg = new HMEFMessage(str);
+ HMEFMessage msg = new HMEFMessage(out.toInputStream());
assertNull(msg.getSubject());
assertNull(msg.getBody());
}
@Test
void testInvalidLevel() throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
// Header
LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out);
@@ -196,10 +195,9 @@ public final class TestHMEFMessage {
// invalid level
LittleEndian.putUShort(90, out);
- InputStream str = new ByteArrayInputStream(out.toByteArray());
IllegalStateException ex = assertThrows(
IllegalStateException.class,
- () -> new HMEFMessage(str)
+ () -> new HMEFMessage(out.toInputStream())
);
assertEquals("Unhandled level 90", ex.getMessage());
}
@@ -226,7 +224,7 @@ public final class TestHMEFMessage {
MAPIStringAttribute propE28b = (MAPIStringAttribute)msg.getMessageMAPIAttribute(propE28);
assertNotNull(propE28b);
- assertEquals(MAPIStringAttribute.class, propE28b.getClass());
+ assertSame(MAPIStringAttribute.class, propE28b.getClass());
assertEquals("Zimbra - Mark Rogers", propE28b.getDataString().substring(10));
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java
index a24901a96d..49ef65cb83 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java
@@ -28,7 +28,7 @@ import java.io.File;
import java.io.PrintStream;
import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.Test;
public class TestHMEFDumper {
@@ -38,13 +38,13 @@ public class TestHMEFDumper {
}
@Test
- void main() throws Exception {
+ void main() {
File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat");
assertDoesNotThrow(() -> doMain(file.getAbsolutePath()));
}
@Test
- void mainFull() throws Exception {
+ void mainFull() {
File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat");
assertDoesNotThrow(() -> doMain("--full", file.getAbsolutePath()));
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java
index 4a786f5bca..81912bbba5 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java
@@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Test;
@@ -62,13 +62,13 @@ public class TestHMEFContentsExtractor {
POIDataSamples samples = POIDataSamples.getHMEFInstance();
File winmailTNEFFile = samples.getFile("quick-winmail.dat");
HMEFContentsExtractor extractor = new HMEFContentsExtractor(winmailTNEFFile);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- extractor.extractMessageBody(out);
- assertTrue(out.size() > 0);
- byte[] expectedMagic = new byte[] { '{', '\\', 'r', 't', 'f' };
- byte[] magic = Arrays.copyOf(out.toByteArray(), 5);
- assertArrayEquals(expectedMagic, magic, "RTF magic number");
- out.close();
+ try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
+ extractor.extractMessageBody(out);
+ assertTrue(out.size() > 0);
+ byte[] expectedMagic = new byte[]{'{', '\\', 'r', 't', 'f'};
+ byte[] magic = Arrays.copyOf(out.toByteArray(), 5);
+ assertArrayEquals(expectedMagic, magic, "RTF magic number");
+ }
}
@Test
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java
index 82b3a46091..9a08f18eb6 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java
@@ -17,12 +17,11 @@
package org.apache.poi.hslf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
@@ -50,32 +49,30 @@ public class HSLFTestDataSamples {
}
/**
- * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back
+ * Writes a slideshow to a {@code UnsynchronizedByteArrayOutputStream} and reads it back
* from a {@code ByteArrayInputStream}.
* Useful for verifying that the serialisation round trip
*/
public static HSLFSlideShowImpl writeOutAndReadBack(HSLFSlideShowImpl original) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
original.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- return new HSLFSlideShowImpl(bais);
+ try (InputStream is = baos.toInputStream()) {
+ return new HSLFSlideShowImpl(is);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
- * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back
+ * Writes a slideshow to a {@code UnsynchronizedByteArrayOutputStream} and reads it back
* from a {@code ByteArrayInputStream}.
* Useful for verifying that the serialisation round trip
*/
public static HSLFSlideShow writeOutAndReadBack(HSLFSlideShow original) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) {
original.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- return new HSLFSlideShow(bais);
+ return new HSLFSlideShow(baos.toInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java
index 774b1fb91b..2d795452b9 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java
@@ -21,22 +21,18 @@
package org.apache.poi.hslf;
+import static org.apache.poi.POIDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import org.apache.poi.POIDataSamples;
import org.apache.poi.POIDocument;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
@@ -47,23 +43,11 @@ import org.junit.jupiter.api.Test;
* which are part of the scratchpad (not main)
*/
public final class TestPOIDocumentScratchpad {
- // The POI Documents to work on
- private POIDocument doc;
- private POIDocument doc2;
-
- /**
- * Set things up, using a PowerPoint document and
- * a Word Document for our testing
- */
- @BeforeEach
- void setUp() throws IOException {
- doc = new HSLFSlideShowImpl(POIDataSamples.getSlideShowInstance().openResourceAsStream("basic_test_ppt_file.ppt"));
- doc2 = HWPFTestDataSamples.openSampleFile("test2.doc");
- }
-
@Test
- void testReadProperties() {
- testReadPropertiesHelper(doc);
+ void testReadProperties() throws IOException {
+ try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt")) {
+ testReadPropertiesHelper(doc);
+ }
}
private void testReadPropertiesHelper(POIDocument docPH) {
@@ -77,49 +61,46 @@ public final class TestPOIDocumentScratchpad {
}
@Test
- void testReadProperties2() {
- // Check again on the word one
- assertNotNull(doc2.getDocumentSummaryInformation());
- assertNotNull(doc2.getSummaryInformation());
-
- assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor());
- assertEquals("", doc2.getSummaryInformation().getKeywords());
- assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
+ void testReadProperties2() throws IOException {
+ try (POIDocument doc2 = HWPFTestDataSamples.openSampleFile("test2.doc")) {
+ // Check again on the word one
+ assertNotNull(doc2.getDocumentSummaryInformation());
+ assertNotNull(doc2.getSummaryInformation());
+
+ assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor());
+ assertEquals("", doc2.getSummaryInformation().getKeywords());
+ assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
+ }
}
@Test
void testWriteProperties() throws IOException {
// Just check we can write them back out into a filesystem
- POIFSFileSystem outFS = new POIFSFileSystem();
- doc.writeProperties(outFS);
-
- // Should now hold them
- assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
- assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME));
- outFS.close();
+ try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt");
+ POIFSFileSystem outFS = new POIFSFileSystem()) {
+ doc.writeProperties(outFS);
+
+ // Should now hold them
+ assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
+ assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME));
+ }
}
@Test
void testWriteReadProperties() throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// Write them out
- POIFSFileSystem outFS = new POIFSFileSystem();
- doc.writeProperties(outFS);
- outFS.writeFilesystem(baos);
-
- // Create a new version
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- POIFSFileSystem inFS = new POIFSFileSystem(bais);
-
- // Check they're still there
- POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS);
- ppt.readProperties();
-
- // Delegate test
- testReadPropertiesHelper(ppt);
-
- ppt.close();
- inFS.close();
+ try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt");
+ POIFSFileSystem outFS = new POIFSFileSystem()) {
+ doc.writeProperties(outFS);
+
+ // Check they're still there
+ try (POIFSFileSystem inFS = writeOutAndReadBack(outFS);
+ POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS)) {
+ ppt.readProperties();
+
+ // Delegate test
+ testReadPropertiesHelper(ppt);
+ }
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java
index 5aec58964a..687888a69a 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java
@@ -25,12 +25,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
@@ -56,7 +55,7 @@ public final class TestReWrite {
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(pfs)) {
// Write out to a byte array, and to a temp file
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
hss.write(baos);
final File file = TempFile.createTempFile("TestHSLF", ".ppt");
@@ -66,8 +65,7 @@ public final class TestReWrite {
// Build an input stream of it, and read back as a POIFS from the stream
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- try (POIFSFileSystem npfS = new POIFSFileSystem(bais);
+ try (POIFSFileSystem npfS = new POIFSFileSystem(baos.toInputStream());
// And the same on the temp file
POIFSFileSystem npfF = new POIFSFileSystem(file)) {
@@ -97,18 +95,16 @@ public final class TestReWrite {
assertNotNull(pfsC.getRoot().getEntry("Macros"));
// Write out normally, will loose the macro stream
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
hssC.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- try (POIFSFileSystem pfsNew = new POIFSFileSystem(bais)) {
+ try (POIFSFileSystem pfsNew = new POIFSFileSystem(baos.toInputStream())) {
assertFalse(pfsNew.getRoot().hasEntry("Macros"));
}
// But if we write out with nodes preserved, will be there
baos.reset();
hssC.write(baos, true);
- bais = new ByteArrayInputStream(baos.toByteArray());
- try (POIFSFileSystem pfsNew = new POIFSFileSystem(bais)) {
+ try (POIFSFileSystem pfsNew = new POIFSFileSystem(baos.toInputStream())) {
assertTrue(pfsNew.getRoot().hasEntry("Macros"));
}
}
@@ -138,14 +134,11 @@ public final class TestReWrite {
assertDoesNotThrow(ss::getNotes);
// Now write out to a byte array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
hss.write(baos);
- // Build an input stream of it
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-
// Use POIFS to query that lot
- try (POIFSFileSystem npfs = new POIFSFileSystem(bais)) {
+ try (POIFSFileSystem npfs = new POIFSFileSystem(baos.toInputStream())) {
assertSame(pfs, npfs);
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java
index 3aca727bee..b2991c1533 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java
@@ -18,14 +18,15 @@
package org.apache.poi.hslf;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
import static org.apache.poi.POITestCase.assertContains;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
+import org.apache.commons.io.output.CountingOutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.record.CurrentUserAtom;
import org.apache.poi.hslf.record.PersistPtrHolder;
@@ -63,55 +64,50 @@ public final class TestReWriteSanity {
@Test
void testUserEditAtomsRight() throws Exception {
// Write out to a byte array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ss.write(baos);
- // Build an input stream of it
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-
// Create a new one from that
- HSLFSlideShowImpl wss = new HSLFSlideShowImpl(bais);
-
- // Find the location of the PersistPtrIncrementalBlocks and
- // UserEditAtoms
- Record[] r = wss.getRecords();
- Map pp = new HashMap<>();
- Map ue = new HashMap<>();
- ue.put(Integer.valueOf(0),Integer.valueOf(0)); // Will show 0 if first
- int pos = 0;
- int lastUEPos = -1;
-
- for (final Record rec : r) {
- if(rec instanceof PersistPtrHolder) {
- pp.put(Integer.valueOf(pos), rec);
- }
- if(rec instanceof UserEditAtom) {
- ue.put(Integer.valueOf(pos), rec);
- lastUEPos = pos;
+ try (HSLFSlideShowImpl wss = new HSLFSlideShowImpl(baos.toInputStream())) {
+
+ // Find the location of the PersistPtrIncrementalBlocks and
+ // UserEditAtoms
+ Record[] r = wss.getRecords();
+ Map pp = new HashMap<>();
+ Map ue = new HashMap<>();
+ ue.put(0, 0); // Will show 0 if first
+ int lastUEPos = -1;
+
+ CountingOutputStream cos = new CountingOutputStream(NULL_OUTPUT_STREAM);
+ for (final Record rec : r) {
+ int pos = cos.getCount();
+ if (rec instanceof PersistPtrHolder) {
+ pp.put(pos, rec);
+ }
+ if (rec instanceof UserEditAtom) {
+ ue.put(pos, rec);
+ lastUEPos = pos;
+ }
+
+ rec.writeOut(cos);
}
- ByteArrayOutputStream bc = new ByteArrayOutputStream();
- rec.writeOut(bc);
- pos += bc.size();
- }
-
- // Check that the UserEditAtom's point to right stuff
- for (final Record rec : r) {
- if(rec instanceof UserEditAtom) {
- UserEditAtom uea = (UserEditAtom)rec;
- int luPos = uea.getLastUserEditAtomOffset();
- int ppPos = uea.getPersistPointersOffset();
+ // Check that the UserEditAtom's point to right stuff
+ for (final Record rec : r) {
+ if (rec instanceof UserEditAtom) {
+ UserEditAtom uea = (UserEditAtom) rec;
+ int luPos = uea.getLastUserEditAtomOffset();
+ int ppPos = uea.getPersistPointersOffset();
- assertContains(ue, Integer.valueOf(luPos));
- assertContains(pp, Integer.valueOf(ppPos));
+ assertContains(ue, luPos);
+ assertContains(pp, ppPos);
+ }
}
- }
-
- // Check that the CurrentUserAtom points to the right UserEditAtom
- CurrentUserAtom cua = wss.getCurrentUserAtom();
- int listedUEPos = (int)cua.getCurrentEditOffset();
- assertEquals(lastUEPos,listedUEPos);
- wss.close();
+ // Check that the CurrentUserAtom points to the right UserEditAtom
+ CurrentUserAtom cua = wss.getCurrentUserAtom();
+ int listedUEPos = (int) cua.getCurrentEditOffset();
+ assertEquals(lastUEPos, listedUEPos);
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java
index 980d6538e8..ca5b1ac380 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java
@@ -34,7 +34,7 @@ import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException;
import org.apache.poi.hslf.exceptions.OldPowerPointFormatException;
import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.parallel.Isolated;
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java
index 8ee2010fa7..3ac7adb84d 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java
@@ -23,7 +23,7 @@ import java.io.IOException;
import java.io.PrintStream;
import org.apache.poi.EmptyFileException;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java
index bd8d634b12..5525cdf808 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java
@@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -35,7 +34,6 @@ import java.util.List;
import com.zaxxer.sparsebits.SparseBitSet;
import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.binary.Hex;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFObjectShape;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
@@ -50,7 +48,6 @@ import org.apache.poi.sl.usermodel.ObjectShape;
import org.apache.poi.sl.usermodel.SlideShow;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.util.IOUtils;
-import org.apache.poi.util.NullOutputStream;
import org.junit.jupiter.api.Test;
/**
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java
index a90c591190..336f6bc4f2 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java
@@ -22,9 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFPictureData;
import org.apache.poi.hslf.usermodel.HSLFSlide;
@@ -33,11 +32,11 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.junit.jupiter.api.Test;
/**
- * Test MovieShape
object.
+ * Test {@code MovieShape} object.
*/
public final class TestMovieShape {
- private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
+ private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
@Test
void testCreate() throws Exception {
@@ -58,10 +57,10 @@ public final class TestMovieShape {
shape.setAutoPlay(false);
assertFalse(shape.isAutoPlay());
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
ppt.write(out);
- ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()));
+ ppt = new HSLFSlideShow(out.toInputStream());
slide = ppt.getSlides().get(0);
shape = (MovieShape)slide.getShapes().get(0);
assertEquals(path, shape.getPath());
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java
index 9c561fb18e..dbab7b9fdc 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java
@@ -21,13 +21,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFObjectData;
import org.apache.poi.hslf.usermodel.HSLFObjectShape;
@@ -146,10 +145,10 @@ public final class TestOleEmbedding {
slide2.addShape(oleShape2);
oleShape2.setAnchor(new Rectangle2D.Double(100,100,100,100));
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
ppt.write(bos);
- ppt = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray()));
+ ppt = new HSLFSlideShow(bos.toInputStream());
HSLFObjectShape comp = (HSLFObjectShape)ppt.getSlides().get(0).getShapes().get(0);
byte[] compData = IOUtils.toByteArray(comp.getObjectData().getInputStream());
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java
index e47467c2ba..426eee09fb 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java
@@ -17,12 +17,16 @@
package org.apache.poi.hslf.model;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-
-import org.apache.poi.hslf.usermodel.*;
+import org.apache.poi.hslf.usermodel.HSLFSlide;
+import org.apache.poi.hslf.usermodel.HSLFSlideShow;
+import org.apache.poi.hslf.usermodel.HSLFTextBox;
+import org.apache.poi.hslf.usermodel.HSLFTextRun;
import org.junit.jupiter.api.Test;
/**
@@ -35,46 +39,46 @@ public final class TestSetBoldItalic {
*/
@Test
void testTextBoxWrite() throws Exception {
- HSLFSlideShow ppt = new HSLFSlideShow();
- HSLFSlide sl = ppt.createSlide();
- HSLFTextRun rt;
-
- String val = "Hello, World!";
+ try (HSLFSlideShow ppt = new HSLFSlideShow()) {
+ HSLFSlide sl = ppt.createSlide();
+ HSLFTextRun rt;
- // Create a new textbox, and give it lots of properties
- HSLFTextBox txtbox = new HSLFTextBox();
- rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
- txtbox.setText(val);
- rt.setFontSize(42d);
- rt.setBold(true);
- rt.setItalic(true);
- rt.setUnderlined(false);
- sl.addShape(txtbox);
+ String val = "Hello, World!";
- // Check it before save
- rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
- assertEquals(val, rt.getRawText());
- assertEquals(42, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isItalic());
+ // Create a new textbox, and give it lots of properties
+ HSLFTextBox txtbox = new HSLFTextBox();
+ rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+ txtbox.setText(val);
+ rt.setFontSize(42d);
+ rt.setBold(true);
+ rt.setItalic(true);
+ rt.setUnderlined(false);
+ sl.addShape(txtbox);
- // Serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
+ // Check it before save
+ rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+ assertEquals(val, rt.getRawText());
+ assertNotNull(rt.getFontSize());
+ assertEquals(42, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isItalic());
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
- sl = ppt.getSlides().get(0);
+ // Serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) {
+ sl = ppt2.getSlides().get(0);
- txtbox = (HSLFTextBox)sl.getShapes().get(0);
- rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+ txtbox = (HSLFTextBox) sl.getShapes().get(0);
+ rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
- // Check after save
- assertEquals(val, rt.getRawText());
- assertEquals(42, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isItalic());
- assertFalse(rt.isUnderlined());
+ // Check after save
+ assertEquals(val, rt.getRawText());
+ assertNotNull(rt.getFontSize());
+ assertEquals(42, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isItalic());
+ assertFalse(rt.isUnderlined());
+ }
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java
index 774fe06468..84af931507 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java
@@ -17,6 +17,9 @@
package org.apache.poi.hslf.model;
+import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow;
+import static org.apache.poi.hslf.HSLFTestDataSamples.openSampleFileStream;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -27,14 +30,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
-import org.apache.poi.POIDataSamples;
import org.apache.poi.ddf.AbstractEscherOptRecord;
import org.apache.poi.ddf.EscherDgRecord;
import org.apache.poi.ddf.EscherDggRecord;
@@ -56,68 +55,52 @@ import org.apache.poi.hslf.usermodel.HSLFTextShape;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.sl.usermodel.StrokeStyle.LineDash;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
/**
* Test drawing shapes via Graphics2D
*/
public final class TestShapes {
- private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
-
- private HSLFSlideShow ppt;
- private HSLFSlideShow pptB;
-
- @BeforeEach
- void setUp() throws Exception {
- try (InputStream is1 = _slTests.openResourceAsStream("empty.ppt");
- InputStream is2 = _slTests.openResourceAsStream("empty_textbox.ppt")) {
- ppt = new HSLFSlideShow(is1);
- pptB = new HSLFSlideShow(is2);
- }
- }
-
@Test
void graphics() throws IOException {
- HSLFSlide slide = ppt.createSlide();
-
- HSLFLine line = new HSLFLine();
- java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60);
- line.setAnchor(lineAnchor);
- line.setLineWidth(3);
- line.setLineDash(LineDash.DASH);
- line.setLineColor(Color.red);
- slide.addShape(line);
-
- HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE);
- Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111);
- ellipse.setAnchor(ellipseAnchor);
- ellipse.setLineWidth(2);
- ellipse.setLineDash(LineDash.SOLID);
- ellipse.setLineColor(Color.green);
- ellipse.setFillColor(Color.lightGray);
- slide.addShape(ellipse);
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- //read ppt from byte array
-
- HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()));
- assertEquals(1, ppt2.getSlides().size());
-
- slide = ppt2.getSlides().get(0);
- List shape = slide.getShapes();
- assertEquals(2, shape.size());
-
- assertTrue(shape.get(0) instanceof HSLFLine); //group shape
- assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape
+ try (HSLFSlideShow ppt = getSlideShow("empty.ppt")) {
+ HSLFSlide slide = ppt.createSlide();
+
+ HSLFLine line = new HSLFLine();
+ java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60);
+ line.setAnchor(lineAnchor);
+ line.setLineWidth(3);
+ line.setLineDash(LineDash.DASH);
+ line.setLineColor(Color.red);
+ slide.addShape(line);
+
+ HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE);
+ Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111);
+ ellipse.setAnchor(ellipseAnchor);
+ ellipse.setLineWidth(2);
+ ellipse.setLineDash(LineDash.SOLID);
+ ellipse.setLineColor(Color.green);
+ ellipse.setFillColor(Color.lightGray);
+ slide.addShape(ellipse);
+
+ //read ppt from byte array
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) {
+ assertEquals(1, ppt2.getSlides().size());
+
+ slide = ppt2.getSlides().get(0);
+ List shape = slide.getShapes();
+ assertEquals(2, shape.size());
+
+ assertTrue(shape.get(0) instanceof HSLFLine); //group shape
+ assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape
+
+ assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape
+ assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape
- assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape
- assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape
-
- ppt2.close();
+ }
+ }
}
/**
@@ -125,40 +108,41 @@ public final class TestShapes {
*/
@Test
void textBoxRead() throws IOException {
- ppt = new HSLFSlideShow(_slTests.openResourceAsStream("with_textbox.ppt"));
- HSLFSlide sl = ppt.getSlides().get(0);
- for (HSLFShape sh : sl.getShapes()) {
- assertTrue(sh instanceof HSLFTextBox);
- HSLFTextBox txtbox = (HSLFTextBox)sh;
- String text = txtbox.getText();
- assertNotNull(text);
-
- assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1);
- HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
-
- switch (text) {
- case "Hello, World!!!":
- assertNotNull(rt.getFontSize());
- assertEquals(32, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isItalic());
- break;
- case "I am just a poor boy":
- assertNotNull(rt.getFontSize());
- assertEquals(44, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- break;
- case "This is Times New Roman":
- assertNotNull(rt.getFontSize());
- assertEquals(16, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isItalic());
- assertTrue(rt.isUnderlined());
- break;
- case "Plain Text":
- assertNotNull(rt.getFontSize());
- assertEquals(18, rt.getFontSize(), 0);
- break;
+ try (HSLFSlideShow ppt = getSlideShow("with_textbox.ppt")) {
+ HSLFSlide sl = ppt.getSlides().get(0);
+ for (HSLFShape sh : sl.getShapes()) {
+ assertTrue(sh instanceof HSLFTextBox);
+ HSLFTextBox txtbox = (HSLFTextBox) sh;
+ String text = txtbox.getText();
+ assertNotNull(text);
+
+ assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1);
+ HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+
+ switch (text) {
+ case "Hello, World!!!":
+ assertNotNull(rt.getFontSize());
+ assertEquals(32, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isItalic());
+ break;
+ case "I am just a poor boy":
+ assertNotNull(rt.getFontSize());
+ assertEquals(44, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ break;
+ case "This is Times New Roman":
+ assertNotNull(rt.getFontSize());
+ assertEquals(16, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isItalic());
+ assertTrue(rt.isUnderlined());
+ break;
+ case "Plain Text":
+ assertNotNull(rt.getFontSize());
+ assertEquals(18, rt.getFontSize(), 0);
+ break;
+ }
}
}
}
@@ -166,43 +150,42 @@ public final class TestShapes {
@SuppressWarnings("unused")
@Test
void testParagraphs() throws IOException {
- HSLFSlideShow ss = new HSLFSlideShow();
- HSLFSlide slide = ss.createSlide();
- HSLFTextBox shape = new HSLFTextBox();
- HSLFTextRun p1r1 = shape.setText("para 1 run 1. ");
- HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false);
- HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true);
- HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false);
- p1r1.setFontColor(Color.black);
- p1r2.setFontColor(Color.red);
- p2r1.setFontColor(Color.yellow);
- p2r2.setStrikethrough(true);
- // run 3 has same text properties as run 2 and will be merged when saving
- HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false);
- shape.setAnchor(new Rectangle2D.Double(100,100,100,10));
- slide.addShape(shape);
- shape.resizeToFitText();
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ss.write(bos);
-
- ss = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray()));
- slide = ss.getSlides().get(0);
- HSLFTextBox tb = (HSLFTextBox)slide.getShapes().get(0);
- List para = tb.getTextParagraphs();
- HSLFTextRun tr = para.get(0).getTextRuns().get(0);
- assertEquals("para 1 run 1. ", tr.getRawText());
- assertEquals(Color.black, getColor(tr.getFontColor()));
- tr = para.get(0).getTextRuns().get(1);
- assertEquals("para 1 run 2.\r", tr.getRawText());
- assertEquals(Color.red, getColor(tr.getFontColor()));
- tr = para.get(1).getTextRuns().get(0);
- assertEquals("para 2 run 1. ", tr.getRawText());
- assertEquals(Color.yellow, getColor(tr.getFontColor()));
- tr = para.get(1).getTextRuns().get(1);
- assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText());
- assertEquals(Color.black, getColor(tr.getFontColor()));
- assertTrue(tr.isStrikethrough());
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ HSLFSlide slide = ppt1.createSlide();
+ HSLFTextBox shape = new HSLFTextBox();
+ HSLFTextRun p1r1 = shape.setText("para 1 run 1. ");
+ HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false);
+ HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true);
+ HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false);
+ p1r1.setFontColor(Color.black);
+ p1r2.setFontColor(Color.red);
+ p2r1.setFontColor(Color.yellow);
+ p2r2.setStrikethrough(true);
+ // run 3 has same text properties as run 2 and will be merged when saving
+ HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false);
+ shape.setAnchor(new Rectangle2D.Double(100, 100, 100, 10));
+ slide.addShape(shape);
+ shape.resizeToFitText();
+
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ slide = ppt2.getSlides().get(0);
+ HSLFTextBox tb = (HSLFTextBox) slide.getShapes().get(0);
+ List para = tb.getTextParagraphs();
+ HSLFTextRun tr = para.get(0).getTextRuns().get(0);
+ assertEquals("para 1 run 1. ", tr.getRawText());
+ assertEquals(Color.black, getColor(tr.getFontColor()));
+ tr = para.get(0).getTextRuns().get(1);
+ assertEquals("para 1 run 2.\r", tr.getRawText());
+ assertEquals(Color.red, getColor(tr.getFontColor()));
+ tr = para.get(1).getTextRuns().get(0);
+ assertEquals("para 2 run 1. ", tr.getRawText());
+ assertEquals(Color.yellow, getColor(tr.getFontColor()));
+ tr = para.get(1).getTextRuns().get(1);
+ assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText());
+ assertEquals(Color.black, getColor(tr.getFontColor()));
+ assertTrue(tr.isStrikethrough());
+ }
+ }
}
@@ -212,169 +195,158 @@ public final class TestShapes {
*/
@Test
void textBoxWriteBytes() throws IOException {
- ppt = new HSLFSlideShow();
- HSLFSlide sl = ppt.createSlide();
- HSLFTextRun rt;
-
- String val = "Hello, World!";
-
- // Create a new textbox, and give it lots of properties
- HSLFTextBox txtbox = new HSLFTextBox();
- rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
- txtbox.setText(val);
- rt.setFontFamily("Arial");
- rt.setFontSize(42d);
- rt.setBold(true);
- rt.setItalic(true);
- rt.setUnderlined(false);
- rt.setFontColor(Color.red);
- sl.addShape(txtbox);
-
- // Check it before save
- rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
- assertEquals(val, rt.getRawText());
- assertNotNull(rt.getFontSize());
- assertEquals(42, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isItalic());
- assertFalse(rt.isUnderlined());
- assertEquals("Arial", rt.getFontFamily());
- assertEquals(Color.red, getColor(rt.getFontColor()));
-
- // Serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()));
- sl = ppt2.getSlides().get(0);
-
- txtbox = (HSLFTextBox)sl.getShapes().get(0);
- rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
-
- // Check after save
- assertEquals(val, rt.getRawText());
- assertNotNull(rt.getFontSize());
- assertEquals(42, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isItalic());
- assertFalse(rt.isUnderlined());
- assertEquals("Arial", rt.getFontFamily());
- assertEquals(Color.red, getColor(rt.getFontColor()));
-
- ppt2.close();
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ HSLFSlide sl = ppt1.createSlide();
+
+ String val = "Hello, World!";
+
+ // Create a new textbox, and give it lots of properties
+ HSLFTextBox txtbox = new HSLFTextBox();
+ HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+ txtbox.setText(val);
+ rt.setFontFamily("Arial");
+ rt.setFontSize(42d);
+ rt.setBold(true);
+ rt.setItalic(true);
+ rt.setUnderlined(false);
+ rt.setFontColor(Color.red);
+ sl.addShape(txtbox);
+
+ // Check it before save
+ rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+ assertEquals(val, rt.getRawText());
+ assertNotNull(rt.getFontSize());
+ assertEquals(42, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isItalic());
+ assertFalse(rt.isUnderlined());
+ assertEquals("Arial", rt.getFontFamily());
+ assertEquals(Color.red, getColor(rt.getFontColor()));
+
+ // Serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ sl = ppt2.getSlides().get(0);
+
+ txtbox = (HSLFTextBox) sl.getShapes().get(0);
+ rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0);
+
+ // Check after save
+ assertEquals(val, rt.getRawText());
+ assertNotNull(rt.getFontSize());
+ assertEquals(42, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isItalic());
+ assertFalse(rt.isUnderlined());
+ assertEquals("Arial", rt.getFontFamily());
+ assertEquals(Color.red, getColor(rt.getFontColor()));
+ }
+ }
}
/**
* Test with an empty text box
*/
@Test
- void emptyTextBox() {
- assertEquals(2, pptB.getSlides().size());
- HSLFSlide s1 = pptB.getSlides().get(0);
- HSLFSlide s2 = pptB.getSlides().get(1);
-
- // Check we can get the shapes count
- assertEquals(2, s1.getShapes().size());
- assertEquals(2, s2.getShapes().size());
+ void emptyTextBox() throws IOException {
+ try (HSLFSlideShow ppt = getSlideShow("empty_textbox.ppt")) {
+ assertEquals(2, ppt.getSlides().size());
+ HSLFSlide s1 = ppt.getSlides().get(0);
+ HSLFSlide s2 = ppt.getSlides().get(1);
+
+ // Check we can get the shapes count
+ assertEquals(2, s1.getShapes().size());
+ assertEquals(2, s2.getShapes().size());
+ }
}
/**
* If you iterate over text shapes in a slide and collect them in a set
* it must be the same as returned by Slide.getTextRuns().
*/
- @Test
- void textBoxSet() throws IOException {
- textBoxSet("with_textbox.ppt");
- textBoxSet("basic_test_ppt_file.ppt");
- textBoxSet("next_test_ppt_file.ppt");
- textBoxSet("Single_Coloured_Page.ppt");
- textBoxSet("Single_Coloured_Page_With_Fonts_and_Alignments.ppt");
- textBoxSet("incorrect_slide_order.ppt");
- }
-
- private void textBoxSet(String filename) throws IOException {
- HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(filename));
- for (HSLFSlide sld : ss.getSlides()) {
- ArrayList lst1 = new ArrayList<>();
- for (List txt : sld.getTextParagraphs()) {
- for (HSLFTextParagraph p : txt) {
- for (HSLFTextRun r : p) {
- lst1.add(r.getRawText());
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "with_textbox.ppt",
+ "basic_test_ppt_file.ppt",
+ "next_test_ppt_file.ppt",
+ "Single_Coloured_Page.ppt",
+ "Single_Coloured_Page_With_Fonts_and_Alignments.ppt",
+ "incorrect_slide_order.ppt"
+ })
+ void textBoxSet(String filename) throws IOException {
+ try (HSLFSlideShow ppt = getSlideShow(filename)) {
+ for (HSLFSlide sld : ppt.getSlides()) {
+ ArrayList lst1 = new ArrayList<>();
+ for (List txt : sld.getTextParagraphs()) {
+ for (HSLFTextParagraph p : txt) {
+ for (HSLFTextRun r : p) {
+ lst1.add(r.getRawText());
+ }
}
}
- }
- ArrayList lst2 = new ArrayList<>();
- for (HSLFShape sh : sld.getShapes()) {
- if (sh instanceof HSLFTextShape){
- HSLFTextShape tbox = (HSLFTextShape)sh;
- for (HSLFTextParagraph p : tbox.getTextParagraphs()) {
- for (HSLFTextRun r : p) {
- lst2.add(r.getRawText());
+ ArrayList lst2 = new ArrayList<>();
+ for (HSLFShape sh : sld.getShapes()) {
+ if (sh instanceof HSLFTextShape) {
+ HSLFTextShape tbox = (HSLFTextShape) sh;
+ for (HSLFTextParagraph p : tbox.getTextParagraphs()) {
+ for (HSLFTextRun r : p) {
+ lst2.add(r.getRawText());
+ }
}
}
}
+ assertTrue(lst1.containsAll(lst2));
+ assertTrue(lst2.containsAll(lst1));
}
- assertTrue(lst1.containsAll(lst2));
- assertTrue(lst2.containsAll(lst1));
}
- ss.close();
}
/**
- * Test adding shapes to ShapeGroup
+ * Test adding shapes to {@code ShapeGroup}
*/
@Test
void shapeGroup() throws IOException {
- HSLFSlideShow ss = new HSLFSlideShow();
-
- HSLFSlide slide = ss.createSlide();
- Dimension pgsize = ss.getPageSize();
-
- HSLFGroupShape group = new HSLFGroupShape();
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
- group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight()));
- slide.addShape(group);
+ HSLFSlide slide = ppt1.createSlide();
+ Dimension pgsize = ppt1.getPageSize();
- HSLFPictureData data = ss.addPicture(_slTests.readFile("clock.jpg"), PictureType.JPEG);
- HSLFPictureShape pict = new HSLFPictureShape(data, group);
- pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200));
- group.addShape(pict);
+ HSLFGroupShape group = new HSLFGroupShape();
- HSLFLine line = new HSLFLine(group);
- line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0));
- group.addShape(line);
+ group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight()));
+ slide.addShape(group);
- //serialize and read again.
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ss.write(out);
- out.close();
- ss.close();
+ HSLFPictureData data = ppt1.addPicture(openSampleFileStream("clock.jpg"), PictureType.JPEG);
+ HSLFPictureShape pict = new HSLFPictureShape(data, group);
+ pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200));
+ group.addShape(pict);
- ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
- ss = new HSLFSlideShow(is);
- is.close();
+ HSLFLine line = new HSLFLine(group);
+ line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0));
+ group.addShape(line);
- slide = ss.getSlides().get(0);
+ //serialize and read again.
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
- List shape = slide.getShapes();
- assertEquals(1, shape.size());
- assertTrue(shape.get(0) instanceof HSLFGroupShape);
+ slide = ppt2.getSlides().get(0);
- group = (HSLFGroupShape)shape.get(0);
- List grshape = group.getShapes();
- assertEquals(2, grshape.size());
- assertTrue(grshape.get(0) instanceof HSLFPictureShape);
- assertTrue(grshape.get(1) instanceof HSLFLine);
+ List shape = slide.getShapes();
+ assertEquals(1, shape.size());
+ assertTrue(shape.get(0) instanceof HSLFGroupShape);
- pict = (HSLFPictureShape)grshape.get(0);
- assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor());
+ group = (HSLFGroupShape) shape.get(0);
+ List grshape = group.getShapes();
+ assertEquals(2, grshape.size());
+ assertTrue(grshape.get(0) instanceof HSLFPictureShape);
+ assertTrue(grshape.get(1) instanceof HSLFLine);
- line = (HSLFLine)grshape.get(1);
- assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor());
+ pict = (HSLFPictureShape) grshape.get(0);
+ assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor());
- ss.close();
+ line = (HSLFLine) grshape.get(1);
+ assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor());
+ }
+ }
}
/**
@@ -382,29 +354,24 @@ public final class TestShapes {
*/
@Test
void removeShapes() throws IOException {
- String file = "with_textbox.ppt";
- HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(file));
- HSLFSlide sl = ss.getSlides().get(0);
- List sh = sl.getShapes();
- assertEquals(4, sh.size(), "expected four shaped in " + file);
- //remove all
- for (int i = 0; i < sh.size(); i++) {
- boolean ok = sl.removeShape(sh.get(i));
- assertTrue(ok, "Failed to delete shape #" + i);
+ try (HSLFSlideShow ppt1 = getSlideShow("with_textbox.ppt")) {
+ HSLFSlide sl = ppt1.getSlides().get(0);
+ List sh = sl.getShapes();
+ assertEquals(4, sh.size());
+ //remove all
+ for (int i = 0; i < sh.size(); i++) {
+ boolean ok = sl.removeShape(sh.get(i));
+ assertTrue(ok, "Failed to delete shape #" + i);
+ }
+ //now Slide.getShapes() should return an empty array
+ assertEquals(0, sl.getShapes().size());
+
+ //serialize and read again. The file should be readable and contain no shapes
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ sl = ppt2.getSlides().get(0);
+ assertEquals(0, sl.getShapes().size());
+ }
}
- //now Slide.getShapes() should return an empty array
- assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file);
-
- //serialize and read again. The file should be readable and contain no shapes
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ss.write(out);
- out.close();
- ss.close();
-
- ss = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()));
- sl = ss.getSlides().get(0);
- assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file);
- ss.close();
}
@Test
@@ -424,79 +391,78 @@ public final class TestShapes {
@Test
void shapeId() throws IOException {
- HSLFSlideShow ss = new HSLFSlideShow();
- HSLFSlide slide = ss.createSlide();
-
- //EscherDgg is a document-level record which keeps track of the drawing groups
- EscherDggRecord dgg = ss.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord();
- EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord();
-
- int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt
- int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId
-
- int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide
- int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide
- //insert 3 shapes and make sure the Ids are properly incremented
- for (int i = 0; i < 3; i++) {
- HSLFShape shape = new HSLFLine();
- assertEquals(0, shape.getShapeId());
- slide.addShape(shape);
- assertTrue(shape.getShapeId() > 0);
-
- //check that EscherDgRecord is updated
- assertEquals(shape.getShapeId(), dg.getLastMSOSPID());
- assertEquals(dgMaxId + 1, dg.getLastMSOSPID());
- assertEquals(dgShapesUsed + 1, dg.getNumShapes());
-
- //check that EscherDggRecord is updated
- assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @"+i);
- assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @"+i);
- assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @"+i);
-
- dggShapesUsed = dgg.getNumShapesSaved();
- dggMaxId = dgg.getShapeIdMax();
- dgMaxId = dg.getLastMSOSPID();
- dgShapesUsed = dg.getNumShapes();
- }
+ try (HSLFSlideShow ppt = new HSLFSlideShow()) {
+ HSLFSlide slide = ppt.createSlide();
+
+ //EscherDgg is a document-level record which keeps track of the drawing groups
+ EscherDggRecord dgg = ppt.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord();
+ EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord();
+
+ int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt
+ int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId
+
+ int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide
+ int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide
+ //insert 3 shapes and make sure the Ids are properly incremented
+ for (int i = 0; i < 3; i++) {
+ HSLFShape shape = new HSLFLine();
+ assertEquals(0, shape.getShapeId());
+ slide.addShape(shape);
+ assertTrue(shape.getShapeId() > 0);
+
+ //check that EscherDgRecord is updated
+ assertEquals(shape.getShapeId(), dg.getLastMSOSPID());
+ assertEquals(dgMaxId + 1, dg.getLastMSOSPID());
+ assertEquals(dgShapesUsed + 1, dg.getNumShapes());
+
+ //check that EscherDggRecord is updated
+ assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @" + i);
+ assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @" + i);
+ assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @" + i);
+
+ dggShapesUsed = dgg.getNumShapesSaved();
+ dggMaxId = dgg.getShapeIdMax();
+ dgMaxId = dg.getLastMSOSPID();
+ dgShapesUsed = dg.getNumShapes();
+ }
- //For each drawing group PPT allocates clusters with size=1024
- //if the number of shapes is greater that 1024 a new cluster is allocated
- //make sure it is so
- int numClusters = dgg.getNumIdClusters();
- for (int i = 0; i < 1025; i++) {
- HSLFShape shape = new HSLFLine();
- slide.addShape(shape);
+ //For each drawing group PPT allocates clusters with size=1024
+ //if the number of shapes is greater that 1024 a new cluster is allocated
+ //make sure it is so
+ int numClusters = dgg.getNumIdClusters();
+ for (int i = 0; i < 1025; i++) {
+ HSLFShape shape = new HSLFLine();
+ slide.addShape(shape);
+ }
+ assertEquals(numClusters + 1, dgg.getNumIdClusters());
}
- assertEquals(numClusters + 1, dgg.getNumIdClusters());
- ss.close();
}
@Test
void lineColor() throws IOException {
- HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream("51731.ppt"));
- List shape = ss.getSlides().get(0).getShapes();
-
- assertEquals(4, shape.size());
+ try (HSLFSlideShow ss = getSlideShow("51731.ppt")) {
+ List shape = ss.getSlides().get(0).getShapes();
- HSLFTextShape sh1 = (HSLFTextShape)shape.get(0);
- assertEquals("Hello Apache POI", sh1.getText());
- assertNull(sh1.getLineColor());
+ assertEquals(4, shape.size());
- HSLFTextShape sh2 = (HSLFTextShape)shape.get(1);
- assertEquals("Why are you showing this border?", sh2.getText());
- assertNull(sh2.getLineColor());
+ HSLFTextShape sh1 = (HSLFTextShape) shape.get(0);
+ assertEquals("Hello Apache POI", sh1.getText());
+ assertNull(sh1.getLineColor());
- HSLFTextShape sh3 = (HSLFTextShape)shape.get(2);
- assertEquals("Text in a black border", sh3.getText());
- assertEquals(Color.black, sh3.getLineColor());
- assertEquals(0.75, sh3.getLineWidth(), 0);
+ HSLFTextShape sh2 = (HSLFTextShape) shape.get(1);
+ assertEquals("Why are you showing this border?", sh2.getText());
+ assertNull(sh2.getLineColor());
- HSLFTextShape sh4 = (HSLFTextShape)shape.get(3);
- assertEquals("Border width is 5 pt", sh4.getText());
- assertEquals(Color.black, sh4.getLineColor());
- assertEquals(5.0, sh4.getLineWidth(), 0);
+ HSLFTextShape sh3 = (HSLFTextShape) shape.get(2);
+ assertEquals("Text in a black border", sh3.getText());
+ assertEquals(Color.black, sh3.getLineColor());
+ assertEquals(0.75, sh3.getLineWidth(), 0);
- ss.close();
+ HSLFTextShape sh4 = (HSLFTextShape) shape.get(3);
+ assertEquals("Border width is 5 pt", sh4.getText());
+ assertEquals(Color.black, sh4.getLineColor());
+ assertEquals(5.0, sh4.getLineWidth(), 0);
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java
index a50958ff79..8c00994768 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java
@@ -17,28 +17,32 @@
package org.apache.poi.hslf.model;
+import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.BODY;
import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_BODY;
import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_TITLE;
import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.TITLE;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
+import java.util.Objects;
+import java.util.stream.IntStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp;
import org.apache.poi.hslf.model.textproperties.TextProp;
import org.apache.poi.hslf.record.Environment;
+import org.apache.poi.hslf.usermodel.HSLFFontInfo;
import org.apache.poi.hslf.usermodel.HSLFMasterSheet;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideMaster;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
-import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
import org.apache.poi.hslf.usermodel.HSLFTextRun;
import org.apache.poi.hslf.usermodel.HSLFTitleMaster;
@@ -49,7 +53,7 @@ import org.junit.jupiter.api.Test;
* Tests for SlideMaster
*/
public final class TestSlideMaster {
- private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
+ private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
/**
* The reference ppt has two masters.
@@ -57,46 +61,54 @@ public final class TestSlideMaster {
*/
@Test
void testSlideMaster() throws IOException {
- final HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"));
-
- final Environment env = ppt.getDocumentRecord().getEnvironment();
-
- assertEquals(2, ppt.getSlideMasters().size());
-
- //character attributes
- assertEquals(40, getMasterVal(ppt, 0, TITLE, "font.size", true));
- assertEquals(48, getMasterVal(ppt, 1, TITLE, "font.size", true));
-
- int font1 = getMasterVal(ppt, 0, TITLE, "font.index", true);
- int font2 = getMasterVal(ppt, 1, TITLE, "font.index", true);
- assertEquals("Arial", env.getFontCollection().getFontInfo(font1).getTypeface());
- assertEquals("Georgia", env.getFontCollection().getFontInfo(font2).getTypeface());
-
- CharFlagsTextProp prop1 = getMasterProp(ppt, 0, TITLE, "char_flags", true);
- assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX));
- assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX));
- assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
-
- CharFlagsTextProp prop2 = getMasterProp(ppt, 1, TITLE, "char_flags", true);
- assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX));
- assertTrue(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX));
- assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
-
- //now paragraph attributes
- assertEquals(0x266B, getMasterVal(ppt, 0, BODY, "bullet.char", false));
- assertEquals(0x2022, getMasterVal(ppt, 1, BODY, "bullet.char", false));
-
- int b1 = getMasterVal(ppt, 0, BODY, "bullet.font", false);
- int b2 = getMasterVal(ppt, 1, BODY, "bullet.font", false);
- assertEquals("Arial", env.getFontCollection().getFontInfo(b1).getTypeface());
- assertEquals("Georgia", env.getFontCollection().getFontInfo(b2).getTypeface());
-
- ppt.close();
+ try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) {
+
+ final Environment env = ppt.getDocumentRecord().getEnvironment();
+
+ assertEquals(2, ppt.getSlideMasters().size());
+
+ //character attributes
+ assertEquals(40, getMasterVal(ppt, 0, TITLE, "font.size", true));
+ assertEquals(48, getMasterVal(ppt, 1, TITLE, "font.size", true));
+
+ int font1 = getMasterVal(ppt, 0, TITLE, "font.index", true);
+ int font2 = getMasterVal(ppt, 1, TITLE, "font.index", true);
+ HSLFFontInfo fontInfo = env.getFontCollection().getFontInfo(font1);
+ assertNotNull(fontInfo);
+ assertEquals("Arial", fontInfo.getTypeface());
+ fontInfo = env.getFontCollection().getFontInfo(font2);
+ assertNotNull(fontInfo);
+ assertEquals("Georgia", fontInfo.getTypeface());
+
+ CharFlagsTextProp prop1 = getMasterProp(ppt, 0, TITLE, "char_flags", true);
+ assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX));
+ assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX));
+ assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
+
+ CharFlagsTextProp prop2 = getMasterProp(ppt, 1, TITLE, "char_flags", true);
+ assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX));
+ assertTrue(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX));
+ assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
+
+ //now paragraph attributes
+ assertEquals(0x266B, getMasterVal(ppt, 0, BODY, "bullet.char", false));
+ assertEquals(0x2022, getMasterVal(ppt, 1, BODY, "bullet.char", false));
+
+ int b1 = getMasterVal(ppt, 0, BODY, "bullet.font", false);
+ int b2 = getMasterVal(ppt, 1, BODY, "bullet.font", false);
+ fontInfo = env.getFontCollection().getFontInfo(b1);
+ assertNotNull(fontInfo);
+ assertEquals("Arial", fontInfo.getTypeface());
+ fontInfo = env.getFontCollection().getFontInfo(b2);
+ assertNotNull(fontInfo);
+ assertEquals("Georgia", fontInfo.getTypeface());
+ }
}
- @SuppressWarnings("unchecked")
private static T getMasterProp(HSLFSlideShow ppt, int masterIdx, TextPlaceholder txtype, String propName, boolean isCharacter) {
- return (T)ppt.getSlideMasters().get(masterIdx).getPropCollection(txtype.nativeId, 0, propName, isCharacter).findByName(propName);
+ return Objects.requireNonNull(ppt.getSlideMasters().get(masterIdx)
+ .getPropCollection(txtype.nativeId, 0, propName, isCharacter))
+ .findByName(propName);
}
private static int getMasterVal(HSLFSlideShow ppt, int masterIdx, TextPlaceholder txtype, String propName, boolean isCharacter) {
@@ -109,22 +121,21 @@ public final class TestSlideMaster {
*/
@Test
void testTitleMasterTextAttributes() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"));
- assertEquals(1, ppt.getTitleMasters().size());
-
- assertEquals(40, getMasterVal(ppt, 0, CENTER_TITLE, "font.size", true));
- CharFlagsTextProp prop1 = getMasterProp(ppt, 0, CENTER_TITLE, "char_flags", true);
- assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX));
- assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX));
- assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
-
- assertEquals(32, getMasterVal(ppt, 0, CENTER_BODY, "font.size", true));
- CharFlagsTextProp prop2 = getMasterProp(ppt, 0, CENTER_BODY, "char_flags", true);
- assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX));
- assertFalse(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX));
- assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
-
- ppt.close();
+ try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) {
+ assertEquals(1, ppt.getTitleMasters().size());
+
+ assertEquals(40, getMasterVal(ppt, 0, CENTER_TITLE, "font.size", true));
+ CharFlagsTextProp prop1 = getMasterProp(ppt, 0, CENTER_TITLE, "char_flags", true);
+ assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX));
+ assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX));
+ assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
+
+ assertEquals(32, getMasterVal(ppt, 0, CENTER_BODY, "font.size", true));
+ CharFlagsTextProp prop2 = getMasterProp(ppt, 0, CENTER_BODY, "char_flags", true);
+ assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX));
+ assertFalse(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX));
+ assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX));
+ }
}
/**
@@ -132,30 +143,32 @@ public final class TestSlideMaster {
*/
@Test
void testTitleMaster() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"));
- HSLFSlide slide = ppt.getSlides().get(2);
- HSLFMasterSheet masterSheet = slide.getMasterSheet();
- assertTrue(masterSheet instanceof HSLFTitleMaster);
-
- for (List txt : slide.getTextParagraphs()) {
- HSLFTextRun rt = txt.get(0).getTextRuns().get(0);
- switch(TextPlaceholder.fromNativeId(txt.get(0).getRunType())){
- case CENTER_TITLE:
- assertEquals("Arial", rt.getFontFamily());
- assertEquals(32, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertTrue(rt.isUnderlined());
- break;
- case CENTER_BODY:
- assertEquals("Courier New", rt.getFontFamily());
- assertEquals(20, rt.getFontSize(), 0);
- assertTrue(rt.isBold());
- assertFalse(rt.isUnderlined());
- break;
+ try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) {
+ HSLFSlide slide = ppt.getSlides().get(2);
+ HSLFMasterSheet masterSheet = slide.getMasterSheet();
+ assertTrue(masterSheet instanceof HSLFTitleMaster);
+
+ for (List txt : slide.getTextParagraphs()) {
+ HSLFTextRun rt = txt.get(0).getTextRuns().get(0);
+ assertNotNull(rt.getFontSize());
+ TextPlaceholder tp = TextPlaceholder.fromNativeId(txt.get(0).getRunType());
+ assertNotNull(tp);
+ switch (tp) {
+ case CENTER_TITLE:
+ assertEquals("Arial", rt.getFontFamily());
+ assertEquals(32, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertTrue(rt.isUnderlined());
+ break;
+ case CENTER_BODY:
+ assertEquals("Courier New", rt.getFontFamily());
+ assertEquals(20, rt.getFontSize(), 0);
+ assertTrue(rt.isBold());
+ assertFalse(rt.isUnderlined());
+ break;
+ }
}
-
}
- ppt.close();
}
/**
@@ -163,48 +176,46 @@ public final class TestSlideMaster {
*/
@Test
void testMasterAttributes() throws Exception {
- HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"));
- List slide = ppt.getSlides();
- assertEquals(3, slide.size());
- for (List tparas : slide.get(0).getTextParagraphs()) {
- HSLFTextParagraph tpara = tparas.get(0);
- if (tpara.getRunType() == TITLE.nativeId){
- HSLFTextRun rt = tpara.getTextRuns().get(0);
- assertEquals(40, rt.getFontSize(), 0);
- assertTrue(rt.isUnderlined());
- assertEquals("Arial", rt.getFontFamily());
- } else if (tpara.getRunType() == BODY.nativeId){
+ try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) {
+ List slide = ppt.getSlides();
+ assertEquals(3, slide.size());
+ for (List tparas : slide.get(0).getTextParagraphs()) {
+ HSLFTextParagraph tpara = tparas.get(0);
HSLFTextRun rt = tpara.getTextRuns().get(0);
- assertEquals(0, tpara.getIndentLevel());
- assertEquals(32, rt.getFontSize(), 0);
- assertEquals("Arial", rt.getFontFamily());
-
- tpara = tparas.get(1);
- rt = tpara.getTextRuns().get(0);
- assertEquals(1, tpara.getIndentLevel());
- assertEquals(28, rt.getFontSize(), 0);
- assertEquals("Arial", rt.getFontFamily());
+ assertNotNull(rt.getFontSize());
+ if (tpara.getRunType() == TITLE.nativeId) {
+ assertEquals(40, rt.getFontSize(), 0);
+ assertTrue(rt.isUnderlined());
+ assertEquals("Arial", rt.getFontFamily());
+ } else if (tpara.getRunType() == BODY.nativeId) {
+ assertEquals(0, tpara.getIndentLevel());
+ assertEquals(32, rt.getFontSize(), 0);
+ assertEquals("Arial", rt.getFontFamily());
+ tpara = tparas.get(1);
+ rt = tpara.getTextRuns().get(0);
+ assertEquals(1, tpara.getIndentLevel());
+ assertNotNull(rt.getFontSize());
+ assertEquals(28, rt.getFontSize(), 0);
+ assertEquals("Arial", rt.getFontFamily());
+ }
}
- }
- for (List tparas : slide.get(1).getTextParagraphs()) {
- HSLFTextParagraph tpara = tparas.get(0);
- if (tpara.getRunType() == TITLE.nativeId){
+ for (List tparas : slide.get(1).getTextParagraphs()) {
+ HSLFTextParagraph tpara = tparas.get(0);
HSLFTextRun rt = tpara.getTextRuns().get(0);
- assertEquals(48, rt.getFontSize(), 0);
- assertTrue(rt.isItalic());
- assertEquals("Georgia", rt.getFontFamily());
- } else if (tpara.getRunType() == BODY.nativeId){
- HSLFTextRun rt;
- rt = tpara.getTextRuns().get(0);
- assertEquals(0, tpara.getIndentLevel());
- assertEquals(32, rt.getFontSize(), 0);
- assertEquals("Courier New", rt.getFontFamily());
+ assertNotNull(rt.getFontSize());
+ if (tpara.getRunType() == TITLE.nativeId) {
+ assertEquals(48, rt.getFontSize(), 0);
+ assertTrue(rt.isItalic());
+ assertEquals("Georgia", rt.getFontFamily());
+ } else if (tpara.getRunType() == BODY.nativeId) {
+ assertEquals(0, tpara.getIndentLevel());
+ assertEquals(32, rt.getFontSize(), 0);
+ assertEquals("Courier New", rt.getFontFamily());
+ }
}
}
-
- ppt.close();
}
/**
@@ -212,35 +223,32 @@ public final class TestSlideMaster {
*/
@Test
void testChangeSlideMaster() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"));
- List master = ppt.getSlideMasters();
- List slide = ppt.getSlides();
- int sheetNo;
-
- //each slide uses its own master
- assertEquals(slide.get(0).getMasterSheet()._getSheetNumber(), master.get(0)._getSheetNumber());
- assertEquals(slide.get(1).getMasterSheet()._getSheetNumber(), master.get(1)._getSheetNumber());
-
- //all slides use the first master slide
- sheetNo = master.get(0)._getSheetNumber();
- for (HSLFSlide s : slide) {
- s.setMasterSheet(master.get(0));
- }
-
- ByteArrayOutputStream out;
-
- out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
- master = ppt.getSlideMasters();
- slide = ppt.getSlides();
- for (HSLFSlide s : slide) {
- assertEquals(sheetNo, s.getMasterSheet()._getSheetNumber());
+ try (HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"))) {
+ int[] masterIds = IntStream.concat(
+ ppt.getSlideMasters().stream().mapToInt(HSLFSlideMaster::_getSheetNumber),
+ ppt.getTitleMasters().stream().mapToInt(HSLFTitleMaster::_getSheetNumber)
+ ).toArray();
+ //each slide uses its own master
+ int[] slideMasters = ppt.getSlides().stream().mapToInt(s -> {
+ HSLFMasterSheet m = s.getMasterSheet();
+ assertNotNull(m);
+ return m._getSheetNumber();
+ }).toArray();
+ assertArrayEquals(masterIds, slideMasters);
+
+ //all slides use the first master slide
+ HSLFSlideMaster master0 = ppt.getSlideMasters().get(0);
+ int sheetNo = master0._getSheetNumber();
+ ppt.getSlides().forEach(s -> s.setMasterSheet(master0));
+
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) {
+ for (HSLFSlide s : ppt2.getSlides()) {
+ HSLFMasterSheet ms = s.getMasterSheet();
+ assertNotNull(ms);
+ assertEquals(sheetNo, ms._getSheetNumber());
+ }
+ }
}
-
- ppt.close();
}
/**
@@ -256,6 +264,7 @@ public final class TestSlideMaster {
HSLFTextParagraph tpara = tparas.get(0);
if (tpara.getRunType() == TITLE.nativeId){
HSLFTextRun rt = tpara.getTextRuns().get(0);
+ assertNotNull(rt.getFontSize());
assertEquals(40, rt.getFontSize(), 0);
assertTrue(rt.isUnderlined());
assertEquals("Arial", rt.getFontFamily());
@@ -263,6 +272,7 @@ public final class TestSlideMaster {
int[] indents = {32, 28, 24};
for (HSLFTextRun rt : tpara.getTextRuns()) {
int indent = tpara.getIndentLevel();
+ assertNotNull(rt.getFontSize());
assertEquals(indents[indent], rt.getFontSize(), 0);
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java
index 31713bae88..15850e6047 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java
@@ -17,14 +17,13 @@
package org.apache.poi.hslf.model;
+import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.hslf.usermodel.*;
+import org.apache.poi.hslf.usermodel.HSLFSlide;
+import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.junit.jupiter.api.Test;
/**
@@ -36,105 +35,96 @@ public final class TestSlides {
/**
* Add 1 slide to an empty ppt.
- * @throws Exception
*/
@Test
void testAddSlides1() throws Exception {
- HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") ));
- assertTrue(ppt.getSlides().isEmpty());
-
- HSLFSlide s1 = ppt.createSlide();
- assertEquals(1, ppt.getSlides().size());
- assertEquals(3, s1._getSheetRefId());
- assertEquals(256, s1._getSheetNumber());
- assertEquals(1, s1.getSlideNumber());
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
- assertEquals(1, ppt.getSlides().size());
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ assertTrue(ppt1.getSlides().isEmpty());
+
+ HSLFSlide s1 = ppt1.createSlide();
+ assertEquals(1, ppt1.getSlides().size());
+ assertEquals(3, s1._getSheetRefId());
+ assertEquals(256, s1._getSheetNumber());
+ assertEquals(1, s1.getSlideNumber());
+
+ //serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)){
+ assertEquals(1, ppt2.getSlides().size());
+ }
+ }
}
/**
* Add 2 slides to an empty ppt
- * @throws Exception
*/
@Test
void testAddSlides2() throws Exception {
- HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") ));
- assertTrue(ppt.getSlides().isEmpty());
-
- HSLFSlide s1 = ppt.createSlide();
- assertEquals(1, ppt.getSlides().size());
- assertEquals(3, s1._getSheetRefId());
- assertEquals(256, s1._getSheetNumber());
- assertEquals(1, s1.getSlideNumber());
-
- HSLFSlide s2 = ppt.createSlide();
- assertEquals(2, ppt.getSlides().size());
- assertEquals(4, s2._getSheetRefId());
- assertEquals(257, s2._getSheetNumber());
- assertEquals(2, s2.getSlideNumber());
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
- assertEquals(2, ppt.getSlides().size());
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ assertTrue(ppt1.getSlides().isEmpty());
+
+ HSLFSlide s1 = ppt1.createSlide();
+ assertEquals(1, ppt1.getSlides().size());
+ assertEquals(3, s1._getSheetRefId());
+ assertEquals(256, s1._getSheetNumber());
+ assertEquals(1, s1.getSlideNumber());
+
+ HSLFSlide s2 = ppt1.createSlide();
+ assertEquals(2, ppt1.getSlides().size());
+ assertEquals(4, s2._getSheetRefId());
+ assertEquals(257, s2._getSheetNumber());
+ assertEquals(2, s2.getSlideNumber());
+
+ //serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ assertEquals(2, ppt2.getSlides().size());
+ }
+ }
}
/**
* Add 3 slides to an empty ppt
- * @throws Exception
*/
@Test
void testAddSlides3() throws Exception {
- HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") ));
- assertTrue(ppt.getSlides().isEmpty());
-
- HSLFSlide s1 = ppt.createSlide();
- assertEquals(1, ppt.getSlides().size());
- assertEquals(3, s1._getSheetRefId());
- assertEquals(256, s1._getSheetNumber());
- assertEquals(1, s1.getSlideNumber());
-
- HSLFSlide s2 = ppt.createSlide();
- assertEquals(2, ppt.getSlides().size());
- assertEquals(4, s2._getSheetRefId());
- assertEquals(257, s2._getSheetNumber());
- assertEquals(2, s2.getSlideNumber());
-
- HSLFSlide s3 = ppt.createSlide();
- assertEquals(3, ppt.getSlides().size());
- assertEquals(5, s3._getSheetRefId());
- assertEquals(258, s3._getSheetNumber());
- assertEquals(3, s3.getSlideNumber());
-
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
- assertEquals(3, ppt.getSlides().size());
-
- // Check IDs are still right
- s1 = ppt.getSlides().get(0);
- assertEquals(256, s1._getSheetNumber());
- assertEquals(3, s1._getSheetRefId());
- s2 = ppt.getSlides().get(1);
- assertEquals(257, s2._getSheetNumber());
- assertEquals(4, s2._getSheetRefId());
- s3 = ppt.getSlides().get(2);
- assertEquals(3, ppt.getSlides().size());
- assertEquals(258, s3._getSheetNumber());
- assertEquals(5, s3._getSheetRefId());
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ assertTrue(ppt1.getSlides().isEmpty());
+
+ HSLFSlide s1 = ppt1.createSlide();
+ assertEquals(1, ppt1.getSlides().size());
+ assertEquals(3, s1._getSheetRefId());
+ assertEquals(256, s1._getSheetNumber());
+ assertEquals(1, s1.getSlideNumber());
+
+ HSLFSlide s2 = ppt1.createSlide();
+ assertEquals(2, ppt1.getSlides().size());
+ assertEquals(4, s2._getSheetRefId());
+ assertEquals(257, s2._getSheetNumber());
+ assertEquals(2, s2.getSlideNumber());
+
+ HSLFSlide s3 = ppt1.createSlide();
+ assertEquals(3, ppt1.getSlides().size());
+ assertEquals(5, s3._getSheetRefId());
+ assertEquals(258, s3._getSheetNumber());
+ assertEquals(3, s3.getSlideNumber());
+
+
+ //serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ assertEquals(3, ppt2.getSlides().size());
+
+ // Check IDs are still right
+ s1 = ppt2.getSlides().get(0);
+ assertEquals(256, s1._getSheetNumber());
+ assertEquals(3, s1._getSheetRefId());
+ s2 = ppt2.getSlides().get(1);
+ assertEquals(257, s2._getSheetNumber());
+ assertEquals(4, s2._getSheetRefId());
+ s3 = ppt2.getSlides().get(2);
+ assertEquals(3, ppt2.getSlides().size());
+ assertEquals(258, s3._getSheetNumber());
+ assertEquals(5, s3._getSheetRefId());
+ }
+ }
}
/**
@@ -142,48 +132,42 @@ public final class TestSlides {
*/
@Test
void testAddSlides2to3() throws Exception {
- POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
- HSLFSlideShow ppt = new HSLFSlideShow(slTests.openResourceAsStream("basic_test_ppt_file.ppt"));
-
- assertEquals(2, ppt.getSlides().size());
-
- // First slide is 256 / 4
- HSLFSlide s1 = ppt.getSlides().get(0);
- assertEquals(256, s1._getSheetNumber());
- assertEquals(4, s1._getSheetRefId());
-
- // Last slide is 257 / 6
- HSLFSlide s2 = ppt.getSlides().get(1);
- assertEquals(257, s2._getSheetNumber());
- assertEquals(6, s2._getSheetRefId());
-
- // Add another slide, goes in at the end
- HSLFSlide s3 = ppt.createSlide();
- assertEquals(3, ppt.getSlides().size());
- assertEquals(258, s3._getSheetNumber());
- assertEquals(8, s3._getSheetRefId());
-
-
- // Serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
- assertEquals(3, ppt.getSlides().size());
-
-
- // Check IDs are still right
- s1 = ppt.getSlides().get(0);
- assertEquals(256, s1._getSheetNumber());
- assertEquals(4, s1._getSheetRefId());
- s2 = ppt.getSlides().get(1);
- assertEquals(257, s2._getSheetNumber());
- assertEquals(6, s2._getSheetRefId());
- s3 = ppt.getSlides().get(2);
- assertEquals(3, ppt.getSlides().size());
- assertEquals(258, s3._getSheetNumber());
- assertEquals(8, s3._getSheetRefId());
+ try (HSLFSlideShow ppt1 = getSlideShow("basic_test_ppt_file.ppt")) {
+
+ assertEquals(2, ppt1.getSlides().size());
+
+ // First slide is 256 / 4
+ HSLFSlide s1 = ppt1.getSlides().get(0);
+ assertEquals(256, s1._getSheetNumber());
+ assertEquals(4, s1._getSheetRefId());
+
+ // Last slide is 257 / 6
+ HSLFSlide s2 = ppt1.getSlides().get(1);
+ assertEquals(257, s2._getSheetNumber());
+ assertEquals(6, s2._getSheetRefId());
+
+ // Add another slide, goes in at the end
+ HSLFSlide s3 = ppt1.createSlide();
+ assertEquals(3, ppt1.getSlides().size());
+ assertEquals(258, s3._getSheetNumber());
+ assertEquals(8, s3._getSheetRefId());
+
+ // Serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ assertEquals(3, ppt2.getSlides().size());
+
+ // Check IDs are still right
+ s1 = ppt2.getSlides().get(0);
+ assertEquals(256, s1._getSheetNumber());
+ assertEquals(4, s1._getSheetRefId());
+ s2 = ppt2.getSlides().get(1);
+ assertEquals(257, s2._getSheetNumber());
+ assertEquals(6, s2._getSheetRefId());
+ s3 = ppt2.getSlides().get(2);
+ assertEquals(3, ppt2.getSlides().size());
+ assertEquals(258, s3._getSheetNumber());
+ assertEquals(8, s3._getSheetRefId());
+ }
+ }
}
-
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java
index 1777ffed2c..b97dcef413 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java
@@ -17,18 +17,17 @@
package org.apache.poi.hslf.model;
+import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
-import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFShape;
import org.apache.poi.hslf.usermodel.HSLFSlide;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
@@ -42,18 +41,15 @@ import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder;
import org.junit.jupiter.api.Test;
/**
- * Test Table
object.
+ * Test {@code Table} object.
*/
public final class TestTable {
- private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
-
/**
- * Test that ShapeFactory works properly and returns Table
+ * Test that ShapeFactory works properly and returns {@code Table}
*/
@Test
void testShapeFactory() throws IOException {
final int noColumns, noRows;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
try (HSLFSlideShow ppt = new HSLFSlideShow()) {
HSLFSlide slide = ppt.createSlide();
@@ -73,16 +69,15 @@ public final class TestTable {
assertEquals(noColumns, tbl2.getNumberOfColumns());
assertEquals(noRows, tbl2.getNumberOfRows());
- ppt.write(out);
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) {
+ HSLFSlide slide2 = ppt2.getSlides().get(0);
+ assertTrue(slide2.getShapes().get(0) instanceof HSLFTable);
+ HSLFTable tbl3 = (HSLFTable) slide2.getShapes().get(0);
+ assertEquals(noColumns, tbl3.getNumberOfColumns());
+ assertEquals(noRows, tbl3.getNumberOfRows());
+ }
}
- try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()))) {
- HSLFSlide slide = ppt.getSlides().get(0);
- assertTrue(slide.getShapes().get(0) instanceof HSLFTable);
- HSLFTable tbl3 = (HSLFTable) slide.getShapes().get(0);
- assertEquals(noColumns, tbl3.getNumberOfColumns());
- assertEquals(noRows, tbl3.getNumberOfRows());
- }
}
/**
@@ -132,7 +127,7 @@ public final class TestTable {
*/
@Test
void test57820() throws IOException {
- try (SlideShow,?> ppt = new HSLFSlideShow(_slTests.openResourceAsStream("bug57820-initTableNullRefrenceException.ppt"))) {
+ try (SlideShow,?> ppt = getSlideShow("bug57820-initTableNullRefrenceException.ppt")) {
List extends Slide, ?>> slides = ppt.getSlides();
assertEquals(1, slides.size());
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java
index f6f7fe6f7c..9509ca6c94 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java
@@ -17,22 +17,20 @@
package org.apache.poi.hslf.model;
+import static org.apache.poi.POIDataSamples.writeOutAndReadBack;
+import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
-import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFTextParagraph;
import org.apache.poi.hslf.usermodel.HSLFTextRun;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
@@ -41,137 +39,111 @@ import org.junit.jupiter.api.Test;
* that we don't break anything in the process.
*/
public final class TestTextRunReWrite {
- // HSLFSlideShow primed on the test data
- private HSLFSlideShow ss;
-
- /**
- * Load up a test PPT file with rich data
- */
- @BeforeEach
- void setUp() throws Exception {
- POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
- String filename = "Single_Coloured_Page_With_Fonts_and_Alignments.ppt";
- ss = new HSLFSlideShow(slTests.openResourceAsStream(filename));
- }
-
@Test
void testWritesOutTheSameNonRich() throws IOException {
- // Ensure the text lengths are as we'd expect to start with
- assertEquals(1, ss.getSlides().size());
- assertEquals(2, ss.getSlides().get(0).getTextParagraphs().size());
-
- // Grab the first text run on the first sheet
- List tr1 = ss.getSlides().get(0).getTextParagraphs().get(0);
- List tr2 = ss.getSlides().get(0).getTextParagraphs().get(1);
-
-
- assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
- assertEquals(179, HSLFTextParagraph.getRawText(tr2).length());
-
- assertEquals(1, tr1.size());
- assertEquals(30, HSLFTextParagraph.getText(tr1).length());
- assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
- assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered());
- assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
-
- // Set the text to be as it is now
- HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1));
- tr1 = ss.getSlides().get(0).getTextParagraphs().get(0);
-
- // Check the text lengths are still right
- assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
- assertEquals(179, HSLFTextParagraph.getRawText(tr2).length());
-
- assertEquals(1, tr1.size());
- assertEquals(30, HSLFTextParagraph.getText(tr1).length());
- assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
- assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered());
- assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
-
-
- // Write the slideshow out to a byte array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ss.write(baos);
-
- // Build an input stream of it
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-
- // Use POIFS to query that lot
- POIFSFileSystem npfs = new POIFSFileSystem(bais);
-
- // Check that the "PowerPoint Document" sections have the same size
- DirectoryNode oDir = ss.getSlideShowImpl().getDirectory();
-
- DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
- DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
- assertEquals(oProps.getSize(),nProps.getSize());
-
- // Check that they contain the same data
- byte[] _oData = new byte[oProps.getSize()];
- byte[] _nData = new byte[nProps.getSize()];
- oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData);
- npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData);
- assertArrayEquals(_oData, _nData);
-
- npfs.close();
+ try (HSLFSlideShow ppt1 = getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt")) {
+ // Ensure the text lengths are as we'd expect to start with
+ assertEquals(1, ppt1.getSlides().size());
+ assertEquals(2, ppt1.getSlides().get(0).getTextParagraphs().size());
+
+ // Grab the first text run on the first sheet
+ List tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0);
+ List tr2 = ppt1.getSlides().get(0).getTextParagraphs().get(1);
+
+
+ assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
+ assertEquals(179, HSLFTextParagraph.getRawText(tr2).length());
+
+ assertEquals(1, tr1.size());
+ assertEquals(30, HSLFTextParagraph.getText(tr1).length());
+ assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
+ assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered());
+ assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
+
+ // Set the text to be as it is now
+ HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1));
+ tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0);
+
+ // Check the text lengths are still right
+ assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
+ assertEquals(179, HSLFTextParagraph.getRawText(tr2).length());
+
+ assertEquals(1, tr1.size());
+ assertEquals(30, HSLFTextParagraph.getText(tr1).length());
+ assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
+ assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered());
+ assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
+
+ // Use POIFS to query that lot
+ try (POIFSFileSystem npfs = writeOutAndReadBack(ppt1.getDirectory().getFileSystem())) {
+ // Check that the "PowerPoint Document" sections have the same size
+ DirectoryNode oDir = ppt1.getSlideShowImpl().getDirectory();
+
+ DocumentEntry oProps = (DocumentEntry) oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
+ DocumentEntry nProps = (DocumentEntry) npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
+ assertEquals(oProps.getSize(), nProps.getSize());
+
+ // Check that they contain the same data
+ byte[] _oData = new byte[oProps.getSize()];
+ byte[] _nData = new byte[nProps.getSize()];
+ int oLen = oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData);
+ int nLen = npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData);
+ assertEquals(_oData.length, oLen);
+ assertEquals(_nData.length, nLen);
+ assertArrayEquals(_oData, _nData);
+ }
+ }
}
@Test
void testWritesOutTheSameRich() throws IOException {
- // Grab the first text run on the first sheet
- List tr1 = ss.getSlides().get(0).getTextParagraphs().get(0);
-
- // Get the first rich text run
- HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0);
-
-
- // Check that the text sizes are as expected
- assertEquals(1, tr1.get(0).getTextRuns().size());
- assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
- assertEquals(30, rtr1.getLength());
- assertEquals(30, rtr1.getRawText().length());
- assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered());
- assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
-
- // Set the text to be as it is now
- rtr1.setText( rtr1.getRawText() );
- rtr1 = tr1.get(0).getTextRuns().get(0);
-
- // Check that the text sizes are still as expected
- assertEquals(1, tr1.get(0).getTextRuns().size());
- assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
- assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length());
- assertEquals(30, rtr1.getLength());
- assertEquals(30, rtr1.getRawText().length());
- assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered());
- assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
-
-
- // Write the slideshow out to a byte array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ss.write(baos);
-
- // Build an input stream of it
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
-
- // Use POIFS to query that lot
- POIFSFileSystem npfs = new POIFSFileSystem(bais);
-
- // Check that the "PowerPoint Document" sections have the same size
- DirectoryNode oDir = ss.getSlideShowImpl().getDirectory();
-
- DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
- DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
- assertEquals(oProps.getSize(),nProps.getSize());
-
- // Check that they contain the same data
- byte[] _oData = new byte[oProps.getSize()];
- byte[] _nData = new byte[nProps.getSize()];
-
- oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData);
- npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData);
- assertArrayEquals(_oData, _nData);
-
- npfs.close();
+ try (HSLFSlideShow ppt1 = getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt")) {
+ // Grab the first text run on the first sheet
+ List tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0);
+
+ // Get the first rich text run
+ HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0);
+
+ // Check that the text sizes are as expected
+ assertEquals(1, tr1.get(0).getTextRuns().size());
+ assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
+ assertEquals(30, rtr1.getLength());
+ assertEquals(30, rtr1.getRawText().length());
+ assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered());
+ assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
+
+ // Set the text to be as it is now
+ rtr1.setText(rtr1.getRawText());
+ rtr1 = tr1.get(0).getTextRuns().get(0);
+
+ // Check that the text sizes are still as expected
+ assertEquals(1, tr1.get(0).getTextRuns().size());
+ assertEquals(30, HSLFTextParagraph.getRawText(tr1).length());
+ assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length());
+ assertEquals(30, rtr1.getLength());
+ assertEquals(30, rtr1.getRawText().length());
+ assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered());
+ assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered());
+
+ // Use POIFS to query that lot
+ try (POIFSFileSystem npfs = writeOutAndReadBack(ppt1.getDirectory().getFileSystem())) {
+ // Check that the "PowerPoint Document" sections have the same size
+ DirectoryNode oDir = ppt1.getSlideShowImpl().getDirectory();
+
+ DocumentEntry oProps = (DocumentEntry) oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
+ DocumentEntry nProps = (DocumentEntry) npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT);
+ assertEquals(oProps.getSize(), nProps.getSize());
+
+ // Check that they contain the same data
+ byte[] _oData = new byte[oProps.getSize()];
+ byte[] _nData = new byte[nProps.getSize()];
+
+ int oLen = oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData);
+ int nLen = npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData);
+ assertEquals(_oData.length, oLen);
+ assertEquals(_nData.length, nLen);
+ assertArrayEquals(_oData, _nData);
+ }
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java
index 21d25007db..dac20b569b 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java
@@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -66,7 +65,7 @@ public final class TestAnimationInfoAtom {
@Test
void testWrite() throws Exception {
AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
@@ -82,7 +81,7 @@ public final class TestAnimationInfoAtom {
record.setFlag(AnimationInfoAtom.Play, true);
record.setFlag(AnimationInfoAtom.Synchronous, true);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java
index a117037832..054b5c9790 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java
@@ -18,11 +18,11 @@
package org.apache.poi.hslf.record;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -70,24 +70,16 @@ public final class TestCString {
@Test
void testWrite() throws Exception {
CString ca = new CString(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ca.writeOut(baos);
byte[] b = baos.toByteArray();
-
- assertEquals(data_a.length, b.length);
- for(int i=0; i picsActual = hss2.getPictureData();
@@ -109,9 +108,9 @@ public class TestDocumentEncryption {
void cryptoAPIEncryption() throws Exception {
/* documents with multiple edits need to be normalized for encryption */
String pptFile = "57272_corrupted_usereditatom.ppt";
- ByteArrayOutputStream encrypted = new ByteArrayOutputStream();
- ByteArrayOutputStream expected = new ByteArrayOutputStream();
- ByteArrayOutputStream actual = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream encrypted = new UnsynchronizedByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream expected = new UnsynchronizedByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream actual = new UnsynchronizedByteArrayOutputStream();
try {
try (POIFSFileSystem fs = new POIFSFileSystem(slTests.getFile(pptFile), true);
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) {
@@ -126,8 +125,9 @@ public class TestDocumentEncryption {
}
// decrypted
- ByteArrayInputStream bis = new ByteArrayInputStream(encrypted.toByteArray());
- try (POIFSFileSystem fs = new POIFSFileSystem(bis);
+
+ try (InputStream bis = encrypted.toInputStream();
+ POIFSFileSystem fs = new POIFSFileSystem(bis);
HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) {
Biff8EncryptionKey.setCurrentUserPassword(null);
hss.write(actual);
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java
index c7bd84e116..2faa7ebfd8 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java
@@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -93,7 +92,7 @@ public final class TestExControl {
@Test
void testWrite() throws Exception {
ExControl record = new ExControl(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
@@ -116,7 +115,7 @@ public final class TestExControl {
record.setProgId("ShockwaveFlash.ShockwaveFlash.9");
record.setClipboardName("Shockwave Flash Object");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java
index 13fea4a83a..42a9867560 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java
@@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl;
@@ -46,14 +46,14 @@ public final class TestExHyperlink {
ExHyperlink exHyperlink = new ExHyperlink(exHyperlinkBytes, 0, exHyperlinkBytes.length);
- assertEquals(4055l, exHyperlink.getRecordType());
+ assertEquals(4055L, exHyperlink.getRecordType());
assertEquals(3, exHyperlink.getExHyperlinkAtom().getNumber());
String expURL = "http://jakarta.apache.org/poi/hssf/";
assertEquals(expURL, exHyperlink.getLinkURL());
assertEquals(expURL, exHyperlink._getDetailsA());
assertEquals(expURL, exHyperlink._getDetailsB());
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
exHyperlink.writeOut(baos);
assertArrayEquals(exHyperlinkBytes, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java
index fb8072bd44..f868d96b16 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java
@@ -21,8 +21,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -57,7 +56,7 @@ public class TestExHyperlinkAtom {
@Test
void testWrite() throws Exception {
ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
eha.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -71,7 +70,7 @@ public class TestExHyperlinkAtom {
eha.setNumber(1);
// Check it's now the same as a
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
eha.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -85,7 +84,7 @@ public class TestExHyperlinkAtom {
eha.setNumber(4);
// Check bytes are now the same
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
eha.writeOut(baos);
assertArrayEquals(data_b, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java
index 5b961d5816..606f0ac827 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java
@@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -50,7 +49,7 @@ public final class TestExMediaAtom {
@Test
void testWrite() throws Exception {
ExMediaAtom record = new ExMediaAtom(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
@@ -68,7 +67,7 @@ public final class TestExMediaAtom {
record.setFlag(HeadersFootersAtom.fHasTodayDate, false);
record.setFlag(HeadersFootersAtom.fHasFooter, false);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java
index 9256b01b9f..97d3ef1707 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java
@@ -20,8 +20,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ss.formula.functions.BaseTestNumeric;
import org.junit.jupiter.api.Test;
@@ -57,7 +56,7 @@ public class TestExObjListAtom {
@Test
void testWrite() throws Exception {
ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
eoa.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -71,7 +70,7 @@ public class TestExObjListAtom {
eoa.setObjectIDSeed(1);
// Check it's now the same as a
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
eoa.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -85,7 +84,7 @@ public class TestExObjListAtom {
eoa.setObjectIDSeed(4);
// Check bytes are now the same
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
eoa.writeOut(baos);
assertArrayEquals(data_b, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java
index 4c7771cac8..a0860abbbe 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java
@@ -20,8 +20,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -50,7 +49,7 @@ public final class TestExOleObjAtom {
@Test
void testWrite() throws Exception {
ExOleObjAtom record = new ExOleObjAtom(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
@@ -65,7 +64,7 @@ public final class TestExOleObjAtom {
record.setObjStgDataRef(2);
record.setOptions(1283584);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java
index fcdadfe211..f9d282a095 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java
@@ -22,12 +22,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
+import org.apache.poi.util.IOUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -58,7 +58,7 @@ public final class TestExOleObjStg {
assertEquals(RecordTypes.ExOleObjStg.typeID, record.getRecordType());
int len = record.getDataLength();
- byte[] oledata = readAll(record.getData());
+ byte[] oledata = IOUtils.toByteArray(record.getData());
assertEquals(len, oledata.length);
try (POIFSFileSystem fs = new POIFSFileSystem(record.getData())) {
@@ -70,7 +70,7 @@ public final class TestExOleObjStg {
@Test
void testWrite() throws Exception {
ExOleObjStg record = new ExOleObjStg(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
byte[] b = baos.toByteArray();
@@ -80,7 +80,7 @@ public final class TestExOleObjStg {
@Test
void testNewRecord() throws Exception {
ExOleObjStg src = new ExOleObjStg(data, 0, data.length);
- byte[] oledata = readAll(src.getData());
+ byte[] oledata = IOUtils.toByteArray(src.getData());
ExOleObjStg tgt = new ExOleObjStg();
tgt.setData(oledata);
@@ -88,22 +88,11 @@ public final class TestExOleObjStg {
assertEquals(src.getDataLength(), tgt.getDataLength());
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
tgt.writeOut(out);
byte[] b = out.toByteArray();
assertEquals(data.length, b.length);
assertArrayEquals(data, b);
}
-
- private byte[] readAll(InputStream is) throws IOException {
- int pos;
- byte[] chunk = new byte[1024];
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- while((pos = is.read(chunk)) > 0){
- out.write(chunk, 0, pos);
- }
- return out.toByteArray();
-
- }
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java
index 3933965ac2..ce02202335 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java
@@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -68,7 +67,7 @@ public final class TestExVideoContainer {
@Test
void testWrite() throws Exception {
ExVideoContainer record = new ExVideoContainer(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
@@ -79,7 +78,7 @@ public final class TestExVideoContainer {
record.getExMediaAtom().setObjectId(1);
record.getPathAtom().setText("D:\\projects\\SchulerAG\\mcom_v_1_0_4\\view\\data\\tests\\images\\cards.mpg");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java
index f5b64da586..3592100af6 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java
@@ -19,12 +19,13 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hslf.usermodel.HSLFFontInfo;
import org.apache.poi.hslf.usermodel.HSLFFontInfoPredefined;
@@ -78,16 +79,22 @@ public final class TestFontCollection {
assertEquals(child.length, 3);
// Check we get the right font name for the indicies
- assertEquals("Times New Roman", fonts.getFontInfo(0).getTypeface());
- assertEquals("Helvetica", fonts.getFontInfo(1).getTypeface());
- assertEquals("Arial", fonts.getFontInfo(2).getTypeface());
+ fi = fonts.getFontInfo(0);
+ assertNotNull(fi);
+ assertEquals("Times New Roman", fi.getTypeface());
+ fi = fonts.getFontInfo(1);
+ assertNotNull(fi);
+ assertEquals("Helvetica", fi.getTypeface());
+ fi = fonts.getFontInfo(2);
+ assertNotNull(fi);
+ assertEquals("Arial", fi.getTypeface());
assertNull(fonts.getFontInfo(3));
}
@Test
void testWrite() throws Exception {
FontCollection fonts = new FontCollection(data, 0, data.length);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
fonts.writeOut(out);
byte[] recdata = out.toByteArray();
assertArrayEquals(recdata, data);
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java
index 3edfadb3de..7277fc4790 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java
@@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -55,7 +54,7 @@ public final class TestHeadersFootersAtom {
@Test
void testWrite() throws Exception {
HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
@@ -67,7 +66,7 @@ public final class TestHeadersFootersAtom {
record.setFlag(HeadersFootersAtom.fHasTodayDate, true);
record.setFlag(HeadersFootersAtom.fHasFooter, true);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java
index f6a25739b2..5d6d15b798 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java
@@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -76,7 +75,7 @@ public final class TestHeadersFootersContainer {
@Test
void testWriteSlideHeadersFootersContainer() throws Exception {
HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(slideData, baos.toByteArray());
}
@@ -100,7 +99,7 @@ public final class TestHeadersFootersContainer {
assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4);
csFooter.setText("My Footer - 1");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(slideData, baos.toByteArray());
}
@@ -129,7 +128,7 @@ public final class TestHeadersFootersContainer {
@Test
void testWriteNotesHeadersFootersContainer() throws Exception {
HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(notesData, baos.toByteArray());
}
@@ -161,7 +160,7 @@ public final class TestHeadersFootersContainer {
assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4);
csFooter.setText("Note Footer");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
record.writeOut(baos);
assertArrayEquals(notesData, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java
index 7da5ee6f5c..1b1ab55491 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java
@@ -24,8 +24,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -57,7 +56,7 @@ public class TestInteractiveInfo {
@Test
void testWrite() throws Exception {
InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ii.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -75,7 +74,7 @@ public class TestInteractiveInfo {
ia.setHyperlinkType((byte)8);
// Check it's now the same as a
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ii.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java
index 7f9bcde86e..9eeab59618 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java
@@ -21,8 +21,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -74,7 +73,7 @@ public class TestInteractiveInfoAtom {
@Test
void testWrite() throws Exception {
InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ia.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -91,7 +90,7 @@ public class TestInteractiveInfoAtom {
ia.setHyperlinkType((byte)8);
// Check it's now the same as a
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ia.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -105,7 +104,7 @@ public class TestInteractiveInfoAtom {
ia.setHyperlinkID(4);
// Check bytes are now the same
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ia.writeOut(baos);
assertArrayEquals(data_b, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java
index e2852088dc..d122f019dd 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java
@@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -52,7 +51,7 @@ public final class TestNotesAtom {
@Test
void testWrite() throws Exception {
NotesAtom na = new NotesAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
na.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java
index ef3c7b84b4..7f67088716 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java
@@ -22,9 +22,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hslf.HSLFTestDataSamples;
import org.apache.poi.hslf.record.SlideAtomLayout.SlideLayoutType;
import org.apache.poi.hslf.usermodel.HSLFSlide;
@@ -43,7 +43,7 @@ public final class TestSlideAtom {
@Test
void testRecordType() {
SlideAtom sa = new SlideAtom(data_a, 0, data_a.length);
- assertEquals(1007l, sa.getRecordType());
+ assertEquals(1007L, sa.getRecordType());
}
@Test
@@ -75,23 +75,23 @@ public final class TestSlideAtom {
@Test
void testWrite() throws IOException {
SlideAtom sa = new SlideAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
sa.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@Test
void testSSSlideInfoAtom() throws IOException {
- HSLFSlideShow ss1 = new HSLFSlideShow();
- HSLFSlide slide1 = ss1.createSlide(), slide2 = ss1.createSlide();
- slide2.setHidden(true);
-
- HSLFSlideShow ss2 = HSLFTestDataSamples.writeOutAndReadBack(ss1);
- slide1 = ss2.getSlides().get(0);
- slide2 = ss2.getSlides().get(1);
- assertFalse(slide1.isHidden());
- assertTrue(slide2.isHidden());
- ss2.close();
- ss1.close();
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ HSLFSlide slide1 = ppt1.createSlide(), slide2 = ppt1.createSlide();
+ slide2.setHidden(true);
+
+ try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) {
+ slide1 = ppt2.getSlides().get(0);
+ slide2 = ppt2.getSlides().get(1);
+ assertFalse(slide1.isHidden());
+ assertTrue(slide2.isHidden());
+ }
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java
index 2a638d5a9a..d5f1105f47 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java
@@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -53,7 +52,7 @@ public final class TestSlidePersistAtom {
@Test
void testWrite() throws Exception {
SlidePersistAtom spa = new SlidePersistAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
spa.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java
index 3de5c8d131..1e57798caf 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java
@@ -26,15 +26,14 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hslf.exceptions.HSLFException;
import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp;
import org.apache.poi.hslf.model.textproperties.TextProp;
import org.apache.poi.hslf.model.textproperties.TextPropCollection;
-import org.apache.poi.util.HexDump;
import org.junit.jupiter.api.Test;
/**
@@ -467,14 +466,9 @@ public final class TestStyleTextPropAtom {
tpc.setValue(0xFE0033FF);
// Should now be the same as data_a
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
stpa.writeOut(baos);
- byte[] b = baos.toByteArray();
-
- assertEquals(data_a.length, b.length);
- for(int i=0; i
* 14 00 00 00 00 00 41 00 0A 00 06 00 50 00 07 00 01 00 00 00 00 00 00 00 02
* 00 00 00 01 04 00 00 01 04 01 00 00 00 01 08 00 00 01 08 0C 00 00 00 01 0C
* 00 00 01 0C 01 00 00 00 01 10 00 00 01 10 01 00 00 00 01 14 00 00 01 14 01
* 00 00 00 01 18 00 00 01 18 01 00 00 00 01 1C 00 00 01 1C
*
+ * }
*/
@Test
void test45815() throws IOException {
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java
index 44f2dc4617..c06eff77d1 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java
@@ -21,9 +21,9 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -64,7 +64,7 @@ public final class TestTextBytesAtom {
TextBytesAtom tba = new TextBytesAtom(data,0,data.length);
tba.setText(alt_text.getBytes(StandardCharsets.ISO_8859_1));
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
tba.writeOut(baos);
assertArrayEquals(alt_data, baos.toByteArray());
}
@@ -72,7 +72,7 @@ public final class TestTextBytesAtom {
@Test
void testWrite() throws Exception {
TextBytesAtom tba = new TextBytesAtom(data,0,data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
tba.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java
index 4c1a71daa0..382719cdfc 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java
@@ -21,8 +21,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -60,7 +59,7 @@ public final class TestTextCharsAtom {
TextCharsAtom tca = new TextCharsAtom(data,0,data.length);
tca.setText(alt_text);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
tca.writeOut(baos);
assertArrayEquals(alt_data, baos.toByteArray());
}
@@ -68,7 +67,7 @@ public final class TestTextCharsAtom {
@Test
void testWrite() throws Exception {
TextCharsAtom tca = new TextCharsAtom(data,0,data.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
tca.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
@@ -82,7 +81,7 @@ public final class TestTextCharsAtom {
assertEquals(data_text, tca.getText());
// Check it's now like data
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
tca.writeOut(baos);
assertArrayEquals(data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java
index 4935940afb..6eddf527af 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java
@@ -21,8 +21,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder;
import org.junit.jupiter.api.Test;
@@ -54,7 +53,7 @@ public final class TestTextHeaderAtom {
@Test
void testWrite() throws Exception {
TextHeaderAtom tha = new TextHeaderAtom(notes_data,0,12);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
tha.writeOut(baos);
assertArrayEquals(notes_data, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java
index e50419c410..a24402ec2a 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java
@@ -21,9 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayOutputStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hslf.model.textproperties.HSLFTabStop;
import org.junit.jupiter.api.Test;
@@ -61,7 +61,7 @@ public final class TestTextRulerAtom {
@Test
void testWriteRuler() throws Exception {
TextRulerAtom ruler = new TextRulerAtom(data_1, 0, data_1.length);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
ruler.writeOut(out);
byte[] result = out.toByteArray();
@@ -72,7 +72,7 @@ public final class TestTextRulerAtom {
void testRead2() throws Exception {
TextRulerAtom ruler = TextRulerAtom.getParagraphInstance();
ruler.setParagraphIndent((short)249, (short)321);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
ruler.writeOut(out);
byte[] result = out.toByteArray();
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java
index 77ded7d795..93e8b5e420 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java
@@ -20,8 +20,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -54,7 +53,7 @@ public final class TestTextSpecInfoAtom {
@Test
void testWrite() throws Exception {
TextSpecInfoAtom spec = new TextSpecInfoAtom(data_1, 0, data_1.length);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
spec.writeOut(out);
assertArrayEquals(data_1, out.toByteArray());
}
@@ -70,7 +69,7 @@ public final class TestTextSpecInfoAtom {
assertEquals(32, run[0].getLength());
//serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
spec.writeOut(out);
byte[] result = out.toByteArray();
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java
index 12874ec041..601baf0dc6 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java
@@ -21,8 +21,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -58,7 +57,7 @@ public final class TestTxInteractiveInfoAtom {
@Test
void testWrite() throws Exception {
TxInteractiveInfoAtom atom = new TxInteractiveInfoAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
atom.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -73,7 +72,7 @@ public final class TestTxInteractiveInfoAtom {
ia.setEndIndex(56);
// Check it's now the same as a
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ia.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
@@ -88,7 +87,7 @@ public final class TestTxInteractiveInfoAtom {
ia.setEndIndex(78);
// Check bytes are now the same
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
ia.writeOut(baos);
assertArrayEquals(data_b, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java
index c09e1e55b3..42b34157d9 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java
@@ -21,8 +21,7 @@ package org.apache.poi.hslf.record;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayOutputStream;
-
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
/**
@@ -57,7 +56,7 @@ public final class TestUserEditAtom {
@Test
void testWrite() throws Exception {
UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
uea.writeOut(baos);
assertArrayEquals(data_a, baos.toByteArray());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java
index e1f453327d..343c1117d9 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java
@@ -18,10 +18,10 @@ package org.apache.poi.hslf.usermodel;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.sl.usermodel.BaseTestSlideShow;
import org.apache.poi.sl.usermodel.SlideShow;
import org.junit.jupiter.api.Test;
@@ -38,15 +38,13 @@ public class TestHSLFSlideShow extends BaseTestSlideShow show) throws IOException {
- BufAccessBAOS bos = new BufAccessBAOS();
- show.write(bos);
- return new HSLFSlideShow(new ByteArrayInputStream(bos.getBuf()));
- }
-
- private static class BufAccessBAOS extends ByteArrayOutputStream {
- byte[] getBuf() {
- return buf;
+ try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
+ show.write(bos);
+ try (InputStream is = bos.toInputStream()) {
+ return new HSLFSlideShow(is);
+ }
}
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java
index 5e50aa9c1f..65a2716711 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java
@@ -17,13 +17,18 @@
package org.apache.poi.hslf.usermodel;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
+import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.awt.Dimension;
+import java.awt.geom.Dimension2D;
+import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
@@ -31,12 +36,13 @@ import java.util.Collections;
import java.util.List;
import java.util.Random;
+import javax.imageio.ImageIO;
+
+import org.apache.commons.io.output.CountingOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ddf.EscherBSERecord;
import org.apache.poi.ddf.EscherContainerRecord;
import org.apache.poi.ddf.EscherRecord;
-import org.apache.poi.hslf.HSLFTestDataSamples;
-import org.apache.poi.hslf.blip.DIB;
import org.apache.poi.hslf.blip.EMF;
import org.apache.poi.hslf.blip.JPEG;
import org.apache.poi.hslf.blip.PICT;
@@ -50,6 +56,8 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.util.Units;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
/**
* Test adding/reading pictures
@@ -58,302 +66,101 @@ public final class TestPictures {
private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance();
/**
- * Test read/write Macintosh PICT
- */
- @Test
- void testPICT() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] src_bytes = slTests.readFile("cow.pict");
- HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PICT);
- ImageHeaderPICT nHeader = new ImageHeaderPICT(src_bytes, 512);
- final int expWidth = 197, expHeight = 137;
- Dimension nDim = nHeader.getSize();
- assertEquals(expWidth, nDim.getWidth(), 0);
- assertEquals(expHeight, nDim.getHeight(), 0);
-
- Dimension dim = data.getImageDimensionInPixels();
- assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0);
- assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0);
-
- HSLFPictureShape pict = new HSLFPictureShape(data);
- assertEquals(data.getIndex(), pict.getPictureIndex());
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
-
- //make sure we can read this picture shape and it refers to the correct picture data
- List sh = ppt.getSlides().get(0).getShapes();
- assertEquals(1, sh.size());
- pict = (HSLFPictureShape)sh.get(0);
- assertEquals(data.getIndex(), pict.getPictureIndex());
-
- //check picture data
- List pictures = ppt.getPictureData();
- assertEquals(1, pictures.size());
-
- HSLFPictureData pd = pictures.get(0);
- dim = pd.getImageDimension();
- assertEquals(expWidth, dim.width);
- assertEquals(expHeight, dim.height);
-
- //the Picture shape refers to the PictureData object in the Presentation
- assertEquals(pict.getPictureData(), pd);
-
- assertEquals(1, pictures.size());
- assertEquals(PictureType.PICT, pd.getType());
- assertTrue(pd instanceof PICT);
- //compare the content of the initial file with what is stored in the PictureData
- byte[] ppt_bytes = pd.getData();
- assertEquals(src_bytes.length, ppt_bytes.length);
- //in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them
- byte[] b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length);
- byte[] b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length);
- assertArrayEquals(b1, b2);
- }
-
- /**
- * Test read/write WMF
- */
- @Test
- void testWMF() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] src_bytes = slTests.readFile("santa.wmf");
- HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.WMF);
- ImageHeaderWMF nHeader = new ImageHeaderWMF(src_bytes, 0);
- final int expWidth = 136, expHeight = 146;
- Dimension nDim = nHeader.getSize();
- assertEquals(expWidth, nDim.getWidth(), 0);
- assertEquals(expHeight, nDim.getHeight(), 0);
-
- Dimension dim = data.getImageDimensionInPixels();
- assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0);
- assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0);
-
- HSLFPictureShape pict = new HSLFPictureShape(data);
- assertEquals(data.getIndex(), pict.getPictureIndex());
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
-
- //make sure we can read this picture shape and it refers to the correct picture data
- List sh = ppt.getSlides().get(0).getShapes();
- assertEquals(1, sh.size());
- pict = (HSLFPictureShape)sh.get(0);
- assertEquals(data.getIndex(), pict.getPictureIndex());
-
- //check picture data
- List pictures = ppt.getPictureData();
- assertEquals(1, pictures.size());
-
- HSLFPictureData pd = pictures.get(0);
- dim = pd.getImageDimension();
- assertEquals(expWidth, dim.width);
- assertEquals(expHeight, dim.height);
-
- //the Picture shape refers to the PictureData object in the Presentation
- assertEquals(pict.getPictureData(), pd);
-
- assertEquals(PictureType.WMF, pd.getType());
- assertTrue(pd instanceof WMF);
- //compare the content of the initial file with what is stored in the PictureData
- byte[] ppt_bytes = pd.getData();
- assertEquals(src_bytes.length, ppt_bytes.length);
- //in WMF the first 22 bytes - is a metafile header
- byte[] b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length);
- byte[] b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length);
- assertArrayEquals(b1, b2);
- }
-
- /**
- * Test read/write EMF
+ * Test add/read/write images
*/
- @Test
- void testEMF() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] src_bytes = slTests.readFile("wrench.emf");
- HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.EMF);
- ImageHeaderEMF nHeader = new ImageHeaderEMF(src_bytes, 0);
- final int expWidth = 190, expHeight = 115;
- Dimension nDim = nHeader.getSize();
- assertEquals(expWidth, nDim.getWidth(), 0);
- assertEquals(expHeight, nDim.getHeight(), 0);
-
- Dimension dim = data.getImageDimensionInPixels();
- assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0);
- assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0);
-
- HSLFPictureShape pict = new HSLFPictureShape(data);
- assertEquals(data.getIndex(), pict.getPictureIndex());
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
-
- //make sure we can get this picture shape and it refers to the correct picture data
- List sh = ppt.getSlides().get(0).getShapes();
- assertEquals(1, sh.size());
- pict = (HSLFPictureShape)sh.get(0);
- assertEquals(data.getIndex(), pict.getPictureIndex());
-
- //check picture data
- List pictures = ppt.getPictureData();
- assertEquals(1, pictures.size());
-
- HSLFPictureData pd = pictures.get(0);
- dim = pd.getImageDimension();
- assertEquals(expWidth, dim.width);
- assertEquals(expHeight, dim.height);
-
- //the Picture shape refers to the PictureData object in the Presentation
- assertEquals(pict.getPictureData(), pd);
-
- assertEquals(1, pictures.size());
- assertEquals(PictureType.EMF, pd.getType());
- assertTrue(pd instanceof EMF);
- //compare the content of the initial file with what is stored in the PictureData
- byte[] ppt_bytes = pd.getData();
- assertArrayEquals(src_bytes, ppt_bytes);
- }
-
- /**
- * Test read/write PNG
- */
- @Test
- void testPNG() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] src_bytes = slTests.readFile("tomcat.png");
- HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PNG);
- HSLFPictureShape pict = new HSLFPictureShape(data);
- assertEquals(data.getIndex(), pict.getPictureIndex());
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
-
- //make sure we can read this picture shape and it refers to the correct picture data
- List sh = ppt.getSlides().get(0).getShapes();
- assertEquals(1, sh.size());
- pict = (HSLFPictureShape)sh.get(0);
- assertEquals(data.getIndex(), pict.getPictureIndex());
-
- //check picture data
- List pictures = ppt.getPictureData();
- //the Picture shape refers to the PictureData object in the Presentation
- assertEquals(pict.getPictureData(), pictures.get(0));
-
- assertEquals(1, pictures.size());
- assertEquals(PictureType.PNG, pictures.get(0).getType());
- assertTrue(pictures.get(0) instanceof PNG);
- //compare the content of the initial file with what is stored in the PictureData
- byte[] ppt_bytes = pictures.get(0).getData();
- assertArrayEquals(src_bytes, ppt_bytes);
- }
-
- /**
- * Test read/write JPEG
- */
- @Test
- void testJPEG() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] src_bytes = slTests.readFile("clock.jpg");
- HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.JPEG);
-
- HSLFPictureShape pict = new HSLFPictureShape(data);
- assertEquals(data.getIndex(), pict.getPictureIndex());
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
-
- //make sure we can read this picture shape and it refers to the correct picture data
- List sh = ppt.getSlides().get(0).getShapes();
- assertEquals(1, sh.size());
- pict = (HSLFPictureShape)sh.get(0);
- assertEquals(data.getIndex(), pict.getPictureIndex());
-
- //check picture data
- List pictures = ppt.getPictureData();
- //the Picture shape refers to the PictureData object in the Presentation
- assertEquals(pict.getPictureData(), pictures.get(0));
-
- assertEquals(1, pictures.size());
- assertEquals(PictureType.JPEG, pictures.get(0).getType());
- assertTrue(pictures.get(0) instanceof JPEG);
- //compare the content of the initial file with what is stored in the PictureData
- byte[] ppt_bytes = pictures.get(0).getData();
- assertArrayEquals(src_bytes, ppt_bytes);
- }
-
- /**
- * Test read/write DIB
- */
- @Test
- void testDIB() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] src_bytes = slTests.readFile("clock.dib");
- HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.DIB);
- HSLFPictureShape pict = new HSLFPictureShape(data);
- assertEquals(data.getIndex(), pict.getPictureIndex());
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray())));
-
- //make sure we can read this picture shape and it refers to the correct picture data
- List sh = ppt.getSlides().get(0).getShapes();
- assertEquals(1, sh.size());
- pict = (HSLFPictureShape)sh.get(0);
- assertEquals(data.getIndex(), pict.getPictureIndex());
-
- //check picture data
- List pictures = ppt.getPictureData();
- //the Picture shape refers to the PictureData object in the Presentation
- assertEquals(pict.getPictureData(), pictures.get(0));
-
- assertEquals(1, pictures.size());
- assertEquals(PictureType.DIB, pictures.get(0).getType());
- assertTrue(pictures.get(0) instanceof DIB);
- //compare the content of the initial file with what is stored in the PictureData
- byte[] ppt_bytes = pictures.get(0).getData();
- assertArrayEquals(src_bytes, ppt_bytes);
+ @ParameterizedTest()
+ @CsvSource(value = {
+ // in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them
+ "PICT, cow.pict, 197, 137, 512, org.apache.poi.hslf.blip.PICT",
+ // in WMF the first 22 bytes - is a metafile header
+ "WMF, santa.wmf, 136, 146, 22, org.apache.poi.hslf.blip.WMF",
+ "EMF, wrench.emf, 190, 115, 0, org.apache.poi.hslf.blip.EMF",
+ "PNG, tomcat.png, 129, 92, 0, org.apache.poi.hslf.blip.PNG",
+ "JPEG, clock.jpg, 192, 176, 0, org.apache.poi.hslf.blip.JPEG",
+ "DIB, clock.dib, 192, 176, 0, org.apache.poi.hslf.blip.DIB"
+ })
+ void testAddPictures(PictureType pictureType, String imgFile, int expWidth, int expHeight, int headerOffset, Class> imgClazz) throws IOException {
+ byte[] src_bytes = slTests.readFile(imgFile);
+
+ int dataIndex;
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+
+ HSLFSlide slide1 = ppt1.createSlide();
+ HSLFPictureData data1 = ppt1.addPicture(src_bytes, pictureType);
+ dataIndex = data1.getIndex();
+
+ // TODO: Fix the differences in the frame sizes
+ Dimension2D dimN, dimFrame1, dimFrame2;
+ switch (pictureType) {
+ case PICT:
+ dimN = new ImageHeaderPICT(src_bytes, headerOffset).getSize();
+ dimFrame1 = Units.pointsToPixel(dimN);
+ dimFrame2 = dimN;
+ break;
+ case WMF:
+ dimN = new ImageHeaderWMF(src_bytes, 0).getSize();
+ dimFrame1 = Units.pointsToPixel(dimN);
+ dimFrame2 = dimN;
+ break;
+ case EMF:
+ dimN = new ImageHeaderEMF(src_bytes, 0).getSize();
+ dimFrame1 = Units.pointsToPixel(dimN);
+ dimFrame2 = dimN;
+ break;
+ case JPEG:
+ case DIB:
+ case PNG: {
+ BufferedImage png = ImageIO.read(new ByteArrayInputStream(src_bytes));
+ dimN = new Dimension(png.getWidth(), png.getHeight());
+ dimFrame1 = dimN;
+ dimFrame2 = Units.pixelToPoints(dimN);
+ break;
+ }
+ default:
+ fail();
+ return;
+ }
+ assertEquals(expWidth, dimN.getWidth(), 1);
+ assertEquals(expHeight, dimN.getHeight(), 1);
+
+ Dimension dim1 = data1.getImageDimensionInPixels();
+ assertEquals(dimFrame1.getWidth(), dim1.getWidth(), 1);
+ assertEquals(dimFrame1.getHeight(), dim1.getHeight(), 1);
+
+ HSLFPictureShape pict1 = new HSLFPictureShape(data1);
+ assertEquals(data1.getIndex(), pict1.getPictureIndex());
+ slide1.addShape(pict1);
+
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ //make sure we can read this picture shape and it refers to the correct picture data
+ List sh2 = ppt2.getSlides().get(0).getShapes();
+ assertEquals(1, sh2.size());
+ HSLFPictureShape pict2 = (HSLFPictureShape) sh2.get(0);
+ assertEquals(dataIndex, pict2.getPictureIndex());
+
+ //check picture data
+ List pictures2 = ppt2.getPictureData();
+ assertEquals(1, pictures2.size());
+
+ HSLFPictureData pd2 = pictures2.get(0);
+ Dimension dim2 = pd2.getImageDimension();
+ assertEquals(dimFrame2.getWidth(), dim2.width, 1);
+ assertEquals(dimFrame2.getHeight(), dim2.height, 1);
+
+ //the Picture shape refers to the PictureData object in the Presentation
+ assertEquals(pict2.getPictureData(), pd2);
+
+ assertEquals(1, pictures2.size());
+ assertEquals(pictureType, pd2.getType());
+ assertTrue(imgClazz.isInstance(pd2));
+ //compare the content of the initial file with what is stored in the PictureData
+ byte[] ppt_bytes = pd2.getData();
+ assertEquals(src_bytes.length, ppt_bytes.length);
+ byte[] b1 = Arrays.copyOfRange(src_bytes, headerOffset, src_bytes.length);
+ byte[] b2 = Arrays.copyOfRange(ppt_bytes, headerOffset, ppt_bytes.length);
+ assertArrayEquals(b1, b2);
+ }
+ }
}
/**
@@ -366,60 +173,59 @@ public final class TestPictures {
HSLFPictureShape pict;
HSLFPictureData pdata;
- HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt");
- List slides = ppt.getSlides();
- List pictures = ppt.getPictureData();
- assertEquals(5, pictures.size());
-
- pict = (HSLFPictureShape)slides.get(0).getShapes().get(0); //the first slide contains JPEG
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof JPEG);
- assertEquals(PictureType.JPEG, pdata.getType());
- src_bytes = pdata.getData();
- ppt_bytes = slTests.readFile("clock.jpg");
- assertArrayEquals(src_bytes, ppt_bytes);
-
- pict = (HSLFPictureShape)slides.get(1).getShapes().get(0); //the second slide contains PNG
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof PNG);
- assertEquals(PictureType.PNG, pdata.getType());
- src_bytes = pdata.getData();
- ppt_bytes = slTests.readFile("tomcat.png");
- assertArrayEquals(src_bytes, ppt_bytes);
-
- pict = (HSLFPictureShape)slides.get(2).getShapes().get(0); //the third slide contains WMF
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof WMF);
- assertEquals(PictureType.WMF, pdata.getType());
- src_bytes = pdata.getData();
- ppt_bytes = slTests.readFile("santa.wmf");
- assertEquals(src_bytes.length, ppt_bytes.length);
- //ignore the first 22 bytes - it is a WMF metafile header
- b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length);
- b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length);
- assertArrayEquals(b1, b2);
-
- pict = (HSLFPictureShape)slides.get(3).getShapes().get(0); //the forth slide contains PICT
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof PICT);
- assertEquals(PictureType.PICT, pdata.getType());
- src_bytes = pdata.getData();
- ppt_bytes = slTests.readFile("cow.pict");
- assertEquals(src_bytes.length, ppt_bytes.length);
- //ignore the first 512 bytes - it is a MAC specific crap
- b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length);
- b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length);
- assertArrayEquals(b1, b2);
-
- pict = (HSLFPictureShape)slides.get(4).getShapes().get(0); //the fifth slide contains EMF
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof EMF);
- assertEquals(PictureType.EMF, pdata.getType());
- src_bytes = pdata.getData();
- ppt_bytes = slTests.readFile("wrench.emf");
- assertArrayEquals(src_bytes, ppt_bytes);
-
- ppt.close();
+ try (HSLFSlideShow ppt = getSlideShow("pictures.ppt")) {
+ List slides = ppt.getSlides();
+ List pictures = ppt.getPictureData();
+ assertEquals(5, pictures.size());
+
+ pict = (HSLFPictureShape) slides.get(0).getShapes().get(0); //the first slide contains JPEG
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof JPEG);
+ assertEquals(PictureType.JPEG, pdata.getType());
+ src_bytes = pdata.getData();
+ ppt_bytes = slTests.readFile("clock.jpg");
+ assertArrayEquals(src_bytes, ppt_bytes);
+
+ pict = (HSLFPictureShape) slides.get(1).getShapes().get(0); //the second slide contains PNG
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof PNG);
+ assertEquals(PictureType.PNG, pdata.getType());
+ src_bytes = pdata.getData();
+ ppt_bytes = slTests.readFile("tomcat.png");
+ assertArrayEquals(src_bytes, ppt_bytes);
+
+ pict = (HSLFPictureShape) slides.get(2).getShapes().get(0); //the third slide contains WMF
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof WMF);
+ assertEquals(PictureType.WMF, pdata.getType());
+ src_bytes = pdata.getData();
+ ppt_bytes = slTests.readFile("santa.wmf");
+ assertEquals(src_bytes.length, ppt_bytes.length);
+ //ignore the first 22 bytes - it is a WMF metafile header
+ b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length);
+ b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length);
+ assertArrayEquals(b1, b2);
+
+ pict = (HSLFPictureShape) slides.get(3).getShapes().get(0); //the forth slide contains PICT
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof PICT);
+ assertEquals(PictureType.PICT, pdata.getType());
+ src_bytes = pdata.getData();
+ ppt_bytes = slTests.readFile("cow.pict");
+ assertEquals(src_bytes.length, ppt_bytes.length);
+ //ignore the first 512 bytes - it is a MAC specific crap
+ b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length);
+ b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length);
+ assertArrayEquals(b1, b2);
+
+ pict = (HSLFPictureShape) slides.get(4).getShapes().get(0); //the fifth slide contains EMF
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof EMF);
+ assertEquals(PictureType.EMF, pdata.getType());
+ src_bytes = pdata.getData();
+ ppt_bytes = slTests.readFile("wrench.emf");
+ assertArrayEquals(src_bytes, ppt_bytes);
+ }
}
/**
@@ -428,35 +234,34 @@ public final class TestPictures {
*/
@Test
void testZeroPictureType() throws IOException {
- HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt"));
-
- // Should still have 2 real pictures
- assertEquals(2, hslf.getPictureData().size());
- // Both are real pictures, both WMF
- assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType());
- assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType());
-
- // Now test what happens when we use the SlideShow interface
- HSLFSlideShow ppt = new HSLFSlideShow(hslf);
- List slides = ppt.getSlides();
- List pictures = ppt.getPictureData();
- assertEquals(12, slides.size());
- assertEquals(2, pictures.size());
-
- HSLFPictureShape pict;
- HSLFPictureData pdata;
-
- pict = (HSLFPictureShape)slides.get(0).getShapes().get(1); // 2nd object on 1st slide
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof WMF);
- assertEquals(PictureType.WMF, pdata.getType());
-
- pict = (HSLFPictureShape)slides.get(0).getShapes().get(2); // 3rd object on 1st slide
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof WMF);
- assertEquals(PictureType.WMF, pdata.getType());
-
- ppt.close();
+ try (HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt"))) {
+
+ // Should still have 2 real pictures
+ assertEquals(2, hslf.getPictureData().size());
+ // Both are real pictures, both WMF
+ assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType());
+ assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType());
+
+ // Now test what happens when we use the SlideShow interface
+ HSLFSlideShow ppt = new HSLFSlideShow(hslf);
+ List slides = ppt.getSlides();
+ List pictures = ppt.getPictureData();
+ assertEquals(12, slides.size());
+ assertEquals(2, pictures.size());
+
+ HSLFPictureShape pict;
+ HSLFPictureData pdata;
+
+ pict = (HSLFPictureShape) slides.get(0).getShapes().get(1); // 2nd object on 1st slide
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof WMF);
+ assertEquals(PictureType.WMF, pdata.getType());
+
+ pict = (HSLFPictureShape) slides.get(0).getShapes().get(2); // 3rd object on 1st slide
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof WMF);
+ assertEquals(PictureType.WMF, pdata.getType());
+ }
}
/**
@@ -490,75 +295,70 @@ public final class TestPictures {
assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType());
// Now test what happens when we use the SlideShow interface
- HSLFSlideShow ppt = new HSLFSlideShow(hslf);
- List slides = ppt.getSlides();
- List pictures = ppt.getPictureData();
- assertEquals(27, slides.size());
- assertEquals(2, pictures.size());
-
- HSLFPictureShape pict;
- HSLFPictureData pdata;
-
- pict = (HSLFPictureShape)slides.get(6).getShapes().get(13);
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof WMF);
- assertEquals(PictureType.WMF, pdata.getType());
-
- pict = (HSLFPictureShape)slides.get(7).getShapes().get(13);
- pdata = pict.getPictureData();
- assertTrue(pdata instanceof WMF);
- assertEquals(PictureType.WMF, pdata.getType());
-
- //add a new picture, it should be correctly appended to the Pictures stream
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- for(HSLFPictureData p : pictures) p.write(out);
- out.close();
-
- int streamSize = out.size();
-
- HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG);
- int offset = data.getOffset();
- assertEquals(streamSize, offset);
- assertEquals(3, ppt.getPictureData().size());
-
- ppt.close();
+ try (HSLFSlideShow ppt = new HSLFSlideShow(hslf)) {
+ List slides = ppt.getSlides();
+ List pictures = ppt.getPictureData();
+ assertEquals(27, slides.size());
+ assertEquals(2, pictures.size());
+
+ HSLFPictureShape pict;
+ HSLFPictureData pdata;
+
+ pict = (HSLFPictureShape) slides.get(6).getShapes().get(13);
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof WMF);
+ assertEquals(PictureType.WMF, pdata.getType());
+
+ pict = (HSLFPictureShape) slides.get(7).getShapes().get(13);
+ pdata = pict.getPictureData();
+ assertTrue(pdata instanceof WMF);
+ assertEquals(PictureType.WMF, pdata.getType());
+
+ //add a new picture, it should be correctly appended to the Pictures stream
+ CountingOutputStream out = new CountingOutputStream(NULL_OUTPUT_STREAM);
+ for (HSLFPictureData p : pictures) p.write(out);
+
+ int streamSize = out.getCount();
+
+ HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG);
+ int offset = data.getOffset();
+ assertEquals(streamSize, offset);
+ assertEquals(3, ppt.getPictureData().size());
+ }
}
@Test
void testGetPictureName() throws IOException {
- HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt");
- HSLFSlide slide = ppt.getSlides().get(0);
+ try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) {
+ HSLFSlide slide = ppt.getSlides().get(0);
- HSLFPictureShape p = (HSLFPictureShape)slide.getShapes().get(0); //the first slide contains JPEG
- assertEquals("test", p.getPictureName());
- ppt.close();
+ HSLFPictureShape p = (HSLFPictureShape) slide.getShapes().get(0); //the first slide contains JPEG
+ assertEquals("test", p.getPictureName());
+ }
}
@Test
void testSetPictureName() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
-
- HSLFSlide slide = ppt.createSlide();
- byte[] img = slTests.readFile("tomcat.png");
- HSLFPictureData data = ppt.addPicture(img, PictureType.PNG);
- HSLFPictureShape pict = new HSLFPictureShape(data);
- pict.setPictureName("tomcat.png");
- slide.addShape(pict);
-
- //serialize and read again
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()));
-
- HSLFPictureShape p = (HSLFPictureShape)ppt.getSlides().get(0).getShapes().get(0);
- assertEquals("tomcat.png", p.getPictureName());
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+
+ HSLFSlide slide = ppt1.createSlide();
+ byte[] img = slTests.readFile("tomcat.png");
+ HSLFPictureData data = ppt1.addPicture(img, PictureType.PNG);
+ HSLFPictureShape pict = new HSLFPictureShape(data);
+ pict.setPictureName("tomcat.png");
+ slide.addShape(pict);
+
+ //serialize and read again
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ HSLFPictureShape p = (HSLFPictureShape) ppt2.getSlides().get(0).getShapes().get(0);
+ assertEquals("tomcat.png", p.getPictureName());
+ }
+ }
}
@Test
void testPictureIndexIsOneBased() throws IOException {
- try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt")) {
+ try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) {
HSLFPictureData picture = ppt.getPictureData().get(0);
assertEquals(1, picture.getIndex());
}
@@ -571,20 +371,18 @@ public final class TestPictures {
@Test
void testEditPictureData() throws IOException {
byte[] newImage = slTests.readFile("tomcat.png");
- ByteArrayOutputStream modifiedSlideShow = new ByteArrayOutputStream();
// Load an existing slideshow and modify the image
- try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt")) {
- HSLFPictureData picture = ppt.getPictureData().get(0);
- picture.setData(newImage);
- ppt.write(modifiedSlideShow);
- }
+ try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png.ppt")) {
+ HSLFPictureData picture1 = ppt1.getPictureData().get(0);
+ picture1.setData(newImage);
- // Load the modified slideshow and verify the image content
- try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(modifiedSlideShow.toByteArray()))) {
- HSLFPictureData picture = ppt.getPictureData().get(0);
- byte[] modifiedImageData = picture.getData();
- assertArrayEquals(newImage, modifiedImageData);
+ // Load the modified slideshow and verify the image content
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ HSLFPictureData picture2 = ppt2.getPictureData().get(0);
+ byte[] modifiedImageData = picture2.getData();
+ assertArrayEquals(newImage, modifiedImageData);
+ }
}
}
@@ -595,22 +393,20 @@ public final class TestPictures {
@Test
void testEditPictureDataEncrypted() throws IOException {
byte[] newImage = slTests.readFile("tomcat.png");
- ByteArrayOutputStream modifiedSlideShow = new ByteArrayOutputStream();
Biff8EncryptionKey.setCurrentUserPassword("password");
try {
// Load an existing slideshow and modify the image
- try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png_encrypted.ppt")) {
- HSLFPictureData picture = ppt.getPictureData().get(0);
- picture.setData(newImage);
- ppt.write(modifiedSlideShow);
- }
-
- // Load the modified slideshow and verify the image content
- try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(modifiedSlideShow.toByteArray()))) {
- HSLFPictureData picture = ppt.getPictureData().get(0);
- byte[] modifiedImageData = picture.getData();
- assertArrayEquals(newImage, modifiedImageData);
+ try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png_encrypted.ppt")) {
+ HSLFPictureData picture1 = ppt1.getPictureData().get(0);
+ picture1.setData(newImage);
+
+ // Load the modified slideshow and verify the image content
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ HSLFPictureData picture2 = ppt2.getPictureData().get(0);
+ byte[] modifiedImageData = picture2.getData();
+ assertArrayEquals(newImage, modifiedImageData);
+ }
}
} finally {
Biff8EncryptionKey.setCurrentUserPassword(null);
@@ -626,27 +422,23 @@ public final class TestPictures {
int[] originalOffsets = {0, 12013, 15081, 34162, 59563};
int[] modifiedOffsets = {0, 35, 3103, 22184, 47585};
- ByteArrayOutputStream inMemory = new ByteArrayOutputStream();
- try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) {
- int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- assertArrayEquals(originalOffsets, offsets);
+ try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) {
+ int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
+ assertArrayEquals(originalOffsets, offsets1);
- HSLFPictureData imageBeingChanged = ppt.getPictureData().get(0);
+ HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0);
// It doesn't matter that this isn't a valid image. We are just testing offsets here.
imageBeingChanged.setData(new byte[10]);
// Verify that the in-memory representations have all been updated
- offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- assertArrayEquals(modifiedOffsets, offsets);
-
- ppt.write(inMemory);
- }
-
- try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) {
+ offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
+ assertArrayEquals(modifiedOffsets, offsets1);
- // Verify that the persisted representations have all been updated
- int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- assertArrayEquals(modifiedOffsets, offsets);
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ // Verify that the persisted representations have all been updated
+ int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
+ assertArrayEquals(modifiedOffsets, offsets2);
+ }
}
}
@@ -662,11 +454,9 @@ public final class TestPictures {
void testEditPictureDataOutOfOrderRecords() throws IOException {
int[] modifiedOffsets = {0, 35, 3103, 22184, 47585};
- ByteArrayOutputStream inMemory = new ByteArrayOutputStream();
- try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) {
-
+ try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) {
// For this test we're going to intentionally manipulate the records into a shuffled order.
- EscherContainerRecord container = ppt.getPictureData().get(0).bStore;
+ EscherContainerRecord container = ppt1.getPictureData().get(0).bStore;
List children = container.getChildRecords();
for (EscherRecord child : children) {
container.removeChildRecord(child);
@@ -676,25 +466,21 @@ public final class TestPictures {
container.addChildRecord(child);
}
- HSLFPictureData imageBeingChanged = ppt.getPictureData().get(0);
+ HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0);
// It doesn't matter that this isn't a valid image. We are just testing offsets here.
imageBeingChanged.setData(new byte[10]);
// Verify that the in-memory representations have all been updated
- int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- Arrays.sort(offsets);
- assertArrayEquals(modifiedOffsets, offsets);
+ int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray();
+ assertArrayEquals(modifiedOffsets, offsets1);
- ppt.write(inMemory);
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ // Verify that the persisted representations have all been updated
+ int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray();
+ assertArrayEquals(modifiedOffsets, offsets2);
+ }
}
- try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) {
-
- // Verify that the persisted representations have all been updated
- int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- Arrays.sort(offsets);
- assertArrayEquals(modifiedOffsets, offsets);
- }
}
/**
@@ -707,28 +493,25 @@ public final class TestPictures {
int originalNumberOfRecords;
// Create a presentation that has records with unmatched offsets, but with matched UIDs.
- ByteArrayOutputStream inMemory = new ByteArrayOutputStream();
- try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) {
- originalOffsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- originalNumberOfRecords = ppt.getPictureData().get(0).bStore.getChildCount();
+ try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) {
+ originalOffsets = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
+ originalNumberOfRecords = ppt1.getPictureData().get(0).bStore.getChildCount();
Random random = new Random();
- for (HSLFPictureData picture : ppt.getPictureData()) {
+ for (HSLFPictureData picture : ppt1.getPictureData()) {
// Bound is arbitrary and irrelevant to the test.
picture.bse.setOffset(random.nextInt(500_000));
}
- ppt.write(inMemory);
- }
- try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) {
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ // Verify that the offsets all got fixed.
+ int[] offsets = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
+ assertArrayEquals(originalOffsets, offsets);
- // Verify that the offsets all got fixed.
- int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
- assertArrayEquals(originalOffsets, offsets);
-
- // Verify that there are the same number of records as in the original slideshow.
- int numberOfRecords = ppt.getPictureData().get(0).bStore.getChildCount();
- assertEquals(originalNumberOfRecords, numberOfRecords);
+ // Verify that there are the same number of records as in the original slideshow.
+ int numberOfRecords = ppt2.getPictureData().get(0).bStore.getChildCount();
+ assertEquals(originalNumberOfRecords, numberOfRecords);
+ }
}
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java
index 8081528a9f..90a84b815e 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java
@@ -24,12 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hslf.HSLFTestDataSamples;
import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.SlideListWithText;
@@ -230,30 +229,30 @@ public final class TestRichTextRun {
assertEquals("Courier", rtr.getFontFamily());
// Write out and back in
- HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h);
-
- // Tweak existing one again, to ensure really worked
- rtr.setBold(false);
- rtr.setFontSize(17d);
- rtr.setFontFamily("CourierZZ");
-
- // Check it took those changes
- assertFalse(rtr.isBold());
- assertEquals(17., rtr.getFontSize(), 0);
- assertEquals("CourierZZ", rtr.getFontFamily());
-
-
- // Now, look at the one we changed, wrote out, and read back in
- // Ensure it does contain our original modifications
- HSLFSlide slideOneRR = readS.getSlides().get(0);
- List> textParassRR = slideOneRR.getTextParagraphs();
- HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0);
-
- assertTrue(rtrRRa.isBold());
- assertNotNull(rtrRRa.getFontSize());
- assertEquals(18., rtrRRa.getFontSize(), 0);
- assertEquals("Courier", rtrRRa.getFontFamily());
- readS.close();
+ try (HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h)) {
+
+ // Tweak existing one again, to ensure really worked
+ rtr.setBold(false);
+ rtr.setFontSize(17d);
+ rtr.setFontFamily("CourierZZ");
+
+ // Check it took those changes
+ assertFalse(rtr.isBold());
+ assertEquals(17., rtr.getFontSize(), 0);
+ assertEquals("CourierZZ", rtr.getFontFamily());
+
+
+ // Now, look at the one we changed, wrote out, and read back in
+ // Ensure it does contain our original modifications
+ HSLFSlide slideOneRR = readS.getSlides().get(0);
+ List> textParassRR = slideOneRR.getTextParagraphs();
+ HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0);
+
+ assertTrue(rtrRRa.isBold());
+ assertNotNull(rtrRRa.getFontSize());
+ assertEquals(18., rtrRRa.getFontSize(), 0);
+ assertEquals("Courier", rtrRRa.getFontFamily());
+ }
}
}
@@ -370,29 +369,30 @@ public final class TestRichTextRun {
*/
private void assertMatchesSLTWC(HSLFSlideShow s) throws IOException {
// Grab a new copy of slideshow C
- HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC);
+ try (HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC)) {
- // Write out the 2nd SLWT in the active document
- SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1];
- byte[] raw_slwt = writeRecord(refSLWT);
+ // Write out the 2nd SLWT in the active document
+ SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1];
+ byte[] raw_slwt = writeRecord(refSLWT);
- // Write out the same for the supplied slideshow
- SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1];
- byte[] s_slwt = writeRecord(s_SLWT);
+ // Write out the same for the supplied slideshow
+ SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1];
+ byte[] s_slwt = writeRecord(s_SLWT);
- // Check the records are the same
- assertEquals(refSLWT.getChildRecords().length, s_SLWT.getChildRecords().length);
- for(int i=0; i txt : sl.getTextParagraphs()) {
- for (HSLFTextParagraph p : txt) {
- int indent = p.getIndentLevel();
- assertTrue(indent >= 0 && indent <= 4 );
- }
+ try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ParagraphStylesShorterThanCharStyles.ppt")) {
+ for (HSLFSlide sl : ppt.getSlides()) {
+ for (List txt : sl.getTextParagraphs()) {
+ for (HSLFTextParagraph p : txt) {
+ int indent = p.getIndentLevel();
+ assertTrue(indent >= 0 && indent <= 4);
+ }
+ }
}
}
- ppt.close();
}
@Test
@@ -502,54 +502,54 @@ public final class TestRichTextRun {
@Test
void testSetParagraphStyles() throws IOException {
- HSLFSlideShow ppt1 = new HSLFSlideShow();
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
- HSLFSlide slide = ppt1.createSlide();
+ HSLFSlide slide = ppt1.createSlide();
- HSLFTextBox shape = new HSLFTextBox();
- shape.setText(
+ HSLFTextBox shape = new HSLFTextBox();
+ shape.setText(
"Hello, World!\r" +
- "This should be\r" +
- "Multiline text");
- HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
- HSLFTextRun tr = rt.getTextRuns().get(0);
- tr.setFontSize(42d);
- rt.setBullet(true);
- rt.setLeftMargin(50d);
- rt.setIndent(0d);
- rt.setBulletChar('\u263A');
- slide.addShape(shape);
-
- assertNotNull(tr.getFontSize());
- assertEquals(42.0, tr.getFontSize(), 0);
- assertTrue(rt.isBullet());
- assertNotNull(rt.getLeftMargin());
- assertEquals(50.0, rt.getLeftMargin(), 0);
- assertNotNull(rt.getIndent());
- assertEquals(0, rt.getIndent(), 0);
- assertNotNull(rt.getBulletChar());
- assertEquals('\u263A', (char)rt.getBulletChar());
-
- shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300));
- slide.addShape(shape);
-
- //serialize and read again
- HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1);
- slide = ppt2.getSlides().get(0);
- shape = (HSLFTextBox)slide.getShapes().get(0);
- rt = shape.getTextParagraphs().get(0);
- tr = rt.getTextRuns().get(0);
- assertNotNull(tr.getFontSize());
- assertEquals(42.0, tr.getFontSize(), 0);
- assertTrue(rt.isBullet());
- assertNotNull(rt.getLeftMargin());
- assertEquals(50.0, rt.getLeftMargin(), 0);
- assertNotNull(rt.getIndent());
- assertEquals(0, rt.getIndent(), 0);
- assertNotNull(rt.getBulletChar());
- assertEquals('\u263A', (char)rt.getBulletChar());
- ppt2.close();
- ppt1.close();
+ "This should be\r" +
+ "Multiline text");
+ HSLFTextParagraph rt = shape.getTextParagraphs().get(0);
+ HSLFTextRun tr = rt.getTextRuns().get(0);
+ tr.setFontSize(42d);
+ rt.setBullet(true);
+ rt.setLeftMargin(50d);
+ rt.setIndent(0d);
+ rt.setBulletChar('\u263A');
+ slide.addShape(shape);
+
+ assertNotNull(tr.getFontSize());
+ assertEquals(42.0, tr.getFontSize(), 0);
+ assertTrue(rt.isBullet());
+ assertNotNull(rt.getLeftMargin());
+ assertEquals(50.0, rt.getLeftMargin(), 0);
+ assertNotNull(rt.getIndent());
+ assertEquals(0, rt.getIndent(), 0);
+ assertNotNull(rt.getBulletChar());
+ assertEquals('\u263A', (char) rt.getBulletChar());
+
+ shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300));
+ slide.addShape(shape);
+
+ //serialize and read again
+ try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) {
+ slide = ppt2.getSlides().get(0);
+ shape = (HSLFTextBox) slide.getShapes().get(0);
+ rt = shape.getTextParagraphs().get(0);
+ tr = rt.getTextRuns().get(0);
+ assertNotNull(tr.getFontSize());
+ assertEquals(42.0, tr.getFontSize(), 0);
+ assertTrue(rt.isBullet());
+ assertNotNull(rt.getLeftMargin());
+ assertEquals(50.0, rt.getLeftMargin(), 0);
+ assertNotNull(rt.getIndent());
+ assertEquals(0, rt.getIndent(), 0);
+ assertNotNull(rt.getBulletChar());
+ assertEquals('\u263A', (char) rt.getBulletChar());
+ }
+ }
}
@Test
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java
index 1176003e7a..437cb592ff 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java
@@ -19,6 +19,7 @@
package org.apache.poi.hslf.usermodel;
+import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -26,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color;
import java.awt.geom.Rectangle2D;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
@@ -108,58 +107,49 @@ public class TestTable {
@Test
void testAddText() throws IOException {
- HSLFSlideShow ppt1 = new HSLFSlideShow();
- HSLFSlide slide = ppt1.createSlide();
- HSLFTable tab = slide.createTable(4, 5);
-
- int rows = tab.getNumberOfRows();
- int cols = tab.getNumberOfColumns();
- for (int row=0; rowTextShape and its sub-classes
+ * Verify behavior of {@code TextShape} and its sub-classes
*/
public final class TestTextShape {
@Test
@@ -72,153 +71,146 @@ public final class TestTextShape {
*/
@Test
void read() throws IOException {
- HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text_shapes.ppt");
-
- List lst1 = new ArrayList<>();
- HSLFSlide slide = ppt.getSlides().get(0);
- for (HSLFShape shape : slide.getShapes()) {
- assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName());
- HSLFTextShape tx = (HSLFTextShape)shape;
- List paras = tx.getTextParagraphs();
- assertNotNull(paras);
- int runType = paras.get(0).getRunType();
-
- ShapeType type = shape.getShapeType();
- String rawText = HSLFTextParagraph.getRawText(paras);
- switch (type){
- case TEXT_BOX:
- assertEquals("Text in a TextBox", rawText);
- break;
- case RECT:
- if(runType == TextPlaceholder.OTHER.nativeId) {
- assertEquals("Rectangle", rawText);
- } else if(runType == TextPlaceholder.TITLE.nativeId) {
- assertEquals("Title Placeholder", rawText);
- }
- break;
- case OCTAGON:
- assertEquals("Octagon", rawText);
- break;
- case ELLIPSE:
- assertEquals("Ellipse", rawText);
- break;
- case ROUND_RECT:
- assertEquals("RoundRectangle", rawText);
- break;
- default:
- fail("Unexpected shape: " + shape.getShapeName());
+ try (HSLFSlideShow ppt = getSlideShow("text_shapes.ppt")) {
+
+ List lst1 = new ArrayList<>();
+ HSLFSlide slide = ppt.getSlides().get(0);
+ for (HSLFShape shape : slide.getShapes()) {
+ assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName());
+ HSLFTextShape tx = (HSLFTextShape) shape;
+ List paras = tx.getTextParagraphs();
+ assertNotNull(paras);
+ int runType = paras.get(0).getRunType();
+
+ ShapeType type = shape.getShapeType();
+ String rawText = HSLFTextParagraph.getRawText(paras);
+ switch (type) {
+ case TEXT_BOX:
+ assertEquals("Text in a TextBox", rawText);
+ break;
+ case RECT:
+ if (runType == TextPlaceholder.OTHER.nativeId) {
+ assertEquals("Rectangle", rawText);
+ } else if (runType == TextPlaceholder.TITLE.nativeId) {
+ assertEquals("Title Placeholder", rawText);
+ }
+ break;
+ case OCTAGON:
+ assertEquals("Octagon", rawText);
+ break;
+ case ELLIPSE:
+ assertEquals("Ellipse", rawText);
+ break;
+ case ROUND_RECT:
+ assertEquals("RoundRectangle", rawText);
+ break;
+ default:
+ fail("Unexpected shape: " + shape.getShapeName());
+
+ }
+ lst1.add(rawText);
+ }
+ List lst2 = new ArrayList<>();
+ for (List paras : slide.getTextParagraphs()) {
+ lst2.add(HSLFTextParagraph.getRawText(paras));
}
- lst1.add(rawText);
- }
- List lst2 = new ArrayList<>();
- for (List paras : slide.getTextParagraphs()) {
- lst2.add(HSLFTextParagraph.getRawText(paras));
+ assertTrue(lst1.containsAll(lst2));
}
-
- assertTrue(lst1.containsAll(lst2));
- ppt.close();
}
@Test
void readWrite() throws IOException {
- HSLFSlideShow ppt = new HSLFSlideShow();
- HSLFSlide slide = ppt.createSlide();
-
- HSLFTextShape shape1 = new HSLFTextBox();
- shape1.setText("Hello, World!");
- slide.addShape(shape1);
-
- shape1.moveTo(100, 100);
-
- HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW);
- shape2.setText("Testing TextShape");
- slide.addShape(shape2);
- shape2.moveTo(300, 300);
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ppt.write(out);
- out.close();
-
- ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()));
- slide = ppt.getSlides().get(0);
- List shape = slide.getShapes();
-
- assertTrue(shape.get(0) instanceof HSLFTextShape);
- shape1 = (HSLFTextShape)shape.get(0);
- assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType());
- assertEquals("Hello, World!", shape1.getText());
-
- assertTrue(shape.get(1) instanceof HSLFTextShape);
- shape1 = (HSLFTextShape)shape.get(1);
- assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType());
- assertEquals("Testing TextShape", shape1.getText());
- ppt.close();
- }
+ try (HSLFSlideShow ppt1 = new HSLFSlideShow()) {
+ HSLFSlide slide = ppt1.createSlide();
- @Test
- void margins() throws IOException {
- HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text-margins.ppt");
+ HSLFTextShape shape1 = new HSLFTextBox();
+ shape1.setText("Hello, World!");
+ slide.addShape(shape1);
+
+ shape1.moveTo(100, 100);
+
+ HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW);
+ shape2.setText("Testing TextShape");
+ slide.addShape(shape2);
+ shape2.moveTo(300, 300);
+
+ try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {
+ slide = ppt2.getSlides().get(0);
+ List shape = slide.getShapes();
- HSLFSlide slide = ppt.getSlides().get(0);
+ assertTrue(shape.get(0) instanceof HSLFTextShape);
+ shape1 = (HSLFTextShape) shape.get(0);
+ assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType());
+ assertEquals("Hello, World!", shape1.getText());
- Map map = new HashMap<>();
- for (HSLFShape shape : slide.getShapes()) {
- if(shape instanceof HSLFTextShape){
- HSLFTextShape tx = (HSLFTextShape)shape;
- map.put(tx.getText(), tx);
+ assertTrue(shape.get(1) instanceof HSLFTextShape);
+ shape1 = (HSLFTextShape) shape.get(1);
+ assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType());
+ assertEquals("Testing TextShape", shape1.getText());
}
}
-
- HSLFTextShape tx;
-
- tx = map.get("TEST1");
- assertEquals(7.2, tx.getLeftInset(), 0);
- assertEquals(7.2, tx.getRightInset(), 0);
- assertEquals(28.34, tx.getTopInset(), 0.01);
- assertEquals(3.6, tx.getBottomInset(), 0);
-
- tx = map.get("TEST2");
- assertEquals(7.2, tx.getLeftInset(), 0);
- assertEquals(7.2, tx.getRightInset(), 0);
- assertEquals(3.6, tx.getTopInset(), 0);
- assertEquals(28.34, tx.getBottomInset(), 0.01);
-
- tx = map.get("TEST3");
- assertEquals(28.34, tx.getLeftInset(), 0.01);
- assertEquals(7.2, tx.getRightInset(), 0);
- assertEquals(3.6, tx.getTopInset(), 0);
- assertEquals(3.6, tx.getBottomInset(), 0);
-
- tx = map.get("TEST4");
- assertEquals(7.2, tx.getLeftInset(), 0);
- assertEquals(28.34, tx.getRightInset(), 0.01);
- assertEquals(3.6, tx.getTopInset(), 0);
- assertEquals(3.6, tx.getBottomInset(), 0);
-
- ppt.close();
}
@Test
- void bug52599() throws IOException {
- HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("52599.ppt");
+ void margins() throws IOException {
+ try (HSLFSlideShow ppt = getSlideShow("text-margins.ppt")) {
- HSLFSlide slide = ppt.getSlides().get(0);
- List sh = slide.getShapes();
- assertEquals(3, sh.size());
+ HSLFSlide slide = ppt.getSlides().get(0);
- HSLFTextShape sh0 = (HSLFTextShape)sh.get(0);
- assertNotNull(sh0.getTextParagraphs());
- assertEquals("", sh0.getText());
+ Map map = new HashMap<>();
+ for (HSLFShape shape : slide.getShapes()) {
+ if (shape instanceof HSLFTextShape) {
+ HSLFTextShape tx = (HSLFTextShape) shape;
+ map.put(tx.getText(), tx);
+ }
+ }
- HSLFTextShape sh1 = (HSLFTextShape)sh.get(1);
- assertNotNull(sh1.getTextParagraphs());
- assertEquals("", sh1.getText());
+ HSLFTextShape tx = map.get("TEST1");
+ assertEquals(7.2, tx.getLeftInset(), 0);
+ assertEquals(7.2, tx.getRightInset(), 0);
+ assertEquals(28.34, tx.getTopInset(), 0.01);
+ assertEquals(3.6, tx.getBottomInset(), 0);
+
+ tx = map.get("TEST2");
+ assertEquals(7.2, tx.getLeftInset(), 0);
+ assertEquals(7.2, tx.getRightInset(), 0);
+ assertEquals(3.6, tx.getTopInset(), 0);
+ assertEquals(28.34, tx.getBottomInset(), 0.01);
+
+ tx = map.get("TEST3");
+ assertEquals(28.34, tx.getLeftInset(), 0.01);
+ assertEquals(7.2, tx.getRightInset(), 0);
+ assertEquals(3.6, tx.getTopInset(), 0);
+ assertEquals(3.6, tx.getBottomInset(), 0);
+
+ tx = map.get("TEST4");
+ assertEquals(7.2, tx.getLeftInset(), 0);
+ assertEquals(28.34, tx.getRightInset(), 0.01);
+ assertEquals(3.6, tx.getTopInset(), 0);
+ assertEquals(3.6, tx.getBottomInset(), 0);
+ }
+ }
- HSLFTextShape sh2 = (HSLFTextShape)sh.get(2);
- assertEquals("this box should be shown just once", sh2.getText());
- assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex());
- ppt.close();
+ @Test
+ void bug52599() throws IOException {
+ try (HSLFSlideShow ppt = getSlideShow("52599.ppt")) {
+ HSLFSlide slide = ppt.getSlides().get(0);
+ List sh = slide.getShapes();
+ assertEquals(3, sh.size());
+
+ HSLFTextShape sh0 = (HSLFTextShape) sh.get(0);
+ assertNotNull(sh0.getTextParagraphs());
+ assertEquals("", sh0.getText());
+
+ HSLFTextShape sh1 = (HSLFTextShape) sh.get(1);
+ assertNotNull(sh1.getTextParagraphs());
+ assertEquals("", sh1.getText());
+
+ HSLFTextShape sh2 = (HSLFTextShape) sh.get(2);
+ assertEquals("this box should be shown just once", sh2.getText());
+ assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex());
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java
index 4f0322b806..a11ba12c90 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java
@@ -21,12 +21,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Map;
import java.util.TimeZone;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.datatypes.AttachmentChunks;
import org.apache.poi.hsmf.datatypes.Chunk;
@@ -54,8 +54,6 @@ public class TestExtractEmbeddedMSG {
/**
* Initialize this test, load up the attachment_msg_pdf.msg mapi message.
- *
- * @throws Exception
*/
@BeforeAll
public static void setUp() throws IOException {
@@ -71,9 +69,6 @@ public class TestExtractEmbeddedMSG {
/**
* Test to see if embedded message properties can be read, extracted, and
* re-parsed
- *
- * @throws ChunkNotFoundException
- *
*/
@Test
void testEmbeddedMSGProperties() throws IOException, ChunkNotFoundException {
@@ -86,11 +81,9 @@ public class TestExtractEmbeddedMSG {
testFixedAndVariableLengthPropertiesOfAttachedMSG(attachedMsg);
// rebuild top level message from embedded message
try (POIFSFileSystem extractedAttachedMsg = rebuildFromAttached(attachedMsg)) {
- try (ByteArrayOutputStream extractedAttachedMsgOut = new ByteArrayOutputStream()) {
+ try (UnsynchronizedByteArrayOutputStream extractedAttachedMsgOut = new UnsynchronizedByteArrayOutputStream()) {
extractedAttachedMsg.writeFilesystem(extractedAttachedMsgOut);
- byte[] extratedAttachedMsgRaw = extractedAttachedMsgOut.toByteArray();
- MAPIMessage extractedMsgTopLevel = new MAPIMessage(
- new ByteArrayInputStream(extratedAttachedMsgRaw));
+ MAPIMessage extractedMsgTopLevel = new MAPIMessage(extractedAttachedMsgOut.toInputStream());
// test properties of rebuilt embedded message
testFixedAndVariableLengthPropertiesOfAttachedMSG(extractedMsgTopLevel);
}
@@ -104,7 +97,7 @@ public class TestExtractEmbeddedMSG {
Calendar messageDate = msg.getMessageDate();
assertNotNull(messageDate);
Calendar expectedMessageDate = LocaleUtil.getLocaleCalendar();
- expectedMessageDate.set(2010, 05, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT
+ expectedMessageDate.set(2010, Calendar.JUNE, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT
expectedMessageDate.setTimeZone(TimeZone.getTimeZone("GMT"));
expectedMessageDate.set(Calendar.MILLISECOND, 0);
assertEquals(expectedMessageDate.getTimeInMillis(), messageDate.getTimeInMillis());
@@ -178,7 +171,7 @@ public class TestExtractEmbeddedMSG {
MAPIType type = Types.getById(iType);
if (type != null && type != Types.UNKNOWN) {
MAPIProperty mprop = MAPIProperty.createCustom(chunk.getChunkId(), type, chunk.getEntryName());
- ByteArrayOutputStream data = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream data = new UnsynchronizedByteArrayOutputStream();
chunk.writeValue(data);
PropertyValue pval = new PropertyValue(mprop, MessagePropertiesChunk.PROPERTIES_FLAG_READABLE
| MessagePropertiesChunk.PROPERTIES_FLAG_WRITEABLE, data.toByteArray(), type);
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java
index 1d8cc9f98a..068fa10883 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java
@@ -22,14 +22,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.datatypes.AttachmentChunks;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
/**
* Tests to verify that we can read attachments from msg file
@@ -74,32 +76,21 @@ public class TestFileWithAttachmentsRead {
/**
* Bug 60550: Test to see if we get the correct Content-IDs of inline images`.
*/
- @Test
- void testReadContentIDField() throws IOException {
- AttachmentChunks[] attachments = inlineImgMsgAttachments.getAttachmentFiles();
-
- AttachmentChunks attachment;
-
- // Check in Content-ID field
- attachment = inlineImgMsgAttachments.getAttachmentFiles()[0];
- assertEquals("image001.png", attachment.getAttachFileName().getValue());
- assertEquals(".png", attachment.getAttachExtension().getValue());
- assertEquals("image001.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue());
-
- attachment = inlineImgMsgAttachments.getAttachmentFiles()[1];
- assertEquals("image002.png", attachment.getAttachFileName().getValue());
- assertEquals(".png", attachment.getAttachExtension().getValue());
- assertEquals("image002.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue());
-
- attachment = inlineImgMsgAttachments.getAttachmentFiles()[2];
- assertEquals("image003.png", attachment.getAttachFileName().getValue());
- assertEquals(".png", attachment.getAttachExtension().getValue());
- assertEquals("image003.png@01D0A526.B4C739C0", attachment.getAttachContentId().getValue());
-
- attachment = inlineImgMsgAttachments.getAttachmentFiles()[3];
- assertEquals("image006.jpg", attachment.getAttachFileName().getValue());
- assertEquals(".jpg", attachment.getAttachExtension().getValue());
- assertEquals("image006.jpg@01D0A526.B649E220", attachment.getAttachContentId().getValue());
+ @ParameterizedTest
+ @CsvSource({
+ "0, image001.png@01D0A524.96D40F30",
+ "1, image002.png@01D0A524.96D40F30",
+ "2, image003.png@01D0A526.B4C739C0",
+ "3, image006.jpg@01D0A526.B649E220"
+ })
+ void testReadContentIDField(int index, String contentId) {
+ AttachmentChunks attachment = inlineImgMsgAttachments.getAttachmentFiles()[index];
+ String fileName = contentId.substring(0, contentId.indexOf("@"));
+ String extension = fileName.substring(fileName.lastIndexOf("."));
+
+ assertEquals(fileName, attachment.getAttachFileName().getValue());
+ assertEquals(extension, attachment.getAttachExtension().getValue());
+ assertEquals(contentId, attachment.getAttachContentId().getValue());
}
@@ -128,7 +119,7 @@ public class TestFileWithAttachmentsRead {
assertEquals("test-unicode.doc", attachment.getAttachLongFileName().getValue());
assertEquals(".doc", attachment.getAttachExtension().getValue());
assertNull(attachment.getAttachMimeTag());
- ByteArrayOutputStream attachmentstream = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream attachmentstream = new UnsynchronizedByteArrayOutputStream();
attachment.getAttachData().writeValue(attachmentstream);
assertEquals(24064, attachmentstream.size());
// or compare the hashes of the attachment data
@@ -141,7 +132,7 @@ public class TestFileWithAttachmentsRead {
assertNull(attachment.getAttachMimeTag());
// or compare the hashes of the attachment data
assertEquals(89, attachment.getAttachData().getValue().length);
- attachmentstream = new ByteArrayOutputStream();
+ attachmentstream.reset();
attachment.getAttachData().writeValue(attachmentstream);
assertEquals(89, attachmentstream.size());
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java
index 04131f3a23..74d6d27ec2 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java
@@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
@@ -33,6 +32,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
+import org.apache.commons.io.output.NullPrintStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hsmf.datatypes.ChunkBasedPropertyValue;
import org.apache.poi.hsmf.datatypes.Chunks;
@@ -44,7 +44,6 @@ import org.apache.poi.hsmf.dev.HSMFDump;
import org.apache.poi.hsmf.extractor.OutlookTextExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.util.NullPrintStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -167,7 +166,7 @@ public final class TestFixedSizedProperties {
* Test to see if we can read the Date Chunk with HSMFDump.
*/
@Test
- void testReadMessageDateSucceedsWithHSMFDump() throws IOException {
+ void testReadMessageDateSucceedsWithHSMFDump() {
HSMFDump dump = new HSMFDump(fsMessageSucceeds);
assertDoesNotThrow(() -> dump.dump(new NullPrintStream()));
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java
index 937bb5367d..fba8bc97c0 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java
@@ -17,10 +17,10 @@
package org.apache.poi.hwpf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -29,7 +29,7 @@ public abstract class HWPFTestCase {
@BeforeEach
void setUp() throws Exception {
- /** @todo verify the constructors */
+ // @TODO verify the constructors
_hWPFDocFixture = new HWPFDocFixture(this, getTestFile());
_hWPFDocFixture.setUp();
@@ -40,7 +40,7 @@ public abstract class HWPFTestCase {
}
@AfterEach
- void tearDown() throws Exception {
+ void tearDown() {
if (_hWPFDocFixture != null) {
_hWPFDocFixture.tearDown();
}
@@ -49,15 +49,13 @@ public abstract class HWPFTestCase {
}
public HWPFDocument writeOutAndRead(HWPFDocument doc) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- HWPFDocument newDoc;
- try {
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
doc.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- newDoc = new HWPFDocument(bais);
+ try (InputStream is = baos.toInputStream()) {
+ return new HWPFDocument(is);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
- return newDoc;
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java
index b8f11dc40f..0d6ce9bc8c 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java
@@ -16,74 +16,24 @@
==================================================================== */
package org.apache.poi.hwpf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.util.zip.ZipInputStream;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.IOUtils;
-
-import static org.apache.logging.log4j.util.Unbox.box;
public class HWPFTestDataSamples {
-
- private static final Logger LOG = LogManager.getLogger(HWPFTestDataSamples.class);
+ private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance();
public static HWPFDocument openSampleFile(String sampleFileName) {
- try {
- InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName);
- try {
- return new HWPFDocument(is);
- } catch (Throwable e) {
- is.close();
- throw e;
- }
+ try (InputStream is = SAMPLES.openResourceAsStream(sampleFileName)) {
+ return new HWPFDocument(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
- public static HWPFDocument openSampleFileFromArchive( String sampleFileName )
- {
- final long start = System.currentTimeMillis();
- try
- {
- try (ZipInputStream is = new ZipInputStream(POIDataSamples
- .getDocumentInstance()
- .openResourceAsStream(sampleFileName))) {
- is.getNextEntry();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try {
- IOUtils.copy(is, baos);
- } finally {
- baos.close();
- }
-
- final long endUnzip = System.currentTimeMillis();
- byte[] byteArray = baos.toByteArray();
-
- LOG.atDebug().log("Unzipped in {} ms -- {} byte(s)", box(endUnzip - start),box(byteArray.length));
-
- ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
- HWPFDocument doc = new HWPFDocument(bais);
- final long endParse = System.currentTimeMillis();
-
- LOG.atDebug().log("Parsed in {} ms", box(endParse - start));
-
- return doc;
- }
- }
- catch ( IOException e )
- {
- throw new RuntimeException( e );
- }
- }
-
public static HWPFOldDocument openOldSampleFile(String sampleFileName) {
try {
InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName);
@@ -98,11 +48,9 @@ public class HWPFTestDataSamples {
* Useful for verifying that the serialisation round trip
*/
public static HWPFDocument writeOutAndReadBack(HWPFDocument original) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) {
original.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- return new HWPFDocument(bais);
+ return new HWPFDocument(baos.toInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java
index 3a94a3efb4..c7cd45c1cc 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java
@@ -22,7 +22,7 @@ import java.io.PrintStream;
import java.util.Arrays;
import org.apache.poi.POIDataSamples;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -38,7 +38,7 @@ public class TestHWPFLister {
"",
" --dop --textPieces --textPiecesText --chpx --chpxProperties --chpxSprms --papx --papxProperties --papxSprms --paragraphs --paragraphsText --bookmarks --escher --fields --pictures --officeDrawings --styles --writereadback"
})
- void main(String args) throws Exception {
+ void main(String args) {
String fileArgs = SAMPLES.getFile("SampleDoc.doc").getAbsolutePath() + args;
PrintStream oldStdOut = System.out;
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java
index 0ae2e4a87a..b98f5208a0 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java
@@ -17,17 +17,15 @@
package org.apache.poi.hwpf.model;
+import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile;
+import static org.apache.poi.hwpf.HWPFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.hwpf.HWPFDocument;
-import org.apache.poi.hwpf.HWPFTestDataSamples;
import org.junit.jupiter.api.Test;
/**
@@ -53,29 +51,21 @@ public final class TestSavedByTable {
* Tests reading in the entries, comparing them against the expected
* entries. Then tests writing the document out and reading the entries yet
* again.
- *
- * @throws Exception if an unexpected error occurs.
*/
@Test
void testReadWrite() throws IOException {
// This document is widely available on the internet as "blair.doc".
// I tried stripping the content and saving the document but my version
// of Word (from Office XP) strips this table out.
- HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc");
+ try (HWPFDocument doc = openSampleFile("saved-by-table.doc")) {
+ // Check what we just read.
+ assertEquals(expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected");
- // Check what we just read.
- assertEquals( expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected" );
-
- // Now write the entire document out, and read it back in...
- ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
- doc.write(byteStream);
- InputStream copyStream = new ByteArrayInputStream(byteStream.toByteArray());
- doc.close();
- HWPFDocument copy = new HWPFDocument(copyStream);
-
- // And check again.
- assertEquals( expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing" );
-
- copy.close();
+ // Now write the entire document out, and read it back in...
+ try (HWPFDocument copy = writeOutAndReadBack(doc)) {
+ // And check again.
+ assertEquals(expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing");
+ }
+ }
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java
index 65c5dac5a8..d8cbba82c8 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java
@@ -19,43 +19,29 @@
package org.apache.poi.hwpf.sprm;
+import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile;
+import static org.apache.poi.hwpf.HWPFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.util.Locale;
-import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.junit.jupiter.api.Test;
public class TestSprms {
- private static HWPFDocument reload( HWPFDocument hwpfDocument )
- throws IOException
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- hwpfDocument.write( baos );
- return new HWPFDocument( new ByteArrayInputStream( baos.toByteArray() ) );
- }
-
/**
* Test correct processing of "sprmPItap" (0x6649) and "sprmPFInTable"
* (0x2416)
*/
@Test
void testInnerTable() throws Exception {
- InputStream resourceAsStream = POIDataSamples.getDocumentInstance()
- .openResourceAsStream( "innertable.doc" );
- try (HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream )) {
- resourceAsStream.close();
-
+ try (HWPFDocument hwpfDocument = openSampleFile("innertable.doc")) {
testInnerTable(hwpfDocument);
- try (HWPFDocument hwpfDocument2 = reload(hwpfDocument)) {
+ try (HWPFDocument hwpfDocument2 = writeOutAndReadBack(hwpfDocument)) {
testInnerTable(hwpfDocument2);
}
}
@@ -87,20 +73,12 @@ public class TestSprms {
*/
@Test
void testSprmPJc() throws IOException {
- try (InputStream resourceAsStream = POIDataSamples.getDocumentInstance()
- .openResourceAsStream( "Bug49820.doc" );
- HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream )) {
- resourceAsStream.close();
+ try (HWPFDocument hwpfDocument = openSampleFile( "Bug49820.doc" )) {
+ assertEquals(1, hwpfDocument.getStyleSheet().getParagraphStyle(8).getJustification());
- assertEquals(1, hwpfDocument.getStyleSheet().getParagraphStyle(8)
- .getJustification());
-
- try (HWPFDocument hwpfDocument2 = reload(hwpfDocument)) {
-
- assertEquals(1, hwpfDocument2.getStyleSheet().getParagraphStyle(8)
- .getJustification());
+ try (HWPFDocument hwpfDocument2 = writeOutAndReadBack(hwpfDocument)) {
+ assertEquals(1, hwpfDocument2.getStyleSheet().getParagraphStyle(8).getJustification());
}
}
-
}
}
diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java
index 3f0f8b7ce0..36ad393a51 100644
--- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java
+++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java
@@ -20,14 +20,13 @@ package org.apache.poi.hwpf.usermodel;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.HWPFTestCase;
@@ -48,20 +47,17 @@ public final class TestHWPFWrite extends HWPFTestCase {
*/
@Test
void testWriteStream() throws IOException {
- HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc");
-
- Range r = doc.getRange();
- assertEquals("I am a test document\r", r.getParagraph(0).text());
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- doc.write(baos);
- doc.close();
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
+ try (HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc")) {
+ Range r = doc.getRange();
+ assertEquals("I am a test document\r", r.getParagraph(0).text());
+ doc.write(baos);
+ }
- doc = new HWPFDocument(bais);
- r = doc.getRange();
- assertEquals("I am a test document\r", r.getParagraph(0).text());
- doc.close();
+ try (HWPFDocument doc = new HWPFDocument(baos.toInputStream())) {
+ Range r = doc.getRange();
+ assertEquals("I am a test document\r", r.getParagraph(0).text());
+ }
}
/**
diff --git a/poi/build.gradle b/poi/build.gradle
index d4388eebfc..23d024c516 100644
--- a/poi/build.gradle
+++ b/poi/build.gradle
@@ -39,6 +39,7 @@ dependencies {
api "commons-codec:commons-codec:${commonsCodecVersion}"
api 'org.apache.commons:commons-collections4:4.4'
api "org.apache.commons:commons-math3:${commonsMathVersion}"
+ api "commons-io:commons-io:${commonsIoVersion}"
api 'com.zaxxer:SparseBitSet:1.2'
implementation "org.apache.logging.log4j:log4j-api:${log4jVersion}"
implementation 'javax.activation:activation:1.1.1'
diff --git a/poi/src/main/java/org/apache/poi/POIDocument.java b/poi/src/main/java/org/apache/poi/POIDocument.java
index e2f613af64..e1405f9977 100644
--- a/poi/src/main/java/org/apache/poi/POIDocument.java
+++ b/poi/src/main/java/org/apache/poi/POIDocument.java
@@ -21,8 +21,6 @@ import static org.apache.logging.log4j.util.Unbox.box;
import static org.apache.poi.hpsf.PropertySetFactory.newDocumentSummaryInformation;
import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
@@ -32,6 +30,7 @@ import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hpsf.DocumentSummaryInformation;
@@ -323,18 +322,16 @@ public abstract class POIDocument implements Closeable {
* {@link POIFSFileSystem} occurs
*/
private void writePropertySet(String name, PropertySet set, POIFSFileSystem outFS) throws IOException {
- try {
+ try (UnsynchronizedByteArrayOutputStream bOut = new UnsynchronizedByteArrayOutputStream()) {
PropertySet mSet = new PropertySet(set);
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
-
mSet.write(bOut);
- byte[] data = bOut.toByteArray();
- ByteArrayInputStream bIn = new ByteArrayInputStream(data);
- // Create or Update the Property Set stream in the POIFS
- outFS.createOrUpdateDocument(bIn, name);
+ try (InputStream bIn = bOut.toInputStream()) {
+ // Create or Update the Property Set stream in the POIFS
+ outFS.createOrUpdateDocument(bIn, name);
+ }
- LOG.atInfo().log("Wrote property set {} of size {}", name, box(data.length));
+ LOG.atInfo().log("Wrote property set {} of size {}", name, box(bOut.size()));
} catch(WritingNotSupportedException ignored) {
LOG.atError().log("Couldn't write property set with name {} as not supported by HPSF yet", name);
}
diff --git a/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java b/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java
index 249e74cb2e..e7f02f471b 100644
--- a/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java
+++ b/poi/src/main/java/org/apache/poi/ddf/DefaultEscherRecordFactory.java
@@ -22,7 +22,6 @@ import java.util.function.Supplier;
import org.apache.poi.util.BitField;
import org.apache.poi.util.BitFieldFactory;
import org.apache.poi.util.LittleEndian;
-import org.apache.poi.util.Removal;
/**
* Generates escher records when provided the byte array containing those records.
@@ -73,23 +72,4 @@ public class DefaultEscherRecordFactory implements EscherRecordFactory {
// catch all
return UnknownEscherRecord::new;
}
-
-
- /**
- * @deprecated this method is not used anymore to identify container records
- */
- @Deprecated
- @Removal(version = "5.0.0")
- public static boolean isContainer(short options, short recordId){
- if(recordId >= EscherContainerRecord.DGG_CONTAINER && recordId
- <= EscherContainerRecord.SOLVER_CONTAINER){
- return true;
- } else {
- if (recordId == EscherTextboxRecord.RECORD_ID) {
- return false;
- } else {
- return ( options & (short) 0x000F ) == (short) 0x000F;
- }
- }
- }
}
diff --git a/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java b/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java
index 6713b5fc17..75062a7005 100644
--- a/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java
+++ b/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java
@@ -17,10 +17,11 @@
package org.apache.poi.ddf;
+import static org.apache.logging.log4j.util.Unbox.box;
+
import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -29,21 +30,30 @@ import java.util.function.Supplier;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
-
-import static org.apache.logging.log4j.util.Unbox.box;
+import org.apache.poi.util.Removal;
public final class EscherMetafileBlip extends EscherBlipRecord {
private static final Logger LOGGER = LogManager.getLogger(EscherMetafileBlip.class);
//arbitrarily selected; may need to increase
private static final int MAX_RECORD_LENGTH = 100_000_000;
+ /** @deprecated use EscherRecordTypes.BLIP_EMF.typeID */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short RECORD_ID_EMF = EscherRecordTypes.BLIP_EMF.typeID;
+ /** @deprecated use EscherRecordTypes.BLIP_WMF.typeID */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short RECORD_ID_WMF = EscherRecordTypes.BLIP_WMF.typeID;
+ /** @deprecated use EscherRecordTypes.BLIP_PICT.typeID */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short RECORD_ID_PICT = EscherRecordTypes.BLIP_PICT.typeID;
private static final int HEADER_SIZE = 8;
@@ -150,9 +160,10 @@ public final class EscherMetafileBlip extends EscherBlipRecord {
data[pos] = field_6_fCompression; pos++;
data[pos] = field_7_fFilter; pos++;
- System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length ); pos += raw_pictureData.length;
+ System.arraycopy( raw_pictureData, 0, data, pos, raw_pictureData.length );
+ pos += raw_pictureData.length;
if(remainingData != null) {
- System.arraycopy( remainingData, 0, data, pos, remainingData.length ); pos += remainingData.length;
+ System.arraycopy( remainingData, 0, data, pos, remainingData.length );
}
listener.afterRecordSerialize(offset + getRecordSize(), getRecordId(), getRecordSize(), this);
@@ -166,15 +177,9 @@ public final class EscherMetafileBlip extends EscherBlipRecord {
* @return the inflated picture data.
*/
private static byte[] inflatePictureData(byte[] data) {
- try {
- InflaterInputStream in = new InflaterInputStream(
- new ByteArrayInputStream( data ) );
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- byte[] buf = new byte[4096];
- int readBytes;
- while ((readBytes = in.read(buf)) > 0) {
- out.write(buf, 0, readBytes);
- }
+ try (InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(data));
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
+ IOUtils.copy(in, out);
return out.toByteArray();
} catch (IOException e) {
LOGGER.atWarn().withThrowable(e).log("Possibly corrupt compression or non-compressed data");
@@ -390,11 +395,10 @@ public final class EscherMetafileBlip extends EscherBlipRecord {
// "... LZ compression algorithm in the format used by GNU Zip deflate/inflate with a 32k window ..."
// not sure what to do, when lookup tables exceed 32k ...
- try {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- DeflaterOutputStream dos = new DeflaterOutputStream(bos);
- dos.write(pictureData);
- dos.close();
+ try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
+ try (DeflaterOutputStream dos = new DeflaterOutputStream(bos)) {
+ dos.write(pictureData);
+ }
raw_pictureData = bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Can't compress metafile picture data", e);
diff --git a/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java b/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java
index a0a5d68fb8..b5fffd5d84 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java
@@ -41,16 +41,18 @@ public class HPSFPropertiesOnlyDocument extends POIDocument {
/**
* Write out to the currently open file the properties changes, but nothing else
*/
+ @Override
public void write() throws IOException {
POIFSFileSystem fs = getDirectory().getFileSystem();
-
- validateInPlaceWritePossible();
+
+ validateInPlaceWritePossible();
writeProperties(fs, null);
fs.writeFilesystem();
}
/**
* Write out, with any properties changes, but nothing else
*/
+ @Override
public void write(File newFile) throws IOException {
try (POIFSFileSystem fs = POIFSFileSystem.create(newFile)) {
write(fs);
@@ -60,25 +62,26 @@ public class HPSFPropertiesOnlyDocument extends POIDocument {
/**
* Write out, with any properties changes, but nothing else
*/
+ @Override
public void write(OutputStream out) throws IOException {
try (POIFSFileSystem fs = new POIFSFileSystem()) {
write(fs);
fs.writeFilesystem(out);
}
}
-
+
private void write(POIFSFileSystem fs) throws IOException {
// For tracking what we've written out, so far
List excepts = new ArrayList<>(2);
// Write out our HPFS properties, with any changes
writeProperties(fs, excepts);
-
+
// Copy over everything else unchanged
FilteringDirectoryNode src = new FilteringDirectoryNode(getDirectory(), excepts);
FilteringDirectoryNode dest = new FilteringDirectoryNode(fs.getRoot(), excepts);
EntryUtils.copyNodes(src, dest);
-
+
// Caller will save the resultant POIFSFileSystem to the stream/file
}
}
diff --git a/poi/src/main/java/org/apache/poi/hpsf/MarkUnsupportedException.java b/poi/src/main/java/org/apache/poi/hpsf/MarkUnsupportedException.java
deleted file mode 100644
index 450c892abc..0000000000
--- a/poi/src/main/java/org/apache/poi/hpsf/MarkUnsupportedException.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/* ====================================================================
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-==================================================================== */
-
-package org.apache.poi.hpsf;
-
-/**
- * This exception is thrown if an {@link java.io.InputStream} does
- * not support the {@link java.io.InputStream#mark} operation.
- */
-public class MarkUnsupportedException extends HPSFException
-{
-
- /**
- * Constructor
- */
- public MarkUnsupportedException()
- {
- super();
- }
-
-
- /**
- * Constructor
- *
- * @param msg The exception's message string
- */
- public MarkUnsupportedException(final String msg)
- {
- super(msg);
- }
-
-
- /**
- * Constructor
- *
- * @param reason This exception's underlying reason
- */
- public MarkUnsupportedException(final Throwable reason)
- {
- super(reason);
- }
-
-
- /**
- * Constructor
- *
- * @param msg The exception's message string
- * @param reason This exception's underlying reason
- */
- public MarkUnsupportedException(final String msg, final Throwable reason)
- {
- super(msg, reason);
- }
-
-}
diff --git a/poi/src/main/java/org/apache/poi/hpsf/Property.java b/poi/src/main/java/org/apache/poi/hpsf/Property.java
index 0e3e2cdea2..2b05f763af 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/Property.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/Property.java
@@ -17,7 +17,8 @@
package org.apache.poi.hpsf;
-import java.io.ByteArrayOutputStream;
+import static org.apache.logging.log4j.util.Unbox.box;
+
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
@@ -29,6 +30,7 @@ import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hpsf.wellknown.PropertyIDMap;
@@ -39,8 +41,6 @@ import org.apache.poi.util.LittleEndianByteArrayInputStream;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.LocaleUtil;
-import static org.apache.logging.log4j.util.Unbox.box;
-
/**
* A property in a {@link Section} of a {@link PropertySet}.
*
@@ -115,7 +115,7 @@ public class Property {
}
/**
- * Creates a {@link Property} instance by reading its bytes
+ * Creates a Property instance by reading its bytes
* from the property set stream.
*
* @param id The property's ID.
@@ -153,7 +153,7 @@ public class Property {
}
/**
- * Creates a {@link Property} instance by reading its bytes
+ * Creates a Property instance by reading its bytes
* from the property set stream.
*
* @param id The property's ID.
@@ -272,7 +272,7 @@ public class Property {
/* Variable length: */
if (type == Variant.VT_LPSTR || type == Variant.VT_LPWSTR) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
length = write(bos, property) - 2*LittleEndianConsts.INT_SIZE;
/* Pad to multiples of 4. */
@@ -295,8 +295,6 @@ public class Property {
* ID == 0 is a special case: It does not have a type, and its value is the
* section's dictionary. Another special case are strings: Two properties
* may have the different types Variant.VT_LPSTR and Variant.VT_LPWSTR;
- *
- * @see Object#equals(Object)
*/
@Override
public boolean equals(final Object o) {
@@ -366,22 +364,12 @@ public class Property {
(t2 == Variant.VT_LPSTR && t1 == Variant.VT_LPWSTR));
}
-
-
- /**
- * @see Object#hashCode()
- */
@Override
public int hashCode() {
return Objects.hash(id,type,value);
}
-
-
- /**
- * @see Object#toString()
- */
@Override
public String toString() {
return toString(Property.DEFAULT_CODEPAGE, null);
@@ -411,7 +399,7 @@ public class Property {
if (value instanceof String) {
b.append((String)value);
b.append("\n");
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
write(bos, codepage);
} catch (Exception e) {
diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java
index d110747d11..324fb4b4c9 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java
@@ -18,7 +18,6 @@
package org.apache.poi.hpsf;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -27,6 +26,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.EmptyFileException;
import org.apache.poi.hpsf.wellknown.PropertyIDMap;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
@@ -38,7 +38,6 @@ import org.apache.poi.util.LittleEndianByteArrayInputStream;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.LittleEndianOutputStream;
import org.apache.poi.util.NotImplemented;
-import org.apache.poi.util.Removal;
/**
* Represents a property set in the Horrible Property Set Format
@@ -166,7 +165,7 @@ public class PropertySet {
/**
- * Creates a {@link PropertySet} instance from an {@link
+ * Creates a PropertySet instance from an {@link
* InputStream} in the Horrible Property Set Format.
*
* The constructor reads the first few bytes from the stream
@@ -198,7 +197,7 @@ public class PropertySet {
/**
- * Creates a {@link PropertySet} instance from a byte array that
+ * Creates a PropertySet instance from a byte array that
* represents a stream in the Horrible Property Set Format.
*
* @param stream The byte array holding the stream data.
@@ -220,7 +219,7 @@ public class PropertySet {
}
/**
- * Creates a {@link PropertySet} instance from a byte array
+ * Creates a PropertySet instance from a byte array
* that represents a stream in the Horrible Property Set Format.
*
* @param stream The byte array holding the stream data. The
@@ -439,7 +438,7 @@ public class PropertySet {
/**
- * Initializes this {@link PropertySet} instance from a byte
+ * Initializes this PropertySet instance from a byte
* array. The method assumes that it has been checked already that
* the byte array indeed represents a property set stream. It does
* no more checks on its own.
@@ -515,7 +514,7 @@ public class PropertySet {
}
private byte[] toBytes() throws WritingNotSupportedException, IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream leos = new LittleEndianOutputStream(bos);
/* Write the number of sections in this property set stream. */
@@ -590,7 +589,7 @@ public class PropertySet {
* document. The input stream represents a snapshot of the property set.
* If the latter is modified while the input stream is still being
* read, the modifications will not be reflected in the input stream but in
- * the {@link PropertySet} only.
+ * the PropertySet only.
*
* @return the contents of this property set stream
*
@@ -657,9 +656,9 @@ public class PropertySet {
}
/**
- * Checks whether this {@link PropertySet} represents a Summary Information.
+ * Checks whether this PropertySet represents a Summary Information.
*
- * @return {@code true} if this {@link PropertySet}
+ * @return {@code true} if this PropertySet
* represents a Summary Information, else {@code false}.
*/
public boolean isSummaryInformation() {
@@ -667,9 +666,9 @@ public class PropertySet {
}
/**
- * Checks whether this {@link PropertySet} is a Document Summary Information.
+ * Checks whether this PropertySet is a Document Summary Information.
*
- * @return {@code true} if this {@link PropertySet}
+ * @return {@code true} if this PropertySet
* represents a Document Summary Information, else {@code false}.
*/
public boolean isDocumentSummaryInformation() {
@@ -687,13 +686,13 @@ public class PropertySet {
/**
* Convenience method returning the {@link Property} array contained in this
- * property set. It is a shortcut for getting he {@link PropertySet}'s
+ * property set. It is a shortcut for getting he PropertySets
* {@link Section}s list and then getting the {@link Property} array from the
* first {@link Section}.
*
* @return The properties of the only {@link Section} of this
- * {@link PropertySet}.
- * @throws NoSingleSectionException if the {@link PropertySet} has
+ * PropertySet.
+ * @throws NoSingleSectionException if the PropertySet has
* more or less than one {@link Section}.
*/
public Property[] getProperties() throws NoSingleSectionException {
@@ -709,7 +708,7 @@ public class PropertySet {
*
* @param id The property ID
* @return The property value
- * @throws NoSingleSectionException if the {@link PropertySet} has
+ * @throws NoSingleSectionException if the PropertySet has
* more or less than one {@link Section}.
*/
protected Object getProperty(final int id) throws NoSingleSectionException {
@@ -726,7 +725,7 @@ public class PropertySet {
*
* @param id The property ID
* @return The property value
- * @throws NoSingleSectionException if the {@link PropertySet} has
+ * @throws NoSingleSectionException if the PropertySet has
* more or less than one {@link Section}.
*/
boolean getPropertyBooleanValue(final int id) throws NoSingleSectionException {
@@ -744,7 +743,7 @@ public class PropertySet {
*
* @param id The property ID
* @return The propertyIntValue value
- * @throws NoSingleSectionException if the {@link PropertySet} has
+ * @throws NoSingleSectionException if the PropertySet has
* more or less than one {@link Section}.
*/
int getPropertyIntValue(final int id) throws NoSingleSectionException {
@@ -765,7 +764,7 @@ public class PropertySet {
* @return {@code true} if the last call to {@link
* #getPropertyIntValue} or {@link #getProperty} tried to access a
* property that was not available, else {@code false}.
- * @throws NoSingleSectionException if the {@link PropertySet} has
+ * @throws NoSingleSectionException if the PropertySet has
* more than one {@link Section}.
*/
public boolean wasNull() throws NoSingleSectionException {
@@ -775,9 +774,9 @@ public class PropertySet {
/**
- * Gets the {@link PropertySet}'s first section.
+ * Gets the PropertySets first section.
*
- * @return The {@link PropertySet}'s first section.
+ * @return The PropertySets first section.
*/
@SuppressWarnings("WeakerAccess")
public Section getFirstSection() {
@@ -825,22 +824,12 @@ public class PropertySet {
return getSections().containsAll(ps.getSections());
}
-
-
- /**
- * @see Object#hashCode()
- */
@NotImplemented
@Override
public int hashCode() {
throw new UnsupportedOperationException("FIXME: Not yet implemented.");
}
-
-
- /**
- * @see Object#toString()
- */
@Override
public String toString() {
final StringBuilder b = new StringBuilder();
@@ -888,7 +877,7 @@ public class PropertySet {
getFirstSection().setProperty((int)id, value);
}
- private static void putClassId(final ByteArrayOutputStream out, final ClassID n) {
+ private static void putClassId(final UnsynchronizedByteArrayOutputStream out, final ClassID n) {
byte[] b = new byte[16];
n.write(b, 0);
out.write(b, 0, b.length);
diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java b/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java
index d5e0c5c0c2..ec2b8bc9dd 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySetFactory.java
@@ -54,8 +54,6 @@ public class PropertySetFactory {
throws FileNotFoundException, NoPropertySetStreamException, IOException, UnsupportedEncodingException {
try (DocumentInputStream inp = ((DirectoryNode)dir).createDocumentInputStream(name)) {
return create(inp);
- } catch (MarkUnsupportedException e) {
- return null;
}
}
@@ -71,14 +69,12 @@ public class PropertySetFactory {
* @return The created {@link PropertySet}.
* @throws NoPropertySetStreamException if the stream does not
* contain a property set.
- * @throws MarkUnsupportedException if the stream does not support
- * the {@code mark} operation.
* @throws IOException if some I/O problem occurs.
* @exception UnsupportedEncodingException if the specified codepage is not
* supported.
*/
public static PropertySet create(final InputStream stream)
- throws NoPropertySetStreamException, MarkUnsupportedException, UnsupportedEncodingException, IOException {
+ throws NoPropertySetStreamException, IOException {
stream.mark(PropertySet.OFFSET_HEADER+ClassID.LENGTH+1);
LittleEndianInputStream leis = new LittleEndianInputStream(stream);
int byteOrder = leis.readUShort();
diff --git a/poi/src/main/java/org/apache/poi/hpsf/Section.java b/poi/src/main/java/org/apache/poi/hpsf/Section.java
index c404e49858..90d20cf448 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/Section.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/Section.java
@@ -17,7 +17,6 @@
package org.apache.poi.hpsf;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
@@ -31,6 +30,7 @@ import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hpsf.wellknown.PropertyIDMap;
@@ -66,7 +66,7 @@ public class Section {
* established when the section's size is calculated and can be reused
* later. If the array is empty, the section was modified and the bytes need to be regenerated.
*/
- private final ByteArrayOutputStream sectionBytes = new ByteArrayOutputStream();
+ private final UnsynchronizedByteArrayOutputStream sectionBytes = new UnsynchronizedByteArrayOutputStream();
/**
* The offset of the section in the stream.
@@ -86,7 +86,7 @@ public class Section {
private transient boolean wasNull;
/**
- * Creates an empty {@link Section}.
+ * Creates an empty Section.
*/
public Section() {
this._offset = -1;
@@ -112,7 +112,7 @@ public class Section {
/**
- * Creates a {@link Section} instance from a byte array.
+ * Creates a Section instance from a byte array.
*
* @param src Contains the complete property set stream.
* @param offset The position in the stream that points to the
@@ -428,7 +428,6 @@ public class Section {
* @see #getProperty
* @see Variant
*/
- @SuppressWarnings("deprecation")
public void setProperty(final int id, final long variantType, final Object value) {
setProperty(new Property(id, variantType, value));
}
@@ -601,7 +600,7 @@ public class Section {
/**
* Returns the PID string associated with a property ID. The ID
- * is first looked up in the {@link Section Sections} private dictionary.
+ * is first looked up in the Sections private dictionary.
* If it is not found there, the property PID string is taken
* from sections format IDs namespace.
* If the PID is also undefined there, i.e. it is not well-known,
@@ -641,14 +640,14 @@ public class Section {
*
*
*
- * - The other object is not a {@link Section}.
+ *
- The other object is not a Section.
*
*
- The format IDs of the two sections are not equal.
*
*
- The sections have a different number of properties. However,
* properties with ID 1 (codepage) are not counted.
*
- *
- The other object is not a {@link Section}.
+ *
- The other object is not a Section.
*
*
- The properties have different values. The order of the properties
* is irrelevant.
@@ -736,7 +735,7 @@ public class Section {
}
final int[][] offsets = new int[properties.size()][2];
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
final LittleEndianOutputStream leos = new LittleEndianOutputStream(bos);
/* Write the section's length - dummy value, fixed later */
@@ -932,19 +931,11 @@ public class Section {
}
}
-
-
- /**
- * @see Object#hashCode()
- */
@Override
public int hashCode() {
return Arrays.deepHashCode(new Object[]{getFormatID(),getProperties()});
}
- /**
- * @see Object#toString()
- */
@Override
public String toString() {
return toString(null);
@@ -1008,7 +999,7 @@ public class Section {
*/
public int getCodepage() {
final Integer codepage = (Integer) getProperty(PropertyIDMap.PID_CODEPAGE);
- return (codepage == null) ? -1 : codepage.intValue();
+ return (codepage == null) ? -1 : codepage;
}
/**
diff --git a/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java b/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java
index 4c85b8fda8..564146a94a 100644
--- a/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java
+++ b/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java
@@ -50,14 +50,14 @@ public final class SummaryInformation extends PropertySet {
}
/**
- * Creates an empty {@link SummaryInformation}.
+ * Creates an empty SummaryInformation.
*/
public SummaryInformation() {
getFirstSection().setFormatID(FORMAT_ID);
}
/**
- * Creates a {@link SummaryInformation} from a given {@link
+ * Creates a SummaryInformation from a given {@link
* PropertySet}.
*
* @param ps A property set which should be created from a summary
@@ -73,7 +73,7 @@ public final class SummaryInformation extends PropertySet {
}
/**
- * Creates a {@link SummaryInformation} instance from an {@link
+ * Creates a SummaryInformation instance from an {@link
* InputStream} in the Horrible Property Set Format.
*
* The constructor reads the first few bytes from the stream
@@ -85,8 +85,6 @@ public final class SummaryInformation extends PropertySet {
*
* @param stream Holds the data making out the property set
* stream.
- * @throws MarkUnsupportedException
- * if the stream does not support the {@link InputStream#markSupported} method.
* @throws IOException
* if the {@link InputStream} cannot be accessed as needed.
* @exception NoPropertySetStreamException
@@ -95,7 +93,7 @@ public final class SummaryInformation extends PropertySet {
* if a character encoding is not supported.
*/
public SummaryInformation(final InputStream stream)
- throws NoPropertySetStreamException, MarkUnsupportedException, IOException, UnsupportedEncodingException {
+ throws NoPropertySetStreamException, IOException {
super(stream);
}
@@ -481,10 +479,10 @@ public final class SummaryInformation extends PropertySet {
/**
- * Returns the page count or 0 if the {@link SummaryInformation} does
+ * Returns the page count or 0 if the SummaryInformation does
* not contain a page count.
*
- * @return The page count or 0 if the {@link SummaryInformation} does not
+ * @return The page count or 0 if the SummaryInformation does not
* contain a page count.
*/
public int getPageCount() {
@@ -514,7 +512,7 @@ public final class SummaryInformation extends PropertySet {
/**
- * Returns the word count or 0 if the {@link SummaryInformation} does
+ * Returns the word count or 0 if the SummaryInformation does
* not contain a word count.
*
* @return The word count or {@code null}
@@ -546,7 +544,7 @@ public final class SummaryInformation extends PropertySet {
/**
- * Returns the character count or 0 if the {@link SummaryInformation}
+ * Returns the character count or 0 if the SummaryInformation
* does not contain a char count.
*
* @return The character count or {@code null}
@@ -665,7 +663,7 @@ public final class SummaryInformation extends PropertySet {
*
*
*
- * - 0 if the {@link SummaryInformation} does not contain a
+ *
- 0 if the SummaryInformation does not contain a
* security field or if there is no security on the document. Use
* {@link PropertySet#wasNull()} to distinguish between the two
* cases!
diff --git a/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java b/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java
index 2f31eb48d8..2254ed58fe 100644
--- a/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java
+++ b/poi/src/main/java/org/apache/poi/hssf/dev/ReSave.java
@@ -17,11 +17,11 @@
package org.apache.poi.hssf.dev;
-import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -60,7 +60,7 @@ public class ReSave {
System.out.print("saving to " + outputFile + "...");
}
- try (OutputStream os = saveToMemory ? new ByteArrayOutputStream() : new FileOutputStream(outputFile)) {
+ try (OutputStream os = saveToMemory ? new UnsynchronizedByteArrayOutputStream() : new FileOutputStream(outputFile)) {
wb.write(os);
}
System.out.println("done");
diff --git a/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java
index ac6bc6bf5c..8a1925e102 100644
--- a/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java
+++ b/poi/src/main/java/org/apache/poi/hssf/record/EscherAggregate.java
@@ -19,7 +19,6 @@ package org.apache.poi.hssf.record;
import static org.apache.poi.hssf.record.RecordInputStream.MAX_RECORD_DATA_SIZE;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -31,6 +30,7 @@ import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ddf.DefaultEscherRecordFactory;
import org.apache.poi.ddf.EscherClientDataRecord;
import org.apache.poi.ddf.EscherContainerRecord;
@@ -40,9 +40,11 @@ import org.apache.poi.ddf.EscherSerializationListener;
import org.apache.poi.ddf.EscherSpRecord;
import org.apache.poi.ddf.EscherSpgrRecord;
import org.apache.poi.ddf.EscherTextboxRecord;
+import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.util.GenericRecordXmlWriter;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.RecordFormatException;
+import org.apache.poi.util.Removal;
/**
* This class is used to aggregate the MSODRAWING and OBJ record
@@ -93,210 +95,825 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
private static final int MAX_RECORD_LENGTH = 100_000_000;
+ /** @deprecated not used */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_MIN = (short) 0;
- public static final short ST_NOT_PRIMATIVE = ST_MIN;
+ /** @deprecated use {@link ShapeType#NOT_PRIMITIVE} */
+ @Deprecated
+ @Removal(version = "5.3")
+ public static final short ST_NOT_PRIMATIVE = (short) 0;
+ /** @deprecated use {@link ShapeType#RECT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RECTANGLE = (short) 1;
+ /** @deprecated use {@link ShapeType#ROUND_RECT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ROUNDRECTANGLE = (short) 2;
+ /** @deprecated use {@link ShapeType#ELLIPSE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ELLIPSE = (short) 3;
+ /** @deprecated use {@link ShapeType#DIAMOND} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_DIAMOND = (short) 4;
+ /** @deprecated use {@link ShapeType#TRIANGLE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ISOCELESTRIANGLE = (short) 5;
+ /** @deprecated use {@link ShapeType#RT_TRIANGLE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RIGHTTRIANGLE = (short) 6;
+ /** @deprecated use {@link ShapeType#PARALLELOGRAM} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_PARALLELOGRAM = (short) 7;
+ /** @deprecated use {@link ShapeType#TRAPEZOID} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TRAPEZOID = (short) 8;
+ /** @deprecated use {@link ShapeType#HEXAGON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_HEXAGON = (short) 9;
+ /** @deprecated use {@link ShapeType#OCTAGON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_OCTAGON = (short) 10;
+ /** @deprecated use {@link ShapeType#PLUS} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_PLUS = (short) 11;
+ /** @deprecated use {@link ShapeType#STAR_5} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_STAR = (short) 12;
+ /** @deprecated use {@link ShapeType#RIGHT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ARROW = (short) 13;
+ /** @deprecated use {@link ShapeType#THICK_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_THICKARROW = (short) 14;
+ /** @deprecated use {@link ShapeType#HOME_PLATE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_HOMEPLATE = (short) 15;
+ /** @deprecated use {@link ShapeType#CUBE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CUBE = (short) 16;
+ /** @deprecated use {@link ShapeType#BALLOON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BALLOON = (short) 17;
+ /** @deprecated use {@link ShapeType#SEAL} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SEAL = (short) 18;
+ /** @deprecated use {@link ShapeType#ARC} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ARC = (short) 19;
+ /** @deprecated use {@link ShapeType#LINE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LINE = (short) 20;
+ /** @deprecated use {@link ShapeType#PLAQUE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_PLAQUE = (short) 21;
+ /** @deprecated use {@link ShapeType#CAN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CAN = (short) 22;
+ /** @deprecated use {@link ShapeType#DONUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_DONUT = (short) 23;
+ /** @deprecated use {@link ShapeType#TEXT_SIMPLE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTSIMPLE = (short) 24;
+ /** @deprecated use {@link ShapeType#TEXT_OCTAGON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTOCTAGON = (short) 25;
+ /** @deprecated use {@link ShapeType#TEXT_HEXAGON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTHEXAGON = (short) 26;
+ /** @deprecated use {@link ShapeType#TEXT_CURVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCURVE = (short) 27;
+ /** @deprecated use {@link ShapeType#TEXT_WAVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTWAVE = (short) 28;
+ /** @deprecated use {@link ShapeType#TEXT_RING} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTRING = (short) 29;
+ /** @deprecated use {@link ShapeType#TEXT_ON_CURVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTONCURVE = (short) 30;
+ /** @deprecated use {@link ShapeType#TEXT_ON_RING} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTONRING = (short) 31;
+ /** @deprecated use {@link ShapeType#STRAIGHT_CONNECTOR_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_STRAIGHTCONNECTOR1 = (short) 32;
+ /** @deprecated use {@link ShapeType#BENT_CONNECTOR_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BENTCONNECTOR2 = (short) 33;
+ /** @deprecated use {@link ShapeType#BENT_CONNECTOR_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BENTCONNECTOR3 = (short) 34;
+ /** @deprecated use {@link ShapeType#BENT_CONNECTOR_4} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BENTCONNECTOR4 = (short) 35;
+ /** @deprecated use {@link ShapeType#BENT_CONNECTOR_5} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BENTCONNECTOR5 = (short) 36;
+ /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDCONNECTOR2 = (short) 37;
+ /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDCONNECTOR3 = (short) 38;
+ /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDCONNECTOR4 = (short) 39;
+ /** @deprecated use {@link ShapeType#CURVED_CONNECTOR_5} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDCONNECTOR5 = (short) 40;
+ /** @deprecated use {@link ShapeType#CALLOUT_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CALLOUT1 = (short) 41;
+ /** @deprecated use {@link ShapeType#CALLOUT_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CALLOUT2 = (short) 42;
+ /** @deprecated use {@link ShapeType#CALLOUT_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CALLOUT3 = (short) 43;
+ /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTCALLOUT1 = (short) 44;
+ /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTCALLOUT2 = (short) 45;
+ /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTCALLOUT3 = (short) 46;
+ /** @deprecated use {@link ShapeType#BORDER_CALLOUT_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BORDERCALLOUT1 = (short) 47;
+ /** @deprecated use {@link ShapeType#BORDER_CALLOUT_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BORDERCALLOUT2 = (short) 48;
+ /** @deprecated use {@link ShapeType#BORDER_CALLOUT_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BORDERCALLOUT3 = (short) 49;
+ /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTBORDERCALLOUT1 = (short) 50;
+ /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTBORDERCALLOUT2 = (short) 51;
+ /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTBORDERCALLOUT3 = (short) 52;
+ /** @deprecated use {@link ShapeType#RIBBON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RIBBON = (short) 53;
+ /** @deprecated use {@link ShapeType#RIBBON_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RIBBON2 = (short) 54;
+ /** @deprecated use {@link ShapeType#CHEVRON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CHEVRON = (short) 55;
+ /** @deprecated use {@link ShapeType#PENTAGON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_PENTAGON = (short) 56;
+ /** @deprecated use {@link ShapeType#NO_SMOKING} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_NOSMOKING = (short) 57;
+ /** @deprecated use {@link ShapeType#STAR_8} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SEAL8 = (short) 58;
+ /** @deprecated use {@link ShapeType#STAR_16} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SEAL16 = (short) 59;
+ /** @deprecated use {@link ShapeType#STAR_32} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SEAL32 = (short) 60;
+ /** @deprecated use {@link ShapeType#WEDGE_RECT_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_WEDGERECTCALLOUT = (short) 61;
+ /** @deprecated use {@link ShapeType#WEDGE_ROUND_RECT_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_WEDGERRECTCALLOUT = (short) 62;
+ /** @deprecated use {@link ShapeType#WEDGE_ELLIPSE_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_WEDGEELLIPSECALLOUT = (short) 63;
+ /** @deprecated use {@link ShapeType#WAVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_WAVE = (short) 64;
+ /** @deprecated use {@link ShapeType#FOLDED_CORNER} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FOLDEDCORNER = (short) 65;
+ /** @deprecated use {@link ShapeType#LEFT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTARROW = (short) 66;
+ /** @deprecated use {@link ShapeType#DOWN_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_DOWNARROW = (short) 67;
+ /** @deprecated use {@link ShapeType#UP_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_UPARROW = (short) 68;
+ /** @deprecated use {@link ShapeType#LEFT_RIGHT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTRIGHTARROW = (short) 69;
+ /** @deprecated use {@link ShapeType#UP_DOWN_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_UPDOWNARROW = (short) 70;
+ /** @deprecated use {@link ShapeType#IRREGULAR_SEAL_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_IRREGULARSEAL1 = (short) 71;
+ /** @deprecated use {@link ShapeType#IRREGULAR_SEAL_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_IRREGULARSEAL2 = (short) 72;
+ /** @deprecated use {@link ShapeType#LIGHTNING_BOLT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LIGHTNINGBOLT = (short) 73;
+ /** @deprecated use {@link ShapeType#HEART} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_HEART = (short) 74;
+ /** @deprecated use {@link ShapeType#FRAME} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_PICTUREFRAME = (short) 75;
+ /** @deprecated use {@link ShapeType#QUAD_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_QUADARROW = (short) 76;
+ /** @deprecated use {@link ShapeType#LEFT_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTARROWCALLOUT = (short) 77;
+ /** @deprecated use {@link ShapeType#RIGHT_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RIGHTARROWCALLOUT = (short) 78;
+ /** @deprecated use {@link ShapeType#UP_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_UPARROWCALLOUT = (short) 79;
+ /** @deprecated use {@link ShapeType#DOWN_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_DOWNARROWCALLOUT = (short) 80;
+ /** @deprecated use {@link ShapeType#LEFT_RIGHT_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTRIGHTARROWCALLOUT = (short) 81;
+ /** @deprecated use {@link ShapeType#UP_DOWN_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_UPDOWNARROWCALLOUT = (short) 82;
+ /** @deprecated use {@link ShapeType#QUAD_ARROW_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_QUADARROWCALLOUT = (short) 83;
+ /** @deprecated use {@link ShapeType#BEVEL} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BEVEL = (short) 84;
+ /** @deprecated use {@link ShapeType#LEFT_BRACKET} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTBRACKET = (short) 85;
+ /** @deprecated use {@link ShapeType#RIGHT_BRACKET} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RIGHTBRACKET = (short) 86;
+ /** @deprecated use {@link ShapeType#LEFT_BRACE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTBRACE = (short) 87;
+ /** @deprecated use {@link ShapeType#RIGHT_BRACE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_RIGHTBRACE = (short) 88;
+ /** @deprecated use {@link ShapeType#LEFT_UP_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTUPARROW = (short) 89;
+ /** @deprecated use {@link ShapeType#BENT_UP_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BENTUPARROW = (short) 90;
+ /** @deprecated use {@link ShapeType#BENT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BENTARROW = (short) 91;
+ /** @deprecated use {@link ShapeType#STAR_24} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SEAL24 = (short) 92;
+ /** @deprecated use {@link ShapeType#STRIPED_RIGHT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_STRIPEDRIGHTARROW = (short) 93;
+ /** @deprecated use {@link ShapeType#NOTCHED_RIGHT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_NOTCHEDRIGHTARROW = (short) 94;
+ /** @deprecated use {@link ShapeType#BLOCK_ARC} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BLOCKARC = (short) 95;
+ /** @deprecated use {@link ShapeType#SMILEY_FACE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SMILEYFACE = (short) 96;
+ /** @deprecated use {@link ShapeType#VERTICAL_SCROLL} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_VERTICALSCROLL = (short) 97;
+ /** @deprecated use {@link ShapeType#HORIZONTAL_SCROLL} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_HORIZONTALSCROLL = (short) 98;
+ /** @deprecated use {@link ShapeType#CIRCULAR_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CIRCULARARROW = (short) 99;
+ /** @deprecated use {@link ShapeType#NOTCHED_CIRCULAR_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_NOTCHEDCIRCULARARROW = (short) 100;
+ /** @deprecated use {@link ShapeType#UTURN_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_UTURNARROW = (short) 101;
+ /** @deprecated use {@link ShapeType#CURVED_RIGHT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDRIGHTARROW = (short) 102;
+ /** @deprecated use {@link ShapeType#CURVED_LEFT_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDLEFTARROW = (short) 103;
+ /** @deprecated use {@link ShapeType#CURVED_UP_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDUPARROW = (short) 104;
+ /** @deprecated use {@link ShapeType#CURVED_DOWN_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CURVEDDOWNARROW = (short) 105;
+ /** @deprecated use {@link ShapeType#CLOUD_CALLOUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CLOUDCALLOUT = (short) 106;
+ /** @deprecated use {@link ShapeType#ELLIPSE_RIBBON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ELLIPSERIBBON = (short) 107;
+ /** @deprecated use {@link ShapeType#ELLIPSE_RIBBON_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ELLIPSERIBBON2 = (short) 108;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_PROCESS} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTPROCESS = (short) 109;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_DECISION} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTDECISION = (short) 110;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_INPUT_OUTPUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTINPUTOUTPUT = (short) 111;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_PREDEFINED_PROCESS} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTPREDEFINEDPROCESS = (short) 112;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_INTERNAL_STORAGE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTINTERNALSTORAGE = (short) 113;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_DOCUMENT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTDOCUMENT = (short) 114;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MULTIDOCUMENT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMULTIDOCUMENT = (short) 115;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_TERMINATOR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTTERMINATOR = (short) 116;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_PREPARATION} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTPREPARATION = (short) 117;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MANUAL_INPUT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMANUALINPUT = (short) 118;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MANUAL_OPERATION} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMANUALOPERATION = (short) 119;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_CONNECTOR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTCONNECTOR = (short) 120;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_PUNCHED_CARD} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTPUNCHEDCARD = (short) 121;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_PUNCHED_TAPE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTPUNCHEDTAPE = (short) 122;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_SUMMING_JUNCTION} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTSUMMINGJUNCTION = (short) 123;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_OR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTOR = (short) 124;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_COLLATE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTCOLLATE = (short) 125;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_SORT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTSORT = (short) 126;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_EXTRACT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTEXTRACT = (short) 127;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MERGE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMERGE = (short) 128;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_OFFLINE_STORAGE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTOFFLINESTORAGE = (short) 129;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_ONLINE_STORAGE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTONLINESTORAGE = (short) 130;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MAGNETIC_TAPE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMAGNETICTAPE = (short) 131;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MAGNETIC_DISK} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMAGNETICDISK = (short) 132;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_MAGNETIC_DRUM} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTMAGNETICDRUM = (short) 133;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_DISPLAY} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTDISPLAY = (short) 134;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_DELAY} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTDELAY = (short) 135;
+ /** @deprecated use {@link ShapeType#TEXT_PLAIN_TEXT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTPLAINTEXT = (short) 136;
+ /** @deprecated use {@link ShapeType#TEXT_STOP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTSTOP = (short) 137;
+ /** @deprecated use {@link ShapeType#TEXT_TRIANGLE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTTRIANGLE = (short) 138;
+ /** @deprecated use {@link ShapeType#TEXT_TRIANGLE_INVERTED} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTTRIANGLEINVERTED = (short) 139;
+ /** @deprecated use {@link ShapeType#TEXT_CHEVRON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCHEVRON = (short) 140;
+ /** @deprecated use {@link ShapeType#TEXT_CHEVRON_INVERTED} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCHEVRONINVERTED = (short) 141;
+ /** @deprecated use {@link ShapeType#TEXT_RING_INSIDE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTRINGINSIDE = (short) 142;
+ /** @deprecated use {@link ShapeType#TEXT_RING_OUTSIDE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTRINGOUTSIDE = (short) 143;
+ /** @deprecated use {@link ShapeType#TEXT_ARCH_UP_CURVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTARCHUPCURVE = (short) 144;
+ /** @deprecated use {@link ShapeType#TEXT_ARCH_DOWN_CURVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTARCHDOWNCURVE = (short) 145;
+ /** @deprecated use {@link ShapeType#TEXT_CIRCLE_CURVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCIRCLECURVE = (short) 146;
+ /** @deprecated use {@link ShapeType#TEXT_BUTTON_CURVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTBUTTONCURVE = (short) 147;
+ /** @deprecated use {@link ShapeType#TEXT_ARCH_UP_POUR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTARCHUPPOUR = (short) 148;
+ /** @deprecated use {@link ShapeType#TEXT_ARCH_DOWN_POUR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTARCHDOWNPOUR = (short) 149;
+ /** @deprecated use {@link ShapeType#TEXT_CIRCLE_POUR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCIRCLEPOUR = (short) 150;
+ /** @deprecated use {@link ShapeType#TEXT_BUTTON_POUR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTBUTTONPOUR = (short) 151;
+ /** @deprecated use {@link ShapeType#TEXT_CURVE_UP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCURVEUP = (short) 152;
+ /** @deprecated use {@link ShapeType#TEXT_CURVE_DOWN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCURVEDOWN = (short) 153;
+ /** @deprecated use {@link ShapeType#TEXT_CASCADE_UP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCASCADEUP = (short) 154;
+ /** @deprecated use {@link ShapeType#TEXT_CASCADE_DOWN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCASCADEDOWN = (short) 155;
+ /** @deprecated use {@link ShapeType#TEXT_WAVE_1} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTWAVE1 = (short) 156;
+ /** @deprecated use {@link ShapeType#TEXT_WAVE_2} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTWAVE2 = (short) 157;
+ /** @deprecated use {@link ShapeType#TEXT_WAVE_3} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTWAVE3 = (short) 158;
+ /** @deprecated use {@link ShapeType#TEXT_WAVE_4} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTWAVE4 = (short) 159;
+ /** @deprecated use {@link ShapeType#TEXT_INFLATE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTINFLATE = (short) 160;
+ /** @deprecated use {@link ShapeType#TEXT_DEFLATE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTDEFLATE = (short) 161;
+ /** @deprecated use {@link ShapeType#TEXT_INFLATE_BOTTOM} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTINFLATEBOTTOM = (short) 162;
+ /** @deprecated use {@link ShapeType#TEXT_DEFLATE_BOTTOM} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTDEFLATEBOTTOM = (short) 163;
+ /** @deprecated use {@link ShapeType#TEXT_INFLATE_TOP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTINFLATETOP = (short) 164;
+ /** @deprecated use {@link ShapeType#TEXT_DEFLATE_TOP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTDEFLATETOP = (short) 165;
+ /** @deprecated use {@link ShapeType#TEXT_DEFLATE_INFLATE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTDEFLATEINFLATE = (short) 166;
+ /** @deprecated use {@link ShapeType#TEXT_DEFLATE_INFLATE_DEFLATE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTDEFLATEINFLATEDEFLATE = (short) 167;
+ /** @deprecated use {@link ShapeType#TEXT_FADE_RIGHT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTFADERIGHT = (short) 168;
+ /** @deprecated use {@link ShapeType#TEXT_FADE_LEFT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTFADELEFT = (short) 169;
+ /** @deprecated use {@link ShapeType#TEXT_FADE_UP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTFADEUP = (short) 170;
+ /** @deprecated use {@link ShapeType#TEXT_FADE_DOWN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTFADEDOWN = (short) 171;
+ /** @deprecated use {@link ShapeType#TEXT_SLANT_UP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTSLANTUP = (short) 172;
+ /** @deprecated use {@link ShapeType#TEXT_SLANT_DOWN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTSLANTDOWN = (short) 173;
+ /** @deprecated use {@link ShapeType#TEXT_CAN_UP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCANUP = (short) 174;
+ /** @deprecated use {@link ShapeType#TEXT_CAN_DOWN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTCANDOWN = (short) 175;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_ALTERNATE_PROCESS} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTALTERNATEPROCESS = (short) 176;
+ /** @deprecated use {@link ShapeType#FLOW_CHART_OFFPAGE_CONNECTOR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_FLOWCHARTOFFPAGECONNECTOR = (short) 177;
+ /** @deprecated use {@link ShapeType#CALLOUT_90} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_CALLOUT90 = (short) 178;
+ /** @deprecated use {@link ShapeType#ACCENT_CALLOUT_90} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTCALLOUT90 = (short) 179;
+ /** @deprecated use {@link ShapeType#BORDER_CALLOUT_90} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BORDERCALLOUT90 = (short) 180;
+ /** @deprecated use {@link ShapeType#ACCENT_BORDER_CALLOUT_90} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACCENTBORDERCALLOUT90 = (short) 181;
+ /** @deprecated use {@link ShapeType#LEFT_RIGHT_UP_ARROW} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_LEFTRIGHTUPARROW = (short) 182;
+ /** @deprecated use {@link ShapeType#SUN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SUN = (short) 183;
+ /** @deprecated use {@link ShapeType#MOON} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_MOON = (short) 184;
+ /** @deprecated use {@link ShapeType#BRACKET_PAIR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BRACKETPAIR = (short) 185;
+ /** @deprecated use {@link ShapeType#BRACE_PAIR} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_BRACEPAIR = (short) 186;
+ /** @deprecated use {@link ShapeType#STAR_4} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_SEAL4 = (short) 187;
+ /** @deprecated use {@link ShapeType#DOUBLE_WAVE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_DOUBLEWAVE = (short) 188;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_BLANK} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONBLANK = (short) 189;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_HOME} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONHOME = (short) 190;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_HELP} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONHELP = (short) 191;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_INFORMATION} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONINFORMATION = (short) 192;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_FORWARD_NEXT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONFORWARDNEXT = (short) 193;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_BACK_PREVIOUS} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONBACKPREVIOUS = (short) 194;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_END} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONEND = (short) 195;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_BEGINNING} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONBEGINNING = (short) 196;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_RETURN} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONRETURN = (short) 197;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_DOCUMENT} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONDOCUMENT = (short) 198;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_SOUND} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONSOUND = (short) 199;
+ /** @deprecated use {@link ShapeType#ACTION_BUTTON_MOVIE} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_ACTIONBUTTONMOVIE = (short) 200;
+ /** @deprecated use {@link ShapeType#HOST_CONTROL} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_HOSTCONTROL = (short) 201;
+ /** @deprecated use {@link ShapeType#TEXT_BOX} */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_TEXTBOX = (short) 202;
+ /** @deprecated not used */
+ @Deprecated
+ @Removal(version = "5.3")
public static final short ST_NIL = (short) 0x0FFF;
/**
@@ -330,6 +947,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
/**
* @return Returns the current sid.
*/
+ @Override
public short getSid() {
return sid;
}
@@ -402,7 +1020,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
private static class ShapeCollector extends DefaultEscherRecordFactory {
final List objShapes = new ArrayList<>();
- final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+ final UnsynchronizedByteArrayOutputStream buffer = new UnsynchronizedByteArrayOutputStream();
void addBytes(byte[] data) {
try {
@@ -412,6 +1030,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
}
}
+ @Override
public EscherRecord createRecord(byte[] data, int offset) {
EscherRecord r = super.createRecord(data, offset);
short rid = r.getRecordId();
@@ -423,9 +1042,10 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
List parse(EscherAggregate agg) {
byte[] buf = buffer.toByteArray();
- for (int pos = 0, bytesRead; pos < buf.length; pos += bytesRead) {
+ int pos = 0;
+ while (pos < buf.length) {
EscherRecord r = createRecord(buf, pos);
- bytesRead = r.fillFields(buf, pos, this);
+ pos += r.fillFields(buf, pos, this);
agg.addEscherRecord(r);
}
return objShapes;
@@ -440,6 +1060,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
* @param data The byte array to serialize to.
* @return The number of bytes serialized.
*/
+ @Override
public int serialize(final int offset, final byte[] data) {
// Determine buffer size
List records = getEscherRecords();
@@ -450,12 +1071,13 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
final List spEndingOffsets = new ArrayList<>();
final List shapes = new ArrayList<>();
int pos = 0;
- for (Object record : records) {
- EscherRecord e = (EscherRecord) record;
- pos += e.serialize(pos, buffer, new EscherSerializationListener() {
+ for (EscherRecord record : records) {
+ pos += record.serialize(pos, buffer, new EscherSerializationListener() {
+ @Override
public void beforeRecordSerialize(int offset, short recordId, EscherRecord record) {
}
+ @Override
public void afterRecordSerialize(int offset, short recordId, int size, EscherRecord record) {
if (recordId == EscherClientDataRecord.RECORD_ID || recordId == EscherTextboxRecord.RECORD_ID) {
spEndingOffsets.add(offset);
@@ -545,6 +1167,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
/**
* @return record size, including header size of obj, text, note, drawing, continue records
*/
+ @Override
public int getRecordSize() {
// To determine size of aggregate record we have to know size of each DrawingRecord because if DrawingRecord
// is split into several continue records we have to add header size to total EscherAggregate size
@@ -557,9 +1180,11 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
int pos = 0;
for (EscherRecord e : records) {
pos += e.serialize(pos, buffer, new EscherSerializationListener() {
+ @Override
public void beforeRecordSerialize(int offset, short recordId, EscherRecord record) {
}
+ @Override
public void afterRecordSerialize(int offset, short recordId, int size, EscherRecord record) {
if (recordId == EscherClientDataRecord.RECORD_ID || recordId == EscherTextboxRecord.RECORD_ID) {
spEndingOffsets.add(offset);
@@ -615,6 +1240,7 @@ public final class EscherAggregate extends AbstractEscherHolderRecord {
/**
* @return "ESCHERAGGREGATE"
*/
+ @Override
protected String getRecordName() {
return "ESCHERAGGREGATE";
}
diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java
index a7fccea0c9..cbb73a65e4 100644
--- a/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java
+++ b/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java
@@ -17,11 +17,11 @@
package org.apache.poi.hssf.record;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.function.Supplier;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
@@ -47,7 +47,7 @@ public final class FilePassRecord extends StandardRecord {
private static final int ENCRYPTION_OTHER = 1;
private final int encryptionType;
- private EncryptionInfo encryptionInfo;
+ private final EncryptionInfo encryptionInfo;
private FilePassRecord(FilePassRecord other) {
super(other);
@@ -122,7 +122,7 @@ public final class FilePassRecord extends StandardRecord {
@Override
protected int getDataSize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream leos = new LittleEndianOutputStream(bos);
serialize(leos);
return bos.size();
diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java
index a8af77c2e1..84c5faf29c 100644
--- a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java
+++ b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java
@@ -17,11 +17,11 @@
package org.apache.poi.hssf.record;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.dev.BiffViewer;
import org.apache.poi.hssf.record.crypto.Biff8DecryptingStream;
import org.apache.poi.poifs.crypt.EncryptionInfo;
@@ -56,7 +56,6 @@ public final class RecordInputStream implements LittleEndianInput {
* For use in {@link BiffViewer} which may construct {@link Record}s that don't completely
* read all available data. This exception should never be thrown otherwise.
*/
- @SuppressWarnings("serial")
public static final class LeftoverDataException extends RuntimeException {
public LeftoverDataException(int sid, int remainingByteCount) {
super("Initialisation of record 0x" + Integer.toHexString(sid).toUpperCase(Locale.ROOT)
@@ -311,6 +310,7 @@ public final class RecordInputStream implements LittleEndianInput {
return Double.longBitsToDouble(readLong());
}
+ @Override
public void readPlain(byte[] buf, int off, int len) {
readFully(buf, 0, buf.length, true);
}
@@ -459,7 +459,7 @@ public final class RecordInputStream implements LittleEndianInput {
*/
@Deprecated
public byte[] readAllContinuedRemainder() {
- ByteArrayOutputStream out = new ByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE);
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE);
while (true) {
byte[] b = readRemainder();
@@ -486,7 +486,7 @@ public final class RecordInputStream implements LittleEndianInput {
/**
*
- * @return
true
when a {@link ContinueRecord} is next.
+ * @return {@code true} when a {@link ContinueRecord} is next.
*/
private boolean isContinueNext() {
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ && _currentDataOffset != _currentDataLength) {
diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java
index 0429267162..e67a9f2ca9 100644
--- a/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java
+++ b/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java
@@ -17,13 +17,13 @@
package org.apache.poi.hssf.record;
-import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.common.Duplicatable;
import org.apache.poi.common.usermodel.GenericRecord;
import org.apache.poi.util.GenericRecordJsonWriter;
@@ -121,7 +121,7 @@ public abstract class SubRecord implements Duplicatable, GenericRecord {
protected abstract int getDataSize();
public byte[] serialize() {
int size = getDataSize() + 4;
- ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(size);
serialize(new LittleEndianOutputStream(baos));
if (baos.size() != size) {
throw new RuntimeException("write size mismatch");
@@ -134,7 +134,7 @@ public abstract class SubRecord implements Duplicatable, GenericRecord {
/**
* Whether this record terminates the sub-record stream.
- * There are two cases when this method must be overridden and return true
+ * There are two cases when this method must be overridden and return {@code true}
* - EndSubRecord (sid = 0x00)
* - LbsDataSubRecord (sid = 0x12)
*
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java
index 262eae5086..7295b74fea 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCombobox.java
@@ -27,15 +27,15 @@ import org.apache.poi.ddf.EscherSimpleProperty;
import org.apache.poi.ddf.EscherSpRecord;
import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
import org.apache.poi.hssf.record.EndSubRecord;
-import org.apache.poi.hssf.record.EscherAggregate;
import org.apache.poi.hssf.record.FtCblsSubRecord;
import org.apache.poi.hssf.record.LbsDataSubRecord;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.TextObjectRecord;
+import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
/**
- *
+ *
*/
public class HSSFCombobox extends HSSFSimpleShape {
@@ -65,7 +65,7 @@ public class HSSFCombobox extends HSSFSimpleShape {
spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER);
spContainer.setOptions((short) 0x000F);
sp.setRecordId(EscherSpRecord.RECORD_ID);
- sp.setOptions((short) ((EscherAggregate.ST_HOSTCONTROL << 4) | 0x2));
+ sp.setOptions((short) ((ShapeType.HOST_CONTROL.nativeId << 4) | 0x2));
sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE);
opt.setRecordId(EscherOptRecord.RECORD_ID);
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java
index 430fe62798..023b47744b 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPolygon.java
@@ -32,9 +32,9 @@ import org.apache.poi.ddf.EscherSimpleProperty;
import org.apache.poi.ddf.EscherSpRecord;
import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
import org.apache.poi.hssf.record.EndSubRecord;
-import org.apache.poi.hssf.record.EscherAggregate;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.TextObjectRecord;
+import org.apache.poi.sl.usermodel.ShapeType;
import org.apache.poi.util.LittleEndian;
/**
@@ -65,6 +65,7 @@ public class HSSFPolygon extends HSSFSimpleShape {
/**
* Generates the shape records for this shape.
*/
+ @Override
protected EscherContainerRecord createSpContainer() {
EscherContainerRecord spContainer = new EscherContainerRecord();
EscherSpRecord sp = new EscherSpRecord();
@@ -74,7 +75,7 @@ public class HSSFPolygon extends HSSFSimpleShape {
spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER);
spContainer.setOptions((short) 0x000F);
sp.setRecordId(EscherSpRecord.RECORD_ID);
- sp.setOptions((short) ((EscherAggregate.ST_NOT_PRIMATIVE << 4) | 0x2));
+ sp.setOptions((short) ((ShapeType.NOT_PRIMITIVE.nativeId << 4) | 0x2));
if (getParent() == null) {
sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE);
} else {
@@ -115,6 +116,7 @@ public class HSSFPolygon extends HSSFSimpleShape {
/**
* Creates the low level OBJ record for this shape.
*/
+ @Override
protected ObjRecord createObjRecord() {
ObjRecord obj = new ObjRecord();
CommonObjectDataSubRecord c = new CommonObjectDataSubRecord();
@@ -216,8 +218,6 @@ public class HSSFPolygon extends HSSFSimpleShape {
/**
* Defines the width and height of the points in the polygon
- * @param width
- * @param height
*/
public void setPolygonDrawArea(int width, int height) {
setPropertyValue(new EscherSimpleProperty(EscherPropertyTypes.GEOMETRY__RIGHT, width));
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java
index 964356f5a6..d9c98e3063 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShape.java
@@ -17,11 +17,6 @@
package org.apache.poi.hssf.usermodel;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
import org.apache.poi.ddf.EscherBoolProperty;
import org.apache.poi.ddf.EscherChildAnchorRecord;
import org.apache.poi.ddf.EscherClientAnchorRecord;
@@ -37,6 +32,7 @@ import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.ss.usermodel.Shape;
import org.apache.poi.util.LittleEndian;
+import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.StringUtil;
/**
@@ -48,8 +44,6 @@ import org.apache.poi.util.StringUtil;
* setFlipVertical() or setFlipHorizontally().
*/
public abstract class HSSFShape implements Shape {
- private static final Logger LOG = LogManager.getLogger(HSSFShape.class);
-
public static final int LINEWIDTH_ONE_PT = 12700;
public static final int LINEWIDTH_DEFAULT = 9525;
public static final int LINESTYLE__COLOR_DEFAULT = 0x08000040;
@@ -85,8 +79,6 @@ public abstract class HSSFShape implements Shape {
/**
* creates shapes from existing file
- * @param spContainer
- * @param objRecord
*/
public HSSFShape(EscherContainerRecord spContainer, ObjRecord objRecord) {
this._escherContainer = spContainer;
@@ -115,7 +107,6 @@ public abstract class HSSFShape implements Shape {
* remove escher container from the patriarch.escherAggregate
* remove obj, textObj and note records if it's necessary
* in case of ShapeGroup remove all contained shapes
- * @param patriarch
*/
protected abstract void afterRemove(HSSFPatriarch patriarch);
@@ -179,7 +170,7 @@ public abstract class HSSFShape implements Shape {
* @see HSSFClientAnchor
*/
public void setAnchor(HSSFAnchor anchor) {
- int i = 0;
+ int i;
int recordId = -1;
if (parent == null) {
if (anchor instanceof HSSFChildAnchor)
@@ -365,18 +356,13 @@ public abstract class HSSFShape implements Shape {
* @return the rotation, in degrees, that is applied to a shape.
*/
public int getRotationDegree(){
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
EscherSimpleProperty property = getOptRecord().lookup(EscherPropertyTypes.TRANSFORM__ROTATION);
if (null == property){
return 0;
}
- try {
- LittleEndian.putInt(property.getPropertyValue(), bos);
- return LittleEndian.getShort(bos.toByteArray(), 2);
- } catch (IOException e) {
- LOG.atError().withThrowable(e).log("can't determine rotation degree");
- return 0;
- }
+ byte[] buf = new byte[LittleEndianConsts.INT_SIZE];
+ LittleEndian.putInt(buf, 0, property.getPropertyValue());
+ return LittleEndian.getShort(buf, 2);
}
/**
@@ -385,7 +371,6 @@ public abstract class HSSFShape implements Shape {
* Negative values specify rotation in the counterclockwise direction.
* Rotation occurs around the center of the shape.
* The default value for this property is 0x00000000
- * @param value
*/
public void setRotationDegree(short value){
setPropertyValue(new EscherSimpleProperty(EscherPropertyTypes.TRANSFORM__ROTATION , (value << 16)));
@@ -415,6 +400,7 @@ public abstract class HSSFShape implements Shape {
/**
* @return the name of this shape
*/
+ @Override
public String getShapeName() {
EscherOptRecord eor = getOptRecord();
if (eor == null) {
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java
index b8001fc651..623409d684 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeGroup.java
@@ -46,7 +46,7 @@ import org.apache.poi.hssf.record.ObjRecord;
*/
public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
private final List shapes = new ArrayList<>();
- private EscherSpgrRecord _spgrRecord;
+ private final EscherSpgrRecord _spgrRecord;
public HSSFShapeGroup(EscherContainerRecord spgrContainer, ObjRecord objRecord) {
super(spgrContainer, objRecord);
@@ -56,14 +56,13 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
_spgrRecord = (EscherSpgrRecord) spContainer.getChild(0);
for (EscherRecord ch : spContainer) {
switch (EscherRecordTypes.forTypeID(ch.getRecordId())) {
- case SPGR:
- break;
case CLIENT_ANCHOR:
anchor = new HSSFClientAnchor((EscherClientAnchorRecord) ch);
break;
case CHILD_ANCHOR:
anchor = new HSSFChildAnchor((EscherChildAnchorRecord) ch);
break;
+ case SPGR:
default:
break;
}
@@ -141,10 +140,12 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
protected void afterRemove(HSSFPatriarch patriarch) {
patriarch.getBoundAggregate().removeShapeToObjRecord(getEscherContainer().getChildContainers().get(0)
.getChildById(EscherClientDataRecord.RECORD_ID));
- for ( int i=0; i getChildren() {
return Collections.unmodifiableList(shapes);
}
@@ -275,6 +278,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
* Sets the coordinate space of this group. All children are constrained
* to these coordinates.
*/
+ @Override
public void setCoordinates(int x1, int y1, int x2, int y2) {
_spgrRecord.setRectX1(x1);
_spgrRecord.setRectX2(x2);
@@ -282,6 +286,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
_spgrRecord.setRectY2(y2);
}
+ @Override
public void clear() {
ArrayList copy = new ArrayList<>(shapes);
for (HSSFShape shape: copy){
@@ -292,6 +297,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
/**
* The top left x coordinate of this group.
*/
+ @Override
public int getX1() {
return _spgrRecord.getRectX1();
}
@@ -299,6 +305,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
/**
* The top left y coordinate of this group.
*/
+ @Override
public int getY1() {
return _spgrRecord.getRectY1();
}
@@ -306,6 +313,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
/**
* The bottom right x coordinate of this group.
*/
+ @Override
public int getX2() {
return _spgrRecord.getRectX2();
}
@@ -313,6 +321,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
/**
* The bottom right y coordinate of this group.
*/
+ @Override
public int getY2() {
return _spgrRecord.getRectY2();
}
@@ -320,6 +329,7 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
/**
* Count of all children and their childrens children.
*/
+ @Override
public int countOfAllChildren() {
int count = shapes.size();
for (HSSFShape shape : shapes) {
@@ -386,10 +396,11 @@ public class HSSFShapeGroup extends HSSFShape implements HSSFShapeContainer {
return group;
}
+ @Override
public boolean removeShape(HSSFShape shape) {
boolean isRemoved = getEscherContainer().removeChildRecord(shape.getEscherContainer());
if (isRemoved){
- shape.afterRemove(this.getPatriarch());
+ shape.afterRemove(getPatriarch());
shapes.remove(shape);
}
return isRemoved;
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java
index 5821a42f57..0a394d601b 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFTextbox.java
@@ -33,6 +33,7 @@ import org.apache.poi.hssf.record.EndSubRecord;
import org.apache.poi.hssf.record.EscherAggregate;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.TextObjectRecord;
+import org.apache.poi.sl.usermodel.ShapeType;
/**
* A textbox is a shape that may hold a rich text string.
@@ -68,7 +69,7 @@ public class HSSFTextbox extends HSSFSimpleShape {
/**
* Construct a new textbox with the given parent and anchor.
*
- * @param parent
+ * @param parent the parent shape
* @param anchor One of HSSFClientAnchor or HSSFChildAnchor
*/
public HSSFTextbox(HSSFShape parent, HSSFAnchor anchor) {
@@ -104,7 +105,7 @@ public class HSSFTextbox extends HSSFSimpleShape {
spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER);
spContainer.setOptions((short) 0x000F);
sp.setRecordId(EscherSpRecord.RECORD_ID);
- sp.setOptions((short) ((EscherAggregate.ST_TEXTBOX << 4) | 0x2));
+ sp.setOptions((short) ((ShapeType.TEXT_BOX.nativeId << 4) | 0x2));
sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE);
opt.setRecordId(EscherOptRecord.RECORD_ID);
diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java
index dc938d2de7..7a943a368e 100644
--- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java
+++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java
@@ -23,7 +23,6 @@ import static org.apache.poi.hssf.model.InternalWorkbook.WORKBOOK_DIR_ENTRY_NAME
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -47,6 +46,7 @@ import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.EncryptedDocumentException;
@@ -942,7 +942,6 @@ public final class HSSFWorkbook extends POIDocument implements Workbook {
private final class SheetIterator implements Iterator {
final private Iterator it;
- private T cursor;
@SuppressWarnings("unchecked")
public SheetIterator() {
@@ -956,8 +955,7 @@ public final class HSSFWorkbook extends POIDocument implements Workbook {
@Override
public T next() throws NoSuchElementException {
- cursor = it.next();
- return cursor;
+ return it.next();
}
/**
@@ -1994,9 +1992,10 @@ public final class HSSFWorkbook extends POIDocument implements Workbook {
}
}
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- poiData.writeFilesystem(bos);
- return addOlePackage(bos.toByteArray(), label, fileName, command);
+ try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
+ poiData.writeFilesystem(bos);
+ return addOlePackage(bos.toByteArray(), label, fileName, command);
+ }
}
@Override
@@ -2021,9 +2020,10 @@ public final class HSSFWorkbook extends POIDocument implements Workbook {
Ole10Native.createOleMarkerEntry(oleDir);
Ole10Native oleNative = new Ole10Native(label, fileName, command, oleData);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- oleNative.writeOut(bos);
- oleDir.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray()));
+ try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
+ oleNative.writeOut(bos);
+ oleDir.createDocument(Ole10Native.OLE10_NATIVE, bos.toInputStream());
+ }
return storageId;
}
diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
index df2a51bc38..36b44efbcc 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
@@ -17,7 +17,6 @@
package org.apache.poi.poifs.crypt.cryptoapi;
-import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
@@ -29,6 +28,7 @@ import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.poifs.crypt.ChunkedCipherInputStream;
import org.apache.poi.poifs.crypt.CryptoFunctions;
@@ -43,7 +43,7 @@ import org.apache.poi.poifs.filesystem.DocumentNode;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.BitField;
import org.apache.poi.util.BitFieldFactory;
-import org.apache.poi.util.BoundedInputStream;
+import org.apache.commons.io.input.BoundedInputStream;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianInputStream;
@@ -171,10 +171,10 @@ public class CryptoAPIDecryptor extends Decryptor {
public POIFSFileSystem getSummaryEntries(DirectoryNode root, String encryptedStream)
throws IOException, GeneralSecurityException {
DocumentNode es = (DocumentNode) root.getEntry(encryptedStream);
- DocumentInputStream dis = root.createDocumentInputStream(es);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- IOUtils.copy(dis, bos);
- dis.close();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
+ try (DocumentInputStream dis = root.createDocumentInputStream(es)) {
+ IOUtils.copy(dis, bos);
+ }
POIFSFileSystem fsOut = null;
try (
CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray());
diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java
index 3a9cae9b04..34c4a74675 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDocumentOutputStream.java
@@ -16,11 +16,13 @@
==================================================================== */
package org.apache.poi.poifs.crypt.cryptoapi;
-import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
+import org.apache.commons.io.input.BoundedInputStream;
+import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.util.Internal;
@@ -38,8 +40,8 @@ import org.apache.poi.util.Internal;
cipher = encryptor.initCipherForBlock(null, 0);
}
- public byte[] getBuf() {
- return buf;
+ public InputStream toInputStream(long maxSize) {
+ return new BoundedInputStream(toInputStream(), maxSize);
}
public void setSize(int count) {
diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java
index 652e7f51d7..176f431eec 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java
@@ -17,7 +17,6 @@
package org.apache.poi.poifs.crypt.cryptoapi;
-import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@@ -188,7 +187,7 @@ public class CryptoAPIEncryptor extends Encryptor {
bos.write(buf, 0, 8);
bos.setSize(savedSize);
- dir.createDocument(encryptedStream, new ByteArrayInputStream(bos.getBuf(), 0, savedSize));
+ dir.createDocument(encryptedStream, bos.toInputStream(savedSize));
}
// protected int getKeySizeInBytes() {
diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java
index 9fedce6122..1624fa97e2 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java
@@ -38,7 +38,7 @@ import org.apache.poi.poifs.crypt.EncryptionVerifier;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
-import org.apache.poi.util.BoundedInputStream;
+import org.apache.commons.io.input.BoundedInputStream;
import org.apache.poi.util.LittleEndian;
/**
diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
index a1052d865c..f8b948ee38 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java
@@ -18,10 +18,10 @@
package org.apache.poi.poifs.filesystem;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.poifs.property.DocumentProperty;
@@ -37,13 +37,13 @@ public final class DocumentOutputStream extends OutputStream {
private boolean _closed = false;
/** the actual Document */
- private POIFSDocument _document;
+ private final POIFSDocument _document;
/** and its Property */
- private DocumentProperty _property;
+ private final DocumentProperty _property;
/** our buffer, when null we're into normal blocks */
- private ByteArrayOutputStream _buffer =
- new ByteArrayOutputStream(POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE);
+ private UnsynchronizedByteArrayOutputStream _buffer =
+ new UnsynchronizedByteArrayOutputStream(POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE);
/** our main block stream, when we're into normal blocks */
private POIFSStream _stream;
@@ -115,11 +115,11 @@ public final class DocumentOutputStream extends OutputStream {
byte[] data = _buffer.toByteArray();
_buffer = null;
write(data, 0, data.length);
- } else {
- // So far, mini stream will work, keep going
}
+ // otherwise mini stream will work, keep going
}
+ @Override
public void write(int b) throws IOException {
write(new byte[] { (byte)b }, 0, 1);
}
@@ -146,11 +146,12 @@ public final class DocumentOutputStream extends OutputStream {
}
}
+ @Override
public void close() throws IOException {
// Do we have a pending buffer for the mini stream?
if (_buffer != null) {
// It's not much data, so ask POIFSDocument to do it for us
- _document.replaceContents(new ByteArrayInputStream(_buffer.toByteArray()));
+ _document.replaceContents(_buffer.toInputStream());
}
else {
// We've been writing to the stream as we've gone along
diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java
index bd21697fcf..81dd891a8c 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java
@@ -25,7 +25,6 @@ import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
-import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
@@ -238,7 +237,7 @@ public final class EntryUtils {
} else {
return isEqual(inpA, inpB);
}
- } catch (MarkUnsupportedException | NoPropertySetStreamException | IOException ex) {
+ } catch (NoPropertySetStreamException | IOException ex) {
throw new RuntimeException(ex);
}
}
diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java
index c2d4a73ae4..680763bac2 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/Ole10Native.java
@@ -18,12 +18,12 @@
package org.apache.poi.poifs.filesystem;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndianByteArrayInputStream;
import org.apache.poi.util.LittleEndianConsts;
@@ -336,7 +336,7 @@ public class Ole10Native {
/**
* Returns the size of the embedded file. If the size is 0 (zero), no data
* has been embedded. To be sure, that no data has been embedded, check
- * whether {@link #getDataBuffer()} returns null
.
+ * whether {@link #getDataBuffer()} returns {@code null}.
*
* @return the dataSize
*/
@@ -346,10 +346,10 @@ public class Ole10Native {
/**
* Returns the buffer containing the embedded file's data, or
- * null
if no data was embedded. Note that an embedding may
+ * {@code null} if no data was embedded. Note that an embedding may
* provide information about the data, but the actual data is not included.
* (So label, filename etc. are available, but this method returns
- * null
.)
+ * {@code null}.)
*
* @return the dataBuffer
*/
@@ -372,7 +372,7 @@ public class Ole10Native {
switch (mode) {
case parsed: {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try (LittleEndianOutputStream leos = new LittleEndianOutputStream(bos)) {
// total size, will be determined later ..
diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
index 7ac288a8a8..ebee94394b 100644
--- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
+++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java
@@ -16,7 +16,6 @@
==================================================================== */
package org.apache.poi.poifs.filesystem;
-import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
@@ -33,6 +32,7 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.commons.math3.util.ArithmeticUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -733,7 +733,7 @@ public class POIFSFileSystem extends BlockStore
// _header.setPropertyStart has been updated on write ...
// HeaderBlock
- ByteArrayOutputStream baos = new ByteArrayOutputStream(
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(
_header.getBigBlockSize().getBigBlockSize()
);
_header.writeData(baos);
diff --git a/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java b/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java
index 76cfd66472..049a805318 100644
--- a/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java
+++ b/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java
@@ -22,7 +22,6 @@ import static org.apache.poi.util.StringUtil.endsWithIgnoreCase;
import static org.apache.poi.util.StringUtil.startsWithIgnoreCase;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
@@ -38,6 +37,7 @@ import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.poifs.filesystem.DirectoryNode;
@@ -167,10 +167,7 @@ public class VBAMacroReader implements Closeable {
ModuleType moduleType;
Charset charset;
void read(InputStream in) throws IOException {
- final ByteArrayOutputStream out = new ByteArrayOutputStream();
- IOUtils.copy(in, out);
- out.close();
- buf = out.toByteArray();
+ buf = IOUtils.toByteArray(in);
}
@Override
public String getContent() {
@@ -414,13 +411,12 @@ public class VBAMacroReader implements Closeable {
UNKNOWN(-2);
- private final int VARIABLE_LENGTH = -1;
private final int id;
private final int constantLength;
RecordType(int id) {
this.id = id;
- this.constantLength = VARIABLE_LENGTH;
+ this.constantLength = -1;
}
RecordType(int id, int constantLength) {
@@ -651,13 +647,13 @@ public class VBAMacroReader implements Closeable {
return;
}
}
- mbcs = readMBCS(b, is, charset, MAX_STRING_LENGTH);
+ mbcs = readMBCS(b, is, charset);
} catch (EOFException e) {
return;
}
try {
- unicode = readUnicode(is, MAX_STRING_LENGTH);
+ unicode = readUnicode(is);
} catch (EOFException e) {
return;
}
@@ -669,14 +665,14 @@ public class VBAMacroReader implements Closeable {
LOGGER.atWarn().log("Hit max name records to read (" + maxNameRecords + "). Stopped early.");
}
- private static String readUnicode(InputStream is, int maxLength) throws IOException {
+ private static String readUnicode(InputStream is) throws IOException {
//reads null-terminated unicode string
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
int b0 = IOUtils.readByte(is);
int b1 = IOUtils.readByte(is);
int read = 2;
- while ((b0 + b1) != 0 && read < maxLength) {
+ while ((b0 + b1) != 0 && read < MAX_STRING_LENGTH) {
bos.write(b0);
bos.write(b1);
@@ -684,22 +680,22 @@ public class VBAMacroReader implements Closeable {
b1 = IOUtils.readByte(is);
read += 2;
}
- if (read >= maxLength) {
+ if (read >= MAX_STRING_LENGTH) {
LOGGER.atWarn().log("stopped reading unicode name after {} bytes", box(read));
}
- return new String (bos.toByteArray(), StandardCharsets.UTF_16LE);
+ return bos.toString(StandardCharsets.UTF_16LE);
}
- private static String readMBCS(int firstByte, InputStream is, Charset charset, int maxLength) throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ private static String readMBCS(int firstByte, InputStream is, Charset charset) throws IOException {
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
int len = 0;
int b = firstByte;
- while (b > 0 && len < maxLength) {
+ while (b > 0 && len < MAX_STRING_LENGTH) {
++len;
bos.write(b);
b = IOUtils.readByte(is);
}
- return new String(bos.toByteArray(), charset);
+ return bos.toString(charset);
}
/**
@@ -796,7 +792,7 @@ public class VBAMacroReader implements Closeable {
*/
private static byte[] findCompressedStreamWBruteForce(InputStream is) throws IOException {
//buffer to memory for multiple tries
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
IOUtils.copy(is, bos);
byte[] compressed = bos.toByteArray();
byte[] decompressed = null;
@@ -825,7 +821,7 @@ public class VBAMacroReader implements Closeable {
}
private static byte[] tryToDecompress(InputStream is) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
try {
IOUtils.copy(new RLEDecompressingInputStream(is), bos);
} catch (IllegalArgumentException | IOException | IllegalStateException e){
diff --git a/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java b/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java
index aa2b13e64c..4f2ca0ffbb 100644
--- a/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java
+++ b/poi/src/main/java/org/apache/poi/sl/draw/BitmapImageRenderer.java
@@ -28,7 +28,6 @@ import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
@@ -40,6 +39,7 @@ import javax.imageio.ImageTypeSpecifier;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
@@ -73,11 +73,11 @@ public class BitmapImageRenderer implements ImageRenderer {
public void loadImage(InputStream data, String contentType) throws IOException {
InputStream in = data;
if (doCache) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
IOUtils.copy(data, bos);
cachedImage = bos.toByteArray();
cachedContentType = contentType;
- in = new ByteArrayInputStream(cachedImage);
+ in = bos.toInputStream();
}
img = readImage(in, contentType);
}
@@ -107,13 +107,13 @@ public class BitmapImageRenderer implements ImageRenderer {
IOException lastException = null;
BufferedImage img = null;
- final ByteArrayInputStream bis;
+ final InputStream bis;
if (data instanceof ByteArrayInputStream) {
- bis = (ByteArrayInputStream)data;
+ bis = data;
} else {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(0x3FFFF);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(0x3FFFF);
IOUtils.copy(data, bos);
- bis = new ByteArrayInputStream(bos.toByteArray());
+ bis = bos.toInputStream();
}
@@ -257,7 +257,7 @@ public class BitmapImageRenderer implements ImageRenderer {
@Override
public BufferedImage getImage(Dimension2D dim) {
if (img == null) {
- return img;
+ return null;
}
double w_old = img.getWidth();
double h_old = img.getHeight();
diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java b/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java
index c7d421950e..3c36c77827 100644
--- a/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java
+++ b/poi/src/main/java/org/apache/poi/sl/usermodel/ObjectShape.java
@@ -17,12 +17,11 @@
package org.apache.poi.sl.usermodel;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@@ -54,7 +53,7 @@ public interface ObjectShape<
* @return the ProgID
*/
String getProgId();
-
+
/**
* Returns the full name of the embedded object,
* e.g. "Microsoft Word Document" or "Microsoft Office Excel Worksheet".
@@ -62,11 +61,11 @@ public interface ObjectShape<
* @return the full name of the embedded object
*/
String getFullName();
-
+
/**
* Updates the ole data. If there wasn't an object registered before, a new
* ole embedding is registered in the parent slideshow.
- *
+ *
* For HSLF this needs to be a {@link POIFSFileSystem} stream.
*
* @param application a preset application enum
@@ -81,10 +80,10 @@ public interface ObjectShape<
/**
* Reads the ole data as stream - the application specific stream is served
* The {@link #readObjectDataRaw() raw data} serves the outer/wrapped object, which is usually a
- * {@link POIFSFileSystem} stream, whereas this method return the unwrapped entry
+ * {@link POIFSFileSystem} stream, whereas this method return the unwrapped entry
*
* @return an {@link InputStream} which serves the object data
- *
+ *
* @throws IOException if the linked object data couldn't be found
*/
default InputStream readObjectData() throws IOException {
@@ -97,8 +96,9 @@ public interface ObjectShape<
final Application app = Application.lookup(progId);
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
- try (final InputStream is = FileMagic.prepareToCheckMagic(readObjectDataRaw())) {
+ try (final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
+ final InputStream is = FileMagic.prepareToCheckMagic(readObjectDataRaw())) {
+
final FileMagic fm = FileMagic.valueOf(is);
if (fm == FileMagic.OLE2) {
try (final POIFSFileSystem poifs = new POIFSFileSystem(is)) {
@@ -129,11 +129,10 @@ public interface ObjectShape<
} else {
IOUtils.copy(is, bos);
}
+ return bos.toInputStream();
}
-
- return new ByteArrayInputStream(bos.toByteArray());
}
-
+
/**
* Convenience method to return the raw data as {@code InputStream}
*
diff --git a/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java b/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java
index dbce0249ea..18eef73108 100644
--- a/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java
+++ b/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java
@@ -19,7 +19,6 @@ package org.apache.poi.ss.extractor;
import static org.apache.poi.util.StringUtil.endsWithIgnoreCase;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
@@ -28,6 +27,7 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hpsf.ClassID;
@@ -162,7 +162,7 @@ public class EmbeddedExtractor implements Iterable {
protected EmbeddedData extract(DirectoryNode dn) throws IOException {
assert(canExtract(dn));
- ByteArrayOutputStream bos = new ByteArrayOutputStream(20000);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(20000);
try (POIFSFileSystem dest = new POIFSFileSystem()) {
copyNodes(dn, dest.getRoot());
// start with a reasonable big size
@@ -204,7 +204,7 @@ public class EmbeddedExtractor implements Iterable {
@Override
public EmbeddedData extract(DirectoryNode dn) throws IOException {
- try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ try(UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
InputStream is = dn.createDocumentInputStream("CONTENTS")) {
IOUtils.copy(is, bos);
return new EmbeddedData(dn.getName() + ".pdf", bos.toByteArray(), CONTENT_TYPE_PDF);
diff --git a/poi/src/main/java/org/apache/poi/util/BoundedInputStream.java b/poi/src/main/java/org/apache/poi/util/BoundedInputStream.java
deleted file mode 100644
index df63cbc11b..0000000000
--- a/poi/src/main/java/org/apache/poi/util/BoundedInputStream.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.poi.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * This is a stream that will only supply bytes up to a certain length - if its
- * position goes above that, it will stop.
- *
- * This is useful to wrap ServletInputStreams. The ServletInputStream will block
- * if you try to read content from it that isn't there, because it doesn't know
- * whether the content hasn't arrived yet or whether the content has finished.
- * So, one of these, initialized with the Content-length sent in the
- * ServletInputStream's header, will stop it blocking, providing it's been sent
- * with a correct content length.
- *
- * @version $Id$
- * @since Commons IO 2.0
- */
-public class BoundedInputStream extends InputStream {
-
- /** the wrapped input stream */
- private final InputStream in;
-
- /** the max length to provide */
- private final long max;
-
- /** the number of bytes already returned */
- private long pos;
-
- /** the marked position */
- private long mark = -1;
-
- /** flag if close shoud be propagated */
- private boolean propagateClose = true;
-
- /**
- * Creates a new BoundedInputStream
that wraps the given input
- * stream and limits it to a certain size.
- *
- * @param in The wrapped input stream
- * @param size The maximum number of bytes to return
- */
- public BoundedInputStream(InputStream in, long size) {
- // Some badly designed methods - eg the servlet API - overload length
- // such that "-1" means stream finished
- this.max = size;
- this.in = in;
- }
-
- /**
- * Creates a new BoundedInputStream
that wraps the given input
- * stream and is unlimited.
- *
- * @param in The wrapped input stream
- */
- public BoundedInputStream(InputStream in) {
- this(in, -1);
- }
-
- /**
- * Invokes the delegate's read()
method if
- * the current position is less than the limit.
- * @return the byte read or -1 if the end of stream or
- * the limit has been reached.
- * @throws IOException if an I/O error occurs
- */
- @Override
- public int read() throws IOException {
- if (max>=0 && pos==max) {
- return -1;
- }
- int result = in.read();
- pos++;
- return result;
- }
-
- /**
- * Invokes the delegate's read(byte[])
method.
- * @param b the buffer to read the bytes into
- * @return the number of bytes read or -1 if the end of stream or
- * the limit has been reached.
- * @throws IOException if an I/O error occurs
- */
- @Override
- public int read(byte[] b) throws IOException {
- return this.read(b, 0, b.length);
- }
-
- /**
- * Invokes the delegate's read(byte[], int, int)
method.
- * @param b the buffer to read the bytes into
- * @param off The start offset
- * @param len The number of bytes to read
- * @return the number of bytes read or -1 if the end of stream or
- * the limit has been reached.
- * @throws IOException if an I/O error occurs
- */
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- if (max>=0 && pos>=max) {
- return -1;
- }
- long maxRead = max>=0 ? Math.min(len, max-pos) : len;
- int bytesRead = in.read(b, off, (int)maxRead);
-
- if (bytesRead==-1) {
- return -1;
- }
-
- pos+=bytesRead;
- return bytesRead;
- }
-
- /**
- * Invokes the delegate's skip(long)
method.
- * @param n the number of bytes to skip
- * @return the actual number of bytes skipped; might be fewer than requested
- * @throws IOException if an I/O error occurs
- */
- @Override
- public long skip(long n) throws IOException {
- long toSkip = max>=0 ? Math.min(n, max-pos) : n;
- long skippedBytes = IOUtils.skipFully(in, toSkip);
- pos+=skippedBytes;
- return skippedBytes;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- @SuppressForbidden("just delegating")
- public int available() throws IOException {
- if (max>=0 && pos>=max) {
- return 0;
- }
- return in.available();
- }
-
- /**
- * Invokes the delegate's toString()
method.
- * @return the delegate's toString()
- */
- @Override
- public String toString() {
- return in.toString();
- }
-
- /**
- * Invokes the delegate's close()
method
- * if {@link #isPropagateClose()} is true
.
- * @throws IOException if an I/O error occurs
- */
- @Override
- public void close() throws IOException {
- if (propagateClose) {
- in.close();
- }
- }
-
- /**
- * Invokes the delegate's reset()
method.
- * @throws IOException if an I/O error occurs
- */
- @Override
- public synchronized void reset() throws IOException {
- in.reset();
- pos = mark;
- }
-
- /**
- * Invokes the delegate's mark(int)
method.
- * @param readlimit read ahead limit
- */
- @Override
- public synchronized void mark(int readlimit) {
- in.mark(readlimit);
- mark = pos;
- }
-
- /**
- * Invokes the delegate's markSupported()
method.
- * @return true if mark is supported, otherwise false
- */
- @Override
- public boolean markSupported() {
- return in.markSupported();
- }
-
- /**
- * Indicates whether the {@link #close()} method
- * should propagate to the underling {@link InputStream}.
- *
- * @return true
if calling {@link #close()}
- * propagates to the close()
method of the
- * underlying stream or false
if it does not.
- */
- public boolean isPropagateClose() {
- return propagateClose;
- }
-
- /**
- * Set whether the {@link #close()} method
- * should propagate to the underling {@link InputStream}.
- *
- * @param propagateClose true
if calling
- * {@link #close()} propagates to the close()
- * method of the underlying stream or
- * false
if it does not.
- */
- public void setPropagateClose(boolean propagateClose) {
- this.propagateClose = propagateClose;
- }
-}
diff --git a/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java b/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java
index c46a535a0b..281b8180b0 100644
--- a/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java
+++ b/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java
@@ -19,6 +19,8 @@
package org.apache.poi.util;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
+
import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
@@ -115,7 +117,7 @@ public class GenericRecordJsonWriter implements Closeable {
protected int childIndex = 0;
public GenericRecordJsonWriter(File fileName) throws IOException {
- OutputStream os = ("null".equals(fileName.getName())) ? new NullOutputStream() : new FileOutputStream(fileName);
+ OutputStream os = ("null".equals(fileName.getName())) ? NULL_OUTPUT_STREAM : new FileOutputStream(fileName);
aw = new AppendableWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
fw = new PrintWriter(aw);
}
@@ -531,23 +533,6 @@ public class GenericRecordJsonWriter implements Closeable {
return ZEROS.substring(0, Math.max(0,size-len)) + b.substring(Math.max(0,len-size), len);
}
- static class NullOutputStream extends OutputStream {
- NullOutputStream() {
- }
-
- @Override
- public void write(byte[] b, int off, int len) {
- }
-
- @Override
- public void write(int b) {
- }
-
- @Override
- public void write(byte[] b) {
- }
- }
-
static class AppendableWriter extends Writer {
private final Appendable appender;
private final Writer writer;
diff --git a/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java b/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java
index c5a949cc63..a90f9c94fb 100644
--- a/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java
+++ b/poi/src/main/java/org/apache/poi/util/GenericRecordXmlWriter.java
@@ -19,6 +19,8 @@
package org.apache.poi.util;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
+
import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
@@ -50,7 +52,6 @@ import java.util.stream.Stream;
import org.apache.poi.common.usermodel.GenericRecord;
import org.apache.poi.util.GenericRecordJsonWriter.AppendableWriter;
-import org.apache.poi.util.GenericRecordJsonWriter.NullOutputStream;
@SuppressWarnings("WeakerAccess")
public class GenericRecordXmlWriter implements Closeable {
@@ -73,7 +74,7 @@ public class GenericRecordXmlWriter implements Closeable {
boolean print(GenericRecordXmlWriter record, String name, Object object);
}
- private static final List> handler = new ArrayList<>();
+ private static final List, GenericRecordHandler>> handler = new ArrayList<>();
static {
char[] t = new char[255];
@@ -97,7 +98,7 @@ public class GenericRecordXmlWriter implements Closeable {
handler(Object.class, GenericRecordXmlWriter::printObject);
}
- private static void handler(Class c, GenericRecordHandler printer) {
+ private static void handler(Class> c, GenericRecordHandler printer) {
handler.add(new AbstractMap.SimpleEntry<>(c, printer));
}
@@ -108,7 +109,7 @@ public class GenericRecordXmlWriter implements Closeable {
private boolean attributePhase = true;
public GenericRecordXmlWriter(File fileName) throws IOException {
- OutputStream os = ("null".equals(fileName.getName())) ? new NullOutputStream() : new FileOutputStream(fileName);
+ OutputStream os = ("null".equals(fileName.getName())) ? NULL_OUTPUT_STREAM : new FileOutputStream(fileName);
fw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
}
@@ -150,10 +151,10 @@ public class GenericRecordXmlWriter implements Closeable {
protected void write(final String name, GenericRecord record) {
final String tabs = tabs();
- Enum type = record.getGenericRecordType();
+ Enum> type = record.getGenericRecordType();
String recordName = (type != null) ? type.name() : record.getClass().getSimpleName();
fw.append(tabs);
- fw.append("<"+name+" type=\"");
+ fw.append("<").append(name).append(" type=\"");
fw.append(recordName);
fw.append("\"");
if (childIndex > 0) {
@@ -279,7 +280,7 @@ public class GenericRecordXmlWriter implements Closeable {
}
}
- protected static boolean matchInstanceOrArray(Class key, Object instance) {
+ protected static boolean matchInstanceOrArray(Class> key, Object instance) {
return key.isInstance(instance) || (Array.class.equals(key) && instance.getClass().isArray());
}
@@ -332,8 +333,7 @@ public class GenericRecordXmlWriter implements Closeable {
openName(name+">");
int oldChildIndex = childIndex;
childIndex = 0;
- //noinspection unchecked
- ((List)o).forEach(e -> { writeValue("item>", e); childIndex++; });
+ ((List>)o).forEach(e -> { writeValue("item>", e); childIndex++; });
childIndex = oldChildIndex;
closeName(name+">");
return true;
@@ -478,7 +478,7 @@ public class GenericRecordXmlWriter implements Closeable {
case "&":
fw.write("&");
break;
- case "\'":
+ case "'":
fw.write("'");
break;
case "\"":
diff --git a/poi/src/main/java/org/apache/poi/util/IOUtils.java b/poi/src/main/java/org/apache/poi/util/IOUtils.java
index ec348b67a2..279b56974c 100644
--- a/poi/src/main/java/org/apache/poi/util/IOUtils.java
+++ b/poi/src/main/java/org/apache/poi/util/IOUtils.java
@@ -17,7 +17,6 @@
package org.apache.poi.util;
-import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
@@ -33,6 +32,8 @@ import java.util.Locale;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
+import org.apache.commons.io.input.BoundedInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.EmptyFileException;
@@ -106,7 +107,7 @@ public final class IOUtils {
checkByteSizeLimit(limit);
stream.mark(limit);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(limit);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(limit);
copy(new BoundedInputStream(stream, limit), bos);
int readBytes = bos.size();
@@ -177,7 +178,7 @@ public final class IOUtils {
}
final int len = Math.min(length, maxLength);
- ByteArrayOutputStream baos = new ByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len);
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len);
byte[] buffer = new byte[4096];
int totalBytes = 0, readBytes;
diff --git a/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java b/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java
index 0ebae8a0ac..1a0052e08b 100644
--- a/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java
+++ b/poi/src/main/java/org/apache/poi/util/LZWDecompresser.java
@@ -16,11 +16,12 @@
==================================================================== */
package org.apache.poi.util;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+
/**
* This class provides common functionality for the
* various LZW implementations in the different file
@@ -86,7 +87,7 @@ public abstract class LZWDecompresser {
* of the decompressed input.
*/
public byte[] decompress(InputStream src) throws IOException {
- ByteArrayOutputStream res = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream res = new UnsynchronizedByteArrayOutputStream();
decompress(src, res);
return res.toByteArray();
}
diff --git a/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java b/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java
index 6bd7fef86e..aa2211eb1a 100644
--- a/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java
+++ b/poi/src/main/java/org/apache/poi/util/RLEDecompressingInputStream.java
@@ -18,11 +18,12 @@
package org.apache.poi.util;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+
/**
* Wrapper of InputStream which provides Run Length Encoding (RLE)
* decompression on the fly. Uses MS-OVBA decompression algorithm. See
@@ -68,7 +69,6 @@ public class RLEDecompressingInputStream extends InputStream {
* Creates a new wrapper RLE Decompression InputStream.
*
* @param in The stream to wrap with the RLE Decompression
- * @throws IOException
*/
public RLEDecompressingInputStream(InputStream in) throws IOException {
this.in = in;
@@ -152,7 +152,6 @@ public class RLEDecompressingInputStream extends InputStream {
* Reads a single chunk from the underlying inputstream.
*
* @return number of bytes that were read, or -1 if the end of the stream was reached.
- * @throws IOException
*/
private int readChunk() throws IOException {
pos = 0;
@@ -216,7 +215,6 @@ public class RLEDecompressingInputStream extends InputStream {
/**
* Helper method to determine how many bits in the CopyToken are used for the CopyLength.
*
- * @param offset
* @return returns the number of bits in the copy token (a value between 4 and 12)
*/
static int getCopyLenBits(int offset) {
@@ -232,7 +230,6 @@ public class RLEDecompressingInputStream extends InputStream {
* Convenience method for read a 2-bytes short in little endian encoding.
*
* @return short value from the stream, -1 if end of stream is reached
- * @throws IOException
*/
public int readShort() throws IOException {
return readShort(this);
@@ -242,7 +239,6 @@ public class RLEDecompressingInputStream extends InputStream {
* Convenience method for read a 4-bytes int in little endian encoding.
*
* @return integer value from the stream, -1 if end of stream is reached
- * @throws IOException
*/
public int readInt() throws IOException {
return readInt(this);
@@ -281,12 +277,12 @@ public class RLEDecompressingInputStream extends InputStream {
}
public static byte[] decompress(byte[] compressed, int offset, int length) throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- InputStream instream = new ByteArrayInputStream(compressed, offset, length);
- InputStream stream = new RLEDecompressingInputStream(instream);
- IOUtils.copy(stream, out);
- stream.close();
- out.close();
- return out.toByteArray();
+ try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
+ InputStream instream = new ByteArrayInputStream(compressed, offset, length);
+ InputStream stream = new RLEDecompressingInputStream(instream)) {
+
+ IOUtils.copy(stream, out);
+ return out.toByteArray();
+ }
}
}
diff --git a/poi/src/test/java/org/apache/poi/POIDataSamples.java b/poi/src/test/java/org/apache/poi/POIDataSamples.java
index 0772017d0a..dc9066c1bc 100644
--- a/poi/src/test/java/org/apache/poi/POIDataSamples.java
+++ b/poi/src/test/java/org/apache/poi/POIDataSamples.java
@@ -16,13 +16,16 @@
==================================================================== */
package org.apache.poi;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
+import org.apache.poi.util.IOUtils;
+
/**
* Centralises logic for finding/opening sample files
*/
@@ -47,7 +50,7 @@ public final class POIDataSamples {
private static POIDataSamples _instXmlDSign;
private File _resolvedDataDir;
- /** {@code true} if standard system propery is not set,
+ /** {@code true} if standard system property is not set,
* but the data is available on the test runtime classpath */
private boolean _sampleDataIsAvaliableOnClassPath;
private final String _moduleDir;
@@ -260,24 +263,19 @@ public final class POIDataSamples {
* @return byte array of sample file content from file found in standard test-data directory
*/
public byte[] readFile(String fileName) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
- try {
- InputStream fis = openResourceAsStream(fileName);
-
- byte[] buf = new byte[512];
- while (true) {
- int bytesRead = fis.read(buf);
- if (bytesRead < 1) {
- break;
- }
- bos.write(buf, 0, bytesRead);
- }
- fis.close();
+ try (InputStream fis = openResourceAsStream(fileName);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) {
+ IOUtils.copy(fis, bos);
+ return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
- return bos.toByteArray();
}
+ public static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException {
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
+ original.writeFilesystem(baos);
+ return new POIFSFileSystem(baos.toInputStream());
+ }
+ }
}
diff --git a/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java b/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java
index c2c44529b8..78fd9db41b 100644
--- a/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java
+++ b/poi/src/test/java/org/apache/poi/TestPOIDocumentMain.java
@@ -17,21 +17,20 @@
package org.apache.poi;
+import static org.apache.poi.hssf.HSSFTestDataSamples.openSampleWorkbook;
+import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
import org.apache.poi.hpsf.SummaryInformation;
-import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
@@ -42,22 +41,11 @@ import org.junit.jupiter.api.Test;
* which are part of the Main (not scratchpad)
*/
final class TestPOIDocumentMain {
- // The POI Documents to work on
- private POIDocument doc;
- private POIDocument doc2;
-
- /**
- * Set things up, two spreadsheets for our testing
- */
- @BeforeEach
- void setUp() {
- doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
- doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls");
- }
-
@Test
- void readProperties() {
- readPropertiesHelper(doc);
+ void readProperties() throws IOException {
+ try (POIDocument xls = openSampleWorkbook("DateFormats.xls")) {
+ readPropertiesHelper(xls);
+ }
}
private void readPropertiesHelper(POIDocument docWB) {
@@ -71,130 +59,108 @@ final class TestPOIDocumentMain {
}
@Test
- void readProperties2() {
- // Check again on the word one
- assertNotNull(doc2.getDocumentSummaryInformation());
- assertNotNull(doc2.getSummaryInformation());
-
- assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
- assertNull(doc2.getSummaryInformation().getKeywords());
- assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
+ void readProperties2() throws IOException {
+ try (POIDocument xls = openSampleWorkbook("StringFormulas.xls")) {
+ // Check again on the word one
+ assertNotNull(xls.getDocumentSummaryInformation());
+ assertNotNull(xls.getSummaryInformation());
+
+ assertEquals("Avik Sengupta", xls.getSummaryInformation().getAuthor());
+ assertNull(xls.getSummaryInformation().getKeywords());
+ assertEquals(0, xls.getDocumentSummaryInformation().getByteCount());
+ }
}
@Test
void writeProperties() throws IOException {
// Just check we can write them back out into a filesystem
- POIFSFileSystem outFS = new POIFSFileSystem();
- doc.readProperties();
- doc.writeProperties(outFS);
-
- // Should now hold them
- assertNotNull(
- outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)
- );
- assertNotNull(
- outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)
- );
+ try (POIDocument xls = openSampleWorkbook("DateFormats.xls");
+ POIFSFileSystem outFS = new POIFSFileSystem()) {
+ xls.readProperties();
+ xls.writeProperties(outFS);
+
+ // Should now hold them
+ assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
+ assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME));
+ }
}
@Test
void WriteReadProperties() throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
// Write them out
- POIFSFileSystem outFS = new POIFSFileSystem();
- doc.readProperties();
- doc.writeProperties(outFS);
- outFS.writeFilesystem(baos);
+ try (POIDocument xls = openSampleWorkbook("DateFormats.xls");
+ POIFSFileSystem outFS = new POIFSFileSystem()) {
+ xls.readProperties();
+ xls.writeProperties(outFS);
+ outFS.writeFilesystem(baos);
+ }
// Create a new version
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- POIFSFileSystem inFS = new POIFSFileSystem(bais);
+ try (POIFSFileSystem inFS = new POIFSFileSystem(baos.toInputStream());
+ POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS)) {
- // Check they're still there
- POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS);
- doc3.readProperties();
+ // Check they're still there
+ doc3.readProperties();
- // Delegate test
- readPropertiesHelper(doc3);
- doc3.close();
+ // Delegate test
+ readPropertiesHelper(doc3);
+ }
}
@Test
void createNewProperties() throws IOException {
- POIDocument doc = new HSSFWorkbook();
-
- // New document won't have them
- assertNull(doc.getSummaryInformation());
- assertNull(doc.getDocumentSummaryInformation());
-
- // Add them in
- doc.createInformationProperties();
- assertNotNull(doc.getSummaryInformation());
- assertNotNull(doc.getDocumentSummaryInformation());
-
- // Write out and back in again, no change
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- doc.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ try (HSSFWorkbook xls1 = new HSSFWorkbook()) {
+ // New document won't have them
+ assertNull(xls1.getSummaryInformation());
+ assertNull(xls1.getDocumentSummaryInformation());
+
+ // Add them in
+ xls1.createInformationProperties();
+ assertNotNull(xls1.getSummaryInformation());
+ assertNotNull(xls1.getDocumentSummaryInformation());
+
+ try (HSSFWorkbook xls2 = writeOutAndReadBack(xls1)) {
+ assertNotNull(xls2.getSummaryInformation());
+ assertNotNull(xls2.getDocumentSummaryInformation());
+ }
+ }
- doc.close();
-
- doc = new HSSFWorkbook(bais);
-
- assertNotNull(doc.getSummaryInformation());
- assertNotNull(doc.getDocumentSummaryInformation());
-
- doc.close();
}
@Test
void createNewPropertiesOnExistingFile() throws IOException {
- POIDocument doc = new HSSFWorkbook();
-
- // New document won't have them
- assertNull(doc.getSummaryInformation());
- assertNull(doc.getDocumentSummaryInformation());
-
- // Write out and back in again, no change
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- doc.write(baos);
-
- doc.close();
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- doc = new HSSFWorkbook(bais);
-
- assertNull(doc.getSummaryInformation());
- assertNull(doc.getDocumentSummaryInformation());
-
- // Create, and change
- doc.createInformationProperties();
- doc.getSummaryInformation().setAuthor("POI Testing");
- doc.getDocumentSummaryInformation().setCompany("ASF");
-
- // Save and re-load
- baos = new ByteArrayOutputStream();
- doc.write(baos);
-
- doc.close();
-
- bais = new ByteArrayInputStream(baos.toByteArray());
- doc = new HSSFWorkbook(bais);
-
- // Check
- assertNotNull(doc.getSummaryInformation());
- assertNotNull(doc.getDocumentSummaryInformation());
- assertEquals("POI Testing", doc.getSummaryInformation().getAuthor());
- assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany());
-
- // Asking to re-create will make no difference now
- doc.createInformationProperties();
- assertNotNull(doc.getSummaryInformation());
- assertNotNull(doc.getDocumentSummaryInformation());
- assertEquals("POI Testing", doc.getSummaryInformation().getAuthor());
- assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany());
-
- doc.close();
+ try (HSSFWorkbook xls1 = new HSSFWorkbook()) {
+ // New document won't have them
+ assertNull(xls1.getSummaryInformation());
+ assertNull(xls1.getDocumentSummaryInformation());
+
+ try (HSSFWorkbook xls2 = writeOutAndReadBack(xls1)) {
+
+ assertNull(xls2.getSummaryInformation());
+ assertNull(xls2.getDocumentSummaryInformation());
+
+ // Create, and change
+ xls2.createInformationProperties();
+ xls2.getSummaryInformation().setAuthor("POI Testing");
+ xls2.getDocumentSummaryInformation().setCompany("ASF");
+
+ try (HSSFWorkbook xls3 = writeOutAndReadBack(xls2)) {
+ // Check
+ assertNotNull(xls3.getSummaryInformation());
+ assertNotNull(xls3.getDocumentSummaryInformation());
+ assertEquals("POI Testing", xls3.getSummaryInformation().getAuthor());
+ assertEquals("ASF", xls3.getDocumentSummaryInformation().getCompany());
+
+ // Asking to re-create will make no difference now
+ xls3.createInformationProperties();
+ assertNotNull(xls3.getSummaryInformation());
+ assertNotNull(xls3.getDocumentSummaryInformation());
+ assertEquals("POI Testing", xls3.getSummaryInformation().getAuthor());
+ assertEquals("ASF", xls3.getDocumentSummaryInformation().getCompany());
+ }
+ }
+ }
}
}
diff --git a/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java b/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java
index a081f61c65..3130b6b9b2 100644
--- a/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java
+++ b/poi/src/test/java/org/apache/poi/ddf/TestEscherBlipRecord.java
@@ -17,6 +17,7 @@
package org.apache.poi.ddf;
+import static org.apache.poi.ddf.EscherRecordTypes.BLIP_PICT;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -100,7 +101,7 @@ final class TestEscherBlipRecord {
EscherMetafileBlip blip1 = (EscherMetafileBlip)bse1.getBlipRecord();
assertEquals(0x5430, blip1.getOptions());
- assertEquals(EscherMetafileBlip.RECORD_ID_PICT, blip1.getRecordId());
+ assertEquals(BLIP_PICT.typeID, blip1.getRecordId());
assertArrayEquals(new byte[]{
0x57, 0x32, 0x7B, (byte)0x91, 0x23, 0x5D, (byte)0xDB, 0x36,
0x7A, (byte)0xDB, (byte)0xFF, 0x17, (byte)0xFE, (byte)0xF3, (byte)0xA7, 0x05
@@ -151,11 +152,13 @@ final class TestEscherBlipRecord {
byte[] data = _samples.readFile("47143.dat");
EscherBSERecord bse = new EscherBSERecord();
bse.fillFields(data, 0, new DefaultEscherRecordFactory());
- bse.toString(); //assert that toString() works
+ //assert that toString() works
+ assertNotNull(bse.toString());
assertTrue(bse.getBlipRecord() instanceof EscherMetafileBlip);
EscherMetafileBlip blip = (EscherMetafileBlip)bse.getBlipRecord();
- blip.toString(); //assert that toString() works
+ //assert that toString() works
+ assertNotNull(blip.toString());
byte[] remaining = blip.getRemainingData();
assertNotNull(remaining);
diff --git a/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java b/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java
index 088d346bae..07c67c4c10 100644
--- a/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java
+++ b/poi/src/test/java/org/apache/poi/ddf/TestEscherDump.java
@@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
@@ -29,6 +28,7 @@ import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.storage.RawDataUtil;
@@ -63,8 +63,8 @@ class TestEscherDump {
"cT19LR+PfTgjN4CKCS5Es4LS+7nLt9hQ7ejwGQnEyxebOgJzlHjotWUACpoZsFkAgGqBeUDZAzB6h4N2MFCNhmIuFJMAgPsH" +
"eJr+iZEHAAA=";
- private EscherDump dumper = new EscherDump();
- private ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ private final EscherDump dumper = new EscherDump();
+ private final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
private PrintStream stream;
@BeforeEach
@@ -126,7 +126,7 @@ class TestEscherDump {
}
private int countProperties() {
- String data = new String(baos.toByteArray(), StandardCharsets.UTF_8);
+ String data = baos.toString(StandardCharsets.UTF_8);
Matcher matcher = Pattern.compile(",? \"[^\"]+\": ").matcher(data);
int count = 0;
while (matcher.find()) {
diff --git a/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java b/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java
index 1cea118353..c3932c3b0a 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/TestVariantSupport.java
@@ -21,11 +21,12 @@ package org.apache.poi.hpsf;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
+import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.wellknown.PropertyIDMap;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.storage.RawDataUtil;
@@ -51,7 +52,7 @@ class TestVariantSupport {
Object hdrs = s.getProperty(PropertyIDMap.PID_HEADINGPAIR);
assertNotNull(hdrs);
- assertEquals(byte[].class, hdrs.getClass());
+ assertSame(byte[].class, hdrs.getClass());
// parse the value
Vector v = new Vector((short)Variant.VT_VARIANT);
@@ -63,10 +64,10 @@ class TestVariantSupport {
Object cp = items[0].getValue();
assertNotNull(cp);
- assertEquals(CodePageString.class, cp.getClass());
+ assertSame(CodePageString.class, cp.getClass());
Object i = items[1].getValue();
assertNotNull(i);
- assertEquals(Integer.class, i.getClass());
+ assertSame(Integer.class, i.getClass());
assertEquals(1, i);
}
@@ -91,34 +92,33 @@ class TestVariantSupport {
{Variant.VT_R8, -999.99d},
};
- POIFSFileSystem poifs = new POIFSFileSystem();
- DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation();
- CustomProperties cpList = new CustomProperties();
- for (Object[] o : exp) {
- int type = (Integer)o[0];
- Property p = new Property(PropertyIDMap.PID_MAX+type, type, o[1]);
- cpList.put("testprop"+type, new CustomProperty(p, "testprop"+type));
+ try (POIFSFileSystem poifs = new POIFSFileSystem()) {
+ DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation();
+ CustomProperties cpList = new CustomProperties();
+ for (Object[] o : exp) {
+ int type = (Integer) o[0];
+ Property p = new Property(PropertyIDMap.PID_MAX + type, type, o[1]);
+ cpList.put("testprop" + type, new CustomProperty(p, "testprop" + type));
- }
- dsi.setCustomProperties(cpList);
- dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- poifs.writeFilesystem(bos);
- poifs.close();
- poifs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
- dsi = (DocumentSummaryInformation)PropertySetFactory.create(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
- assertNotNull(dsi);
- cpList = dsi.getCustomProperties();
- int i=0;
- for (Object[] o : exp) {
- Object obj = cpList.get("testprop"+o[0]);
- if (o[1] instanceof byte[]) {
- assertArrayEquals((byte[])o[1], (byte[])obj, "property "+i);
- } else {
- assertEquals(o[1], obj, "property "+i);
}
- i++;
+ dsi.setCustomProperties(cpList);
+ dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+
+ try (POIFSFileSystem poifs2 = POIDataSamples.writeOutAndReadBack(poifs)) {
+ DocumentSummaryInformation dsi2 = (DocumentSummaryInformation) PropertySetFactory.create(poifs2.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+ assertNotNull(dsi2);
+ CustomProperties cpList2 = dsi2.getCustomProperties();
+ int i = 0;
+ for (Object[] o : exp) {
+ Object obj = cpList2.get("testprop" + o[0]);
+ if (o[1] instanceof byte[]) {
+ assertArrayEquals((byte[]) o[1], (byte[]) obj, "property " + i);
+ } else {
+ assertEquals(o[1], obj, "property " + i);
+ }
+ i++;
+ }
+ }
}
- poifs.close();
}
}
diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java
index 6d95b38450..cc75abc874 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java
@@ -19,6 +19,7 @@ package org.apache.poi.hpsf.basic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
@@ -35,7 +36,6 @@ import org.apache.poi.hpsf.ClassID;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.Filetime;
import org.apache.poi.hpsf.HPSFException;
-import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
@@ -109,8 +109,7 @@ final class TestBasic {
* supported.
*/
@Test
- void testCreatePropertySets()
- throws UnsupportedEncodingException, IOException {
+ void testCreatePropertySets() throws IOException {
Class>[] expected = {
SummaryInformation.class,
DocumentSummaryInformation.class,
@@ -123,11 +122,11 @@ final class TestBasic {
Object o;
try {
o = PropertySetFactory.create(in);
- } catch (NoPropertySetStreamException | MarkUnsupportedException ex) {
+ } catch (NoPropertySetStreamException ex) {
o = ex;
}
in.close();
- assertEquals(expected[i], o.getClass());
+ assertSame(expected[i], o.getClass());
}
}
diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java
index 9ef1289461..300f6f245a 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java
@@ -20,6 +20,7 @@ package org.apache.poi.hpsf.basic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -32,7 +33,6 @@ import java.util.List;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFException;
-import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
@@ -101,8 +101,7 @@ final class TestEmptyProperties {
* supported.
*/
@Test
- void testCreatePropertySets()
- throws UnsupportedEncodingException, IOException {
+ void testCreatePropertySets() throws IOException {
Class>[] expected = {
NoPropertySetStreamException.class,
SummaryInformation.class,
@@ -113,11 +112,11 @@ final class TestEmptyProperties {
Object o;
try {
o = PropertySetFactory.create(in);
- } catch (NoPropertySetStreamException | MarkUnsupportedException ex) {
+ } catch (NoPropertySetStreamException ex) {
o = ex;
}
in.close();
- assertEquals(o.getClass(), expected[i]);
+ assertSame(o.getClass(), expected[i]);
}
}
diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java
index 6205713fa3..001fc2b238 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestHPSFBugs.java
@@ -21,17 +21,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.POIDocument;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
-import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
@@ -112,38 +110,37 @@ final class TestHPSFBugs {
* reading junk
*/
@Test
- void test54233() throws IOException, NoPropertySetStreamException, MarkUnsupportedException {
- InputStream is = _samples.openResourceAsStream("TestNon4ByteBoundary.doc");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- is.close();
-
- SummaryInformation si = (SummaryInformation)
- PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME);
- DocumentSummaryInformation dsi = (DocumentSummaryInformation)
- PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
-
- // Test
- assertEquals("Microsoft Word 10.0", si.getApplicationName());
- assertEquals("", si.getTitle());
- assertEquals("", si.getAuthor());
- assertEquals("Cour de Justice", dsi.getCompany());
-
-
- // Write out and read back, should still be valid
- POIDocument doc = new HPSFPropertiesOnlyDocument(fs);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- doc.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- doc = new HPSFPropertiesOnlyDocument(new POIFSFileSystem(bais));
-
- // Check properties are still there
- assertEquals("Microsoft Word 10.0", si.getApplicationName());
- assertEquals("", si.getTitle());
- assertEquals("", si.getAuthor());
- assertEquals("Cour de Justice", dsi.getCompany());
-
- doc.close();
- fs.close();
+ void test54233() throws IOException, NoPropertySetStreamException {
+ try (InputStream is = _samples.openResourceAsStream("TestNon4ByteBoundary.doc");
+ POIFSFileSystem fs = new POIFSFileSystem(is)) {
+
+ SummaryInformation si = (SummaryInformation)
+ PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME);
+ DocumentSummaryInformation dsi = (DocumentSummaryInformation)
+ PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
+
+ // Test
+ assertEquals("Microsoft Word 10.0", si.getApplicationName());
+ assertEquals("", si.getTitle());
+ assertEquals("", si.getAuthor());
+ assertEquals("Cour de Justice", dsi.getCompany());
+
+
+ // Write out and read back, should still be valid
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
+ try (POIDocument doc = new HPSFPropertiesOnlyDocument(fs)) {
+ doc.write(baos);
+ }
+ try (POIDocument doc = new HPSFPropertiesOnlyDocument(new POIFSFileSystem(baos.toInputStream()))) {
+ si = doc.getSummaryInformation();
+ dsi = doc.getDocumentSummaryInformation();
+ // Check properties are still there
+ assertEquals("Microsoft Word 10.0", si.getApplicationName());
+ assertEquals("", si.getTitle());
+ assertEquals("", si.getAuthor());
+ assertEquals("Cour de Justice", dsi.getCompany());
+ }
+ }
}
/**
diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java
index f8fb0aad13..999d0a608b 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestMetaDataIPI.java
@@ -23,13 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Random;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFException;
@@ -44,7 +43,7 @@ import org.junit.jupiter.api.Test;
/**
* Basing on: src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java
* This class tests reading and writing of meta data. No actual document is created. All information
- * is stored in a virtual document in a ByteArrayOutputStream
+ * is stored in a virtual document in a UnsynchronizedByteArrayOutputStream
*/
final class TestMetaDataIPI {
@@ -520,7 +519,7 @@ final class TestMetaDataIPI {
/**
- * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream.
+ * Closes the UnsynchronizedByteArrayOutputStream and reads it into a ByteArrayInputStream.
* When finished writing information this method is used in the tests to
* start reading from the created document and then the see if the results match.
*/
@@ -528,13 +527,13 @@ final class TestMetaDataIPI {
dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME);
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream();
poifs.writeFilesystem(bout);
poifs.close();
- InputStream is = new ByteArrayInputStream(bout.toByteArray());
- poifs = new POIFSFileSystem(is);
- is.close();
+ try (InputStream is = bout.toInputStream()) {
+ poifs = new POIFSFileSystem(is);
+ }
/* Read the document summary information. */
DirectoryEntry dir = poifs.getRoot();
diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java
index 13eb537fe2..057e16ae87 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestReadAllFiles.java
@@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -31,12 +30,12 @@ import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.CustomProperties;
import org.apache.poi.hpsf.CustomProperty;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.HPSFException;
-import org.apache.poi.hpsf.MarkUnsupportedException;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
@@ -70,7 +69,7 @@ class TestReadAllFiles {
*/
@ParameterizedTest
@MethodSource("files")
- void read(File file) throws IOException, NoPropertySetStreamException, MarkUnsupportedException {
+ void read(File file) throws IOException, NoPropertySetStreamException {
/* Read the POI filesystem's property set streams: */
for (POIFile pf : Util.readPropertySets(file)) {
try (InputStream in = new ByteArrayInputStream(pf.getBytes())) {
@@ -84,7 +83,7 @@ class TestReadAllFiles {
/**
* This test method does a write and read back test with all POI
* filesystems in the "data" directory by performing the following
- * actions for each file:
+ * actions for each file:
*
*
* - Read its property set streams.
@@ -102,35 +101,35 @@ class TestReadAllFiles {
/* Create a new POI filesystem containing the origin file's
* property set streams: */
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- final POIFSFileSystem poiFs = new POIFSFileSystem();
- for (POIFile poifile : Util.readPropertySets(file)) {
- final InputStream in = new ByteArrayInputStream(poifile.getBytes());
- final PropertySet psIn = PropertySetFactory.create(in);
- psMap.put(poifile.getName(), psIn);
- bos.reset();
- psIn.write(bos);
- poiFs.createDocument(new ByteArrayInputStream(bos.toByteArray()), poifile.getName());
- }
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
+ try (POIFSFileSystem poiFs = new POIFSFileSystem()) {
+ for (POIFile poifile : Util.readPropertySets(file)) {
+ final InputStream in = new ByteArrayInputStream(poifile.getBytes());
+ final PropertySet psIn = PropertySetFactory.create(in);
+ psMap.put(poifile.getName(), psIn);
+ bos.reset();
+ psIn.write(bos);
+ poiFs.createDocument(bos.toInputStream(), poifile.getName());
+ }
- /* Read the property set streams from the POI filesystem just
- * created. */
- for (Map.Entry me : psMap.entrySet()) {
- final PropertySet ps1 = me.getValue();
- final PropertySet ps2 = PropertySetFactory.create(poiFs.getRoot(), me.getKey());
- assertNotNull(ps2);
+ /* Read the property set streams from the POI filesystem just
+ * created. */
+ for (Map.Entry me : psMap.entrySet()) {
+ final PropertySet ps1 = me.getValue();
+ final PropertySet ps2 = PropertySetFactory.create(poiFs.getRoot(), me.getKey());
+ assertNotNull(ps2);
- /* Compare the property set stream with the corresponding one
- * from the origin file and check whether they are equal. */
+ /* Compare the property set stream with the corresponding one
+ * from the origin file and check whether they are equal. */
- // Because of missing 0-paddings in the original input files, the bytes might differ.
- // This fixes the comparison
- String ps1str = ps1.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)","");
- String ps2str = ps2.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)","");
+ // Because of missing 0-paddings in the original input files, the bytes might differ.
+ // This fixes the comparison
+ String ps1str = ps1.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)", "");
+ String ps2str = ps2.toString().replace(" 00", " ").replace(".", " ").replaceAll("(?m)( +$|(size|offset): [0-9]+)", "");
- assertEquals(ps1str, ps2str, "Equality for file " + file.getName());
+ assertEquals(ps1str, ps2str, "Equality for file " + file.getName());
+ }
}
- poiFs.close();
}
/**
diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java
index 85ae090206..7d1df36fb8 100644
--- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java
+++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestWrite.java
@@ -26,10 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -44,6 +42,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.ClassID;
import org.apache.poi.hpsf.ClassIDPredefined;
@@ -118,9 +117,9 @@ class TestWrite {
/* Write it to a POIFS and the latter to disk: */
try (OutputStream out = new FileOutputStream(filename);
POIFSFileSystem poiFs = new POIFSFileSystem();
- ByteArrayOutputStream psStream = new ByteArrayOutputStream()) {
+ UnsynchronizedByteArrayOutputStream psStream = new UnsynchronizedByteArrayOutputStream()) {
assertThrows(NoFormatIDException.class, () -> ps.write(psStream));
- poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME);
+ poiFs.createDocument(psStream.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME);
poiFs.writeFilesystem(out);
}
}
@@ -142,12 +141,12 @@ class TestWrite {
/* Create a mutable property set and write it to a POIFS: */
try (OutputStream out = new FileOutputStream(filename);
POIFSFileSystem poiFs = new POIFSFileSystem();
- ByteArrayOutputStream psStream = new ByteArrayOutputStream()) {
+ UnsynchronizedByteArrayOutputStream psStream = new UnsynchronizedByteArrayOutputStream()) {
final PropertySet ps = new PropertySet();
final Section s = ps.getSections().get(0);
s.setFormatID(SummaryInformation.FORMAT_ID);
ps.write(psStream);
- poiFs.createDocument(new ByteArrayInputStream(psStream.toByteArray()), SummaryInformation.DEFAULT_STREAM_NAME);
+ poiFs.createDocument(psStream.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME);
poiFs.writeFilesystem(out);
}
@@ -254,9 +253,8 @@ class TestWrite {
/* Read the POIFS: */
final PropertySet[] psa = new PropertySet[1];
final POIFSReader r = new POIFSReader();
- final POIFSReaderListener listener = (event) -> {
+ final POIFSReaderListener listener = (event) ->
assertDoesNotThrow(() -> psa[0] = PropertySetFactory.create(event.getStream()));
- };
r.registerListener(listener,STREAM_NAME);
r.read(filename);
@@ -357,9 +355,8 @@ class TestWrite {
p.setValue(TITLE);
ms.setProperty(p);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
mps.write(out);
- out.close();
byte[] bytes = out.toByteArray();
PropertySet psr = new PropertySet(bytes);
@@ -388,9 +385,8 @@ class TestWrite {
private void check(final long variantType, final Object value, final int codepage)
throws UnsupportedVariantTypeException, IOException
{
- final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ final UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
VariantSupport.write(out, variantType, value, codepage);
- out.close();
final byte[] b = out.toByteArray();
final Object objRead =
VariantSupport.read(b, 0, b.length + LittleEndianConsts.INT_SIZE, variantType, codepage);
@@ -402,7 +398,7 @@ class TestWrite {
}
/**
- *
Tests writing and reading back a proper dictionary.
+ * Tests writing and reading back a proper dictionary.
*/
@Test
void dictionary() throws IOException, HPSFException {
@@ -410,37 +406,36 @@ class TestWrite {
copy.deleteOnExit();
/* Write: */
- final OutputStream out = new FileOutputStream(copy);
- final POIFSFileSystem poiFs = new POIFSFileSystem();
- final PropertySet ps1 = new PropertySet();
- final Section s = ps1.getSections().get(0);
- final Map m = new HashMap<>(3, 1.0f);
- m.put(1L, "String 1");
- m.put(2L, "String 2");
- m.put(3L, "String 3");
- s.setDictionary(m);
- s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]);
- int codepage = CodePageUtil.CP_UNICODE;
- s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage);
- poiFs.createDocument(ps1.toInputStream(), "Test");
- poiFs.writeFilesystem(out);
- poiFs.close();
- out.close();
-
- /* Read back: */
- final List psf = Util.readPropertySets(copy);
- assertEquals(1, psf.size());
- final byte[] bytes = psf.get(0).getBytes();
- final InputStream in = new ByteArrayInputStream(bytes);
- final PropertySet ps2 = PropertySetFactory.create(in);
-
- /* Check if the result is a DocumentSummaryInformation stream, as
- * specified. */
- assertTrue(ps2.isDocumentSummaryInformation());
-
- /* Compare the property set stream with the corresponding one
- * from the origin file and check whether they are equal. */
- assertEquals(ps1, ps2);
+ try (OutputStream out = new FileOutputStream(copy);
+ POIFSFileSystem poiFs = new POIFSFileSystem()) {
+ final PropertySet ps1 = new PropertySet();
+ final Section s = ps1.getSections().get(0);
+ final Map m = new HashMap<>(3, 1.0f);
+ m.put(1L, "String 1");
+ m.put(2L, "String 2");
+ m.put(3L, "String 3");
+ s.setDictionary(m);
+ s.setFormatID(DocumentSummaryInformation.FORMAT_ID[0]);
+ int codepage = CodePageUtil.CP_UNICODE;
+ s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, codepage);
+ poiFs.createDocument(ps1.toInputStream(), "Test");
+ poiFs.writeFilesystem(out);
+
+ /* Read back: */
+ final List psf = Util.readPropertySets(copy);
+ assertEquals(1, psf.size());
+ final byte[] bytes = psf.get(0).getBytes();
+ final InputStream in = new ByteArrayInputStream(bytes);
+ final PropertySet ps2 = PropertySetFactory.create(in);
+
+ /* Check if the result is a DocumentSummaryInformation stream, as
+ * specified. */
+ assertTrue(ps2.isDocumentSummaryInformation());
+
+ /* Compare the property set stream with the corresponding one
+ * from the origin file and check whether they are equal. */
+ assertEquals(ps1, ps2);
+ }
}
/**
@@ -543,9 +538,9 @@ class TestWrite {
doufStream.close();
// And also write to some bytes for checking
- ByteArrayOutputStream sinfBytes = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream sinfBytes = new UnsynchronizedByteArrayOutputStream();
sinf.write(sinfBytes);
- ByteArrayOutputStream dinfBytes = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream dinfBytes = new UnsynchronizedByteArrayOutputStream();
dinf.write(dinfBytes);
@@ -656,7 +651,7 @@ class TestWrite {
* codepage. (HPSF writes Unicode dictionaries only.)
*/
@Test
- void dictionaryWithInvalidCodepage() throws IOException, HPSFException {
+ void dictionaryWithInvalidCodepage() throws IOException {
final File copy = TempFile.createTempFile("Test-HPSF", "ole2");
copy.deleteOnExit();
@@ -696,8 +691,8 @@ class TestWrite {
* method checks whether the application is runing in an environment
* where the default character set is 16-bit-capable.
*
- * @return true
if the default character set is 16-bit-capable,
- * else false
.
+ * @return {@code true} if the default character set is 16-bit-capable,
+ * else {@code false}.
*/
private boolean hasProperDefaultCharset() {
final String charSetName = System.getProperty("file.encoding");
diff --git a/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java b/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java
index 3835802725..fbef50b6af 100644
--- a/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java
+++ b/poi/src/test/java/org/apache/poi/hssf/HSSFTestDataSamples.java
@@ -17,12 +17,11 @@
package org.apache.poi.hssf;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -56,11 +55,11 @@ public final class HSSFTestDataSamples {
* Useful for verifying that the serialisation round trip
*/
public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
original.write(baos);
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- return new HSSFWorkbook(bais);
+ try (InputStream is = baos.toInputStream()) {
+ return new HSSFWorkbook(is);
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
index 0f346f50ee..a957f67557 100644
--- a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
+++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java
@@ -16,6 +16,8 @@
==================================================================== */
package org.apache.poi.hssf.dev;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
@@ -23,7 +25,6 @@ import java.util.Map;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullOutputStream;
class TestBiffDrawingToXml extends BaseTestIteratingXLS {
@@ -44,7 +45,7 @@ class TestBiffDrawingToXml extends BaseTestIteratingXLS {
@Override
void runOneFile(File pFile) throws Exception {
try (InputStream wb = new FileInputStream(pFile)) {
- BiffDrawingToXml.writeToFile(new NullOutputStream(), wb, false, new String[0]);
+ BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[0]);
}
}
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java
index 0a99128a76..790ca14b58 100644
--- a/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java
+++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestBiffViewer.java
@@ -16,6 +16,8 @@
==================================================================== */
package org.apache.poi.hssf.dev;
+import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM;
+
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -25,7 +27,6 @@ import java.util.Map;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.LocaleUtil;
-import org.apache.poi.util.NullOutputStream;
import org.apache.poi.util.RecordFormatException;
class TestBiffViewer extends BaseTestIteratingXLS {
@@ -54,7 +55,7 @@ class TestBiffViewer extends BaseTestIteratingXLS {
try (POIFSFileSystem fs = new POIFSFileSystem(fileIn, true);
InputStream is = BiffViewer.getPOIFSInputStream(fs)) {
// use a NullOutputStream to not write the bytes anywhere for best runtime
- PrintWriter dummy = new PrintWriter(new OutputStreamWriter(new NullOutputStream(), LocaleUtil.CHARSET_1252));
+ PrintWriter dummy = new PrintWriter(new OutputStreamWriter(NULL_OUTPUT_STREAM, LocaleUtil.CHARSET_1252));
BiffViewer.runBiffViewer(dummy, is, true, true, true, false);
}
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java
index 9f072b37b3..79f8e7f426 100644
--- a/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java
+++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestEFBiffViewer.java
@@ -23,7 +23,7 @@ import java.util.Map;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
@@ -32,13 +32,16 @@ class TestEFBiffViewer extends BaseTestIteratingXLS {
@Override
protected Map> getExcludes() {
Map> excludes = super.getExcludes();
- excludes.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
+ // unsupported crypto api header
+ excludes.put("35897-type4.xls", EncryptedDocumentException.class);
excludes.put("51832.xls", EncryptedDocumentException.class);
excludes.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
excludes.put("password.xls", EncryptedDocumentException.class);
- excludes.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well
+ // HSSFWorkbook cannot open it as well
+ excludes.put("43493.xls", RecordInputStream.LeftoverDataException.class);
excludes.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
- // EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun"
+ // "Buffer overrun"
+ excludes.put("XRefCalc.xls", RuntimeException.class);
return excludes;
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java
index df2247b22c..4f5a7295ac 100644
--- a/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java
+++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestFormulaViewer.java
@@ -24,7 +24,7 @@ import java.util.Map;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java
index 1d890ef4a6..f5e3644acd 100644
--- a/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java
+++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestReSave.java
@@ -25,7 +25,7 @@ import java.util.Map;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.record.RecordInputStream;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Isolated;
diff --git a/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java b/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java
index 6087dab647..003f43896a 100644
--- a/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java
+++ b/poi/src/test/java/org/apache/poi/hssf/dev/TestRecordLister.java
@@ -20,7 +20,7 @@ import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
diff --git a/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java b/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java
index 8bb1b6771c..990221b6d2 100644
--- a/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java
+++ b/poi/src/test/java/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java
@@ -20,10 +20,10 @@ package org.apache.poi.hssf.eventmodel;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
@@ -31,6 +31,7 @@ import java.util.Iterator;
import java.util.stream.Stream;
import org.apache.commons.collections4.IteratorUtils;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.EOFRecord;
@@ -130,16 +131,15 @@ final class TestEventRecordFactory {
* OBJECTIVE: Test that the RecordFactory given an InputStream
* constructs the expected records.
* SUCCESS: Record factory creates the expected records.
- * FAILURE: The wrong records are created or contain the wrong values
- *
+ * FAILURE: The wrong records are created or contain the wrong values
*/
@Test
void testContinuedUnknownRecord() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
for (byte[] b : CONTINUE_DATA) {
bos.write(b);
}
- continueHelper(new ByteArrayInputStream(bos.toByteArray()));
+ continueHelper(bos.toInputStream());
}
@Test
@@ -156,7 +156,7 @@ final class TestEventRecordFactory {
Iterator expectedData = Stream.of(CONTINUE_DATA).iterator();
ERFListener listener = rec -> {
- assertEquals(expectedType.next(), rec.getClass());
+ assertSame(expectedType.next(), rec.getClass());
assertArrayEquals(expectedData.next(), rec.serialize());
return true;
};
diff --git a/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java b/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java
index 7dbabe14b1..c9438fd990 100644
--- a/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java
+++ b/poi/src/test/java/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java
@@ -23,15 +23,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
import java.security.Permission;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.EmptyFileException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIDataSamples;
@@ -39,7 +40,7 @@ import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.apache.poi.util.RecordFormatException;
import org.junit.jupiter.api.Test;
@@ -321,12 +322,11 @@ final class TestOldExcelExtractor {
void testMain() throws IOException {
File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls");
PrintStream save = System.out;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintStream str = new PrintStream(out, false, "UTF-8");
+ try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
+ PrintStream str = new PrintStream(out, false, StandardCharsets.UTF_8.displayName())) {
System.setOut(str);
OldExcelExtractor.main(new String[] {file.getAbsolutePath()});
- String string = out.toString("UTF-8");
+ String string = out.toString(StandardCharsets.UTF_8);
assertTrue(string.contains("Table C-13--Lemons"), "Had: " + string);
} finally {
System.setOut(save);
diff --git a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java
index 18138de8ed..59c9eba317 100644
--- a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java
+++ b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingAggregate.java
@@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -33,6 +32,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ddf.DefaultEscherRecordFactory;
import org.apache.poi.ddf.EscherContainerRecord;
import org.apache.poi.ddf.EscherDggRecord;
@@ -113,7 +113,7 @@ class TestDrawingAggregate {
* @return the raw data being aggregated
*/
byte[] getRawBytes(){
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
for (RecordBase rb : aggRecords) {
Record r = (org.apache.poi.hssf.record.Record) rb;
try {
@@ -216,7 +216,7 @@ class TestDrawingAggregate {
assertEquals(dgBytes.length, pos, "data was not fully read");
// serialize to byte array
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
for(EscherRecord r : records) {
out.write(r.serialize());
}
@@ -242,7 +242,7 @@ class TestDrawingAggregate {
}
private static byte[] toByteArray(List records) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
for (RecordBase rb : records) {
Record r = (org.apache.poi.hssf.record.Record) rb;
try {
diff --git a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java
index 22cd1ee11c..1618e03791 100644
--- a/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java
+++ b/poi/src/test/java/org/apache/poi/hssf/model/TestDrawingShapes.java
@@ -469,152 +469,152 @@ class TestDrawingShapes {
@Test
void testRemoveShapes() throws IOException {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
+ try (HSSFWorkbook wb1 = new HSSFWorkbook()) {
+ HSSFSheet sheet1 = wb1.createSheet();
+ HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch();
- HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor());
- rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
+ HSSFSimpleShape rectangle = patriarch1.createSimpleShape(new HSSFClientAnchor());
+ rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE);
- int idx = wb1.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG);
- patriarch.createPicture(new HSSFClientAnchor(), idx);
+ int idx = wb1.addPicture(new byte[]{1, 2, 3}, Workbook.PICTURE_TYPE_JPEG);
+ patriarch1.createPicture(new HSSFClientAnchor(), idx);
- patriarch.createCellComment(new HSSFClientAnchor());
+ patriarch1.createCellComment(new HSSFClientAnchor());
- HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor());
- polygon.setPoints(new int[]{1,2}, new int[]{2,3});
+ HSSFPolygon polygon1 = patriarch1.createPolygon(new HSSFClientAnchor());
+ polygon1.setPoints(new int[]{1, 2}, new int[]{2, 3});
- patriarch.createTextbox(new HSSFClientAnchor());
+ patriarch1.createTextbox(new HSSFClientAnchor());
- HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor());
- group.createTextbox(new HSSFChildAnchor());
- group.createPicture(new HSSFChildAnchor(), idx);
+ HSSFShapeGroup group1 = patriarch1.createGroup(new HSSFClientAnchor());
+ group1.createTextbox(new HSSFChildAnchor());
+ group1.createPicture(new HSSFChildAnchor(), idx);
- assertEquals(patriarch.getChildren().size(), 6);
- assertEquals(group.getChildren().size(), 2);
+ assertEquals(patriarch1.getChildren().size(), 6);
+ assertEquals(group1.getChildren().size(), 2);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch1).getShapeToObjMapping().size(), 12);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch1).getTailRecords().size(), 1);
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
- sheet = wb2.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
+ HSSFSheet sheet2 = wb2.getSheetAt(0);
+ HSSFPatriarch patriarch2 = sheet2.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getShapeToObjMapping().size(), 12);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 6);
+ assertEquals(patriarch2.getChildren().size(), 6);
- group = (HSSFShapeGroup) patriarch.getChildren().get(5);
- group.removeShape(group.getChildren().get(0));
+ HSSFShapeGroup group2 = (HSSFShapeGroup) patriarch2.getChildren().get(5);
+ group2.removeShape(group2.getChildren().get(0));
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getShapeToObjMapping().size(), 10);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch2).getTailRecords().size(), 1);
- HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2);
- wb2.close();
- sheet = wb3.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2)) {
+ HSSFSheet sheet3 = wb3.getSheetAt(0);
+ HSSFPatriarch patriarch3 = sheet3.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getShapeToObjMapping().size(), 10);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getTailRecords().size(), 1);
- group = (HSSFShapeGroup) patriarch.getChildren().get(5);
- patriarch.removeShape(group);
+ HSSFShapeGroup group3 = (HSSFShapeGroup) patriarch3.getChildren().get(5);
+ patriarch3.removeShape(group3);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getShapeToObjMapping().size(), 8);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch3).getTailRecords().size(), 1);
- HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3);
- wb3.close();
- sheet = wb4.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3)) {
+ HSSFSheet sheet4 = wb4.getSheetAt(0);
+ HSSFPatriarch patriarch4 = sheet4.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 5);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getShapeToObjMapping().size(), 8);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getTailRecords().size(), 1);
+ assertEquals(patriarch4.getChildren().size(), 5);
- HSSFShape shape = patriarch.getChildren().get(0);
- patriarch.removeShape(shape);
+ HSSFShape shape4 = patriarch4.getChildren().get(0);
+ patriarch4.removeShape(shape4);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 4);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getShapeToObjMapping().size(), 6);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch4).getTailRecords().size(), 1);
+ assertEquals(patriarch4.getChildren().size(), 4);
- HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4);
- wb4.close();
- sheet = wb5.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4)) {
+ HSSFSheet sheet5 = wb5.getSheetAt(0);
+ HSSFPatriarch patriarch5 = sheet5.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 4);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getShapeToObjMapping().size(), 6);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getTailRecords().size(), 1);
+ assertEquals(patriarch5.getChildren().size(), 4);
- HSSFPicture picture = (HSSFPicture) patriarch.getChildren().get(0);
- patriarch.removeShape(picture);
+ HSSFPicture picture5 = (HSSFPicture) patriarch5.getChildren().get(0);
+ patriarch5.removeShape(picture5);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 3);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getShapeToObjMapping().size(), 5);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch5).getTailRecords().size(), 1);
+ assertEquals(patriarch5.getChildren().size(), 3);
- HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5);
- wb5.close();
- sheet = wb6.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5)) {
+ HSSFSheet sheet6 = wb6.getSheetAt(0);
+ HSSFPatriarch patriarch6 = sheet6.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1);
- assertEquals(patriarch.getChildren().size(), 3);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getShapeToObjMapping().size(), 5);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getTailRecords().size(), 1);
+ assertEquals(patriarch6.getChildren().size(), 3);
- HSSFComment comment = (HSSFComment) patriarch.getChildren().get(0);
- patriarch.removeShape(comment);
+ HSSFComment comment6 = (HSSFComment) patriarch6.getChildren().get(0);
+ patriarch6.removeShape(comment6);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 2);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getShapeToObjMapping().size(), 3);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch6).getTailRecords().size(), 0);
+ assertEquals(patriarch6.getChildren().size(), 2);
- HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6);
- wb6.close();
- sheet = wb7.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6)) {
+ HSSFSheet sheet7 = wb7.getSheetAt(0);
+ HSSFPatriarch patriarch7 = sheet7.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 2);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getShapeToObjMapping().size(), 3);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getTailRecords().size(), 0);
+ assertEquals(patriarch7.getChildren().size(), 2);
- polygon = (HSSFPolygon) patriarch.getChildren().get(0);
- patriarch.removeShape(polygon);
+ HSSFPolygon polygon7 = (HSSFPolygon) patriarch7.getChildren().get(0);
+ patriarch7.removeShape(polygon7);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getShapeToObjMapping().size(), 2);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch7).getTailRecords().size(), 0);
+ assertEquals(patriarch7.getChildren().size(), 1);
- HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7);
- wb7.close();
- sheet = wb8.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7)) {
+ HSSFSheet sheet8 = wb8.getSheetAt(0);
+ HSSFPatriarch patriarch8 = sheet8.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 1);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getShapeToObjMapping().size(), 2);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getTailRecords().size(), 0);
+ assertEquals(patriarch8.getChildren().size(), 1);
- HSSFTextbox textbox = (HSSFTextbox) patriarch.getChildren().get(0);
- patriarch.removeShape(textbox);
+ HSSFTextbox textbox8 = (HSSFTextbox) patriarch8.getChildren().get(0);
+ patriarch8.removeShape(textbox8);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 0);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getShapeToObjMapping().size(), 0);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch8).getTailRecords().size(), 0);
+ assertEquals(patriarch8.getChildren().size(), 0);
- HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8);
- wb8.close();
- sheet = wb9.getSheetAt(0);
- patriarch = sheet.getDrawingPatriarch();
+ try (HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8)) {
+ HSSFSheet sheet9 = wb9.getSheetAt(0);
+ HSSFPatriarch patriarch9 = sheet9.getDrawingPatriarch();
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0);
- assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0);
- assertEquals(patriarch.getChildren().size(), 0);
- wb9.close();
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch9).getShapeToObjMapping().size(), 0);
+ assertEquals(HSSFTestHelper.getEscherAggregate(patriarch9).getTailRecords().size(), 0);
+ assertEquals(patriarch9.getChildren().size(), 0);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
@Test
diff --git a/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java b/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java
index efd3f5feff..69566e59f5 100644
--- a/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java
+++ b/poi/src/test/java/org/apache/poi/hssf/model/TestEscherRecordFactory.java
@@ -17,20 +17,16 @@
package org.apache.poi.hssf.model;
-import static org.apache.poi.ddf.DefaultEscherRecordFactory.isContainer;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
-import java.util.Random;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ddf.EscherContainerRecord;
-import org.apache.poi.ddf.EscherTextboxRecord;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.EscherAggregate;
import org.apache.poi.hssf.record.Record;
@@ -43,7 +39,7 @@ import org.junit.jupiter.api.Test;
class TestEscherRecordFactory {
private static byte[] toByteArray(List records) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
for (RecordBase rb : records) {
Record r = (org.apache.poi.hssf.record.Record) rb;
try {
@@ -55,31 +51,6 @@ class TestEscherRecordFactory {
return out.toByteArray();
}
- @Test
- void testDetectContainer() {
- Random rnd = new Random();
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.DG_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.SOLVER_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.SP_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.DGG_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.BSTORE_CONTAINER));
- assertTrue(isContainer((short) 0x0, EscherContainerRecord.SPGR_CONTAINER));
-
- for (short i=EscherContainerRecord.DGG_CONTAINER; i<= EscherContainerRecord.SOLVER_CONTAINER; i++){
- assertTrue(isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i));
- }
-
- assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER + 1).shortValue()));
-
- assertTrue(isContainer((short) 0x000F, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertTrue(isContainer((short) 0xFFFF, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0x000C, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0xCCCC, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER - 1).shortValue()));
- assertFalse(isContainer((short) 0x000F, EscherTextboxRecord.RECORD_ID));
- assertFalse(isContainer((short) 0xCCCC, EscherTextboxRecord.RECORD_ID));
- }
-
@Test
void testDgContainerMustBeRootOfHSSFSheetEscherRecords() {
HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47251.xls");
diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java
index c6ea64d6b6..466f596650 100644
--- a/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java
+++ b/poi/src/test/java/org/apache/poi/hssf/record/TestDConRefRecord.java
@@ -24,10 +24,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.util.LittleEndianOutputStream;
import org.junit.jupiter.api.Test;
@@ -209,7 +209,7 @@ class TestDConRefRecord {
private void testReadWrite(byte[] data, String message) throws IOException {
RecordInputStream is = TestcaseRecordInputStream.create(81, data);
DConRefRecord d = new DConRefRecord(is);
- ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(data.length);
LittleEndianOutputStream o = new LittleEndianOutputStream(bos);
d.serialize(o);
o.flush();
diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java
index bac766e08a..d519393c8c 100644
--- a/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java
+++ b/poi/src/test/java/org/apache/poi/hssf/record/TestDrawingRecord.java
@@ -21,12 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
final class TestDrawingRecord {
@@ -39,7 +38,7 @@ final class TestDrawingRecord {
void testReadContinued() throws IOException {
//simulate a continues drawing record
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
//main part
DrawingRecord dg = new DrawingRecord();
byte[] data1 = new byte[8224];
@@ -53,7 +52,7 @@ final class TestDrawingRecord {
ContinueRecord cn = new ContinueRecord(data2);
out.write(cn.serialize());
- List rec = RecordFactory.createRecords(new ByteArrayInputStream(out.toByteArray()));
+ List rec = RecordFactory.createRecords(out.toInputStream());
assertEquals(2, rec.size());
assertTrue(rec.get(0) instanceof DrawingRecord);
assertTrue(rec.get(1) instanceof ContinueRecord);
diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
index afd988fb37..005d03d6ef 100644
--- a/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
+++ b/poi/src/test/java/org/apache/poi/hssf/record/TestLbsDataSubRecord.java
@@ -25,9 +25,9 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.ss.formula.ptg.AreaPtg;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.HexRead;
@@ -166,7 +166,7 @@ final class TestLbsDataSubRecord {
try (LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data))) {
LbsDataSubRecord.LbsDropData lbs = new LbsDataSubRecord.LbsDropData(in);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
try (LittleEndianOutputStream out = new LittleEndianOutputStream(baos)) {
lbs.serialize(out);
diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java b/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java
index 11f66367e1..01dee7e08e 100644
--- a/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java
+++ b/poi/src/test/java/org/apache/poi/hssf/record/TestRecordFactory.java
@@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.HexRead;
import org.junit.jupiter.api.Test;
@@ -185,7 +185,7 @@ final class TestRecordFactory {
assertTrue(records.get(4) instanceof ObjRecord);
//serialize and verify that the serialized data is the same as the original
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
for(org.apache.poi.hssf.record.Record rec : records){
out.write(rec.serialize());
}
@@ -204,7 +204,7 @@ final class TestRecordFactory {
BOFRecord.createSheetBOF(),
EOFRecord.instance,
};
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
for (org.apache.poi.hssf.record.Record rec : recs) {
try {
baos.write(rec.serialize());
@@ -222,13 +222,13 @@ final class TestRecordFactory {
}
- POIFSFileSystem fs = new POIFSFileSystem();
- fs.createDocument(new ByteArrayInputStream(baos.toByteArray()), "dummy");
- InputStream is = fs.getRoot().createDocumentInputStream("dummy");
+ try (POIFSFileSystem fs = new POIFSFileSystem()) {
+ fs.createDocument(baos.toInputStream(), "dummy");
+ InputStream is = fs.getRoot().createDocumentInputStream("dummy");
- List outRecs = RecordFactory.createRecords(is);
- // Buffer underrun - requested 512 bytes but 192 was available
- assertEquals(5, outRecs.size());
- fs.close();
+ List outRecs = RecordFactory.createRecords(is);
+ // Buffer underrun - requested 512 bytes but 192 was available
+ assertEquals(5, outRecs.size());
+ }
}
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java b/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java
index b2206b86b7..eed605b661 100644
--- a/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java
+++ b/poi/src/test/java/org/apache/poi/hssf/record/TestSSTRecord.java
@@ -24,13 +24,13 @@ import static org.junit.jupiter.api.Assertions.fail;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.common.UnicodeString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
@@ -49,7 +49,7 @@ final class TestSSTRecord {
*/
private static byte[] concatHexDumps(String... hexDumpFileNames) throws IOException {
int nFiles = hexDumpFileNames.length;
- ByteArrayOutputStream baos = new ByteArrayOutputStream(nFiles * 8228);
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(nFiles * 8228);
for (String sampleFileName : hexDumpFileNames) {
try (InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName)) {
BufferedReader br = new BufferedReader(new InputStreamReader(is, LocaleUtil.CHARSET_1252));
diff --git a/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java b/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java
index 35f84590f7..57b344bd25 100644
--- a/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java
+++ b/poi/src/test/java/org/apache/poi/hssf/record/common/TestUnicodeString.java
@@ -21,10 +21,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.record.ContinueRecord;
import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.hssf.record.SSTRecord;
@@ -36,11 +36,11 @@ import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.util.LittleEndianByteArrayInputStream;
-import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.LittleEndianInput;
import org.apache.poi.util.LittleEndianInputStream;
import org.apache.poi.util.LittleEndianOutputStream;
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.StringUtil;
import org.junit.jupiter.api.Test;
@@ -185,7 +185,7 @@ final class TestUnicodeString {
assertEquals(4, fr.getCharacterPos());
assertEquals(0x15c, fr.getFontIndex());
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream out = new LittleEndianOutputStream(baos);
fr.serialize(out);
@@ -216,7 +216,7 @@ final class TestUnicodeString {
assertEquals(0, ext.getPhRuns().length);
assertEquals(10, ext.getDataSize()); // Excludes 4 byte header
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
LittleEndianOutputStream out = new LittleEndianOutputStream(baos);
ContinuableRecordOutput cout = new ContinuableRecordOutput(out, 0xffff);
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java
index b30f9f71ec..10cad91c66 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestBugs.java
@@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
@@ -46,6 +45,7 @@ import java.util.stream.IntStream;
import javax.imageio.ImageIO;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.HSSFITestDataProvider;
@@ -1175,9 +1175,9 @@ final class TestBugs extends BaseTestBugzillaIssues {
@Test
void bug32191() throws IOException {
try (HSSFWorkbook wb = openSampleWorkbook("27394.xls");
- ByteArrayOutputStream out1 = new ByteArrayOutputStream();
- ByteArrayOutputStream out2 = new ByteArrayOutputStream();
- ByteArrayOutputStream out3 = new ByteArrayOutputStream()) {
+ UnsynchronizedByteArrayOutputStream out1 = new UnsynchronizedByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out2 = new UnsynchronizedByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out3 = new UnsynchronizedByteArrayOutputStream()) {
wb.write(out1);
wb.write(out2);
wb.write(out3);
@@ -2220,7 +2220,7 @@ final class TestBugs extends BaseTestBugzillaIssues {
/**
* Read, write, read for formulas point to cells in other files.
- * See {@link #bug46670()} for the main test, this just
+ * See bug46670() for the main test, this just
* covers reading an existing file and checking it.
*
* See base-test-class for some related tests that still fail
@@ -2331,7 +2331,7 @@ final class TestBugs extends BaseTestBugzillaIssues {
}
// Convert BufferedImage to byte[]
- ByteArrayOutputStream imageBAOS = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream imageBAOS = new UnsynchronizedByteArrayOutputStream();
ImageIO.write(bimage, "jpeg", imageBAOS);
imageBAOS.flush();
byte[] imageBytes = imageBAOS.toByteArray();
@@ -2552,7 +2552,7 @@ final class TestBugs extends BaseTestBugzillaIssues {
"46904.xls, org.apache.poi.hssf.OldExcelFormatException, The supplied spreadsheet seems to be Excel",
"51832.xls, org.apache.poi.EncryptedDocumentException, Default password is invalid for salt/verifier/verifierHash"
})
- void simpleTest(String fileName, String exClazz, String exMessage) throws IOException, ClassNotFoundException {
+ void simpleTest(String fileName, String exClazz, String exMessage) throws ClassNotFoundException {
Class extends Exception> ex = (Class extends Exception>)Class.forName(exClazz);
Exception e = assertThrows(ex, () -> simpleTest(fileName, null));
assertTrue(e.getMessage().startsWith(exMessage));
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java
index 777e436e32..36c61a08d8 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestDataValidation.java
@@ -24,13 +24,13 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hssf.HSSFITestDataProvider;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.hssf.record.DVRecord;
@@ -61,7 +61,7 @@ final class TestDataValidation extends BaseTestDataValidation {
void assertDataValidation(Workbook wb) {
byte[] generatedContent;
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream(22000)) {
+ try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(22000)) {
wb.write(baos);
generatedContent = baos.toByteArray();
} catch (IOException e) {
@@ -133,7 +133,7 @@ final class TestDataValidation extends BaseTestDataValidation {
sheet.addValidationData(dv);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
wb.write(baos);
byte[] wbData = baos.toByteArray();
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java
index 3ddac1b794..3b12a4dd32 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestEscherGraphics.java
@@ -17,6 +17,7 @@
package org.apache.poi.hssf.usermodel;
+import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -24,8 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
@@ -46,7 +45,7 @@ final class TestEscherGraphics {
private EscherGraphics graphics;
@BeforeEach
- void setUp() throws IOException {
+ void setUp() {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("test");
@@ -82,7 +81,7 @@ final class TestEscherGraphics {
@Test
void testSetFont() {
- Font f = new Font("Helvetica", 0, 12);
+ Font f = new Font("Helvetica", Font.PLAIN, 12);
graphics.setFont(f);
assertEquals(f, graphics.getFont());
}
@@ -112,18 +111,15 @@ final class TestEscherGraphics {
}
@Test
- void testGetDataBackAgain() throws Exception {
+ void testGetDataBackAgain() {
HSSFSheet s;
HSSFShapeGroup s1;
HSSFShapeGroup s2;
patriarch.setCoordinates(10, 20, 30, 40);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
-
+ workbook = writeOutAndReadBack(workbook);
+ s = workbook.getSheetAt(0);
patriarch = s.getDrawingPatriarch();
assertNotNull(patriarch);
@@ -160,11 +156,9 @@ final class TestEscherGraphics {
// Write and re-load once more, to check that's ok
- baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
- patriarch = s.getDrawingPatriarch();
+ workbook = writeOutAndReadBack(workbook);
+ s = workbook.getSheetAt(0);
+ patriarch = s.getDrawingPatriarch();
assertNotNull(patriarch);
assertEquals(10, patriarch.getX1());
@@ -202,11 +196,9 @@ final class TestEscherGraphics {
// but not of their anchors
s1.setCoordinates(2, 3, 1021, 242);
- baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
- patriarch = s.getDrawingPatriarch();
+ workbook = writeOutAndReadBack(workbook);
+ s = workbook.getSheetAt(0);
+ patriarch = s.getDrawingPatriarch();
assertNotNull(patriarch);
assertEquals(10, patriarch.getX1());
@@ -254,12 +246,9 @@ final class TestEscherGraphics {
assertEquals(3, patriarch.getChildren().size());
- baos = new ByteArrayOutputStream();
- workbook.write(baos);
- workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray()));
- s = workbook.getSheetAt(0);
-
- patriarch = s.getDrawingPatriarch();
+ workbook = writeOutAndReadBack(workbook);
+ s = workbook.getSheetAt(0);
+ patriarch = s.getDrawingPatriarch();
assertNotNull(patriarch);
assertEquals(10, patriarch.getX1());
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java
index b2a793f972..5e99f213f2 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFPicture.java
@@ -47,6 +47,7 @@ final class TestHSSFPicture extends BaseTestPicture {
super(HSSFITestDataProvider.instance);
}
+ @Override
protected Picture getPictureShape(Drawing> pat, int picIdx) {
return (Picture)((HSSFPatriarch)pat).getChildren().get(picIdx);
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java
index ac4f32cb0e..3110783837 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java
@@ -28,8 +28,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -41,6 +39,7 @@ import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.ddf.EscherBSERecord;
import org.apache.poi.hpsf.ClassID;
@@ -72,6 +71,7 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
+import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -554,21 +554,17 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
*/
@Test
void bug47920() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls"));
- HSSFWorkbook wb = new HSSFWorkbook(fs1);
- ClassID clsid1 = fs1.getRoot().getStorageClsid();
-
- ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
- wb.write(out);
- byte[] bytes = out.toByteArray();
- POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes));
- ClassID clsid2 = fs2.getRoot().getStorageClsid();
-
- assertEquals(clsid1, clsid2);
-
- fs2.close();
- wb.close();
- fs1.close();
+ try (POIFSFileSystem fs1 = new POIFSFileSystem(samples.openResourceAsStream("47920.xls"));
+ HSSFWorkbook wb = new HSSFWorkbook(fs1)) {
+ ClassID clsid1 = fs1.getRoot().getStorageClsid();
+
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(4096);
+ wb.write(out);
+ try (POIFSFileSystem fs2 = new POIFSFileSystem(out.toInputStream())) {
+ ClassID clsid2 = fs2.getRoot().getStorageClsid();
+ assertEquals(clsid1, clsid2);
+ }
+ }
}
/**
@@ -582,8 +578,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
"testEXCEL_95.xls,BIFF5"
})
void helpfulExceptionOnOldFiles(String file, String format) throws Exception {
- POIDataSamples xlsData = samples;
- try (InputStream is = xlsData.openResourceAsStream(file)) {
+ try (InputStream is = samples.openResourceAsStream(file)) {
OldExcelFormatException e = assertThrows(OldExcelFormatException.class, () -> new HSSFWorkbook(is),
"Shouldn't be able to load an Excel " + format + " file");
assertContains(e.getMessage(), format);
@@ -978,7 +973,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
assertNotNull(name);
assertEquals("ASheet!A1", name.getRefersToFormula());
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream();
wb.write(stream);
assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet");
@@ -989,15 +984,15 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet");
assertEquals("ASheet!A1", name.getRefersToFormula());
- ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream stream2 = new UnsynchronizedByteArrayOutputStream();
wb.write(stream2);
assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet");
assertEquals("ASheet!A1", name.getRefersToFormula());
- HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray()));
+ HSSFWorkbook wb2 = new HSSFWorkbook(stream.toInputStream());
expectName(wb2, nameName, "ASheet!A1");
- HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray()));
+ HSSFWorkbook wb3 = new HSSFWorkbook(stream2.toInputStream());
expectName(wb3, nameName, "ASheet!A1");
wb3.close();
wb2.close();
@@ -1078,7 +1073,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
private void writeAndCloseWorkbook(Workbook workbook, File file)
throws IOException {
- final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
+ final UnsynchronizedByteArrayOutputStream bytesOut = new UnsynchronizedByteArrayOutputStream();
workbook.write(bytesOut);
workbook.close();
@@ -1183,7 +1178,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook {
}
}
- void createDrawing() throws Exception {
+ @Disabled
+ void createDrawing() {
// the dimensions for this image are different than for XSSF and SXSSF
}
}
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java
index 1183c5f6b5..60b15c8061 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java
@@ -21,12 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.DirectoryNode;
@@ -60,73 +59,70 @@ final class TestOLE2Embeding {
@Test
void testReallyEmbedSomething() throws Exception {
- HSSFWorkbook wb1 = new HSSFWorkbook();
- HSSFSheet sheet = wb1.createSheet();
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
-
- byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png");
- byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg");
- int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
- POIFSFileSystem pptPoifs = getSamplePPT();
- int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt");
- POIFSFileSystem xlsPoifs = getSampleXLS();
- int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG);
- int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls");
- int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt");
-
- int rowoffset = 5;
- int coloffset = 5;
-
- CreationHelper ch = wb1.getCreationHelper();
- HSSFClientAnchor anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(2+coloffset), 1+rowoffset, 0, 0, (short)(3+coloffset), 5+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- patriarch.createObjectData(anchor, pptIdx, imgPPT);
-
- anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(5+coloffset), 1+rowoffset, 0, 0, (short)(6+coloffset), 5+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- patriarch.createObjectData(anchor, xlsIdx, imgIdx);
-
- anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(3+coloffset), 10+rowoffset, 0, 0, (short)(5+coloffset), 11+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- patriarch.createObjectData(anchor, txtIdx, imgIdx);
-
- anchor = (HSSFClientAnchor)ch.createClientAnchor();
- anchor.setAnchor((short)(1+coloffset), -2+rowoffset, 0, 0, (short)(7+coloffset), 14+rowoffset, 0, 0);
- anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
-
- HSSFSimpleShape circle = patriarch.createSimpleShape(anchor);
- circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
- circle.setNoFill(true);
-
- HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1);
- wb1.close();
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0);
- Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory());
- bos.reset();
- pptPoifs.writeFilesystem(bos);
- assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray());
-
- od = wb2.getAllEmbeddedObjects().get(1);
- ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory());
- bos.reset();
- xlsPoifs.writeFilesystem(bos);
- assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray());
-
- od = wb2.getAllEmbeddedObjects().get(2);
- ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory());
- assertArrayEquals(ole10.getDataBuffer(), getSampleTXT());
-
- xlsPoifs.close();
- pptPoifs.close();
- wb2.close();
+ try (HSSFWorkbook wb1 = new HSSFWorkbook();
+ POIFSFileSystem pptPoifs = getSamplePPT();
+ POIFSFileSystem xlsPoifs = getSampleXLS()) {
+ HSSFSheet sheet = wb1.createSheet();
+ HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
+
+ byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png");
+ byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg");
+ int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
+
+ int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt");
+ int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG);
+ int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls");
+ int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt");
+
+ int rowoffset = 5;
+ int coloffset = 5;
+
+ CreationHelper ch = wb1.getCreationHelper();
+ HSSFClientAnchor anchor = (HSSFClientAnchor) ch.createClientAnchor();
+ anchor.setAnchor((short) (2 + coloffset), 1 + rowoffset, 0, 0, (short) (3 + coloffset), 5 + rowoffset, 0, 0);
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+
+ patriarch.createObjectData(anchor, pptIdx, imgPPT);
+
+ anchor = (HSSFClientAnchor) ch.createClientAnchor();
+ anchor.setAnchor((short) (5 + coloffset), 1 + rowoffset, 0, 0, (short) (6 + coloffset), 5 + rowoffset, 0, 0);
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+
+ patriarch.createObjectData(anchor, xlsIdx, imgIdx);
+
+ anchor = (HSSFClientAnchor) ch.createClientAnchor();
+ anchor.setAnchor((short) (3 + coloffset), 10 + rowoffset, 0, 0, (short) (5 + coloffset), 11 + rowoffset, 0, 0);
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+
+ patriarch.createObjectData(anchor, txtIdx, imgIdx);
+
+ anchor = (HSSFClientAnchor) ch.createClientAnchor();
+ anchor.setAnchor((short) (1 + coloffset), -2 + rowoffset, 0, 0, (short) (7 + coloffset), 14 + rowoffset, 0, 0);
+ anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
+
+ HSSFSimpleShape circle = patriarch.createSimpleShape(anchor);
+ circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
+ circle.setNoFill(true);
+
+ try (HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1)) {
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
+ HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0);
+ Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) od.getDirectory());
+ bos.reset();
+ pptPoifs.writeFilesystem(bos);
+ assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray());
+
+ od = wb2.getAllEmbeddedObjects().get(1);
+ ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) od.getDirectory());
+ bos.reset();
+ xlsPoifs.writeFilesystem(bos);
+ assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray());
+
+ od = wb2.getAllEmbeddedObjects().get(2);
+ ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) od.getDirectory());
+ assertArrayEquals(ole10.getDataBuffer(), getSampleTXT());
+ }
+ }
}
static POIFSFileSystem getSamplePPT() throws IOException {
@@ -139,15 +135,15 @@ final class TestOLE2Embeding {
}
static POIFSFileSystem getSampleXLS() throws IOException {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet();
- sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file");
+ UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
+ try (HSSFWorkbook wb = new HSSFWorkbook()) {
+ HSSFSheet sheet = wb.createSheet();
+ sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file");
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- wb.write(bos);
- wb.close();
+ wb.write(bos);
+ }
- return new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
+ return new POIFSFileSystem(bos.toInputStream());
}
static byte[] getSampleTXT() {
diff --git a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java
index 6d62955f0c..5ff7c4e5ca 100644
--- a/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java
+++ b/poi/src/test/java/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java
@@ -21,11 +21,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import org.apache.poi.hpsf.*;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+import org.apache.poi.hpsf.NoPropertySetStreamException;
+import org.apache.poi.hpsf.PropertySetFactory;
+import org.apache.poi.hpsf.SummaryInformation;
+import org.apache.poi.hpsf.WritingNotSupportedException;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.HexDump;
@@ -38,12 +41,11 @@ class TestPOIFSProperties {
private static final String title = "Testing POIFS properties";
@Test
- void testFail() throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- { // read the workbook, adjust the SummaryInformation and write the data to a byte array
- POIFSFileSystem fs = openFileSystem();
-
- HSSFWorkbook wb = new HSSFWorkbook(fs);
+ void testFail() throws IOException, NoPropertySetStreamException, WritingNotSupportedException {
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
+ // read the workbook, adjust the SummaryInformation and write the data to a byte array
+ try (POIFSFileSystem fs = openFileSystem();
+ HSSFWorkbook wb = new HSSFWorkbook(fs)) {
//set POIFS properties after constructing HSSFWorkbook
//(a piece of code that used to work up to POI 3.0.2)
@@ -51,8 +53,6 @@ class TestPOIFSProperties {
//save the workbook and read the property
wb.write(out);
- out.close();
- wb.close();
}
// process the byte array
@@ -61,18 +61,16 @@ class TestPOIFSProperties {
@Test
void testOK() throws Exception {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- { // read the workbook, adjust the SummaryInformation and write the data to a byte array
- POIFSFileSystem fs = openFileSystem();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
+ // read the workbook, adjust the SummaryInformation and write the data to a byte array
+ try (POIFSFileSystem fs = openFileSystem()) {
//set POIFS properties before constructing HSSFWorkbook
setTitle(fs);
- HSSFWorkbook wb = new HSSFWorkbook(fs);
-
- wb.write(out);
- out.close();
- wb.close();
+ try (HSSFWorkbook wb = new HSSFWorkbook(fs)) {
+ wb.write(out);
+ }
}
// process the byte array
@@ -80,13 +78,12 @@ class TestPOIFSProperties {
}
private POIFSFileSystem openFileSystem() throws IOException {
- InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls");
- POIFSFileSystem fs = new POIFSFileSystem(is);
- is.close();
- return fs;
+ try (InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls")) {
+ return new POIFSFileSystem(is);
+ }
}
- private void setTitle(POIFSFileSystem fs) throws NoPropertySetStreamException, MarkUnsupportedException, IOException, WritingNotSupportedException {
+ private void setTitle(POIFSFileSystem fs) throws NoPropertySetStreamException, IOException, WritingNotSupportedException {
SummaryInformation summary1 = (SummaryInformation) PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
assertNotNull(summary1);
@@ -100,16 +97,15 @@ class TestPOIFSProperties {
assertNotNull(summaryCheck);
}
- private void checkFromByteArray(byte[] bytes) throws IOException, NoPropertySetStreamException, MarkUnsupportedException {
+ private void checkFromByteArray(byte[] bytes) throws IOException, NoPropertySetStreamException {
// on some environments in CI we see strange failures, let's verify that the size is exactly right
// this can be removed again after the problem is identified
assertEquals(5120, bytes.length, "Had: " + HexDump.toHex(bytes));
- POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes));
- SummaryInformation summary2 = (SummaryInformation) PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
- assertNotNull(summary2);
-
- assertEquals(title, summary2.getTitle());
- fs2.close();
+ try (POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes))) {
+ SummaryInformation summary2 = (SummaryInformation) PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
+ assertNotNull(summary2);
+ assertEquals(title, summary2.getTitle());
+ }
}
}
diff --git a/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java b/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java
index 2bca550236..3250bc0307 100644
--- a/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java
+++ b/poi/src/test/java/org/apache/poi/poifs/crypt/TestXorEncryption.java
@@ -17,12 +17,12 @@
package org.apache.poi.poifs.crypt;
+import static org.apache.poi.hssf.HSSFTestDataSamples.getSampleFile;
+import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -37,9 +37,6 @@ import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class TestXorEncryption {
-
- private static final HSSFTestDataSamples samples = new HSSFTestDataSamples();
-
@Test
void testXorEncryption() {
// Xor-Password: abc
@@ -56,10 +53,9 @@ class TestXorEncryption {
assertThat(xorArrExp, equalTo(xorArrAct));
}
- @SuppressWarnings("static-access")
@Test
void testUserFile() throws IOException {
- File f = samples.getSampleFile("xor-encryption-abc.xls");
+ File f = getSampleFile("xor-encryption-abc.xls");
Biff8EncryptionKey.setCurrentUserPassword("abc");
try (POIFSFileSystem fs = new POIFSFileSystem(f, true);
HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true)) {
@@ -75,16 +71,14 @@ class TestXorEncryption {
@Test
@Disabled("currently not supported")
void encrypt() throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
try (HSSFWorkbook hwb = HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")) {
Biff8EncryptionKey.setCurrentUserPassword("abc");
hwb.getInternalWorkbook().getWorkbookRecordList()
.add(1, new FilePassRecord(EncryptionMode.xor));
- hwb.write(bos);
- }
- try (HSSFWorkbook hwb = new HSSFWorkbook(new ByteArrayInputStream(bos.toByteArray()))) {
- assertEquals(3, hwb.getNumberOfSheets());
+ try (HSSFWorkbook hwb2 = writeOutAndReadBack(hwb)) {
+ assertEquals(3, hwb2.getNumberOfSheets());
+ }
}
} finally {
Biff8EncryptionKey.setCurrentUserPassword(null);
diff --git a/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java b/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java
index 1fa1802bea..4482607e62 100644
--- a/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java
+++ b/poi/src/test/java/org/apache/poi/poifs/dev/TestPOIFSDump.java
@@ -34,7 +34,7 @@ import org.apache.poi.poifs.filesystem.NotOLE2FileException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.property.PropertyTable;
-import org.apache.poi.util.NullPrintStream;
+import org.apache.commons.io.output.NullPrintStream;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
@@ -150,7 +150,7 @@ public class TestPOIFSDump {
}
@Test
- void testMainNoArgs() throws Exception {
+ void testMainNoArgs() {
SecurityManager sm = System.getSecurityManager();
try {
System.setSecurityManager(new SecurityManager() {
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java
index 15edc14e92..4994d5db98 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocument.java
@@ -21,14 +21,15 @@ import static org.apache.poi.poifs.common.POIFSConstants.LARGER_BIG_BLOCK_SIZE;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.stream.IntStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.poifs.property.DocumentProperty;
import org.apache.poi.poifs.storage.RawDataUtil;
import org.apache.poi.util.IOUtils;
@@ -67,7 +68,7 @@ class TestDocument {
// verify that output is correct
POIFSDocument document = checkDocument(poifs, LARGER_BIG_BLOCK_SIZE + 1);
DocumentProperty property = document.getDocumentProperty();
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream();
property.writeData(stream);
byte[] output = stream.toByteArray();
@@ -111,7 +112,7 @@ class TestDocument {
private static byte[] checkValues(final int blockCountExp, POIFSDocument document, byte[] input) throws IOException {
assertNotNull(document);
assertNotNull(document.getDocumentProperty().getDocument());
- assertEquals(document, document.getDocumentProperty().getDocument());
+ assertSame(document, document.getDocumentProperty().getDocument());
ByteArrayInputStream bis = new ByteArrayInputStream(input);
@@ -134,7 +135,7 @@ class TestDocument {
assertEquals(blockCountExp, blockCountAct);
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream stream = new UnsynchronizedByteArrayOutputStream();
try (DocumentInputStream dis = document.getFileSystem().createDocumentInputStream(
document.getDocumentProperty().getName())) {
IOUtils.copy(dis, stream);
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java
index d2815e0254..95133ff478 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java
@@ -22,10 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.util.IOUtils;
import org.junit.jupiter.api.Test;
@@ -46,7 +46,7 @@ final class TestDocumentOutputStream {
try {
for (byte b : expected) {
- dstream.write((int)b);
+ dstream.write(b);
}
} catch (IOException ignored) {
fail("stream exhausted too early");
@@ -115,7 +115,7 @@ final class TestDocumentOutputStream {
root.createDocument("foo", expected.length, l);
try (DocumentInputStream is = root.createDocumentInputStream("foo")) {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream(expected.length);
+ final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(expected.length);
IOUtils.copy(is, bos);
assertArrayEquals(expected, bos.toByteArray());
}
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java
index c594fb513d..ed08a1fa08 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEmptyDocument.java
@@ -22,10 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.stream.Stream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.util.IOUtils;
@@ -82,9 +82,9 @@ final class TestEmptyDocument {
DirectoryEntry dir = fs.getRoot();
emptyDoc.handle(dir);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
fs.writeFilesystem(out);
- assertDoesNotThrow(() -> new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())));
+ assertDoesNotThrow(() -> new POIFSFileSystem(out.toInputStream()));
}
}
@@ -92,7 +92,7 @@ final class TestEmptyDocument {
void testEmptyDocumentBug11744() throws Exception {
byte[] testData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream();
try (POIFSFileSystem fs = new POIFSFileSystem()) {
fs.createDocument(new ByteArrayInputStream(new byte[0]), "Empty");
fs.createDocument(new ByteArrayInputStream(testData), "NotEmpty");
@@ -100,7 +100,7 @@ final class TestEmptyDocument {
}
// This line caused the error.
- try (POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()))) {
+ try (POIFSFileSystem fs = new POIFSFileSystem(out.toInputStream())) {
DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty");
assertEquals(0, entry.getSize(), "Expected zero size");
byte[] actualReadbackData;
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java
index b85550cc15..e2abb090ab 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestEntryUtils.java
@@ -24,12 +24,13 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.junit.jupiter.api.Test;
class TestEntryUtils {
@@ -101,51 +102,52 @@ class TestEntryUtils {
@Test
void testAreDocumentsIdentical() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem();
- DirectoryEntry dirA = fs.createDirectory("DirA");
- DirectoryEntry dirB = fs.createDirectory("DirB");
+ try (POIFSFileSystem fs = new POIFSFileSystem()) {
+ DirectoryEntry dirA = fs.createDirectory("DirA");
+ DirectoryEntry dirB = fs.createDirectory("DirB");
- DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
- DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA));
- DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB));
- DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
+ DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
+ DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA));
+ DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB));
+ DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA));
- // Names must match
- assertNotEquals(entryA1.getName(), entryA1b.getName());
- assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA1b));
+ // Names must match
+ assertNotEquals(entryA1.getName(), entryA1b.getName());
+ assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA1b));
- // Contents must match
- assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA2));
+ // Contents must match
+ assertFalse(EntryUtils.areDocumentsIdentical(entryA1, entryA2));
- // Parents don't matter if contents + names are the same
- assertNotEquals(entryA1.getParent(), entryB1.getParent());
- assertTrue(EntryUtils.areDocumentsIdentical(entryA1, entryB1));
+ // Parents don't matter if contents + names are the same
+ assertNotEquals(entryA1.getParent(), entryB1.getParent());
+ assertTrue(EntryUtils.areDocumentsIdentical(entryA1, entryB1));
- // Can work with POIFS
- ByteArrayOutputStream tmpO = new ByteArrayOutputStream();
- fs.writeFilesystem(tmpO);
+ // Can work with POIFS
+ try (UnsynchronizedByteArrayOutputStream tmpO = new UnsynchronizedByteArrayOutputStream()) {
+ fs.writeFilesystem(tmpO);
- ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray());
- POIFSFileSystem nfs = new POIFSFileSystem(tmpI);
+ try (InputStream tmpI = tmpO.toInputStream();
+ POIFSFileSystem nfs = new POIFSFileSystem(tmpI)) {
- DirectoryEntry dN1 = (DirectoryEntry)nfs.getRoot().getEntry("DirA");
- DirectoryEntry dN2 = (DirectoryEntry)nfs.getRoot().getEntry("DirB");
- DocumentEntry eNA1 = (DocumentEntry)dN1.getEntry(entryA1.getName());
- DocumentEntry eNA2 = (DocumentEntry)dN1.getEntry(entryA2.getName());
- DocumentEntry eNB1 = (DocumentEntry)dN2.getEntry(entryB1.getName());
+ DirectoryEntry dN1 = (DirectoryEntry) nfs.getRoot().getEntry("DirA");
+ DirectoryEntry dN2 = (DirectoryEntry) nfs.getRoot().getEntry("DirB");
+ DocumentEntry eNA1 = (DocumentEntry) dN1.getEntry(entryA1.getName());
+ DocumentEntry eNA2 = (DocumentEntry) dN1.getEntry(entryA2.getName());
+ DocumentEntry eNB1 = (DocumentEntry) dN2.getEntry(entryB1.getName());
- assertFalse(EntryUtils.areDocumentsIdentical(eNA1, eNA2));
- assertTrue(EntryUtils.areDocumentsIdentical(eNA1, eNB1));
+ assertFalse(EntryUtils.areDocumentsIdentical(eNA1, eNA2));
+ assertTrue(EntryUtils.areDocumentsIdentical(eNA1, eNB1));
- assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA1b));
- assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA2));
+ assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA1b));
+ assertFalse(EntryUtils.areDocumentsIdentical(eNA1, entryA2));
- assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryA1));
- assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryB1));
- nfs.close();
- fs.close();
+ assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryA1));
+ assertTrue(EntryUtils.areDocumentsIdentical(eNA1, entryB1));
+ }
+ }
+ }
}
@Test
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java
index ef504aca69..dd52a10a58 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java
@@ -20,8 +20,6 @@ package org.apache.poi.poifs.filesystem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
@@ -29,6 +27,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -141,11 +140,10 @@ final class TestFileSystemBugs {
EntryUtils.copyNodes(root, dest);
// Re-load
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
root.getFileSystem().writeFilesystem(baos);
- POIFSFileSystem read = new POIFSFileSystem(
- new ByteArrayInputStream(baos.toByteArray()));
+ POIFSFileSystem read = new POIFSFileSystem(baos.toInputStream());
// Check the structure matches
checkSizes("/", read.getRoot(), entries);
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java
index 6becf23aa1..3a3f2fa8dc 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestOle10Native.java
@@ -23,7 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -31,6 +30,7 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.RecordFormatException;
@@ -62,25 +62,24 @@ class TestOle10Native {
};
for (File f : files) {
- POIFSFileSystem fs = new POIFSFileSystem(f, true);
- List entries = new ArrayList<>();
- findOle10(entries, fs.getRoot(), "/");
+ try (POIFSFileSystem fs = new POIFSFileSystem(f, true)) {
+ List entries = new ArrayList<>();
+ findOle10(entries, fs.getRoot(), "/");
- for (Entry e : entries) {
- ByteArrayOutputStream bosExp = new ByteArrayOutputStream();
- InputStream is = ((DirectoryNode)e.getParent()).createDocumentInputStream(e);
- IOUtils.copy(is,bosExp);
- is.close();
+ for (Entry e : entries) {
+ UnsynchronizedByteArrayOutputStream bosExp = new UnsynchronizedByteArrayOutputStream();
+ try (InputStream is = ((DirectoryNode) e.getParent()).createDocumentInputStream(e)) {
+ IOUtils.copy(is, bosExp);
+ }
- Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)e.getParent());
+ Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode) e.getParent());
- ByteArrayOutputStream bosAct = new ByteArrayOutputStream();
- ole.writeOut(bosAct);
+ UnsynchronizedByteArrayOutputStream bosAct = new UnsynchronizedByteArrayOutputStream();
+ ole.writeOut(bosAct);
- assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray()));
+ assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray()));
+ }
}
-
- fs.close();
}
}
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
index c644fb1c60..db6a062872 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
@@ -23,13 +23,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.HashMap;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.Property;
@@ -44,7 +44,6 @@ import org.apache.poi.util.IOUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
-import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests for the older OPOIFS-based POIFSFileSystem
@@ -147,7 +146,7 @@ final class TestPOIFSFileSystem {
try (POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream(file))) {
// Write it into a temp output array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
fs.writeFilesystem(baos);
// Check sizes
@@ -186,7 +185,7 @@ final class TestPOIFSFileSystem {
"BIG", new ByteArrayInputStream(hugeStream)
);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
fs.writeFilesystem(baos);
byte[] fsData = baos.toByteArray();
diff --git a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
index 2a2a8122d1..430cd8e5d2 100644
--- a/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
+++ b/poi/src/test/java/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
@@ -17,6 +17,7 @@
package org.apache.poi.poifs.filesystem;
+import static org.apache.poi.POIDataSamples.writeOutAndReadBack;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
@@ -26,21 +27,28 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Iterator;
+import java.util.List;
import java.util.NoSuchElementException;
+import java.util.function.Function;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.POIDataSamples;
import org.apache.poi.hpsf.DocumentSummaryInformation;
+import org.apache.poi.hpsf.NoPropertySetStreamException;
import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
@@ -55,6 +63,9 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
/**
* Tests {@link POIFSStream}
@@ -67,26 +78,25 @@ final class TestPOIFSStream {
*/
@Test
void testReadTinyStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // 98 is actually the last block in a two block stream...
- POIFSStream stream = new POIFSStream(fs, 98);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents
- assertEquals((byte) 0x81, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x82, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
- assertEquals((byte) 0x00, b.get());
-
- fs.close();
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {
+
+ // 98 is actually the last block in a two block stream...
+ POIFSStream stream = new POIFSStream(fs, 98);
+ Iterator i = stream.getBlockIterator();
+ assertTrue(i.hasNext());
+ ByteBuffer b = i.next();
+ assertFalse(i.hasNext());
+
+ // Check the contents
+ assertEquals((byte) 0x81, b.get());
+ assertEquals((byte) 0x00, b.get());
+ assertEquals((byte) 0x00, b.get());
+ assertEquals((byte) 0x00, b.get());
+ assertEquals((byte) 0x82, b.get());
+ assertEquals((byte) 0x00, b.get());
+ assertEquals((byte) 0x00, b.get());
+ assertEquals((byte) 0x00, b.get());
+ }
}
/**
@@ -94,38 +104,37 @@ final class TestPOIFSStream {
*/
@Test
void testReadShortStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // 97 -> 98 -> end
- POIFSStream stream = new POIFSStream(fs, 97);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b97 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b98 = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents of the 1st block
- assertEquals((byte) 0x01, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x02, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
- assertEquals((byte) 0x00, b97.get());
-
- // Check the contents of the 2nd block
- assertEquals((byte) 0x81, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x82, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
- assertEquals((byte) 0x00, b98.get());
-
- fs.close();
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {
+
+ // 97 -> 98 -> end
+ POIFSStream stream = new POIFSStream(fs, 97);
+ Iterator i = stream.getBlockIterator();
+ assertTrue(i.hasNext());
+ ByteBuffer b97 = i.next();
+ assertTrue(i.hasNext());
+ ByteBuffer b98 = i.next();
+ assertFalse(i.hasNext());
+
+ // Check the contents of the 1st block
+ assertEquals((byte) 0x01, b97.get());
+ assertEquals((byte) 0x00, b97.get());
+ assertEquals((byte) 0x00, b97.get());
+ assertEquals((byte) 0x00, b97.get());
+ assertEquals((byte) 0x02, b97.get());
+ assertEquals((byte) 0x00, b97.get());
+ assertEquals((byte) 0x00, b97.get());
+ assertEquals((byte) 0x00, b97.get());
+
+ // Check the contents of the 2nd block
+ assertEquals((byte) 0x81, b98.get());
+ assertEquals((byte) 0x00, b98.get());
+ assertEquals((byte) 0x00, b98.get());
+ assertEquals((byte) 0x00, b98.get());
+ assertEquals((byte) 0x82, b98.get());
+ assertEquals((byte) 0x00, b98.get());
+ assertEquals((byte) 0x00, b98.get());
+ assertEquals((byte) 0x00, b98.get());
+ }
}
/**
@@ -133,59 +142,58 @@ final class TestPOIFSStream {
*/
@Test
void testReadLongerStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {
- ByteBuffer b0 = null;
- ByteBuffer b1 = null;
- ByteBuffer b22 = null;
+ ByteBuffer b0 = null;
+ ByteBuffer b1 = null;
+ ByteBuffer b22 = null;
- // The stream at 0 has 23 blocks in it
- POIFSStream stream = new POIFSStream(fs, 0);
- Iterator i = stream.getBlockIterator();
- int count = 0;
- while (i.hasNext()) {
- ByteBuffer b = i.next();
- if (count == 0) {
- b0 = b;
- }
- if (count == 1) {
- b1 = b;
- }
- if (count == 22) {
- b22 = b;
- }
+ // The stream at 0 has 23 blocks in it
+ POIFSStream stream = new POIFSStream(fs, 0);
+ Iterator i = stream.getBlockIterator();
+ int count = 0;
+ while (i.hasNext()) {
+ ByteBuffer b = i.next();
+ if (count == 0) {
+ b0 = b;
+ }
+ if (count == 1) {
+ b1 = b;
+ }
+ if (count == 22) {
+ b22 = b;
+ }
- count++;
+ count++;
+ }
+ assertEquals(23, count);
+
+ // Check the contents
+ // 1st block is at 0
+ assertNotNull(b0);
+ assertEquals((byte) 0x9e, b0.get());
+ assertEquals((byte) 0x75, b0.get());
+ assertEquals((byte) 0x97, b0.get());
+ assertEquals((byte) 0xf6, b0.get());
+
+ // 2nd block is at 1
+ assertNotNull(b1);
+ assertEquals((byte) 0x86, b1.get());
+ assertEquals((byte) 0x09, b1.get());
+ assertEquals((byte) 0x22, b1.get());
+ assertEquals((byte) 0xfb, b1.get());
+
+ // last block is at 89
+ assertNotNull(b22);
+ assertEquals((byte) 0xfe, b22.get());
+ assertEquals((byte) 0xff, b22.get());
+ assertEquals((byte) 0x00, b22.get());
+ assertEquals((byte) 0x00, b22.get());
+ assertEquals((byte) 0x05, b22.get());
+ assertEquals((byte) 0x01, b22.get());
+ assertEquals((byte) 0x02, b22.get());
+ assertEquals((byte) 0x00, b22.get());
}
- assertEquals(23, count);
-
- // Check the contents
- // 1st block is at 0
- assertNotNull(b0);
- assertEquals((byte) 0x9e, b0.get());
- assertEquals((byte) 0x75, b0.get());
- assertEquals((byte) 0x97, b0.get());
- assertEquals((byte) 0xf6, b0.get());
-
- // 2nd block is at 1
- assertNotNull(b1);
- assertEquals((byte) 0x86, b1.get());
- assertEquals((byte) 0x09, b1.get());
- assertEquals((byte) 0x22, b1.get());
- assertEquals((byte) 0xfb, b1.get());
-
- // last block is at 89
- assertNotNull(b22);
- assertEquals((byte) 0xfe, b22.get());
- assertEquals((byte) 0xff, b22.get());
- assertEquals((byte) 0x00, b22.get());
- assertEquals((byte) 0x00, b22.get());
- assertEquals((byte) 0x05, b22.get());
- assertEquals((byte) 0x01, b22.get());
- assertEquals((byte) 0x02, b22.get());
- assertEquals((byte) 0x00, b22.get());
-
- fs.close();
}
/**
@@ -193,50 +201,48 @@ final class TestPOIFSStream {
*/
@Test
void testReadStream4096() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
-
- // 0 -> 1 -> 2 -> end
- POIFSStream stream = new POIFSStream(fs, 0);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b0 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b1 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b2 = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents of the 1st block
- assertEquals((byte) 0x9E, b0.get());
- assertEquals((byte) 0x75, b0.get());
- assertEquals((byte) 0x97, b0.get());
- assertEquals((byte) 0xF6, b0.get());
- assertEquals((byte) 0xFF, b0.get());
- assertEquals((byte) 0x21, b0.get());
- assertEquals((byte) 0xD2, b0.get());
- assertEquals((byte) 0x11, b0.get());
-
- // Check the contents of the 2nd block
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x03, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
- assertEquals((byte) 0x00, b1.get());
-
- // Check the contents of the 3rd block
- assertEquals((byte) 0x6D, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x03, b2.get());
- assertEquals((byte) 0x00, b2.get());
- assertEquals((byte) 0x46, b2.get());
- assertEquals((byte) 0x00, b2.get());
-
- fs.close();
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"))) {
+ // 0 -> 1 -> 2 -> end
+ POIFSStream stream = new POIFSStream(fs, 0);
+ Iterator i = stream.getBlockIterator();
+ assertTrue(i.hasNext());
+ ByteBuffer b0 = i.next();
+ assertTrue(i.hasNext());
+ ByteBuffer b1 = i.next();
+ assertTrue(i.hasNext());
+ ByteBuffer b2 = i.next();
+ assertFalse(i.hasNext());
+
+ // Check the contents of the 1st block
+ assertEquals((byte) 0x9E, b0.get());
+ assertEquals((byte) 0x75, b0.get());
+ assertEquals((byte) 0x97, b0.get());
+ assertEquals((byte) 0xF6, b0.get());
+ assertEquals((byte) 0xFF, b0.get());
+ assertEquals((byte) 0x21, b0.get());
+ assertEquals((byte) 0xD2, b0.get());
+ assertEquals((byte) 0x11, b0.get());
+
+ // Check the contents of the 2nd block
+ assertEquals((byte) 0x00, b1.get());
+ assertEquals((byte) 0x00, b1.get());
+ assertEquals((byte) 0x03, b1.get());
+ assertEquals((byte) 0x00, b1.get());
+ assertEquals((byte) 0x00, b1.get());
+ assertEquals((byte) 0x00, b1.get());
+ assertEquals((byte) 0x00, b1.get());
+ assertEquals((byte) 0x00, b1.get());
+
+ // Check the contents of the 3rd block
+ assertEquals((byte) 0x6D, b2.get());
+ assertEquals((byte) 0x00, b2.get());
+ assertEquals((byte) 0x00, b2.get());
+ assertEquals((byte) 0x00, b2.get());
+ assertEquals((byte) 0x03, b2.get());
+ assertEquals((byte) 0x00, b2.get());
+ assertEquals((byte) 0x46, b2.get());
+ assertEquals((byte) 0x00, b2.get());
+ }
}
/**
@@ -244,35 +250,33 @@ final class TestPOIFSStream {
*/
@Test
void testReadFailsOnLoop() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // Hack the FAT so that it goes 0->1->2->0
- fs.setNextBlock(0, 1);
- fs.setNextBlock(1, 2);
- fs.setNextBlock(2, 0);
-
- // Now try to read
- POIFSStream stream = new POIFSStream(fs, 0);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {
+ // Hack the FAT so that it goes 0->1->2->0
+ fs.setNextBlock(0, 1);
+ fs.setNextBlock(1, 2);
+ fs.setNextBlock(2, 0);
- // 1st read works
- i.next();
- assertTrue(i.hasNext());
+ // Now try to read
+ POIFSStream stream = new POIFSStream(fs, 0);
+ Iterator i = stream.getBlockIterator();
+ assertTrue(i.hasNext());
- // 2nd read works
- i.next();
- assertTrue(i.hasNext());
+ // 1st read works
+ i.next();
+ assertTrue(i.hasNext());
- // 3rd read works
- i.next();
- assertTrue(i.hasNext());
+ // 2nd read works
+ i.next();
+ assertTrue(i.hasNext());
- // 4th read blows up as it loops back to 0
- assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!");
- assertTrue(i.hasNext());
+ // 3rd read works
+ i.next();
+ assertTrue(i.hasNext());
- fs.close();
+ // 4th read blows up as it loops back to 0
+ assertThrows(RuntimeException.class, i::next, "Loop should have been detected but wasn't!");
+ assertTrue(i.hasNext());
+ }
}
/**
@@ -281,51 +285,50 @@ final class TestPOIFSStream {
*/
@Test
void testReadMiniStreams() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSMiniStore ministore = fs.getMiniStore();
-
- // 178 -> 179 -> 180 -> end
- POIFSStream stream = new POIFSStream(ministore, 178);
- Iterator i = stream.getBlockIterator();
- assertTrue(i.hasNext());
- ByteBuffer b178 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b179 = i.next();
- assertTrue(i.hasNext());
- ByteBuffer b180 = i.next();
- assertFalse(i.hasNext());
-
- // Check the contents of the 1st block
- assertEquals((byte) 0xfe, b178.get());
- assertEquals((byte) 0xff, b178.get());
- assertEquals((byte) 0x00, b178.get());
- assertEquals((byte) 0x00, b178.get());
- assertEquals((byte) 0x05, b178.get());
- assertEquals((byte) 0x01, b178.get());
- assertEquals((byte) 0x02, b178.get());
- assertEquals((byte) 0x00, b178.get());
-
- // And the 2nd
- assertEquals((byte) 0x6c, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x28, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
- assertEquals((byte) 0x00, b179.get());
-
- // And the 3rd
- assertEquals((byte) 0x30, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x00, b180.get());
- assertEquals((byte) 0x80, b180.get());
-
- fs.close();
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) {
+ POIFSMiniStore ministore = fs.getMiniStore();
+
+ // 178 -> 179 -> 180 -> end
+ POIFSStream stream = new POIFSStream(ministore, 178);
+ Iterator i = stream.getBlockIterator();
+ assertTrue(i.hasNext());
+ ByteBuffer b178 = i.next();
+ assertTrue(i.hasNext());
+ ByteBuffer b179 = i.next();
+ assertTrue(i.hasNext());
+ ByteBuffer b180 = i.next();
+ assertFalse(i.hasNext());
+
+ // Check the contents of the 1st block
+ assertEquals((byte) 0xfe, b178.get());
+ assertEquals((byte) 0xff, b178.get());
+ assertEquals((byte) 0x00, b178.get());
+ assertEquals((byte) 0x00, b178.get());
+ assertEquals((byte) 0x05, b178.get());
+ assertEquals((byte) 0x01, b178.get());
+ assertEquals((byte) 0x02, b178.get());
+ assertEquals((byte) 0x00, b178.get());
+
+ // And the 2nd
+ assertEquals((byte) 0x6c, b179.get());
+ assertEquals((byte) 0x00, b179.get());
+ assertEquals((byte) 0x00, b179.get());
+ assertEquals((byte) 0x00, b179.get());
+ assertEquals((byte) 0x28, b179.get());
+ assertEquals((byte) 0x00, b179.get());
+ assertEquals((byte) 0x00, b179.get());
+ assertEquals((byte) 0x00, b179.get());
+
+ // And the 3rd
+ assertEquals((byte) 0x30, b180.get());
+ assertEquals((byte) 0x00, b180.get());
+ assertEquals((byte) 0x00, b180.get());
+ assertEquals((byte) 0x00, b180.get());
+ assertEquals((byte) 0x00, b180.get());
+ assertEquals((byte) 0x00, b180.get());
+ assertEquals((byte) 0x00, b180.get());
+ assertEquals((byte) 0x80, b180.get());
+ }
}
/**
@@ -333,32 +336,31 @@ final class TestPOIFSStream {
*/
@Test
void testReplaceStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) {
- byte[] data = new byte[512];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
+ byte[] data = new byte[512];
+ for (int i = 0; i < data.length; i++) {
+ data[i] = (byte) (i % 256);
+ }
- // 98 is actually the last block in a two block stream...
- POIFSStream stream = new POIFSStream(fs, 98);
- stream.updateContents(data);
-
- // Check the reading of blocks
- Iterator it = stream.getBlockIterator();
- assertTrue(it.hasNext());
- ByteBuffer b = it.next();
- assertFalse(it.hasNext());
-
- // Now check the contents
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
- }
+ // 98 is actually the last block in a two block stream...
+ POIFSStream stream = new POIFSStream(fs, 98);
+ stream.updateContents(data);
- fs.close();
+ // Check the reading of blocks
+ Iterator it = stream.getBlockIterator();
+ assertTrue(it.hasNext());
+ ByteBuffer b = it.next();
+ assertFalse(it.hasNext());
+
+ // Now check the contents
+ data = new byte[512];
+ b.get(data);
+ for (int i = 0; i < data.length; i++) {
+ byte exp = (byte) (i % 256);
+ assertEquals(exp, data[i]);
+ }
+ }
}
/**
@@ -455,92 +457,91 @@ final class TestPOIFSStream {
*/
@Test
void testWriteNewStream() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) {
- // 100 is our first free one
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
+ // 100 is our first free one
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
- // Add a single block one
- byte[] data = new byte[512];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
+ // Add a single block one
+ byte[] data = new byte[512];
+ for (int i = 0; i < data.length; i++) {
+ data[i] = (byte) (i % 256);
+ }
- POIFSStream stream = new POIFSStream(fs);
- stream.updateContents(data);
+ POIFSStream stream = new POIFSStream(fs);
+ stream.updateContents(data);
- // Check it was allocated properly
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
+ // Check it was allocated properly
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
- // And check the contents
- Iterator it = stream.getBlockIterator();
- int count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
+ // And check the contents
+ Iterator it = stream.getBlockIterator();
+ int count = 0;
+ while (it.hasNext()) {
+ ByteBuffer b = it.next();
+ data = new byte[512];
+ b.get(data);
+ for (int i = 0; i < data.length; i++) {
+ byte exp = (byte) (i % 256);
+ assertEquals(exp, data[i]);
+ }
+ count++;
+ }
+ assertEquals(1, count);
+
+
+ // And a multi block one
+ data = new byte[512 * 3];
for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
+ data[i] = (byte) (i % 256);
}
- count++;
- }
- assertEquals(1, count);
+ stream = new POIFSStream(fs);
+ stream.updateContents(data);
- // And a multi block one
- data = new byte[512 * 3];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
+ // Check it was allocated properly
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
+ assertEquals(102, fs.getNextBlock(101));
+ assertEquals(103, fs.getNextBlock(102));
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
- stream = new POIFSStream(fs);
- stream.updateContents(data);
-
- // Check it was allocated properly
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
- assertEquals(102, fs.getNextBlock(101));
- assertEquals(103, fs.getNextBlock(102));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
-
- // And check the contents
- it = stream.getBlockIterator();
- count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
- for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
+ // And check the contents
+ it = stream.getBlockIterator();
+ count = 0;
+ while (it.hasNext()) {
+ ByteBuffer b = it.next();
+ data = new byte[512];
+ b.get(data);
+ for (int i = 0; i < data.length; i++) {
+ byte exp = (byte) (i % 256);
+ assertEquals(exp, data[i]);
+ }
+ count++;
}
- count++;
+ assertEquals(3, count);
+
+ // Free it
+ stream.free();
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
}
- assertEquals(3, count);
-
- // Free it
- stream.free();
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(104));
-
- fs.close();
}
/**
@@ -550,40 +551,39 @@ final class TestPOIFSStream {
*/
@Test
void testWriteNewStreamExtraFATs() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
-
- // Allocate almost all the blocks
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
- for (int i = 100; i < 127; i++) {
- fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
- }
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
- assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) {
+ // Allocate almost all the blocks
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
+ for (int i = 100; i < 127; i++) {
+ fs.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
+ }
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(127));
+ assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- // Write a 3 block stream
- byte[] data = new byte[512 * 3];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
+
+ // Write a 3 block stream
+ byte[] data = new byte[512 * 3];
+ for (int i = 0; i < data.length; i++) {
+ data[i] = (byte) (i % 256);
+ }
+ POIFSStream stream = new POIFSStream(fs);
+ stream.updateContents(data);
+
+ // Check we got another BAT
+ assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
+ assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
+
+ // the BAT will be in the first spot of the new block
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126));
+ assertEquals(129, fs.getNextBlock(127));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128));
+ assertEquals(130, fs.getNextBlock(129));
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131));
}
- POIFSStream stream = new POIFSStream(fs);
- stream.updateContents(data);
-
- // Check we got another BAT
- assertFalse(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertTrue(fs.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
-
- // the BAT will be in the first spot of the new block
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(126));
- assertEquals(129, fs.getNextBlock(127));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(128));
- assertEquals(130, fs.getNextBlock(129));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(130));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(131));
-
- fs.close();
}
/**
@@ -592,54 +592,53 @@ final class TestPOIFSStream {
*/
@Test
void testWriteStream4096() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"))) {
- // 0 -> 1 -> 2 -> end
- assertEquals(1, fs.getNextBlock(0));
- assertEquals(2, fs.getNextBlock(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
- assertEquals(4, fs.getNextBlock(3));
+ // 0 -> 1 -> 2 -> end
+ assertEquals(1, fs.getNextBlock(0));
+ assertEquals(2, fs.getNextBlock(1));
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2));
+ assertEquals(4, fs.getNextBlock(3));
- // First free one is at 15
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15));
+ // First free one is at 15
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15));
- // Write a 5 block file
- byte[] data = new byte[4096 * 5];
- for (int i = 0; i < data.length; i++) {
- data[i] = (byte) (i % 256);
- }
- POIFSStream stream = new POIFSStream(fs, 0);
- stream.updateContents(data);
-
-
- // Check it
- assertEquals(1, fs.getNextBlock(0));
- assertEquals(2, fs.getNextBlock(1));
- assertEquals(15, fs.getNextBlock(2)); // Jumps
- assertEquals(4, fs.getNextBlock(3)); // Next stream
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
- assertEquals(16, fs.getNextBlock(15)); // Continues
- assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free
-
- // Check the contents too
- Iterator it = stream.getBlockIterator();
- int count = 0;
- while (it.hasNext()) {
- ByteBuffer b = it.next();
- data = new byte[512];
- b.get(data);
+ // Write a 5 block file
+ byte[] data = new byte[4096 * 5];
for (int i = 0; i < data.length; i++) {
- byte exp = (byte) (i % 256);
- assertEquals(exp, data[i]);
+ data[i] = (byte) (i % 256);
}
- count++;
- }
- assertEquals(5, count);
+ POIFSStream stream = new POIFSStream(fs, 0);
+ stream.updateContents(data);
+
- fs.close();
+ // Check it
+ assertEquals(1, fs.getNextBlock(0));
+ assertEquals(2, fs.getNextBlock(1));
+ assertEquals(15, fs.getNextBlock(2)); // Jumps
+ assertEquals(4, fs.getNextBlock(3)); // Next stream
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14));
+ assertEquals(16, fs.getNextBlock(15)); // Continues
+ assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(16)); // Ends
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(17)); // Free
+
+ // Check the contents too
+ Iterator it = stream.getBlockIterator();
+ int count = 0;
+ while (it.hasNext()) {
+ ByteBuffer b = it.next();
+ data = new byte[512];
+ b.get(data);
+ for (int i = 0; i < data.length; i++) {
+ byte exp = (byte) (i % 256);
+ assertEquals(exp, data[i]);
+ }
+ count++;
+ }
+ assertEquals(5, count);
+ }
}
/**
@@ -933,191 +932,192 @@ final class TestPOIFSStream {
*/
@Test
void testWriteThenReplace() throws Exception {
- POIFSFileSystem fs = new POIFSFileSystem();
-
- // Starts empty, other that Properties and BAT
- BATBlock bat = fs.getBATBlockAndIndex(0).getBlock();
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2));
-
- // Write something that uses a main stream
- byte[] main4106 = new byte[4106];
- main4106[0] = -10;
- main4106[4105] = -11;
- fs.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106));
-
- // Should have used 9 blocks
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
-
- DocumentEntry normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4106, normal.getSize());
- assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Replace with one still big enough for a main stream, but one block smaller
- byte[] main4096 = new byte[4096];
- main4096[0] = -10;
- main4096[4095] = -11;
-
- DocumentOutputStream nout = new DocumentOutputStream(normal);
- nout.write(main4096);
- nout.close();
-
- // Will have dropped to 8
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Write and check
- fs = writeOutAndReadBack(fs);
- bat = fs.getBATBlockAndIndex(0).getBlock();
-
- // No change after write
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Make longer, take 1 block at the end
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- nout = new DocumentOutputStream(normal);
- nout.write(main4106);
- nout.close();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(3, bat.getValueAt(2));
- assertEquals(4, bat.getValueAt(3));
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4106, normal.getSize());
- assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Make it small, will trigger the SBAT stream and free lots up
- byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- nout = new DocumentOutputStream(normal);
- nout.write(mini);
- nout.close();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(7, normal.getSize());
- assertEquals(7, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Finally back to big again
- nout = new DocumentOutputStream(normal);
- nout.write(main4096);
- nout.close();
-
- // Will keep the mini stream, now empty
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(11, bat.getValueAt(10));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
-
- // Save, re-load, re-check
- fs = writeOutAndReadBack(fs);
- bat = fs.getBATBlockAndIndex(0).getBlock();
-
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
- assertEquals(5, bat.getValueAt(4));
- assertEquals(6, bat.getValueAt(5));
- assertEquals(7, bat.getValueAt(6));
- assertEquals(8, bat.getValueAt(7));
- assertEquals(9, bat.getValueAt(8));
- assertEquals(10, bat.getValueAt(9));
- assertEquals(11, bat.getValueAt(10));
- assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
- assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));
-
- normal = (DocumentEntry) fs.getRoot().getEntry("Normal");
- assertEquals(4096, normal.getSize());
- assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
-
- fs.close();
+ try (POIFSFileSystem fs1 = new POIFSFileSystem()) {
+
+ // Starts empty, other that Properties and BAT
+ BATBlock bat = fs1.getBATBlockAndIndex(0).getBlock();
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2));
+
+ // Write something that uses a main stream
+ byte[] main4106 = new byte[4106];
+ main4106[0] = -10;
+ main4106[4105] = -11;
+ fs1.getRoot().createDocument("Normal", new ByteArrayInputStream(main4106));
+
+ // Should have used 9 blocks
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(3, bat.getValueAt(2));
+ assertEquals(4, bat.getValueAt(3));
+ assertEquals(5, bat.getValueAt(4));
+ assertEquals(6, bat.getValueAt(5));
+ assertEquals(7, bat.getValueAt(6));
+ assertEquals(8, bat.getValueAt(7));
+ assertEquals(9, bat.getValueAt(8));
+ assertEquals(10, bat.getValueAt(9));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
+
+ DocumentEntry normal = (DocumentEntry) fs1.getRoot().getEntry("Normal");
+ assertEquals(4106, normal.getSize());
+ assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());
+
+
+ // Replace with one still big enough for a main stream, but one block smaller
+ byte[] main4096 = new byte[4096];
+ main4096[0] = -10;
+ main4096[4095] = -11;
+
+ try (DocumentOutputStream nout = new DocumentOutputStream(normal)) {
+ nout.write(main4096);
+ }
+
+ // Will have dropped to 8
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(3, bat.getValueAt(2));
+ assertEquals(4, bat.getValueAt(3));
+ assertEquals(5, bat.getValueAt(4));
+ assertEquals(6, bat.getValueAt(5));
+ assertEquals(7, bat.getValueAt(6));
+ assertEquals(8, bat.getValueAt(7));
+ assertEquals(9, bat.getValueAt(8));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
+
+ normal = (DocumentEntry) fs1.getRoot().getEntry("Normal");
+ assertEquals(4096, normal.getSize());
+ assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
+
+
+ // Write and check
+ try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) {
+ bat = fs2.getBATBlockAndIndex(0).getBlock();
+
+ // No change after write
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); // Properties
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(3, bat.getValueAt(2));
+ assertEquals(4, bat.getValueAt(3));
+ assertEquals(5, bat.getValueAt(4));
+ assertEquals(6, bat.getValueAt(5));
+ assertEquals(7, bat.getValueAt(6));
+ assertEquals(8, bat.getValueAt(7));
+ assertEquals(9, bat.getValueAt(8));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(9)); // End of Normal
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
+
+ normal = (DocumentEntry) fs2.getRoot().getEntry("Normal");
+ assertEquals(4096, normal.getSize());
+ assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
+
+
+ // Make longer, take 1 block at the end
+ normal = (DocumentEntry) fs2.getRoot().getEntry("Normal");
+ try (DocumentOutputStream nout = new DocumentOutputStream(normal)) {
+ nout.write(main4106);
+ }
+
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(3, bat.getValueAt(2));
+ assertEquals(4, bat.getValueAt(3));
+ assertEquals(5, bat.getValueAt(4));
+ assertEquals(6, bat.getValueAt(5));
+ assertEquals(7, bat.getValueAt(6));
+ assertEquals(8, bat.getValueAt(7));
+ assertEquals(9, bat.getValueAt(8));
+ assertEquals(10, bat.getValueAt(9));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(10)); // Normal
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
+
+ normal = (DocumentEntry) fs2.getRoot().getEntry("Normal");
+ assertEquals(4106, normal.getSize());
+ assertEquals(4106, ((DocumentNode) normal).getProperty().getSize());
+
+
+ // Make it small, will trigger the SBAT stream and free lots up
+ byte[] mini = new byte[]{42, 0, 1, 2, 3, 4, 42};
+ normal = (DocumentEntry) fs2.getRoot().getEntry("Normal");
+ try (DocumentOutputStream nout = new DocumentOutputStream(normal)) {
+ nout.write(mini);
+ }
+
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(4));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(5));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(6));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(7));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(8));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(9));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(10));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(11));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
+
+ normal = (DocumentEntry) fs2.getRoot().getEntry("Normal");
+ assertEquals(7, normal.getSize());
+ assertEquals(7, ((DocumentNode) normal).getProperty().getSize());
+
+
+ // Finally back to big again
+ try (DocumentOutputStream nout = new DocumentOutputStream(normal)) {
+ nout.write(main4096);
+ }
+
+ // Will keep the mini stream, now empty
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
+ assertEquals(5, bat.getValueAt(4));
+ assertEquals(6, bat.getValueAt(5));
+ assertEquals(7, bat.getValueAt(6));
+ assertEquals(8, bat.getValueAt(7));
+ assertEquals(9, bat.getValueAt(8));
+ assertEquals(10, bat.getValueAt(9));
+ assertEquals(11, bat.getValueAt(10));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));
+
+ normal = (DocumentEntry) fs2.getRoot().getEntry("Normal");
+ assertEquals(4096, normal.getSize());
+ assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
+
+
+ // Save, re-load, re-check
+ try (POIFSFileSystem fs3 = writeOutAndReadBack(fs2)) {
+ bat = fs3.getBATBlockAndIndex(0).getBlock();
+
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0));
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, bat.getValueAt(1));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(2)); // SBAT
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(3)); // Mini Stream
+ assertEquals(5, bat.getValueAt(4));
+ assertEquals(6, bat.getValueAt(5));
+ assertEquals(7, bat.getValueAt(6));
+ assertEquals(8, bat.getValueAt(7));
+ assertEquals(9, bat.getValueAt(8));
+ assertEquals(10, bat.getValueAt(9));
+ assertEquals(11, bat.getValueAt(10));
+ assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(11));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(12));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(13));
+
+ normal = (DocumentEntry) fs3.getRoot().getEntry("Normal");
+ assertEquals(4096, normal.getSize());
+ assertEquals(4096, ((DocumentNode) normal).getProperty().getSize());
+ }
+ }
+ }
}
@@ -1125,14 +1125,43 @@ final class TestPOIFSStream {
* Returns test files with 512 byte and 4k block sizes, loaded
* both from InputStreams and Files
*/
- private POIFSFileSystem[] get512and4kFileAndInput() throws IOException {
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- POIFSFileSystem fsC = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- POIFSFileSystem fsD = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- return new POIFSFileSystem[]{fsA, fsB, fsC, fsD};
+ public static Collection get512and4kFileAndInput() {
+ return CollectionUtils.union(get512FileAndInput(), get4kFileAndInput());
+ }
+
+ public static List get512FileAndInput() {
+ return Arrays.asList(
+ Arguments.of("BlockSize512.zvi", (Function)TestPOIFSStream::openAsFile),
+ Arguments.of("BlockSize512.zvi", (Function)TestPOIFSStream::openAsStream)
+ );
}
+ public static List get4kFileAndInput() {
+ return Arrays.asList(
+ Arguments.of("BlockSize4096.zvi", (Function)TestPOIFSStream::openAsFile),
+ Arguments.of("BlockSize4096.zvi", (Function)TestPOIFSStream::openAsStream)
+ );
+ }
+
+ private static POIFSFileSystem openAsFile(String fileName) {
+ try {
+ return new POIFSFileSystem(_inst.getFile(fileName));
+ } catch (IOException e) {
+ fail(e);
+ return null;
+ }
+ }
+
+ private static POIFSFileSystem openAsStream(String fileName) {
+ try {
+ return new POIFSFileSystem(_inst.openResourceAsStream(fileName));
+ } catch (IOException e) {
+ fail(e);
+ return null;
+ }
+ }
+
+
private static void assertBATCount(POIFSFileSystem fs, int expectedBAT, int expectedXBAT) throws IOException {
int foundBAT = 0;
int foundXBAT = 0;
@@ -1161,16 +1190,9 @@ final class TestPOIFSStream {
}
private static HeaderBlock writeOutAndReadHeader(POIFSFileSystem fs) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
fs.writeFilesystem(baos);
-
- return new HeaderBlock(new ByteArrayInputStream(baos.toByteArray()));
- }
-
- private static POIFSFileSystem writeOutAndReadBack(POIFSFileSystem original) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- original.writeFilesystem(baos);
- return new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray()));
+ return new HeaderBlock(baos.toInputStream());
}
private static POIFSFileSystem writeOutFileAndReadBack(POIFSFileSystem original) throws IOException {
@@ -1181,37 +1203,29 @@ final class TestPOIFSStream {
return new POIFSFileSystem(file, false);
}
- @Test
- void basicOpen() throws IOException {
- POIFSFileSystem fsA, fsB;
-
+ @ParameterizedTest()
+ @MethodSource("get512FileAndInput")
+ void basicOpen512(String file, Function opener) throws IOException {
// With a simple 512 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
+ try (POIFSFileSystem fs = opener.apply(file)) {
assertEquals(512, fs.getBigBlockSize());
}
- fsA.close();
- fsB.close();
+ }
+ @ParameterizedTest()
+ @MethodSource("get4kFileAndInput")
+ void basicOpen4k(String file, Function opener) throws IOException {
// Now with a simple 4096 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
+ try (POIFSFileSystem fs = opener.apply(file)) {
assertEquals(4096, fs.getBigBlockSize());
}
- fsA.close();
- fsB.close();
}
- @Test
- void propertiesAndFatOnRead() throws IOException {
- POIFSFileSystem fsA, fsB;
-
+ @ParameterizedTest()
+ @MethodSource("get512FileAndInput")
+ void propertiesAndFatOnRead512(String file, Function opener) throws IOException {
// With a simple 512 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
+ try (POIFSFileSystem fs = opener.apply(file)) {
// Check the FAT was properly processed:
// Verify we only got one block
fs.getBATBlockAndIndex(0);
@@ -1266,14 +1280,14 @@ final class TestPOIFSStream {
assertEquals(i + 1, ministore.getNextBlock(i));
}
assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
-
- fs.close();
}
+ }
+ @ParameterizedTest()
+ @MethodSource("get4kFileAndInput")
+ void propertiesAndFatOnRead4k(String file, Function opener) throws IOException {
// Now with a simple 4096 block file
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
+ try (POIFSFileSystem fs = opener.apply(file)) {
// Check the FAT was properly processed
// Verify we only got one block
fs.getBATBlockAndIndex(0);
@@ -1330,8 +1344,6 @@ final class TestPOIFSStream {
assertEquals(i + 1, ministore.getNextBlock(i));
}
assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50));
-
- fs.close();
}
}
@@ -1339,11 +1351,10 @@ final class TestPOIFSStream {
* Check that for a given block, we can correctly figure
* out what the next one is
*/
- @Test
- void nextBlock() throws IOException {
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
+ @ParameterizedTest()
+ @MethodSource("get512FileAndInput")
+ void nextBlock512(String file, Function opener) throws IOException {
+ try (POIFSFileSystem fs = opener.apply(file)) {
// 0 -> 21 are simple
for (int i = 0; i < 21; i++) {
assertEquals(i + 1, fs.getNextBlock(i));
@@ -1375,14 +1386,14 @@ final class TestPOIFSStream {
for (int i = 100; i < fs.getBigBlockSizeDetails().getBATEntriesPerBlock(); i++) {
assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(i));
}
-
- fs.close();
}
+ }
+ @ParameterizedTest()
+ @MethodSource("get4kFileAndInput")
+ void nextBlock4k(String file, Function opener) throws IOException {
// Quick check on 4096 byte blocks too
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
+ try (POIFSFileSystem fs = opener.apply(file)) {
// 0 -> 1 -> 2 -> end
assertEquals(1, fs.getNextBlock(0));
assertEquals(2, fs.getNextBlock(1));
@@ -1393,23 +1404,18 @@ final class TestPOIFSStream {
assertEquals(i + 1, fs.getNextBlock(i));
}
assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11));
-
- fs.close();
}
}
/**
* Check we get the right data back for each block
*/
- @Test
- void getBlock() throws IOException {
- POIFSFileSystem fsA = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
- POIFSFileSystem fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- ByteBuffer b;
-
+ @ParameterizedTest()
+ @MethodSource("get512FileAndInput")
+ void getBlock512(String file, Function opener) throws IOException {
+ try (POIFSFileSystem fs = opener.apply(file)) {
// The 0th block is the first data block
- b = fs.getBlockAt(0);
+ ByteBuffer b = fs.getBlockAt(0);
assertEquals((byte) 0x9e, b.get());
assertEquals((byte) 0x75, b.get());
assertEquals((byte) 0x97, b.get());
@@ -1432,18 +1438,16 @@ final class TestPOIFSStream {
assertEquals((byte) 0x00, b.get());
assertEquals((byte) 0x00, b.get());
assertEquals((byte) 0x00, b.get());
-
- fs.close();
}
+ }
+ @ParameterizedTest()
+ @MethodSource("get4kFileAndInput")
+ void getBlock4k(String file, Function opener) throws IOException {
// Quick check on 4096 byte blocks too
- fsA = new POIFSFileSystem(_inst.getFile("BlockSize4096.zvi"));
- fsB = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi"));
- for (POIFSFileSystem fs : new POIFSFileSystem[]{fsA, fsB}) {
- ByteBuffer b;
-
+ try (POIFSFileSystem fs = opener.apply(file)) {
// The 0th block is the first data block
- b = fs.getBlockAt(0);
+ ByteBuffer b = fs.getBlockAt(0);
assertEquals((byte) 0x9e, b.get());
assertEquals((byte) 0x75, b.get());
assertEquals((byte) 0x97, b.get());
@@ -1466,8 +1470,6 @@ final class TestPOIFSStream {
assertEquals((byte) 0x00, b.get());
assertEquals((byte) 0x00, b.get());
assertEquals((byte) 0x00, b.get());
-
- fs.close();
}
}
@@ -1477,29 +1479,26 @@ final class TestPOIFSStream {
*/
@Test
void getFreeBlockWithSpare() throws IOException {
- POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"));
-
- // Our first BAT block has spares
- assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
-
- // First free one is 100
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
+ try (POIFSFileSystem fs = new POIFSFileSystem(_inst.getFile("BlockSize512.zvi"))) {
+ // Our first BAT block has spares
+ assertTrue(fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- // Ask, will get 100
- assertEquals(100, fs.getFreeBlock());
+ // First free one is 100
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103));
- // Ask again, will still get 100 as not written to
- assertEquals(100, fs.getFreeBlock());
+ // Ask, will get 100
+ assertEquals(100, fs.getFreeBlock());
- // Allocate it, then ask again
- fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN);
- assertEquals(101, fs.getFreeBlock());
+ // Ask again, will still get 100 as not written to
+ assertEquals(100, fs.getFreeBlock());
- // All done
- fs.close();
+ // Allocate it, then ask again
+ fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN);
+ assertEquals(101, fs.getFreeBlock());
+ }
}
/**
@@ -1508,136 +1507,134 @@ final class TestPOIFSStream {
*/
@Test
void getFreeBlockWithNoneSpare() throws IOException {
- POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"));
- int free;
+ try (POIFSFileSystem fs1 = new POIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi"))) {
+ int free;
- // We have one BAT at block 99
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99));
- assertBATCount(fs1, 1, 0);
+ // We have one BAT at block 99
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99));
+ assertBATCount(fs1, 1, 0);
- // We've spare ones from 100 to 128
- for (int i = 100; i < 128; i++) {
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i));
- }
+ // We've spare ones from 100 to 128
+ for (int i = 100; i < 128; i++) {
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i));
+ }
- // Check our BAT knows it's free
- assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
+ // Check our BAT knows it's free
+ assertTrue(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- // Allocate all the spare ones
- for (int i = 100; i < 128; i++) {
- fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
- }
+ // Allocate all the spare ones
+ for (int i = 100; i < 128; i++) {
+ fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN);
+ }
- // BAT is now full, but there's only the one
- assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT");
- assertBATCount(fs1, 1, 0);
+ // BAT is now full, but there's only the one
+ assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
+ assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(128), "Should only be one BAT");
+ assertBATCount(fs1, 1, 0);
- // Now ask for a free one, will need to extend the file
- assertEquals(129, fs1.getFreeBlock());
+ // Now ask for a free one, will need to extend the file
+ assertEquals(129, fs1.getFreeBlock());
- assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
- assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
- assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128));
- assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129));
+ assertFalse(fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors());
+ assertTrue(fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors());
+ assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128));
+ assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129));
- // We now have 2 BATs, but no XBATs
- assertBATCount(fs1, 2, 0);
+ // We now have 2 BATs, but no XBATs
+ assertBATCount(fs1, 2, 0);
- // Fill up to hold 109 BAT blocks
- for (int i = 0; i < 109; i++) {
- fs1.getFreeBlock();
- int startOffset = i * 128;
- while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
- free = fs1.getFreeBlock();
- fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
+ // Fill up to hold 109 BAT blocks
+ for (int i = 0; i < 109; i++) {
+ fs1.getFreeBlock();
+ int startOffset = i * 128;
+ while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
+ free = fs1.getFreeBlock();
+ fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
+ }
}
- }
- assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs");
+ assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
+ assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(109 * 128), "Should only be 109 BATs");
- // We now have 109 BATs, but no XBATs
- assertBATCount(fs1, 109, 0);
+ // We now have 109 BATs, but no XBATs
+ assertBATCount(fs1, 109, 0);
- // Ask for it to be written out, and check the header
- HeaderBlock header = writeOutAndReadHeader(fs1);
- assertEquals(109, header.getBATCount());
- assertEquals(0, header.getXBATCount());
+ // Ask for it to be written out, and check the header
+ HeaderBlock header = writeOutAndReadHeader(fs1);
+ assertEquals(109, header.getBATCount());
+ assertEquals(0, header.getXBATCount());
- // Ask for another, will get our first XBAT
- free = fs1.getFreeBlock();
- assertTrue(free > 0, "Had: " + free);
+ // Ask for another, will get our first XBAT
+ free = fs1.getFreeBlock();
+ assertTrue(free > 0, "Had: " + free);
- assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
- assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs");
- assertBATCount(fs1, 110, 1);
+ assertFalse(fs1.getBATBlockAndIndex(109 * 128 - 1).getBlock().hasFreeSectors());
+ assertTrue(fs1.getBATBlockAndIndex(110 * 128 - 1).getBlock().hasFreeSectors());
+ assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(110 * 128), "Should only be 110 BATs");
+ assertBATCount(fs1, 110, 1);
- header = writeOutAndReadHeader(fs1);
- assertEquals(110, header.getBATCount());
- assertEquals(1, header.getXBATCount());
+ header = writeOutAndReadHeader(fs1);
+ assertEquals(110, header.getBATCount());
+ assertEquals(1, header.getXBATCount());
- // Fill the XBAT, which means filling 127 BATs
- for (int i = 109; i < 109 + 127; i++) {
- fs1.getFreeBlock();
- int startOffset = i * 128;
- while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
- free = fs1.getFreeBlock();
- fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
+ // Fill the XBAT, which means filling 127 BATs
+ for (int i = 109; i < 109 + 127; i++) {
+ fs1.getFreeBlock();
+ int startOffset = i * 128;
+ while (fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors()) {
+ free = fs1.getFreeBlock();
+ fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN);
+ }
+ assertBATCount(fs1, i + 1, 1);
}
- assertBATCount(fs1, i + 1, 1);
- }
-
- // Should now have 109+127 = 236 BATs
- assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs");
- assertBATCount(fs1, 236, 1);
-
- // Ask for another, will get our 2nd XBAT
- free = fs1.getFreeBlock();
- assertTrue(free > 0, "Had: " + free);
+ // Should now have 109+127 = 236 BATs
+ assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
+ assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(236 * 128), "Should only be 236 BATs");
+ assertBATCount(fs1, 236, 1);
- assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
- assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");
+ // Ask for another, will get our 2nd XBAT
+ free = fs1.getFreeBlock();
+ assertTrue(free > 0, "Had: " + free);
- // Check the counts now
- assertBATCount(fs1, 237, 2);
+ assertFalse(fs1.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
+ assertTrue(fs1.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
+ assertThrows(IndexOutOfBoundsException.class, () -> fs1.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");
- // Check the header
- header = writeOutAndReadHeader(fs1);
- assertNotNull(header);
+ // Check the counts now
+ assertBATCount(fs1, 237, 2);
- // Now, write it out, and read it back in again fully
- POIFSFileSystem fs2 = writeOutAndReadBack(fs1);
- fs1.close();
+ // Check the header
+ header = writeOutAndReadHeader(fs1);
+ assertNotNull(header);
- // Check that it is seen correctly
- assertBATCount(fs2, 237, 2);
+ // Now, write it out, and read it back in again fully
+ try (POIFSFileSystem fs2 = writeOutAndReadBack(fs1)) {
- assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
- assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
- assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");
+ // Check that it is seen correctly
+ assertBATCount(fs2, 237, 2);
- // All done
- fs2.close();
+ assertFalse(fs2.getBATBlockAndIndex(236 * 128 - 1).getBlock().hasFreeSectors());
+ assertTrue(fs2.getBATBlockAndIndex(237 * 128 - 1).getBlock().hasFreeSectors());
+ assertThrows(IndexOutOfBoundsException.class, () -> fs2.getBATBlockAndIndex(237 * 128), "Should only be 237 BATs");
+ }
+ }
}
/**
* Test that we can correctly get the list of directory
* entries, and the details on the files in them
*/
- @Test
- void listEntries() throws IOException {
- for (POIFSFileSystem fs : get512and4kFileAndInput()) {
+ @ParameterizedTest
+ @MethodSource("get512and4kFileAndInput")
+ void listEntries(String file, Function opener) throws IOException {
+ try (POIFSFileSystem fs = opener.apply(file)) {
DirectoryEntry root = fs.getRoot();
assertEquals(5, root.getEntryCount());
@@ -1665,8 +1662,6 @@ final class TestPOIFSStream {
// Look inside another
DirectoryEntry imageD = (DirectoryEntry) image;
assertEquals(7, imageD.getEntryCount());
-
- fs.close();
}
}
@@ -1674,9 +1669,11 @@ final class TestPOIFSStream {
* Tests that we can get the correct contents for
* a document in the filesystem
*/
- @Test
- void getDocumentEntry() throws Exception {
- for (POIFSFileSystem fs : get512and4kFileAndInput()) {
+ @ParameterizedTest
+ @MethodSource("get512and4kFileAndInput")
+ void getDocumentEntry(String file, Function