diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2021-05-14 00:37:50 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2021-05-14 00:37:50 +0000 |
commit | 0614835c55f44ab6f3e9b0850ca51e0e53a65a49 (patch) | |
tree | 586c68c89edb0978a441facf0066ff56d84fa2c7 /poi-scratchpad | |
parent | fe753d473788fc24030d7066654c56c33fff23b5 (diff) | |
download | poi-0614835c55f44ab6f3e9b0850ca51e0e53a65a49.tar.gz poi-0614835c55f44ab6f3e9b0850ca51e0e53a65a49.zip |
#65304 - Add commons-io as a dependency
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1889871 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'poi-scratchpad')
103 files changed, 2024 insertions, 2563 deletions
diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java b/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java index 9879eee028..5e70f033a2 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hdgf/HDGFLZW.java @@ -16,11 +16,11 @@ ==================================================================== */ package org.apache.poi.hdgf; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LZWDecompresser; /** @@ -53,7 +53,7 @@ public class HDGFLZW extends LZWDecompresser { * @throws IOException when the InputStream can't be read */ public byte[] compress(InputStream src) throws IOException { - ByteArrayOutputStream res = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream res = new UnsynchronizedByteArrayOutputStream(); compress(src,res); return res.toByteArray(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java index 803fb98855..f1b668e3f0 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emf/HemfFill.java @@ -26,8 +26,6 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -36,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hemf.draw.HemfDrawProperties; import org.apache.poi.hemf.draw.HemfGraphics; import org.apache.poi.hwmf.draw.HwmfGraphics; @@ -793,14 +792,14 @@ public final class HemfFill { return (long)undefinedSpace1 + bitmap.init(leis, dibSize); } - final ByteArrayOutputStream bos = new ByteArrayOutputStream(cbBmi+cbBits); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(cbBmi+cbBits); final long cbBmiSrcAct = IOUtils.copy(leis, bos, cbBmi); assert (cbBmiSrcAct == cbBmi); leis.skipFully(undefinedSpace2); final long cbBitsSrcAct = IOUtils.copy(leis, bos, cbBits); assert (cbBitsSrcAct == cbBits); - final LittleEndianInputStream leisDib = new LittleEndianInputStream(new ByteArrayInputStream(bos.toByteArray())); + final LittleEndianInputStream leisDib = new LittleEndianInputStream(bos.toInputStream()); final int dibSizeAct = bitmap.init(leisDib, dibSize); assert (dibSizeAct <= dibSize); return (long)undefinedSpace1 + cbBmi + undefinedSpace2 + cbBits; diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java index 71ade3fdb3..9739635c21 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusBrush.java @@ -27,7 +27,6 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.AbstractMap; import java.util.Arrays; @@ -41,6 +40,7 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.common.usermodel.GenericRecord; import org.apache.poi.hemf.draw.HemfDrawProperties; import org.apache.poi.hemf.draw.HemfGraphics; @@ -399,7 +399,7 @@ public class HemfPlusBrush { } public byte[] getRawData(List<? extends EmfPlusObjectData> continuedObjectData) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { bos.write(getBrushBytes()); if (continuedObjectData != null) { @@ -473,6 +473,7 @@ public class HemfPlusBrush { public static class EmfPlusHatchBrushData implements EmfPlusBrushData { private EmfPlusHatchStyle style; private Color foreColor, backColor; + @Override public long init(LittleEndianInputStream leis, long dataSize) { style = EmfPlusHatchStyle.valueOf(leis.readInt()); foreColor = readARGB(leis.readInt()); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java index 840b752f37..1ea137dc1a 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/record/emfplus/HemfPlusImage.java @@ -23,7 +23,6 @@ import java.awt.Color; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashMap; @@ -33,6 +32,7 @@ import java.util.function.Supplier; import javax.imageio.ImageIO; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hemf.draw.HemfDrawProperties; import org.apache.poi.hemf.draw.HemfGraphics; import org.apache.poi.hemf.record.emfplus.HemfPlusHeader.EmfPlusGraphicsVersion; @@ -445,7 +445,7 @@ public class HemfPlusImage { } public byte[] getRawData(List<? extends EmfPlusObjectData> continuedObjectData) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { bos.write(getImageData()); if (continuedObjectData != null) { @@ -607,6 +607,7 @@ public class HemfPlusImage { return size + 5*LittleEndianConsts.INT_SIZE; } + @Override public EmfPlusGraphicsVersion getGraphicsVersion() { return graphicsVersion; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java b/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java index 1b02478861..f94c05a598 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hemf/usermodel/HemfEmbeddedIterator.java @@ -18,7 +18,6 @@ package org.apache.poi.hemf.usermodel; import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; @@ -27,6 +26,7 @@ import java.util.NoSuchElementException; import javax.imageio.ImageIO; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hemf.record.emf.HemfComment; import org.apache.poi.hemf.record.emf.HemfComment.EmfComment; import org.apache.poi.hemf.record.emf.HemfComment.EmfCommentDataFormat; @@ -273,7 +273,7 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> { private void compressGDIBitmap(EmfPlusImage img, HwmfEmbedded emb, HwmfEmbeddedType et) { BufferedImage bi = img.readGDIImage(emb.getRawData()); try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); // use HwmfEmbeddedType literal for conversion ImageIO.write(bi, et.toString(), bos); emb.setData(bos.toByteArray()); @@ -298,7 +298,7 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> { int totalSize = epo.getTotalObjectSize(); IOUtils.safelyAllocateCheck(totalSize, MAX_RECORD_LENGTH); - ByteArrayOutputStream bos = new ByteArrayOutputStream(epo.getTotalObjectSize()); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(epo.getTotalObjectSize()); try { for (;;) { bos.write(img.getImageData()); @@ -315,8 +315,8 @@ public class HemfEmbeddedIterator implements Iterator<HwmfEmbedded> { return emb; } } - } catch (IOException e) { - // ByteArrayOutputStream doesn't throw IOException + } catch (IOException ignored) { + // UnsynchronizedByteArrayOutputStream doesn't throw IOException return null; } finally { emb.setData(bos.toByteArray()); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java b/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java index c3e2ab0c38..46988b9ec0 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hmef/CompressedRTF.java @@ -70,6 +70,7 @@ public final class CompressedRTF extends LZWDecompresser { * if you need to know how much of the result is * real. (Padding may be up to 7 bytes). */ + @Override public void decompress(InputStream src, OutputStream res) throws IOException { // Validate the header on the front of the RTF compressedSize = LittleEndian.readInt(src); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java index e6bf60da16..ec8d2b2fec 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/EMF.java @@ -19,11 +19,11 @@ package org.apache.poi.hslf.blip; import java.awt.Dimension; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.hslf.exceptions.HSLFException; @@ -41,7 +41,7 @@ public final class EMF extends Metafile { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link EMF}. This API led to detached {@link EMF} instances (See Bugzilla + * EMF. This API led to detached EMF instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -64,23 +64,19 @@ public final class EMF extends Metafile { @Override public byte[] getData(){ - try { - byte[] rawdata = getRawData(); + byte[] rawdata = getRawData(); + Header header = new Header(); + header.read(rawdata, CHECKSUM_SIZE); + + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); + InputStream is = new ByteArrayInputStream(rawdata); + InflaterInputStream inflater = new InflaterInputStream(is)) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - InputStream is = new ByteArrayInputStream( rawdata ); - Header header = new Header(); - header.read(rawdata, CHECKSUM_SIZE); long len = IOUtils.skipFully(is,header.getSize() + (long)CHECKSUM_SIZE); assert(len == header.getSize() + CHECKSUM_SIZE); - InflaterInputStream inflater = new InflaterInputStream( is ); - byte[] chunk = new byte[4096]; - int count; - while ((count = inflater.read(chunk)) >=0 ) { - out.write(chunk,0,count); - } - inflater.close(); + IOUtils.copy(inflater, out); + return out.toByteArray(); } catch (IOException e){ throw new HSLFException(e); @@ -129,13 +125,15 @@ public final class EMF extends Metafile { * * @return EMF signature ({@code 0x3D40} or {@code 0x3D50}) */ + @Override public int getSignature(){ return (getUIDInstanceCount() == 1 ? 0x3D40 : 0x3D50); } - + /** * Sets the EMF signature - either {@code 0x3D40} or {@code 0x3D50} */ + @Override public void setSignature(int signature) { switch (signature) { case 0x3D40: @@ -146,6 +144,6 @@ public final class EMF extends Metafile { break; default: throw new IllegalArgumentException(signature+" is not a valid instance/signature value for EMF"); - } + } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java index ea855d460e..ca0b01556e 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/Metafile.java @@ -20,11 +20,11 @@ package org.apache.poi.hslf.blip; import java.awt.Dimension; import java.awt.Rectangle; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.DeflaterOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.hslf.usermodel.HSLFPictureData; @@ -44,7 +44,7 @@ public abstract class Metafile extends HSLFPictureData { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link Metafile}. This API led to detached {@link Metafile} instances (See Bugzilla + * Metafile. This API led to detached Metafile instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -70,7 +70,7 @@ public abstract class Metafile extends HSLFPictureData { */ public static class Header{ private static final int RECORD_LENGTH = 34; - + /** * size of the original file */ @@ -105,7 +105,7 @@ public abstract class Metafile extends HSLFPictureData { @SuppressWarnings("resource") LittleEndianInputStream leis = new LittleEndianInputStream( new ByteArrayInputStream(data, offset, RECORD_LENGTH)); - + wmfsize = leis.readInt(); int left = leis.readInt(); @@ -126,7 +126,7 @@ public abstract class Metafile extends HSLFPictureData { public void write(OutputStream out) throws IOException { @SuppressWarnings("resource") LittleEndianOutputStream leos = new LittleEndianOutputStream(out); - + //hmf leos.writeInt(wmfsize); //left @@ -140,8 +140,8 @@ public abstract class Metafile extends HSLFPictureData { //inch leos.writeInt(size.width); //inch - leos.writeInt(size.height); - leos.writeInt(zipsize); + leos.writeInt(size.height); + leos.writeInt(zipsize); leos.writeByte(compression); leos.writeByte(filter); } @@ -187,15 +187,15 @@ public abstract class Metafile extends HSLFPictureData { public int getSize(){ return 34; } - + public int getWmfSize() { return wmfsize; } - + protected void setWmfSize(int wmfSize) { this.wmfsize = wmfSize; } - + protected void setZipSize(int zipSize) { this.zipsize = zipSize; } @@ -203,25 +203,25 @@ public abstract class Metafile extends HSLFPictureData { public Rectangle getBounds() { return (Rectangle)bounds.clone(); } - + protected void setBounds(Rectangle bounds) { this.bounds.setBounds(bounds); } - + protected void setDimension(Dimension size) { this.size.setSize(size); } } protected static byte[] compress(byte[] bytes, int offset, int length) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); try (DeflaterOutputStream deflater = new DeflaterOutputStream(out)) { deflater.write(bytes, offset, length); - } catch (IOException e) { + } catch (IOException ignored) { // IOException won't get thrown by the DeflaterOutputStream in this configuration because: - // 1. ByteArrayOutputStream doesn't throw an IOException during writes. + // 1. UnsynchronizedByteArrayOutputStream doesn't throw an IOException during writes. // 2. The DeflaterOutputStream is not finished until we're done writing. - throw new AssertionError("Won't happen", e); + throw new AssertionError("Won't happen", ignored); } return out.toByteArray(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java index a6c2765ec7..dc1e93cc67 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/PICT.java @@ -17,13 +17,15 @@ package org.apache.poi.hslf.blip; +import static org.apache.logging.log4j.util.Unbox.box; + import java.awt.Dimension; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherBSERecord; @@ -36,8 +38,6 @@ import org.apache.poi.util.Internal; import org.apache.poi.util.Removal; import org.apache.poi.util.Units; -import static org.apache.logging.log4j.util.Unbox.box; - /** * Represents Macintosh PICT picture data. */ @@ -46,7 +46,7 @@ public final class PICT extends Metafile { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link PICT}. This API led to detached {@link PICT} instances (See Bugzilla + * PICT. This API led to detached PICT instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -72,7 +72,7 @@ public final class PICT extends Metafile { byte[] rawdata = getRawData(); try { byte[] macheader = new byte[512]; - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); out.write(macheader); int pos = CHECKSUM_SIZE*getUIDInstanceCount(); byte[] pict = read(rawdata, pos); @@ -93,7 +93,7 @@ public final class PICT extends Metafile { throw new EOFException(); } byte[] chunk = new byte[4096]; - ByteArrayOutputStream out = new ByteArrayOutputStream(header.getWmfSize()); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(header.getWmfSize()); try (InflaterInputStream inflater = new InflaterInputStream(bis)) { int count; while ((count = inflater.read(chunk)) >= 0) { @@ -163,6 +163,7 @@ public final class PICT extends Metafile { * * @return PICT signature ({@code 0x5420} or {@code 0x5430}) */ + @Override public int getSignature(){ return (getUIDInstanceCount() == 1 ? 0x5420 : 0x5430); } @@ -170,6 +171,7 @@ public final class PICT extends Metafile { /** * Sets the PICT signature - either {@code 0x5420} or {@code 0x5430} */ + @Override public void setSignature(int signature) { switch (signature) { case 0x5420: diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java index 55b74bdb6f..6a039510c6 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/blip/WMF.java @@ -19,11 +19,11 @@ package org.apache.poi.hslf.blip; import java.awt.Dimension; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.hslf.exceptions.HSLFException; @@ -41,7 +41,7 @@ public final class WMF extends Metafile { /** * @deprecated Use {@link HSLFSlideShow#addPicture(byte[], PictureType)} or one of it's overloads to create new - * {@link WMF}. This API led to detached {@link WMF} instances (See Bugzilla + * WMF. This API led to detached WMF instances (See Bugzilla * 46122) and prevented adding additional functionality. */ @Deprecated @@ -67,7 +67,6 @@ public final class WMF extends Metafile { try { byte[] rawdata = getRawData(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream is = new ByteArrayInputStream( rawdata ); Header header = new Header(); header.read(rawdata, CHECKSUM_SIZE*getUIDInstanceCount()); @@ -76,15 +75,12 @@ public final class WMF extends Metafile { assert(skipped == skipLen); ImageHeaderWMF aldus = new ImageHeaderWMF(header.getBounds()); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); aldus.write(out); - InflaterInputStream inflater = new InflaterInputStream( is ); - byte[] chunk = new byte[4096]; - int count; - while ((count = inflater.read(chunk)) >=0 ) { - out.write(chunk,0,count); + try (InflaterInputStream inflater = new InflaterInputStream( is )) { + IOUtils.copy(inflater, out); } - inflater.close(); return out.toByteArray(); } catch (IOException e){ throw new HSLFException(e); @@ -133,6 +129,7 @@ public final class WMF extends Metafile { /** * WMF signature is either {@code 0x2160} or {@code 0x2170} */ + @Override public int getSignature(){ return (getUIDInstanceCount() == 1 ? 0x2160 : 0x2170); } @@ -140,6 +137,7 @@ public final class WMF extends Metafile { /** * Sets the WMF signature - either {@code 0x2160} or {@code 0x2170} */ + @Override public void setSignature(int signature) { switch (signature) { case 0x2160: diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java index 4e431976a3..b15d37c987 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/PPTXMLDump.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -28,6 +27,7 @@ import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.record.RecordTypes; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.poifs.filesystem.DirectoryNode; @@ -41,19 +41,15 @@ import org.apache.poi.util.LittleEndianConsts; */ public final class PPTXMLDump { - - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 1_000_000; - private static final int HEADER_SIZE = 8; //size of the record header private static final int PICT_HEADER_SIZE = 25; //size of the picture header private static final String PICTURES_ENTRY = "Pictures"; private static final String CR = System.getProperty("line.separator"); private Writer out; - private byte[] docstream; - private byte[] pictstream; - private boolean hexHeader = true; + private final byte[] docstream; + private final byte[] pictstream; + private final boolean hexHeader = true; public PPTXMLDump(File ppt) throws IOException { try (POIFSFileSystem fs = new POIFSFileSystem(ppt, true)) { @@ -68,8 +64,8 @@ public final class PPTXMLDump { if (!dn.hasEntry(entry)) { return null; } - try (InputStream is = dn.createDocumentInputStream(entry)) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try (InputStream is = dn.createDocumentInputStream(entry); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { IOUtils.copy(is, bos); return bos.toByteArray(); } @@ -77,7 +73,7 @@ public final class PPTXMLDump { /** * Dump the structure of the supplied PPT file into XML - * @param outWriter <code>Writer</code> to write out + * @param outWriter {@code Writer} to write out * @throws java.io.IOException If writing to the writer fails */ public void dump(Writer outWriter) throws IOException { @@ -229,7 +225,7 @@ public final class PPTXMLDump { /** - * write a string to <code>out</code> with the specified padding + * write a string to {@code out} with the specified padding */ private static void write(Writer out, String str, int padding) throws IOException { for (int i = 0; i < padding; i++) out.write(" "); @@ -250,7 +246,7 @@ public final class PPTXMLDump { } /** - * dump binary data to <code>out</code> with the specified padding + * dump binary data to {@code out} with the specified padding */ private static void dump(Writer out, byte[] data, int offset, int length, int padding, boolean nl) throws IOException { int linesize = 25; diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java index e80cbc18ec..b335752e9c 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideIdListing.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.record.Document; import org.apache.poi.hslf.record.Notes; import org.apache.poi.hslf.record.NotesAtom; @@ -136,7 +136,7 @@ public final class SlideIdListing { System.out.println(" Knows about sheet " + id); System.out.println(" That sheet lives at " + offset); - Record atPos = findRecordAtPos(offset.intValue()); + Record atPos = findRecordAtPos(offset); System.out.println(" The record at that pos is of type " + atPos.getRecordType()); System.out.println(" The record at that pos has class " + atPos.getClass().getName()); @@ -147,7 +147,7 @@ public final class SlideIdListing { } // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); pos += baos.size(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java index 88b6407cab..eb7a1a7ece 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/SlideShowRecordDumper.java @@ -17,12 +17,11 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; -import java.util.List; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherRecord; @@ -44,9 +43,9 @@ import org.apache.poi.util.HexDump; public final class SlideShowRecordDumper { static final String tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; - private boolean optVerbose; - private boolean optEscher; - private HSLFSlideShowImpl doc; + private final boolean optVerbose; + private final boolean optEscher; + private final HSLFSlideShowImpl doc; private final PrintStream ps; /** @@ -59,7 +58,7 @@ public final class SlideShowRecordDumper { int ndx = 0; for (; ndx < args.length; ndx++) { - if (!args[ndx].substring(0, 1).equals("-")) + if (args[ndx].charAt(0) != '-') break; if (args[ndx].equals("-escher")) { @@ -147,7 +146,7 @@ public final class SlideShowRecordDumper { public int getDiskLen(org.apache.poi.hslf.record.Record r) throws IOException { int diskLen = 0; if (r != null) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); diskLen = baos.size(); } @@ -159,7 +158,7 @@ public final class SlideShowRecordDumper { return "<<null>>"; } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); byte[] b = baos.toByteArray(); return HexDump.dump(b, 0, 0); @@ -259,7 +258,7 @@ public final class SlideShowRecordDumper { if (optEscher && cname.equals("PPDrawing")) { DefaultEscherRecordFactory factory = new HSLFEscherRecordFactory(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); byte[] b = baos.toByteArray(); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java index 116582e7f3..d17eafc346 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/dev/UserEditAndPersistListing.java @@ -17,10 +17,10 @@ package org.apache.poi.hslf.dev; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.record.CurrentUserAtom; import org.apache.poi.hslf.record.PersistPtrHolder; import org.apache.poi.hslf.record.PositionDependentRecord; @@ -68,7 +68,7 @@ public final class UserEditAndPersistListing { System.out.println(" Knows about sheet " + id); System.out.println(" That sheet lives at " + offset); - Record atPos = findRecordAtPos(offset.intValue()); + Record atPos = findRecordAtPos(offset); System.out.println(" The record at that pos is of type " + atPos.getRecordType()); System.out.println(" The record at that pos has class " + atPos.getClass().getName()); @@ -79,7 +79,7 @@ public final class UserEditAndPersistListing { } // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); pos += baos.size(); } @@ -99,7 +99,7 @@ public final class UserEditAndPersistListing { } // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); pos += baos.size(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java index 9155731dcd..62c2f935f3 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/model/textproperties/TextPropCollection.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.model.textproperties; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -29,6 +28,7 @@ import java.util.Map; import java.util.Objects; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.common.Duplicatable; @@ -355,10 +355,10 @@ public class TextPropCollection implements GenericRecord, Duplicatable { public String toString() { StringBuilder out = new StringBuilder(); - out.append(" chars covered: " + getCharactersCovered()); - out.append(" special mask flags: 0x" + HexDump.toHex(getSpecialMask()) + "\n"); + out.append(" chars covered: ").append(getCharactersCovered()); + out.append(" special mask flags: 0x").append(HexDump.toHex(getSpecialMask())).append("\n"); if (textPropType == TextPropType.paragraph) { - out.append(" indent level: "+getIndentLevel()+"\n"); + out.append(" indent level: ").append(getIndentLevel()).append("\n"); } for(TextProp p : getTextPropList()) { out.append(" "); @@ -369,7 +369,7 @@ public class TextPropCollection implements GenericRecord, Duplicatable { int i = 0; for (String s : bm.getSubPropNames()) { if (bm.getSubPropMatches()[i]) { - out.append(" " + s + " = " + bm.getSubValue(i) + "\n"); + out.append(" ").append(s).append(" = ").append(bm.getSubValue(i)).append("\n"); } i++; } @@ -379,7 +379,7 @@ public class TextPropCollection implements GenericRecord, Duplicatable { out.append(" bytes that would be written: \n"); try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); writeOut(baos); byte[] b = baos.toByteArray(); out.append(HexDump.dump(b, 0, 0)); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java index bd2ac34d98..7a8dc9dbf6 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ColorSchemeAtom.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; @@ -26,6 +25,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.LittleEndian; @@ -36,9 +36,9 @@ import org.apache.poi.util.LittleEndian; * defines the colours to be used */ public final class ColorSchemeAtom extends RecordAtom { - private byte[] _header; - private static long _type = 2032l; + private static final long _type = 2032L; + private final byte[] _header; private int backgroundColourRGB; private int textAndLinesColourRGB; private int shadowsColourRGB; @@ -99,8 +99,7 @@ public final class ColorSchemeAtom extends RecordAtom { */ protected ColorSchemeAtom(byte[] source, int start, int len) { // Sanity Checking - we're always 40 bytes long - if(len < 40) { - len = 40; + if (len < 40) { if(source.length - start < 40) { throw new HSLFException("Not enough data to form a ColorSchemeAtom (always 40 bytes long) - found " + (source.length - start)); } @@ -155,7 +154,7 @@ public final class ColorSchemeAtom extends RecordAtom { byte[] ret = new byte[3]; // Serialise to bytes, then grab the right ones out - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); try { writeLittleEndian(rgb,baos); } catch(IOException ie) { diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java index ebb3fc01b9..e9e16b91ed 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/CurrentUserAtom.java @@ -23,12 +23,11 @@ package org.apache.poi.hslf.record; import static org.apache.logging.log4j.util.Unbox.box; import static org.apache.poi.hslf.usermodel.HSLFSlideShow.PP95_DOCUMENT; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; @@ -267,12 +266,12 @@ public class CurrentUserAtom */ public void writeToFS(POIFSFileSystem fs) throws IOException { // Grab contents - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - writeOut(baos); - ByteArrayInputStream bais = - new ByteArrayInputStream(baos.toByteArray()); - - // Write out - fs.createOrUpdateDocument(bais,"Current User"); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + writeOut(baos); + try (InputStream is = baos.toInputStream()) { + // Write out + fs.createOrUpdateDocument(is, "Current User"); + } + } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java index 273c3a6a2c..4764c91d21 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/DocumentAtom.java @@ -66,7 +66,7 @@ public final class DocumentAtom extends RecordAtom { private final byte[] _header = new byte[8]; - private static long _type = RecordTypes.DocumentAtom.typeID; + private static final long _type = RecordTypes.DocumentAtom.typeID; private long slideSizeX; // PointAtom, assume 1st 4 bytes = X private long slideSizeY; // PointAtom, assume 2nd 4 bytes = Y @@ -75,18 +75,18 @@ public final class DocumentAtom extends RecordAtom { private long serverZoomFrom; // RatioAtom, assume 1st 4 bytes = from private long serverZoomTo; // RatioAtom, assume 2nd 4 bytes = to - private long notesMasterPersist; // ref to NotesMaster, 0 if none - private long handoutMasterPersist; // ref to HandoutMaster, 0 if none + private final long notesMasterPersist; // ref to NotesMaster, 0 if none + private final long handoutMasterPersist; // ref to HandoutMaster, 0 if none - private int firstSlideNum; + private final int firstSlideNum; private int slideSizeType; // see DocumentAtom.SlideSize private byte saveWithFonts; - private byte omitTitlePlace; - private byte rightToLeft; - private byte showComments; + private final byte omitTitlePlace; + private final byte rightToLeft; + private final byte showComments; - private byte[] reserved; + private final byte[] reserved; public long getSlideSizeX() { return slideSizeX; } @@ -197,12 +197,14 @@ public final class DocumentAtom extends RecordAtom { /** * We are of type 1001 */ + @Override public long getRecordType() { return _type; } /** * Write the contents of the record back, so it can be written * to disk */ + @Override public void writeOut(OutputStream out) throws IOException { // Header out.write(_header); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java index 7a47e9fd4e..751bf291f9 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/EscherTextboxWrapper.java @@ -17,12 +17,12 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherTextboxRecord; import org.apache.poi.util.GenericRecordUtil; @@ -34,7 +34,7 @@ import org.apache.poi.util.GenericRecordUtil; * parent PPDrawing) will do the actual write out */ public final class EscherTextboxWrapper extends RecordContainer { - private EscherTextboxRecord _escherRecord; + private final EscherTextboxRecord _escherRecord; private long _type; private int shapeId; private StyleTextPropAtom styleTextPropAtom; @@ -75,6 +75,7 @@ public final class EscherTextboxWrapper extends RecordContainer { /** * Return the type of the escher record (normally in the 0xFnnn range) */ + @Override public long getRecordType() { return _type; } /** @@ -83,11 +84,12 @@ public final class EscherTextboxWrapper extends RecordContainer { * layer to do. Must be called before writeOut/serialize is called * on the underlying Escher object! */ + @Override public void writeOut(OutputStream out) throws IOException { // Write out our children, and stuff them into the Escher layer // Grab the children's data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); for (org.apache.poi.hslf.record.Record r : _children) r.writeOut(baos); byte[] data = baos.toByteArray(); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java index 4fc8a838e0..8aa091fdb2 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/ExOleObjStg.java @@ -18,7 +18,6 @@ package org.apache.poi.hslf.record; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -28,7 +27,8 @@ import java.util.function.Supplier; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import org.apache.poi.util.BoundedInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.commons.io.input.BoundedInputStream; import org.apache.poi.util.GenericRecordUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; @@ -124,7 +124,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * @param data the embedded data. */ public void setData(byte[] data) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); //first four bytes is the length of the raw data byte[] b = new byte[4]; LittleEndian.putInt(b, 0, data.length); @@ -133,6 +133,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR DeflaterOutputStream def = new DeflaterOutputStream(out); def.write(data, 0, data.length); def.finish(); + // TODO: CHECK if it's correct that DeflaterOutputStream is only finished and not closed? _data = out.toByteArray(); LittleEndian.putInt(_header, 4, _data.length); } @@ -142,6 +143,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * * @return the record type. */ + @Override public long getRecordType() { return RecordTypes.ExOleObjStg.typeID; } @@ -162,6 +164,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * @param out the output stream to write to. * @throws IOException if an error occurs. */ + @Override public void writeOut(OutputStream out) throws IOException { out.write(_header); out.write(_data); @@ -171,6 +174,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR * Fetch our sheet ID, as found from a PersistPtrHolder. * Should match the RefId of our matching SlidePersistAtom */ + @Override public int getPersistId() { return _persistId; } @@ -178,6 +182,7 @@ public class ExOleObjStg extends PositionDependentRecordAtom implements PersistR /** * Set our sheet ID, as found from a PersistPtrHolder */ + @Override public void setPersistId(int id) { _persistId = id; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java index af0e0a5ec5..47efe8e829 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java @@ -17,11 +17,11 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.EscherClientDataRecord; import org.apache.poi.ddf.EscherRecordFactory; import org.apache.poi.ddf.EscherSerializationListener; @@ -49,7 +49,7 @@ public class HSLFEscherClientDataRecord extends EscherClientDataRecord { super(other); // TODO: for now only reference others children, later copy them when Record.copy is available // other._childRecords.stream().map(Record::copy).forEach(_childRecords::add); - other._childRecords.addAll(other._childRecords); + _childRecords.addAll(other._childRecords); } @@ -96,15 +96,14 @@ public class HSLFEscherClientDataRecord extends EscherClientDataRecord { @Override public byte[] getRemainingData() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { for (org.apache.poi.hslf.record.Record r : _childRecords) { r.writeOut(bos); } + return bos.toByteArray(); } catch (IOException e) { throw new HSLFException(e); } - return bos.toByteArray(); } @Override @@ -121,6 +120,7 @@ public class HSLFEscherClientDataRecord extends EscherClientDataRecord { } } + @Override public String getRecordName() { return "HSLFClientData"; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java index 6ff8b4577f..3bc4f0fe57 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PPDrawingGroup.java @@ -17,13 +17,13 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ddf.DefaultEscherRecordFactory; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherDggRecord; @@ -44,8 +44,8 @@ public final class PPDrawingGroup extends RecordAtom { private static final int MAX_RECORD_LENGTH = 10_485_760; - private byte[] _header; - private EscherContainerRecord dggContainer; + private final byte[] _header; + private final EscherContainerRecord dggContainer; //cached dgg private EscherDggRecord dgg; @@ -65,6 +65,7 @@ public final class PPDrawingGroup extends RecordAtom { /** * We are type 1035 */ + @Override public long getRecordType() { return RecordTypes.PPDrawingGroup.typeID; } @@ -72,17 +73,19 @@ public final class PPDrawingGroup extends RecordAtom { /** * We're pretending to be an atom, so return null */ + @Override public org.apache.poi.hslf.record.Record[] getChildRecords() { return null; } + @Override public void writeOut(OutputStream out) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bout = new UnsynchronizedByteArrayOutputStream(); for (EscherRecord r : dggContainer) { if (r.getRecordId() == EscherContainerRecord.BSTORE_CONTAINER){ EscherContainerRecord bstore = (EscherContainerRecord)r; - ByteArrayOutputStream b2 = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream b2 = new UnsynchronizedByteArrayOutputStream(); for (EscherRecord br : bstore) { byte[] b = new byte[36+8]; br.serialize(0, b); @@ -114,8 +117,7 @@ public final class PPDrawingGroup extends RecordAtom { out.write(dgghead); // Finally, write out the children - out.write(bout.toByteArray()); - + bout.writeTo(out); } public EscherContainerRecord getDggContainer(){ diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java index 1ee2403cf7..4e47cb7195 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/PersistPtrHolder.java @@ -17,24 +17,23 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.TreeMap; import java.util.function.Supplier; import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; import org.apache.poi.util.GenericRecordUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; +import org.apache.poi.util.LittleEndianConsts; /** * General holder for PersistPtrFullBlock and PersistPtrIncrementalBlock @@ -54,14 +53,14 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom private final byte[] _header; private byte[] _ptrData; // Will need to update this once we allow updates to _slideLocations - private long _type; + private final long _type; /** * Holds the lookup for slides to their position on disk. * You always need to check the most recent PersistPtrHolder * that knows about a given slide to find the right location */ - private Map<Integer,Integer> _slideLocations; + private final Map<Integer,Integer> _slideLocations; private static final BitField persistIdFld = BitFieldFactory.getInstance(0X000FFFFF); private static final BitField cntPersistFld = BitFieldFactory.getInstance(0XFFF00000); @@ -185,51 +184,47 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom } private void normalizePersistDirectory() { - TreeMap<Integer,Integer> orderedSlideLocations = new TreeMap<>(_slideLocations); - - @SuppressWarnings("resource") - BufAccessBAOS bos = new BufAccessBAOS(); // NOSONAR - byte[] intbuf = new byte[4]; - int lastPersistEntry = -1; - int lastSlideId = -1; - for (Entry<Integer,Integer> me : orderedSlideLocations.entrySet()) { - int nextSlideId = me.getKey(); - int offset = me.getValue(); - try { - // Building the info block - // First 20 bits = offset number = slide ID (persistIdFld, i.e. first slide ID of a continuous group) - // Remaining 12 bits = offset count = 1 (cntPersistFld, i.e. continuous entries in a group) - - if (lastSlideId+1 == nextSlideId) { - // use existing PersistDirectoryEntry, need to increase entry count - assert(lastPersistEntry != -1); - int infoBlock = LittleEndian.getInt(bos.getBuf(), lastPersistEntry); - int entryCnt = cntPersistFld.getValue(infoBlock); - infoBlock = cntPersistFld.setValue(infoBlock, entryCnt+1); - LittleEndian.putInt(bos.getBuf(), lastPersistEntry, infoBlock); - } else { - // start new PersistDirectoryEntry - lastPersistEntry = bos.size(); - int infoBlock = persistIdFld.setValue(0, nextSlideId); - infoBlock = cntPersistFld.setValue(infoBlock, 1); - LittleEndian.putInt(intbuf, 0, infoBlock); - bos.write(intbuf); - } - // Add to the ptrData offset lookup hash - LittleEndian.putInt(intbuf, 0, offset); - bos.write(intbuf); - lastSlideId = nextSlideId; - } catch (IOException e) { - // ByteArrayOutputStream is very unlikely throwing a IO exception (maybe because of OOM ...) - throw new HSLFException(e); - } - } + // Building the info block + // First 20 bits = offset number = slide ID (persistIdFld, i.e. first slide ID of a continuous group) + // Remaining 12 bits = offset count = 1 (cntPersistFld, i.e. continuous entries in a group) + // + // the info block is then followed by the slide offset (32 bits) + + int[] infoBlocks = new int[_slideLocations.size()*2]; + int lastSlideId = -1; + int lastPersistIdx = 0; + int lastIdx = -1; + int entryCnt = 0; + int baseSlideId = -1; + + Iterable<Entry<Integer,Integer>> iter = _slideLocations.entrySet().stream() + .sorted(Comparator.comparingInt(Entry::getKey))::iterator; + for (Entry<Integer, Integer> me : iter) { + int nextSlideId = me.getKey(); + if (lastSlideId + 1 < nextSlideId) { + // start new PersistDirectoryEntry + lastPersistIdx = ++lastIdx; + entryCnt = 0; + baseSlideId = nextSlideId; + } + + int infoBlock = persistIdFld.setValue(0, baseSlideId); + infoBlock = cntPersistFld.setValue(infoBlock, ++entryCnt); + infoBlocks[lastPersistIdx] = infoBlock; + // add the offset + infoBlocks[++lastIdx] = me.getValue(); + + lastSlideId = nextSlideId; + } - // Save the new ptr data - _ptrData = bos.toByteArray(); + // Save the new ptr data + _ptrData = new byte[(lastIdx+1)*LittleEndianConsts.INT_SIZE]; + for (int idx = 0; idx<=lastIdx; idx++) { + LittleEndian.putInt(_ptrData, idx*LittleEndianConsts.INT_SIZE, infoBlocks[idx]); + } - // Update the atom header - LittleEndian.putInt(_header,4,bos.size()); + // Update the atom header + LittleEndian.putInt(_header, 4, _ptrData.length); } /** @@ -243,12 +238,6 @@ public final class PersistPtrHolder extends PositionDependentRecordAtom out.write(_ptrData); } - private static class BufAccessBAOS extends ByteArrayOutputStream { - public byte[] getBuf() { - return buf; - } - } - @Override public Map<String, Supplier<?>> getGenericProperties() { return GenericRecordUtil.getGenericProperties( diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java index 635ad85b28..98e48067c2 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/RecordContainer.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -25,6 +24,7 @@ import java.util.Arrays; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.ArrayUtil; import org.apache.poi.util.LittleEndian; @@ -226,8 +226,8 @@ public abstract class RecordContainer extends Record * @param out the stream to write to */ public void writeOut(byte headerA, byte headerB, long type, Record[] children, OutputStream out) throws IOException { - // Create a ByteArrayOutputStream to hold everything in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // Create a UnsynchronizedByteArrayOutputStream to hold everything in + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); // Write out our header, less the size baos.write(new byte[] {headerA,headerB}); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java index de2b28c311..e758d57fce 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/StyleTextPropAtom.java @@ -17,7 +17,8 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; +import static org.apache.logging.log4j.util.Unbox.box; + import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -26,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.hslf.model.textproperties.TextPropCollection; import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType; @@ -34,8 +36,6 @@ import org.apache.poi.util.HexDump; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; -import static org.apache.logging.log4j.util.Unbox.box; - /** * A StyleTextPropAtom (type 4001). Holds basic character properties * (bold, italic, underline, font size etc) and paragraph properties @@ -55,7 +55,7 @@ public final class StyleTextPropAtom extends RecordAtom { //arbitrarily selected; may need to increase private static final int MAX_RECORD_LENGTH = 1_000_000; - private byte[] _header; + private final byte[] _header; private byte[] reserved; private byte[] rawContents; // Holds the contents between write-outs @@ -312,7 +312,7 @@ public final class StyleTextPropAtom extends RecordAtom { // Only update the style bytes, if the styles have been potentially // changed - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); // First up, we need to serialise the paragraph properties for(TextPropCollection tpc : paragraphStyles) { diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java index 5de317cc0c..a9b083b236 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextRulerAtom.java @@ -19,7 +19,6 @@ package org.apache.poi.hslf.record; import static org.apache.poi.util.BitFieldFactory.getInstance; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -28,6 +27,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.model.textproperties.HSLFTabStop; import org.apache.poi.hslf.model.textproperties.HSLFTabStopPropCollection; import org.apache.poi.util.BitField; @@ -120,7 +120,7 @@ public final class TextRulerAtom extends RecordAtom { */ @Override public void writeOut(final OutputStream out) throws IOException { - final ByteArrayOutputStream bos = new ByteArrayOutputStream(200); + final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(200); final LittleEndianOutputStream lbos = new LittleEndianOutputStream(bos); int mask = 0; mask |= writeIf(lbos, numLevels, C_LEVELS); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java index fdc16db465..1071422e3b 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TextSpecInfoAtom.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -26,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.util.GenericRecordUtil; import org.apache.poi.util.IOUtils; @@ -46,7 +46,7 @@ public final class TextSpecInfoAtom extends RecordAtom { /** * Record header. */ - private byte[] _header; + private final byte[] _header; /** * Record data. @@ -112,7 +112,7 @@ public final class TextSpecInfoAtom extends RecordAtom { */ public void reset(int size){ TextSpecInfoRun sir = new TextSpecInfoRun(size); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { sir.writeOut(bos); } catch (IOException e) { @@ -127,13 +127,11 @@ public final class TextSpecInfoAtom extends RecordAtom { /** * Adapts the size by enlarging the last {@link TextSpecInfoRun} * or chopping the runs to the given length - * - * @param size */ public void setParentSize(int size) { assert(size > 0); int covered = 0; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); TextSpecInfoRun[] runs = getTextSpecInfoRuns(); assert(runs.length > 0); for (int i=0; i<runs.length && covered < size; i++) { diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java index a396cd95bf..ee419faf31 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/record/TxMasterStyleAtom.java @@ -17,7 +17,6 @@ package org.apache.poi.hslf.record; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; @@ -26,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hslf.exceptions.HSLFException; @@ -64,7 +64,7 @@ public final class TxMasterStyleAtom extends RecordAtom { private static final long _type = RecordTypes.TxMasterStyleAtom.typeID; - private byte[] _header; + private final byte[] _header; private byte[] _data; private List<TextPropCollection> paragraphStyles; @@ -89,6 +89,7 @@ public final class TxMasterStyleAtom extends RecordAtom { * @return type of this record * @see RecordTypes#TxMasterStyleAtom */ + @Override public long getRecordType() { return _type; } @@ -97,6 +98,7 @@ public final class TxMasterStyleAtom extends RecordAtom { * Write the contents of the record back, so it can be written * to disk */ + @Override public void writeOut(OutputStream out) throws IOException { // Write out the (new) header out.write(_header); @@ -126,7 +128,7 @@ public final class TxMasterStyleAtom extends RecordAtom { /** * Return type of the text. - * Must be a constant defined in <code>TextHeaderAtom</code> + * Must be a constant defined in {@code TextHeaderAtom} * * @return type of the text * @see TextHeaderAtom @@ -187,7 +189,7 @@ public final class TxMasterStyleAtom extends RecordAtom { int type = getTextType(); try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); int levels = paragraphStyles.size(); leos.writeShort(levels); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java index 60f864188d..3bc921dc96 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectData.java @@ -16,7 +16,6 @@ ==================================================================== */ package org.apache.poi.hslf.usermodel; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -25,8 +24,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.poi.common.usermodel.GenericRecord; import org.apache.poi.hslf.record.ExOleObjStg; import org.apache.poi.sl.usermodel.ObjectData; @@ -35,12 +33,10 @@ import org.apache.poi.sl.usermodel.ObjectData; * A class that represents object data embedded in a slide show. */ public class HSLFObjectData implements ObjectData, GenericRecord { - private static final Logger LOG = LogManager.getLogger(HSLFObjectData.class); - /** * The record that contains the object data. */ - private ExOleObjStg storage; + private final ExOleObjStg storage; /** * Creates the object data wrapping the record that contains the object data. @@ -55,10 +51,12 @@ public class HSLFObjectData implements ObjectData, GenericRecord { public InputStream getInputStream() { return storage.getData(); } - + @Override - public OutputStream getOutputStream() throws IOException { - return new ByteArrayOutputStream(100000) { + public OutputStream getOutputStream() { + // can't use UnsynchronizedByteArrayOutputStream here, because it's final + return new ByteArrayOutputStream() { + @Override public void close() throws IOException { setData(getBytes()); } @@ -71,7 +69,7 @@ public class HSLFObjectData implements ObjectData, GenericRecord { * @param data the embedded data. */ public void setData(byte[] data) throws IOException { - storage.setData(data); + storage.setData(data); } /** diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java index 344e038374..a5414672b9 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFObjectShape.java @@ -17,11 +17,12 @@ package org.apache.poi.hslf.usermodel; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; +import org.apache.commons.io.output.AbstractByteArrayOutputStream; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherContainerRecord; @@ -51,7 +52,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha private ExEmbed _exEmbed; /** - * Create a new <code>OLEShape</code> + * Create a new {@code OLEShape} * * @param data the picture data */ @@ -60,7 +61,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } /** - * Create a new <code>OLEShape</code> + * Create a new {@code OLEShape} * * @param data the picture data * @param parent the parent shape @@ -70,10 +71,10 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } /** - * Create a <code>OLEShape</code> object + * Create a {@code OLEShape} object * - * @param escherRecord the <code>EscherSpContainer</code> record which holds information about - * this picture in the <code>Slide</code> + * @param escherRecord the {@code EscherSpContainer} record which holds information about + * this picture in the {@code Slide} * @param parent the parent shape of this picture */ public HSLFObjectShape(EscherContainerRecord escherRecord, ShapeContainer<HSLFShape,HSLFTextParagraph> parent){ @@ -100,7 +101,11 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha EscherContainerRecord ecr = getSpContainer(); EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID); - spRecord.setFlags(spRecord.getFlags()|EscherSpRecord.FLAG_OLESHAPE); + if (spRecord != null) { + spRecord.setFlags(spRecord.getFlags() | EscherSpRecord.FLAG_OLESHAPE); + } else { + LOG.atWarn().log("Ole shape record not found."); + } HSLFEscherClientDataRecord cldata = getClientData(true); ExObjRefAtom uer = null; @@ -123,6 +128,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha * * @return the unique identifier for the OLE object */ + @Override public HSLFObjectData getObjectData(){ HSLFSlideShow ppt = getSheet().getSlideShow(); HSLFObjectData[] ole = ppt.getEmbeddedObjects(); @@ -184,7 +190,7 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } } } - + if (_exEmbed == null && create) { _exEmbed = new ExEmbed(); _exEmbed.getExOleObjAtom().setObjID(id); @@ -193,8 +199,8 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } return _exEmbed; } - - + + /** * Returns the instance name of the embedded object, e.g. "Document" or "Workbook". * @@ -231,45 +237,51 @@ public final class HSLFObjectShape extends HSLFPictureShape implements ObjectSha } } - public OutputStream updateObjectData(final Application application, final ObjectMetaData metaData) throws IOException { + @Override + public OutputStream updateObjectData(final Application application, final ObjectMetaData metaData) { final ObjectMetaData md = (application != null) ? application.getMetaData() : metaData; if (md == null) { throw new RuntimeException("either application or metaData needs to be set"); } - return new ByteArrayOutputStream(100000) { + // can't use UnsynchronizedByteArrayOutputStream here, because it's final + return new ByteArrayOutputStream() { + @Override public void close() throws IOException { - final FileMagic fm = FileMagic.valueOf(this.buf); - final ByteArrayInputStream bis = new ByteArrayInputStream(this.buf, 0, this.count); - final HSLFSlideShow ppt = getSheet().getSlideShow(); - - try (POIFSFileSystem poifs = (fm == FileMagic.OLE2) ? new POIFSFileSystem(bis) : new POIFSFileSystem()) { - if (fm != FileMagic.OLE2) { - poifs.createDocument(bis, md.getOleEntry()); - } + addUpdatedData(md,this); + } + }; + } - Ole10Native.createOleMarkerEntry(poifs); - - poifs.getRoot().setStorageClsid(md.getClassID()); - - int oid = getObjectID(); - if (oid == 0) { - // assign new embedding - oid = ppt.addEmbed(poifs); - setObjectID(oid); - } else { - final HSLFObjectData od = getObjectData(); - if (od != null) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(this.size()+1000); - poifs.writeFilesystem(bos); - od.setData(bos.toByteArray()); - } + private void addUpdatedData(ObjectMetaData md, AbstractByteArrayOutputStream baos) throws IOException { + try (InputStream bis = FileMagic.prepareToCheckMagic(baos.toInputStream())) { + final FileMagic fm = FileMagic.valueOf(bis); + try (POIFSFileSystem poifs = (fm == FileMagic.OLE2) ? new POIFSFileSystem(bis) : new POIFSFileSystem()) { + if (fm != FileMagic.OLE2) { + poifs.createDocument(bis, md.getOleEntry()); + } + baos.reset(); + + Ole10Native.createOleMarkerEntry(poifs); + + poifs.getRoot().setStorageClsid(md.getClassID()); + + int oid = getObjectID(); + if (oid == 0) { + // assign new embedding + oid = getSheet().getSlideShow().addEmbed(poifs); + setObjectID(oid); + } else { + final HSLFObjectData od = getObjectData(); + if (od != null) { + poifs.writeFilesystem(baos); + od.setData(baos.toByteArray()); } - - setProgId(md.getProgId()); - setFullName(md.getObjectName()); } + + setProgId(md.getProgId()); + setFullName(md.getObjectName()); } - }; + } } } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java index 5e2e5d9ebc..e2a3b51155 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShow.java @@ -17,8 +17,9 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.logging.log4j.util.Unbox.box; + import java.awt.Dimension; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; @@ -33,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.POIDocument; @@ -66,8 +68,6 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.Internal; import org.apache.poi.util.Units; -import static org.apache.logging.log4j.util.Unbox.box; - /** * This class is a friendly wrapper on top of the more scary HSLFSlideShow. * @@ -708,9 +708,9 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh } /** - * Create a blank <code>Slide</code>. + * Create a blank {@code Slide}. * - * @return the created <code>Slide</code> + * @return the created {@code Slide} */ @Override public HSLFSlide createSlide() { @@ -882,6 +882,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh * * @since POI 4.1.0 */ + @Override public HSLFFontInfo addFont(InputStream fontData) throws IOException { Document doc = getDocumentRecord(); doc.getDocumentAtom().setSaveWithFonts(true); @@ -893,7 +894,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh * * @param idx * 0-based index of the font - * @return of an instance of <code>PPFont</code> or <code>null</code> if not + * @return of an instance of {@code PPFont} or {@code null} if not * found */ public HSLFFontInfo getFont(int idx) { @@ -1040,7 +1041,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh ExOleObjStg exOleObjStg = new ExOleObjStg(); try { Ole10Native.createOleMarkerEntry(poiData); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); poiData.writeFilesystem(bos); exOleObjStg.setData(bos.toByteArray()); } catch (IOException e) { @@ -1246,7 +1247,7 @@ public final class HSLFSlideShow extends POIDocument implements SlideShow<HSLFSh } @Override - public EncryptionInfo getEncryptionInfo() throws IOException { + public EncryptionInfo getEncryptionInfo() { return getSlideShowImpl().getEncryptionInfo(); } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java index f697e859ce..62a9d997b1 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java @@ -23,17 +23,18 @@ import static org.apache.poi.hslf.usermodel.HSLFSlideShow.PP95_DOCUMENT; import static org.apache.poi.hslf.usermodel.HSLFSlideShow.PP97_DOCUMENT; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; +import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -44,6 +45,8 @@ import java.util.Objects; import java.util.TreeMap; import java.util.stream.Collectors; +import org.apache.commons.collections4.IteratorUtils; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.POIDocument; @@ -659,7 +662,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { /** * Writes out the slideshow to the currently open file. * <p> - * <p>This will fail (with an {@link IllegalStateException} if the + * This will fail (with an {@link IllegalStateException} if the * slideshow was opened read-only, opened from an {@link InputStream} * instead of a File, or if this is not the root document. For those cases, * you must use {@link #write(OutputStream)} or {@link #write(File)} to @@ -686,7 +689,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * of this class. * <p>This will write out only the common OLE2 streams. If you require all * streams to be written out, use {@link #write(File, boolean)} - * with <code>preserveNodes</code> set to <code>true</code>. + * with {@code preserveNodes} set to {@code true}. * * @param newFile The File to write to. * @throws IOException If there is an unexpected IOException from writing to the File @@ -701,7 +704,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * Writes out the slideshow file the is represented by an instance * of this class. * If you require all streams to be written out (eg Marcos, embeded - * documents), then set <code>preserveNodes</code> set to <code>true</code> + * documents), then set {@code preserveNodes} set to {@code true} * * @param newFile The File to write to. * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones? @@ -724,7 +727,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * of this class. * <p>This will write out only the common OLE2 streams. If you require all * streams to be written out, use {@link #write(OutputStream, boolean)} - * with <code>preserveNodes</code> set to <code>true</code>. + * with {@code preserveNodes} set to {@code true}. * * @param out The OutputStream to write to. * @throws IOException If there is an unexpected IOException from @@ -740,7 +743,7 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { * Writes out the slideshow file the is represented by an instance * of this class. * If you require all streams to be written out (eg Marcos, embeded - * documents), then set <code>preserveNodes</code> set to <code>true</code> + * documents), then set {@code preserveNodes} set to {@code true} * * @param out The OutputStream to write to. * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones? @@ -776,16 +779,16 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { // Write out the Property Streams writeProperties(outFS, writtenEntries); - BufAccessBAOS baos = new BufAccessBAOS(); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { - // For position dependent records, hold where they were and now are - // As we go along, update, and hand over, to any Position Dependent - // records we happen across - updateAndWriteDependantRecords(baos, null); + // For position dependent records, hold where they were and now are + // As we go along, update, and hand over, to any Position Dependent + // records we happen across + updateAndWriteDependantRecords(baos, null); - // Update our cached copy of the bytes that make up the PPT stream - _docstream = baos.toByteArray(); - baos.close(); + // Update our cached copy of the bytes that make up the PPT stream + _docstream = baos.toByteArray(); + } // Write the PPT stream into the POIFS layer ByteArrayInputStream bais = new ByteArrayInputStream(_docstream); @@ -796,20 +799,18 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { currentUser.writeToFS(outFS); writtenEntries.add("Current User"); - if (_pictures.size() > 0) { - BufAccessBAOS pict = new BufAccessBAOS(); - for (HSLFPictureData p : _pictures) { - int offset = pict.size(); - p.write(pict); - encryptedSS.encryptPicture(pict.getBuf(), offset); - } - outFS.createOrUpdateDocument( - new ByteArrayInputStream(pict.getBuf(), 0, pict.size()), "Pictures" + if (!_pictures.isEmpty()) { + Enumeration<InputStream> pictEnum = IteratorUtils.asEnumeration( + _pictures.stream().map(data -> encryptOnePicture(encryptedSS, data)).iterator() ); - writtenEntries.add("Pictures"); - pict.close(); - } + try (SequenceInputStream sis = new SequenceInputStream(pictEnum)) { + outFS.createOrUpdateDocument(sis, "Pictures"); + writtenEntries.add("Pictures"); + } catch (IllegalStateException e) { + throw (IOException)e.getCause(); + } + } } // If requested, copy over any other streams we spot, eg Macros @@ -818,6 +819,17 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { } } + private static InputStream encryptOnePicture(HSLFSlideShowEncrypted encryptedSS, HSLFPictureData data) { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + data.write(baos); + byte[] pictBytes = baos.toByteArray(); + encryptedSS.encryptPicture(pictBytes, 0); + return new ByteArrayInputStream(pictBytes); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + @Override public EncryptionInfo getEncryptionInfo() { @@ -1017,12 +1029,6 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable { super.replaceDirectory(newDirectory); } - private static class BufAccessBAOS extends ByteArrayOutputStream { - public byte[] getBuf() { - return buf; - } - } - private static class CountingOS extends OutputStream { int count; diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java b/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java index 6cf92111a6..7915ca5c66 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hsmf/datatypes/PropertiesChunk.java @@ -17,8 +17,9 @@ package org.apache.poi.hsmf.datatypes; +import static org.apache.logging.log4j.util.Unbox.box; + import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -30,6 +31,7 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.hsmf.datatypes.PropertyValue.BooleanPropertyValue; @@ -47,8 +49,6 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndian.BufferUnderrunException; -import static org.apache.logging.log4j.util.Unbox.box; - /** * <p> * A Chunk which holds (single) fixed-length properties, and pointer to the @@ -76,13 +76,13 @@ public abstract class PropertiesChunk extends Chunk { * Holds properties, indexed by type. If a property is multi-valued, or * variable length, it will be held via a {@link ChunkBasedPropertyValue}. */ - private Map<MAPIProperty, PropertyValue> properties = new HashMap<>(); + private final Map<MAPIProperty, PropertyValue> properties = new HashMap<>(); /** * The ChunkGroup that these properties apply to. Used when matching chunks * to variable sized and multi-valued properties */ - private ChunkGroup parentGroup; + private final ChunkGroup parentGroup; /** * Creates a Properties Chunk. @@ -254,7 +254,7 @@ public abstract class PropertiesChunk extends Chunk { } // Wrap and store - PropertyValue propVal = null; + PropertyValue propVal; if (isPointer) { // We'll match up the chunk later propVal = new ChunkBasedPropertyValue(prop, flags, data, type); @@ -302,16 +302,17 @@ public abstract class PropertiesChunk extends Chunk { * If an I/O error occurs. */ public void writeProperties(DirectoryEntry directory) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - List<PropertyValue> values = writeProperties(baos); - baos.close(); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { + List<PropertyValue> values = writeProperties(baos); - // write the header data with the properties declaration - directory.createDocument(PropertiesChunk.NAME, - new ByteArrayInputStream(baos.toByteArray())); + // write the header data with the properties declaration + try (InputStream is = baos.toInputStream()) { + directory.createDocument(PropertiesChunk.NAME, is); + } - // write the property values - writeNodeData(directory, values); + // write the property values + writeNodeData(directory, values); + } } /** diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java index 82baf52036..c56ae3f17f 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/record/HwmfEscape.java @@ -190,7 +190,7 @@ public class HwmfEscape implements HwmfRecord { } public interface HwmfEscapeData { - public int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException; + int init(LittleEndianInputStream leis, long recordSize, EscapeFunction escapeFunction) throws IOException; } diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java index 19fda80509..fb24af7cb4 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwmf/usermodel/HwmfEmbeddedIterator.java @@ -17,13 +17,13 @@ package org.apache.poi.hwmf.usermodel; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hwmf.record.HwmfEscape; import org.apache.poi.hwmf.record.HwmfEscape.EscapeFunction; import org.apache.poi.hwmf.record.HwmfEscape.WmfEscapeEMF; @@ -120,7 +120,7 @@ public class HwmfEmbeddedIterator implements Iterator<HwmfEmbedded> { final HwmfEmbedded emb = new HwmfEmbedded(); emb.setEmbeddedType(HwmfEmbeddedType.EMF); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); try { for (;;) { bos.write(img.getEmfData()); @@ -132,8 +132,8 @@ public class HwmfEmbeddedIterator implements Iterator<HwmfEmbedded> { return emb; } } - } catch (IOException e) { - // ByteArrayOutputStream doesn't throw IOException + } catch (IOException ignored) { + // UnsynchronizedByteArrayOutputStream doesn't throw IOException return null; } finally { emb.setData(bos.toByteArray()); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java index 8fb9055bc5..71079c3b1b 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/dev/HWPFLister.java @@ -17,8 +17,6 @@ package org.apache.poi.hwpf.dev; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -31,6 +29,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFDocumentCore; import org.apache.poi.hwpf.HWPFOldDocument; @@ -262,12 +261,11 @@ public final class HWPFLister { private static HWPFDocumentCore writeOutAndReadBack( HWPFDocumentCore original ) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream( 4096 ); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { original.write( baos ); - ByteArrayInputStream bais = new ByteArrayInputStream( - baos.toByteArray() ); - return loadDoc( bais ); + try (InputStream is = baos.toInputStream()) { + return loadDoc(is); + } } catch ( IOException e ) { throw new RuntimeException( e ); @@ -388,7 +386,7 @@ public final class HWPFLister { } } - public void dumpFileSystem() throws Exception { + public void dumpFileSystem() { System.out.println( dumpFileSystem( _doc.getDirectory() ) ); } @@ -439,8 +437,7 @@ public final class HWPFLister { } } - public void dumpPapx( boolean withProperties, boolean withSprms ) - throws Exception { + public void dumpPapx( boolean withProperties, boolean withSprms ) { if ( _doc instanceof HWPFDocument ) { System.out.println( "binary PAP pages " ); @@ -514,8 +511,8 @@ public final class HWPFLister { if ( dumpAssotiatedPapx ) { boolean hasAssotiatedPapx = false; for ( PAPX papx : _doc.getParagraphTable().getParagraphs() ) { - if ( papx.getStart() <= endOfParagraphCharOffset.intValue() - && endOfParagraphCharOffset.intValue() < papx + if ( papx.getStart() <= endOfParagraphCharOffset + && endOfParagraphCharOffset < papx .getEnd() ) { hasAssotiatedPapx = true; System.out.println( "* " + papx ); diff --git a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java index 913b4950ae..d4283a612b 100644 --- a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java +++ b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/usermodel/Picture.java @@ -18,13 +18,13 @@ package org.apache.poi.hwpf.usermodel; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.List; import java.util.zip.InflaterInputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ddf.EscherBSERecord; @@ -37,6 +37,7 @@ import org.apache.poi.ddf.EscherRecord; import org.apache.poi.hwpf.model.PICF; import org.apache.poi.hwpf.model.PICFAndOfficeArtData; import org.apache.poi.sl.image.ImageHeaderPNG; +import org.apache.poi.util.IOUtils; import org.apache.poi.util.StringUtil; /** @@ -120,10 +121,10 @@ public final class Picture { } } - private void fillImageContent() - { - if ( content != null && content.length > 0 ) + private void fillImageContent() { + if ( content != null && content.length > 0 ) { return; + } byte[] rawContent = getRawContent(); @@ -134,33 +135,21 @@ public final class Picture { * similarity in the data block contents. */ if ( matchSignature( rawContent, COMPRESSED1, 32 ) - || matchSignature( rawContent, COMPRESSED2, 32 ) ) - { - try - { - InflaterInputStream in = new InflaterInputStream( - new ByteArrayInputStream( rawContent, 33, - rawContent.length - 33 ) ); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - int readBytes; - while ( ( readBytes = in.read( buf ) ) > 0 ) - { - out.write( buf, 0, readBytes ); - } + || matchSignature( rawContent, COMPRESSED2, 32 ) ) { + try (ByteArrayInputStream bis = new ByteArrayInputStream( rawContent, 33, rawContent.length - 33 ); + InflaterInputStream in = new InflaterInputStream(bis); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + + IOUtils.copy(in, out); content = out.toByteArray(); - } - catch ( IOException e ) - { + } catch (IOException e) { /* * Problems reading from the actual ByteArrayInputStream should * never happen so this will only ever be a ZipException. */ LOGGER.atInfo().withThrowable(e).log("Possibly corrupt compression or non-compressed data"); } - } - else - { + } else { // Raw data is not compressed. content = new ImageHeaderPNG(rawContent).extractPNG(); } @@ -186,8 +175,8 @@ public final class Picture { byte[] jpegContent = getContent(); int pointer = 2; - int firstByte = jpegContent[pointer]; - int secondByte = jpegContent[pointer + 1]; + int firstByte; + int secondByte; int endOfPicture = jpegContent.length; while ( pointer < endOfPicture - 1 ) { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java b/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java index 302eacc928..6a1a830a0b 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hdgf/dev/TestVSDDumper.java @@ -26,7 +26,7 @@ import java.io.File; import java.io.PrintStream; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.Test; public class TestVSDDumper { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java b/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java index 6d39586729..d52873779c 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hemf/usermodel/TestHemfPicture.java @@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.geom.Point2D; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -34,6 +33,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hemf.record.emf.HemfComment; import org.apache.poi.hemf.record.emf.HemfComment.EmfComment; @@ -52,7 +52,6 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.RecordFormatException; import org.junit.jupiter.api.Test; -@SuppressWarnings("StatementWithEmptyBody") public class TestHemfPicture { private static final POIDataSamples ss_samples = POIDataSamples.getSpreadSheetInstance(); @@ -286,10 +285,10 @@ public class TestHemfPicture { @Test void testInfiniteLoopOnByteArray() throws Exception { try (InputStream is = ss_samples.openResourceAsStream("61294.emf")) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); IOUtils.copy(is, bos); - HemfPicture pic = new HemfPicture(new ByteArrayInputStream(bos.toByteArray())); + HemfPicture pic = new HemfPicture(bos.toInputStream()); assertThrows(RecordFormatException.class, () -> pic.forEach(r -> {})); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java index d0359a6d2e..5717e5157d 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/TestHMEFMessage.java @@ -21,15 +21,16 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hmef.attribute.MAPIAttribute; import org.apache.poi.hmef.attribute.MAPIRtfAttribute; @@ -83,10 +84,10 @@ public final class TestHMEFMessage { assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_MAPIPROPERTIES)); // Check the order - assertEquals(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty()); - assertEquals(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty()); - assertEquals(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty()); - assertEquals(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty()); + assertSame(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty()); + assertSame(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty()); + assertSame(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty()); + assertSame(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty()); // Check some that aren't there assertNull(msg.getMessageAttribute(TNEFProperty.ID_AIDOWNER)); @@ -168,7 +169,7 @@ public final class TestHMEFMessage { @Test void testNoData() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); // Header LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out); @@ -176,16 +177,14 @@ public final class TestHMEFMessage { // field LittleEndian.putUShort(0, out); - byte[] bytes = out.toByteArray(); - InputStream str = new ByteArrayInputStream(bytes); - HMEFMessage msg = new HMEFMessage(str); + HMEFMessage msg = new HMEFMessage(out.toInputStream()); assertNull(msg.getSubject()); assertNull(msg.getBody()); } @Test void testInvalidLevel() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); // Header LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out); @@ -196,10 +195,9 @@ public final class TestHMEFMessage { // invalid level LittleEndian.putUShort(90, out); - InputStream str = new ByteArrayInputStream(out.toByteArray()); IllegalStateException ex = assertThrows( IllegalStateException.class, - () -> new HMEFMessage(str) + () -> new HMEFMessage(out.toInputStream()) ); assertEquals("Unhandled level 90", ex.getMessage()); } @@ -226,7 +224,7 @@ public final class TestHMEFMessage { MAPIStringAttribute propE28b = (MAPIStringAttribute)msg.getMessageMAPIAttribute(propE28); assertNotNull(propE28b); - assertEquals(MAPIStringAttribute.class, propE28b.getClass()); + assertSame(MAPIStringAttribute.class, propE28b.getClass()); assertEquals("Zimbra - Mark Rogers", propE28b.getDataString().substring(10)); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java index a24901a96d..49ef65cb83 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/dev/TestHMEFDumper.java @@ -28,7 +28,7 @@ import java.io.File; import java.io.PrintStream; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.Test; public class TestHMEFDumper { @@ -38,13 +38,13 @@ public class TestHMEFDumper { } @Test - void main() throws Exception { + void main() { File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat"); assertDoesNotThrow(() -> doMain(file.getAbsolutePath())); } @Test - void mainFull() throws Exception { + void mainFull() { File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat"); assertDoesNotThrow(() -> doMain("--full", file.getAbsolutePath())); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java index 4a786f5bca..81912bbba5 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java @@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Arrays; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.util.TempFile; import org.junit.jupiter.api.Test; @@ -62,13 +62,13 @@ public class TestHMEFContentsExtractor { POIDataSamples samples = POIDataSamples.getHMEFInstance(); File winmailTNEFFile = samples.getFile("quick-winmail.dat"); HMEFContentsExtractor extractor = new HMEFContentsExtractor(winmailTNEFFile); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - extractor.extractMessageBody(out); - assertTrue(out.size() > 0); - byte[] expectedMagic = new byte[] { '{', '\\', 'r', 't', 'f' }; - byte[] magic = Arrays.copyOf(out.toByteArray(), 5); - assertArrayEquals(expectedMagic, magic, "RTF magic number"); - out.close(); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { + extractor.extractMessageBody(out); + assertTrue(out.size() > 0); + byte[] expectedMagic = new byte[]{'{', '\\', 'r', 't', 'f'}; + byte[] magic = Arrays.copyOf(out.toByteArray(), 5); + assertArrayEquals(expectedMagic, magic, "RTF magic number"); + } } @Test diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java index 82b3a46091..9a08f18eb6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/HSLFTestDataSamples.java @@ -17,12 +17,11 @@ package org.apache.poi.hslf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -50,32 +49,30 @@ public class HSLFTestDataSamples { } /** - * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back + * Writes a slideshow to a {@code UnsynchronizedByteArrayOutputStream} and reads it back * from a {@code ByteArrayInputStream}.<p> * Useful for verifying that the serialisation round trip */ public static HSLFSlideShowImpl writeOutAndReadBack(HSLFSlideShowImpl original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSLFSlideShowImpl(bais); + try (InputStream is = baos.toInputStream()) { + return new HSLFSlideShowImpl(is); + } } catch (IOException e) { throw new RuntimeException(e); } } /** - * Writes a slideshow to a {@code ByteArrayOutputStream} and reads it back + * Writes a slideshow to a {@code UnsynchronizedByteArrayOutputStream} and reads it back * from a {@code ByteArrayInputStream}.<p> * Useful for verifying that the serialisation round trip */ public static HSLFSlideShow writeOutAndReadBack(HSLFSlideShow original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSLFSlideShow(bais); + return new HSLFSlideShow(baos.toInputStream()); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java index 774b1fb91b..2d795452b9 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestPOIDocumentScratchpad.java @@ -21,22 +21,18 @@ package org.apache.poi.hslf; +import static org.apache.poi.POIDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import org.apache.poi.POIDataSamples; import org.apache.poi.POIDocument; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.hwpf.HWPFTestDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -47,23 +43,11 @@ import org.junit.jupiter.api.Test; * which are part of the scratchpad (not main) */ public final class TestPOIDocumentScratchpad { - // The POI Documents to work on - private POIDocument doc; - private POIDocument doc2; - - /** - * Set things up, using a PowerPoint document and - * a Word Document for our testing - */ - @BeforeEach - void setUp() throws IOException { - doc = new HSLFSlideShowImpl(POIDataSamples.getSlideShowInstance().openResourceAsStream("basic_test_ppt_file.ppt")); - doc2 = HWPFTestDataSamples.openSampleFile("test2.doc"); - } - @Test - void testReadProperties() { - testReadPropertiesHelper(doc); + void testReadProperties() throws IOException { + try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt")) { + testReadPropertiesHelper(doc); + } } private void testReadPropertiesHelper(POIDocument docPH) { @@ -77,49 +61,46 @@ public final class TestPOIDocumentScratchpad { } @Test - void testReadProperties2() { - // Check again on the word one - assertNotNull(doc2.getDocumentSummaryInformation()); - assertNotNull(doc2.getSummaryInformation()); - - assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor()); - assertEquals("", doc2.getSummaryInformation().getKeywords()); - assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); + void testReadProperties2() throws IOException { + try (POIDocument doc2 = HWPFTestDataSamples.openSampleFile("test2.doc")) { + // Check again on the word one + assertNotNull(doc2.getDocumentSummaryInformation()); + assertNotNull(doc2.getSummaryInformation()); + + assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor()); + assertEquals("", doc2.getSummaryInformation().getKeywords()); + assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); + } } @Test void testWriteProperties() throws IOException { // Just check we can write them back out into a filesystem - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.writeProperties(outFS); - - // Should now hold them - assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)); - outFS.close(); + try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); + POIFSFileSystem outFS = new POIFSFileSystem()) { + doc.writeProperties(outFS); + + // Should now hold them + assertNotNull(outFS.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); + assertNotNull(outFS.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME)); + } } @Test void testWriteReadProperties() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // Write them out - POIFSFileSystem outFS = new POIFSFileSystem(); - doc.writeProperties(outFS); - outFS.writeFilesystem(baos); - - // Create a new version - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem inFS = new POIFSFileSystem(bais); - - // Check they're still there - POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS); - ppt.readProperties(); - - // Delegate test - testReadPropertiesHelper(ppt); - - ppt.close(); - inFS.close(); + try (POIDocument doc = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); + POIFSFileSystem outFS = new POIFSFileSystem()) { + doc.writeProperties(outFS); + + // Check they're still there + try (POIFSFileSystem inFS = writeOutAndReadBack(outFS); + POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS)) { + ppt.readProperties(); + + // Delegate test + testReadPropertiesHelper(ppt); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java index 5aec58964a..687888a69a 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWrite.java @@ -25,12 +25,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -56,7 +55,7 @@ public final class TestReWrite { HSLFSlideShowImpl hss = new HSLFSlideShowImpl(pfs)) { // Write out to a byte array, and to a temp file - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); hss.write(baos); final File file = TempFile.createTempFile("TestHSLF", ".ppt"); @@ -66,8 +65,7 @@ public final class TestReWrite { // Build an input stream of it, and read back as a POIFS from the stream - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - try (POIFSFileSystem npfS = new POIFSFileSystem(bais); + try (POIFSFileSystem npfS = new POIFSFileSystem(baos.toInputStream()); // And the same on the temp file POIFSFileSystem npfF = new POIFSFileSystem(file)) { @@ -97,18 +95,16 @@ public final class TestReWrite { assertNotNull(pfsC.getRoot().getEntry("Macros")); // Write out normally, will loose the macro stream - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); hssC.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - try (POIFSFileSystem pfsNew = new POIFSFileSystem(bais)) { + try (POIFSFileSystem pfsNew = new POIFSFileSystem(baos.toInputStream())) { assertFalse(pfsNew.getRoot().hasEntry("Macros")); } // But if we write out with nodes preserved, will be there baos.reset(); hssC.write(baos, true); - bais = new ByteArrayInputStream(baos.toByteArray()); - try (POIFSFileSystem pfsNew = new POIFSFileSystem(bais)) { + try (POIFSFileSystem pfsNew = new POIFSFileSystem(baos.toInputStream())) { assertTrue(pfsNew.getRoot().hasEntry("Macros")); } } @@ -138,14 +134,11 @@ public final class TestReWrite { assertDoesNotThrow(ss::getNotes); // Now write out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); hss.write(baos); - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - // Use POIFS to query that lot - try (POIFSFileSystem npfs = new POIFSFileSystem(bais)) { + try (POIFSFileSystem npfs = new POIFSFileSystem(baos.toInputStream())) { assertSame(pfs, npfs); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java index 3aca727bee..b2991c1533 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/TestReWriteSanity.java @@ -18,14 +18,15 @@ package org.apache.poi.hslf; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; import static org.apache.poi.POITestCase.assertContains; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; +import org.apache.commons.io.output.CountingOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.record.CurrentUserAtom; import org.apache.poi.hslf.record.PersistPtrHolder; @@ -63,55 +64,50 @@ public final class TestReWriteSanity { @Test void testUserEditAtomsRight() throws Exception { // Write out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ss.write(baos); - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - // Create a new one from that - HSLFSlideShowImpl wss = new HSLFSlideShowImpl(bais); - - // Find the location of the PersistPtrIncrementalBlocks and - // UserEditAtoms - Record[] r = wss.getRecords(); - Map<Integer,Record> pp = new HashMap<>(); - Map<Integer,Object> ue = new HashMap<>(); - ue.put(Integer.valueOf(0),Integer.valueOf(0)); // Will show 0 if first - int pos = 0; - int lastUEPos = -1; - - for (final Record rec : r) { - if(rec instanceof PersistPtrHolder) { - pp.put(Integer.valueOf(pos), rec); - } - if(rec instanceof UserEditAtom) { - ue.put(Integer.valueOf(pos), rec); - lastUEPos = pos; + try (HSLFSlideShowImpl wss = new HSLFSlideShowImpl(baos.toInputStream())) { + + // Find the location of the PersistPtrIncrementalBlocks and + // UserEditAtoms + Record[] r = wss.getRecords(); + Map<Integer, Record> pp = new HashMap<>(); + Map<Integer, Object> ue = new HashMap<>(); + ue.put(0, 0); // Will show 0 if first + int lastUEPos = -1; + + CountingOutputStream cos = new CountingOutputStream(NULL_OUTPUT_STREAM); + for (final Record rec : r) { + int pos = cos.getCount(); + if (rec instanceof PersistPtrHolder) { + pp.put(pos, rec); + } + if (rec instanceof UserEditAtom) { + ue.put(pos, rec); + lastUEPos = pos; + } + + rec.writeOut(cos); } - ByteArrayOutputStream bc = new ByteArrayOutputStream(); - rec.writeOut(bc); - pos += bc.size(); - } - - // Check that the UserEditAtom's point to right stuff - for (final Record rec : r) { - if(rec instanceof UserEditAtom) { - UserEditAtom uea = (UserEditAtom)rec; - int luPos = uea.getLastUserEditAtomOffset(); - int ppPos = uea.getPersistPointersOffset(); + // Check that the UserEditAtom's point to right stuff + for (final Record rec : r) { + if (rec instanceof UserEditAtom) { + UserEditAtom uea = (UserEditAtom) rec; + int luPos = uea.getLastUserEditAtomOffset(); + int ppPos = uea.getPersistPointersOffset(); - assertContains(ue, Integer.valueOf(luPos)); - assertContains(pp, Integer.valueOf(ppPos)); + assertContains(ue, luPos); + assertContains(pp, ppPos); + } } - } - - // Check that the CurrentUserAtom points to the right UserEditAtom - CurrentUserAtom cua = wss.getCurrentUserAtom(); - int listedUEPos = (int)cua.getCurrentEditOffset(); - assertEquals(lastUEPos,listedUEPos); - wss.close(); + // Check that the CurrentUserAtom points to the right UserEditAtom + CurrentUserAtom cua = wss.getCurrentUserAtom(); + int listedUEPos = (int) cua.getCurrentEditOffset(); + assertEquals(lastUEPos, listedUEPos); + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java index 980d6538e8..ca5b1ac380 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/BaseTestPPTIterating.java @@ -34,7 +34,7 @@ import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.exceptions.OldPowerPointFormatException; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.parallel.Isolated; diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java index 8ee2010fa7..3ac7adb84d 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/dev/TestSLWTListing.java @@ -23,7 +23,7 @@ import java.io.IOException; import java.io.PrintStream; import org.apache.poi.EmptyFileException; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java index bd8d634b12..5525cdf808 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java @@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -35,7 +34,6 @@ import java.util.List; import com.zaxxer.sparsebits.SparseBitSet; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.codec.binary.Hex; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFObjectShape; import org.apache.poi.hslf.usermodel.HSLFSlideShow; @@ -50,7 +48,6 @@ import org.apache.poi.sl.usermodel.ObjectShape; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NullOutputStream; import org.junit.jupiter.api.Test; /** diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java index a90c591190..336f6bc4f2 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestMovieShape.java @@ -22,9 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFPictureData; import org.apache.poi.hslf.usermodel.HSLFSlide; @@ -33,11 +32,11 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.junit.jupiter.api.Test; /** - * Test <code>MovieShape</code> object. + * Test {@code MovieShape} object. */ public final class TestMovieShape { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); @Test void testCreate() throws Exception { @@ -58,10 +57,10 @@ public final class TestMovieShape { shape.setAutoPlay(false); assertFalse(shape.isAutoPlay()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ppt.write(out); - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); + ppt = new HSLFSlideShow(out.toInputStream()); slide = ppt.getSlides().get(0); shape = (MovieShape)slide.getShapes().get(0); assertEquals(path, shape.getPath()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java index 9c561fb18e..dbab7b9fdc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestOleEmbedding.java @@ -21,13 +21,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFObjectData; import org.apache.poi.hslf.usermodel.HSLFObjectShape; @@ -146,10 +145,10 @@ public final class TestOleEmbedding { slide2.addShape(oleShape2); oleShape2.setAnchor(new Rectangle2D.Double(100,100,100,100)); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); ppt.write(bos); - ppt = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); + ppt = new HSLFSlideShow(bos.toInputStream()); HSLFObjectShape comp = (HSLFObjectShape)ppt.getSlides().get(0).getShapes().get(0); byte[] compData = IOUtils.toByteArray(comp.getObjectData().getInputStream()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java index e47467c2ba..426eee09fb 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSetBoldItalic.java @@ -17,12 +17,16 @@ package org.apache.poi.hslf.model; -import static org.junit.jupiter.api.Assertions.*; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.usermodel.HSLFSlide; +import org.apache.poi.hslf.usermodel.HSLFSlideShow; +import org.apache.poi.hslf.usermodel.HSLFTextBox; +import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.junit.jupiter.api.Test; /** @@ -35,46 +39,46 @@ public final class TestSetBoldItalic { */ @Test void testTextBoxWrite() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide sl = ppt.createSlide(); - HSLFTextRun rt; - - String val = "Hello, World!"; + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide sl = ppt.createSlide(); + HSLFTextRun rt; - // Create a new textbox, and give it lots of properties - HSLFTextBox txtbox = new HSLFTextBox(); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - txtbox.setText(val); - rt.setFontSize(42d); - rt.setBold(true); - rt.setItalic(true); - rt.setUnderlined(false); - sl.addShape(txtbox); + String val = "Hello, World!"; - // Check it before save - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); + // Create a new textbox, and give it lots of properties + HSLFTextBox txtbox = new HSLFTextBox(); + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + txtbox.setText(val); + rt.setFontSize(42d); + rt.setBold(true); + rt.setItalic(true); + rt.setUnderlined(false); + sl.addShape(txtbox); - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); + // Check it before save + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - sl = ppt.getSlides().get(0); + // Serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + sl = ppt2.getSlides().get(0); - txtbox = (HSLFTextBox)sl.getShapes().get(0); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + txtbox = (HSLFTextBox) sl.getShapes().get(0); + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - // Check after save - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); + // Check after save + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertFalse(rt.isUnderlined()); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java index 774fe06468..84af931507 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java @@ -17,6 +17,9 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.openSampleFileStream; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.apache.poi.sl.usermodel.BaseTestSlideShow.getColor; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -27,14 +30,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.Dimension; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.AbstractEscherOptRecord; import org.apache.poi.ddf.EscherDgRecord; import org.apache.poi.ddf.EscherDggRecord; @@ -56,68 +55,52 @@ import org.apache.poi.hslf.usermodel.HSLFTextShape; import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Test drawing shapes via Graphics2D */ public final class TestShapes { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - private HSLFSlideShow ppt; - private HSLFSlideShow pptB; - - @BeforeEach - void setUp() throws Exception { - try (InputStream is1 = _slTests.openResourceAsStream("empty.ppt"); - InputStream is2 = _slTests.openResourceAsStream("empty_textbox.ppt")) { - ppt = new HSLFSlideShow(is1); - pptB = new HSLFSlideShow(is2); - } - } - @Test void graphics() throws IOException { - HSLFSlide slide = ppt.createSlide(); - - HSLFLine line = new HSLFLine(); - java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60); - line.setAnchor(lineAnchor); - line.setLineWidth(3); - line.setLineDash(LineDash.DASH); - line.setLineColor(Color.red); - slide.addShape(line); - - HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE); - Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111); - ellipse.setAnchor(ellipseAnchor); - ellipse.setLineWidth(2); - ellipse.setLineDash(LineDash.SOLID); - ellipse.setLineColor(Color.green); - ellipse.setFillColor(Color.lightGray); - slide.addShape(ellipse); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - //read ppt from byte array - - HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - assertEquals(1, ppt2.getSlides().size()); - - slide = ppt2.getSlides().get(0); - List<HSLFShape> shape = slide.getShapes(); - assertEquals(2, shape.size()); - - assertTrue(shape.get(0) instanceof HSLFLine); //group shape - assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape + try (HSLFSlideShow ppt = getSlideShow("empty.ppt")) { + HSLFSlide slide = ppt.createSlide(); + + HSLFLine line = new HSLFLine(); + java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60); + line.setAnchor(lineAnchor); + line.setLineWidth(3); + line.setLineDash(LineDash.DASH); + line.setLineColor(Color.red); + slide.addShape(line); + + HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE); + Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111); + ellipse.setAnchor(ellipseAnchor); + ellipse.setLineWidth(2); + ellipse.setLineDash(LineDash.SOLID); + ellipse.setLineColor(Color.green); + ellipse.setFillColor(Color.lightGray); + slide.addShape(ellipse); + + //read ppt from byte array + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + assertEquals(1, ppt2.getSlides().size()); + + slide = ppt2.getSlides().get(0); + List<HSLFShape> shape = slide.getShapes(); + assertEquals(2, shape.size()); + + assertTrue(shape.get(0) instanceof HSLFLine); //group shape + assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape + + assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape + assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape - assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape - assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape - - ppt2.close(); + } + } } /** @@ -125,40 +108,41 @@ public final class TestShapes { */ @Test void textBoxRead() throws IOException { - ppt = new HSLFSlideShow(_slTests.openResourceAsStream("with_textbox.ppt")); - HSLFSlide sl = ppt.getSlides().get(0); - for (HSLFShape sh : sl.getShapes()) { - assertTrue(sh instanceof HSLFTextBox); - HSLFTextBox txtbox = (HSLFTextBox)sh; - String text = txtbox.getText(); - assertNotNull(text); - - assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1); - HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - switch (text) { - case "Hello, World!!!": - assertNotNull(rt.getFontSize()); - assertEquals(32, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - break; - case "I am just a poor boy": - assertNotNull(rt.getFontSize()); - assertEquals(44, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - break; - case "This is Times New Roman": - assertNotNull(rt.getFontSize()); - assertEquals(16, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertTrue(rt.isUnderlined()); - break; - case "Plain Text": - assertNotNull(rt.getFontSize()); - assertEquals(18, rt.getFontSize(), 0); - break; + try (HSLFSlideShow ppt = getSlideShow("with_textbox.ppt")) { + HSLFSlide sl = ppt.getSlides().get(0); + for (HSLFShape sh : sl.getShapes()) { + assertTrue(sh instanceof HSLFTextBox); + HSLFTextBox txtbox = (HSLFTextBox) sh; + String text = txtbox.getText(); + assertNotNull(text); + + assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1); + HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + + switch (text) { + case "Hello, World!!!": + assertNotNull(rt.getFontSize()); + assertEquals(32, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + break; + case "I am just a poor boy": + assertNotNull(rt.getFontSize()); + assertEquals(44, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + break; + case "This is Times New Roman": + assertNotNull(rt.getFontSize()); + assertEquals(16, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertTrue(rt.isUnderlined()); + break; + case "Plain Text": + assertNotNull(rt.getFontSize()); + assertEquals(18, rt.getFontSize(), 0); + break; + } } } } @@ -166,43 +150,42 @@ public final class TestShapes { @SuppressWarnings("unused") @Test void testParagraphs() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - HSLFSlide slide = ss.createSlide(); - HSLFTextBox shape = new HSLFTextBox(); - HSLFTextRun p1r1 = shape.setText("para 1 run 1. "); - HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false); - HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true); - HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false); - p1r1.setFontColor(Color.black); - p1r2.setFontColor(Color.red); - p2r1.setFontColor(Color.yellow); - p2r2.setStrikethrough(true); - // run 3 has same text properties as run 2 and will be merged when saving - HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false); - shape.setAnchor(new Rectangle2D.Double(100,100,100,10)); - slide.addShape(shape); - shape.resizeToFitText(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ss.write(bos); - - ss = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); - slide = ss.getSlides().get(0); - HSLFTextBox tb = (HSLFTextBox)slide.getShapes().get(0); - List<HSLFTextParagraph> para = tb.getTextParagraphs(); - HSLFTextRun tr = para.get(0).getTextRuns().get(0); - assertEquals("para 1 run 1. ", tr.getRawText()); - assertEquals(Color.black, getColor(tr.getFontColor())); - tr = para.get(0).getTextRuns().get(1); - assertEquals("para 1 run 2.\r", tr.getRawText()); - assertEquals(Color.red, getColor(tr.getFontColor())); - tr = para.get(1).getTextRuns().get(0); - assertEquals("para 2 run 1. ", tr.getRawText()); - assertEquals(Color.yellow, getColor(tr.getFontColor())); - tr = para.get(1).getTextRuns().get(1); - assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText()); - assertEquals(Color.black, getColor(tr.getFontColor())); - assertTrue(tr.isStrikethrough()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide = ppt1.createSlide(); + HSLFTextBox shape = new HSLFTextBox(); + HSLFTextRun p1r1 = shape.setText("para 1 run 1. "); + HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false); + HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true); + HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false); + p1r1.setFontColor(Color.black); + p1r2.setFontColor(Color.red); + p2r1.setFontColor(Color.yellow); + p2r2.setStrikethrough(true); + // run 3 has same text properties as run 2 and will be merged when saving + HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false); + shape.setAnchor(new Rectangle2D.Double(100, 100, 100, 10)); + slide.addShape(shape); + shape.resizeToFitText(); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + HSLFTextBox tb = (HSLFTextBox) slide.getShapes().get(0); + List<HSLFTextParagraph> para = tb.getTextParagraphs(); + HSLFTextRun tr = para.get(0).getTextRuns().get(0); + assertEquals("para 1 run 1. ", tr.getRawText()); + assertEquals(Color.black, getColor(tr.getFontColor())); + tr = para.get(0).getTextRuns().get(1); + assertEquals("para 1 run 2.\r", tr.getRawText()); + assertEquals(Color.red, getColor(tr.getFontColor())); + tr = para.get(1).getTextRuns().get(0); + assertEquals("para 2 run 1. ", tr.getRawText()); + assertEquals(Color.yellow, getColor(tr.getFontColor())); + tr = para.get(1).getTextRuns().get(1); + assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText()); + assertEquals(Color.black, getColor(tr.getFontColor())); + assertTrue(tr.isStrikethrough()); + } + } } @@ -212,169 +195,158 @@ public final class TestShapes { */ @Test void textBoxWriteBytes() throws IOException { - ppt = new HSLFSlideShow(); - HSLFSlide sl = ppt.createSlide(); - HSLFTextRun rt; - - String val = "Hello, World!"; - - // Create a new textbox, and give it lots of properties - HSLFTextBox txtbox = new HSLFTextBox(); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - txtbox.setText(val); - rt.setFontFamily("Arial"); - rt.setFontSize(42d); - rt.setBold(true); - rt.setItalic(true); - rt.setUnderlined(false); - rt.setFontColor(Color.red); - sl.addShape(txtbox); - - // Check it before save - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(val, rt.getRawText()); - assertNotNull(rt.getFontSize()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - assertEquals(Color.red, getColor(rt.getFontColor())); - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - sl = ppt2.getSlides().get(0); - - txtbox = (HSLFTextBox)sl.getShapes().get(0); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - // Check after save - assertEquals(val, rt.getRawText()); - assertNotNull(rt.getFontSize()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - assertEquals(Color.red, getColor(rt.getFontColor())); - - ppt2.close(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide sl = ppt1.createSlide(); + + String val = "Hello, World!"; + + // Create a new textbox, and give it lots of properties + HSLFTextBox txtbox = new HSLFTextBox(); + HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + txtbox.setText(val); + rt.setFontFamily("Arial"); + rt.setFontSize(42d); + rt.setBold(true); + rt.setItalic(true); + rt.setUnderlined(false); + rt.setFontColor(Color.red); + sl.addShape(txtbox); + + // Check it before save + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertFalse(rt.isUnderlined()); + assertEquals("Arial", rt.getFontFamily()); + assertEquals(Color.red, getColor(rt.getFontColor())); + + // Serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + sl = ppt2.getSlides().get(0); + + txtbox = (HSLFTextBox) sl.getShapes().get(0); + rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); + + // Check after save + assertEquals(val, rt.getRawText()); + assertNotNull(rt.getFontSize()); + assertEquals(42, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isItalic()); + assertFalse(rt.isUnderlined()); + assertEquals("Arial", rt.getFontFamily()); + assertEquals(Color.red, getColor(rt.getFontColor())); + } + } } /** * Test with an empty text box */ @Test - void emptyTextBox() { - assertEquals(2, pptB.getSlides().size()); - HSLFSlide s1 = pptB.getSlides().get(0); - HSLFSlide s2 = pptB.getSlides().get(1); - - // Check we can get the shapes count - assertEquals(2, s1.getShapes().size()); - assertEquals(2, s2.getShapes().size()); + void emptyTextBox() throws IOException { + try (HSLFSlideShow ppt = getSlideShow("empty_textbox.ppt")) { + assertEquals(2, ppt.getSlides().size()); + HSLFSlide s1 = ppt.getSlides().get(0); + HSLFSlide s2 = ppt.getSlides().get(1); + + // Check we can get the shapes count + assertEquals(2, s1.getShapes().size()); + assertEquals(2, s2.getShapes().size()); + } } /** * If you iterate over text shapes in a slide and collect them in a set * it must be the same as returned by Slide.getTextRuns(). */ - @Test - void textBoxSet() throws IOException { - textBoxSet("with_textbox.ppt"); - textBoxSet("basic_test_ppt_file.ppt"); - textBoxSet("next_test_ppt_file.ppt"); - textBoxSet("Single_Coloured_Page.ppt"); - textBoxSet("Single_Coloured_Page_With_Fonts_and_Alignments.ppt"); - textBoxSet("incorrect_slide_order.ppt"); - } - - private void textBoxSet(String filename) throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(filename)); - for (HSLFSlide sld : ss.getSlides()) { - ArrayList<String> lst1 = new ArrayList<>(); - for (List<HSLFTextParagraph> txt : sld.getTextParagraphs()) { - for (HSLFTextParagraph p : txt) { - for (HSLFTextRun r : p) { - lst1.add(r.getRawText()); + @ParameterizedTest + @ValueSource(strings = { + "with_textbox.ppt", + "basic_test_ppt_file.ppt", + "next_test_ppt_file.ppt", + "Single_Coloured_Page.ppt", + "Single_Coloured_Page_With_Fonts_and_Alignments.ppt", + "incorrect_slide_order.ppt" + }) + void textBoxSet(String filename) throws IOException { + try (HSLFSlideShow ppt = getSlideShow(filename)) { + for (HSLFSlide sld : ppt.getSlides()) { + ArrayList<String> lst1 = new ArrayList<>(); + for (List<HSLFTextParagraph> txt : sld.getTextParagraphs()) { + for (HSLFTextParagraph p : txt) { + for (HSLFTextRun r : p) { + lst1.add(r.getRawText()); + } } } - } - ArrayList<String> lst2 = new ArrayList<>(); - for (HSLFShape sh : sld.getShapes()) { - if (sh instanceof HSLFTextShape){ - HSLFTextShape tbox = (HSLFTextShape)sh; - for (HSLFTextParagraph p : tbox.getTextParagraphs()) { - for (HSLFTextRun r : p) { - lst2.add(r.getRawText()); + ArrayList<String> lst2 = new ArrayList<>(); + for (HSLFShape sh : sld.getShapes()) { + if (sh instanceof HSLFTextShape) { + HSLFTextShape tbox = (HSLFTextShape) sh; + for (HSLFTextParagraph p : tbox.getTextParagraphs()) { + for (HSLFTextRun r : p) { + lst2.add(r.getRawText()); + } } } } + assertTrue(lst1.containsAll(lst2)); + assertTrue(lst2.containsAll(lst1)); } - assertTrue(lst1.containsAll(lst2)); - assertTrue(lst2.containsAll(lst1)); } - ss.close(); } /** - * Test adding shapes to <code>ShapeGroup</code> + * Test adding shapes to {@code ShapeGroup} */ @Test void shapeGroup() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - - HSLFSlide slide = ss.createSlide(); - Dimension pgsize = ss.getPageSize(); - - HSLFGroupShape group = new HSLFGroupShape(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { - group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight())); - slide.addShape(group); + HSLFSlide slide = ppt1.createSlide(); + Dimension pgsize = ppt1.getPageSize(); - HSLFPictureData data = ss.addPicture(_slTests.readFile("clock.jpg"), PictureType.JPEG); - HSLFPictureShape pict = new HSLFPictureShape(data, group); - pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200)); - group.addShape(pict); + HSLFGroupShape group = new HSLFGroupShape(); - HSLFLine line = new HSLFLine(group); - line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0)); - group.addShape(line); + group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight())); + slide.addShape(group); - //serialize and read again. - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ss.write(out); - out.close(); - ss.close(); + HSLFPictureData data = ppt1.addPicture(openSampleFileStream("clock.jpg"), PictureType.JPEG); + HSLFPictureShape pict = new HSLFPictureShape(data, group); + pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200)); + group.addShape(pict); - ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray()); - ss = new HSLFSlideShow(is); - is.close(); + HSLFLine line = new HSLFLine(group); + line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0)); + group.addShape(line); - slide = ss.getSlides().get(0); + //serialize and read again. + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { - List<HSLFShape> shape = slide.getShapes(); - assertEquals(1, shape.size()); - assertTrue(shape.get(0) instanceof HSLFGroupShape); + slide = ppt2.getSlides().get(0); - group = (HSLFGroupShape)shape.get(0); - List<HSLFShape> grshape = group.getShapes(); - assertEquals(2, grshape.size()); - assertTrue(grshape.get(0) instanceof HSLFPictureShape); - assertTrue(grshape.get(1) instanceof HSLFLine); + List<HSLFShape> shape = slide.getShapes(); + assertEquals(1, shape.size()); + assertTrue(shape.get(0) instanceof HSLFGroupShape); - pict = (HSLFPictureShape)grshape.get(0); - assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor()); + group = (HSLFGroupShape) shape.get(0); + List<HSLFShape> grshape = group.getShapes(); + assertEquals(2, grshape.size()); + assertTrue(grshape.get(0) instanceof HSLFPictureShape); + assertTrue(grshape.get(1) instanceof HSLFLine); - line = (HSLFLine)grshape.get(1); - assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor()); + pict = (HSLFPictureShape) grshape.get(0); + assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor()); - ss.close(); + line = (HSLFLine) grshape.get(1); + assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor()); + } + } } /** @@ -382,29 +354,24 @@ public final class TestShapes { */ @Test void removeShapes() throws IOException { - String file = "with_textbox.ppt"; - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(file)); - HSLFSlide sl = ss.getSlides().get(0); - List<HSLFShape> sh = sl.getShapes(); - assertEquals(4, sh.size(), "expected four shaped in " + file); - //remove all - for (int i = 0; i < sh.size(); i++) { - boolean ok = sl.removeShape(sh.get(i)); - assertTrue(ok, "Failed to delete shape #" + i); + try (HSLFSlideShow ppt1 = getSlideShow("with_textbox.ppt")) { + HSLFSlide sl = ppt1.getSlides().get(0); + List<HSLFShape> sh = sl.getShapes(); + assertEquals(4, sh.size()); + //remove all + for (int i = 0; i < sh.size(); i++) { + boolean ok = sl.removeShape(sh.get(i)); + assertTrue(ok, "Failed to delete shape #" + i); + } + //now Slide.getShapes() should return an empty array + assertEquals(0, sl.getShapes().size()); + + //serialize and read again. The file should be readable and contain no shapes + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + sl = ppt2.getSlides().get(0); + assertEquals(0, sl.getShapes().size()); + } } - //now Slide.getShapes() should return an empty array - assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file); - - //serialize and read again. The file should be readable and contain no shapes - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ss.write(out); - out.close(); - ss.close(); - - ss = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - sl = ss.getSlides().get(0); - assertEquals(0, sl.getShapes().size(), "expected 0 shaped in " + file); - ss.close(); } @Test @@ -424,79 +391,78 @@ public final class TestShapes { @Test void shapeId() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - HSLFSlide slide = ss.createSlide(); - - //EscherDgg is a document-level record which keeps track of the drawing groups - EscherDggRecord dgg = ss.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); - EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord(); - - int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt - int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId - - int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide - int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide - //insert 3 shapes and make sure the Ids are properly incremented - for (int i = 0; i < 3; i++) { - HSLFShape shape = new HSLFLine(); - assertEquals(0, shape.getShapeId()); - slide.addShape(shape); - assertTrue(shape.getShapeId() > 0); - - //check that EscherDgRecord is updated - assertEquals(shape.getShapeId(), dg.getLastMSOSPID()); - assertEquals(dgMaxId + 1, dg.getLastMSOSPID()); - assertEquals(dgShapesUsed + 1, dg.getNumShapes()); - - //check that EscherDggRecord is updated - assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @"+i); - assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @"+i); - assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @"+i); - - dggShapesUsed = dgg.getNumShapesSaved(); - dggMaxId = dgg.getShapeIdMax(); - dgMaxId = dg.getLastMSOSPID(); - dgShapesUsed = dg.getNumShapes(); - } + try (HSLFSlideShow ppt = new HSLFSlideShow()) { + HSLFSlide slide = ppt.createSlide(); + + //EscherDgg is a document-level record which keeps track of the drawing groups + EscherDggRecord dgg = ppt.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); + EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord(); + + int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt + int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId + + int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide + int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide + //insert 3 shapes and make sure the Ids are properly incremented + for (int i = 0; i < 3; i++) { + HSLFShape shape = new HSLFLine(); + assertEquals(0, shape.getShapeId()); + slide.addShape(shape); + assertTrue(shape.getShapeId() > 0); + + //check that EscherDgRecord is updated + assertEquals(shape.getShapeId(), dg.getLastMSOSPID()); + assertEquals(dgMaxId + 1, dg.getLastMSOSPID()); + assertEquals(dgShapesUsed + 1, dg.getNumShapes()); + + //check that EscherDggRecord is updated + assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax(), "mismatch @" + i); + assertEquals(dggMaxId + 1, dgg.getShapeIdMax(), "mismatch @" + i); + assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved(), "mismatch @" + i); + + dggShapesUsed = dgg.getNumShapesSaved(); + dggMaxId = dgg.getShapeIdMax(); + dgMaxId = dg.getLastMSOSPID(); + dgShapesUsed = dg.getNumShapes(); + } - //For each drawing group PPT allocates clusters with size=1024 - //if the number of shapes is greater that 1024 a new cluster is allocated - //make sure it is so - int numClusters = dgg.getNumIdClusters(); - for (int i = 0; i < 1025; i++) { - HSLFShape shape = new HSLFLine(); - slide.addShape(shape); + //For each drawing group PPT allocates clusters with size=1024 + //if the number of shapes is greater that 1024 a new cluster is allocated + //make sure it is so + int numClusters = dgg.getNumIdClusters(); + for (int i = 0; i < 1025; i++) { + HSLFShape shape = new HSLFLine(); + slide.addShape(shape); + } + assertEquals(numClusters + 1, dgg.getNumIdClusters()); } - assertEquals(numClusters + 1, dgg.getNumIdClusters()); - ss.close(); } @Test void lineColor() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream("51731.ppt")); - List<HSLFShape> shape = ss.getSlides().get(0).getShapes(); - - assertEquals(4, shape.size()); + try (HSLFSlideShow ss = getSlideShow("51731.ppt")) { + List<HSLFShape> shape = ss.getSlides().get(0).getShapes(); - HSLFTextShape sh1 = (HSLFTextShape)shape.get(0); - assertEquals("Hello Apache POI", sh1.getText()); - assertNull(sh1.getLineColor()); + assertEquals(4, shape.size()); - HSLFTextShape sh2 = (HSLFTextShape)shape.get(1); - assertEquals("Why are you showing this border?", sh2.getText()); - assertNull(sh2.getLineColor()); + HSLFTextShape sh1 = (HSLFTextShape) shape.get(0); + assertEquals("Hello Apache POI", sh1.getText()); + assertNull(sh1.getLineColor()); - HSLFTextShape sh3 = (HSLFTextShape)shape.get(2); - assertEquals("Text in a black border", sh3.getText()); - assertEquals(Color.black, sh3.getLineColor()); - assertEquals(0.75, sh3.getLineWidth(), 0); + HSLFTextShape sh2 = (HSLFTextShape) shape.get(1); + assertEquals("Why are you showing this border?", sh2.getText()); + assertNull(sh2.getLineColor()); - HSLFTextShape sh4 = (HSLFTextShape)shape.get(3); - assertEquals("Border width is 5 pt", sh4.getText()); - assertEquals(Color.black, sh4.getLineColor()); - assertEquals(5.0, sh4.getLineWidth(), 0); + HSLFTextShape sh3 = (HSLFTextShape) shape.get(2); + assertEquals("Text in a black border", sh3.getText()); + assertEquals(Color.black, sh3.getLineColor()); + assertEquals(0.75, sh3.getLineWidth(), 0); - ss.close(); + HSLFTextShape sh4 = (HSLFTextShape) shape.get(3); + assertEquals("Border width is 5 pt", sh4.getText()); + assertEquals(Color.black, sh4.getLineColor()); + assertEquals(5.0, sh4.getLineWidth(), 0); + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java index a50958ff79..8c00994768 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlideMaster.java @@ -17,28 +17,32 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.BODY; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_BODY; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.CENTER_TITLE; import static org.apache.poi.sl.usermodel.TextShape.TextPlaceholder.TITLE; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; +import java.util.Objects; +import java.util.stream.IntStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp; import org.apache.poi.hslf.model.textproperties.TextProp; import org.apache.poi.hslf.record.Environment; +import org.apache.poi.hslf.usermodel.HSLFFontInfo; import org.apache.poi.hslf.usermodel.HSLFMasterSheet; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideMaster; import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; import org.apache.poi.hslf.usermodel.HSLFTextParagraph; import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.apache.poi.hslf.usermodel.HSLFTitleMaster; @@ -49,7 +53,7 @@ import org.junit.jupiter.api.Test; * Tests for SlideMaster */ public final class TestSlideMaster { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); + private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); /** * The reference ppt has two masters. @@ -57,46 +61,54 @@ public final class TestSlideMaster { */ @Test void testSlideMaster() throws IOException { - final HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - - final Environment env = ppt.getDocumentRecord().getEnvironment(); - - assertEquals(2, ppt.getSlideMasters().size()); - - //character attributes - assertEquals(40, getMasterVal(ppt, 0, TITLE, "font.size", true)); - assertEquals(48, getMasterVal(ppt, 1, TITLE, "font.size", true)); - - int font1 = getMasterVal(ppt, 0, TITLE, "font.index", true); - int font2 = getMasterVal(ppt, 1, TITLE, "font.index", true); - assertEquals("Arial", env.getFontCollection().getFontInfo(font1).getTypeface()); - assertEquals("Georgia", env.getFontCollection().getFontInfo(font2).getTypeface()); - - CharFlagsTextProp prop1 = getMasterProp(ppt, 0, TITLE, "char_flags", true); - assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - CharFlagsTextProp prop2 = getMasterProp(ppt, 1, TITLE, "char_flags", true); - assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertTrue(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - //now paragraph attributes - assertEquals(0x266B, getMasterVal(ppt, 0, BODY, "bullet.char", false)); - assertEquals(0x2022, getMasterVal(ppt, 1, BODY, "bullet.char", false)); - - int b1 = getMasterVal(ppt, 0, BODY, "bullet.font", false); - int b2 = getMasterVal(ppt, 1, BODY, "bullet.font", false); - assertEquals("Arial", env.getFontCollection().getFontInfo(b1).getTypeface()); - assertEquals("Georgia", env.getFontCollection().getFontInfo(b2).getTypeface()); - - ppt.close(); + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + + final Environment env = ppt.getDocumentRecord().getEnvironment(); + + assertEquals(2, ppt.getSlideMasters().size()); + + //character attributes + assertEquals(40, getMasterVal(ppt, 0, TITLE, "font.size", true)); + assertEquals(48, getMasterVal(ppt, 1, TITLE, "font.size", true)); + + int font1 = getMasterVal(ppt, 0, TITLE, "font.index", true); + int font2 = getMasterVal(ppt, 1, TITLE, "font.index", true); + HSLFFontInfo fontInfo = env.getFontCollection().getFontInfo(font1); + assertNotNull(fontInfo); + assertEquals("Arial", fontInfo.getTypeface()); + fontInfo = env.getFontCollection().getFontInfo(font2); + assertNotNull(fontInfo); + assertEquals("Georgia", fontInfo.getTypeface()); + + CharFlagsTextProp prop1 = getMasterProp(ppt, 0, TITLE, "char_flags", true); + assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + + CharFlagsTextProp prop2 = getMasterProp(ppt, 1, TITLE, "char_flags", true); + assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertTrue(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + + //now paragraph attributes + assertEquals(0x266B, getMasterVal(ppt, 0, BODY, "bullet.char", false)); + assertEquals(0x2022, getMasterVal(ppt, 1, BODY, "bullet.char", false)); + + int b1 = getMasterVal(ppt, 0, BODY, "bullet.font", false); + int b2 = getMasterVal(ppt, 1, BODY, "bullet.font", false); + fontInfo = env.getFontCollection().getFontInfo(b1); + assertNotNull(fontInfo); + assertEquals("Arial", fontInfo.getTypeface()); + fontInfo = env.getFontCollection().getFontInfo(b2); + assertNotNull(fontInfo); + assertEquals("Georgia", fontInfo.getTypeface()); + } } - @SuppressWarnings("unchecked") private static <T extends TextProp> T getMasterProp(HSLFSlideShow ppt, int masterIdx, TextPlaceholder txtype, String propName, boolean isCharacter) { - return (T)ppt.getSlideMasters().get(masterIdx).getPropCollection(txtype.nativeId, 0, propName, isCharacter).findByName(propName); + return Objects.requireNonNull(ppt.getSlideMasters().get(masterIdx) + .getPropCollection(txtype.nativeId, 0, propName, isCharacter)) + .findByName(propName); } private static int getMasterVal(HSLFSlideShow ppt, int masterIdx, TextPlaceholder txtype, String propName, boolean isCharacter) { @@ -109,22 +121,21 @@ public final class TestSlideMaster { */ @Test void testTitleMasterTextAttributes() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - assertEquals(1, ppt.getTitleMasters().size()); - - assertEquals(40, getMasterVal(ppt, 0, CENTER_TITLE, "font.size", true)); - CharFlagsTextProp prop1 = getMasterProp(ppt, 0, CENTER_TITLE, "char_flags", true); - assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - assertEquals(32, getMasterVal(ppt, 0, CENTER_BODY, "font.size", true)); - CharFlagsTextProp prop2 = getMasterProp(ppt, 0, CENTER_BODY, "char_flags", true); - assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertFalse(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - ppt.close(); + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + assertEquals(1, ppt.getTitleMasters().size()); + + assertEquals(40, getMasterVal(ppt, 0, CENTER_TITLE, "font.size", true)); + CharFlagsTextProp prop1 = getMasterProp(ppt, 0, CENTER_TITLE, "char_flags", true); + assertFalse(prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertFalse(prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertTrue(prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + + assertEquals(32, getMasterVal(ppt, 0, CENTER_BODY, "font.size", true)); + CharFlagsTextProp prop2 = getMasterProp(ppt, 0, CENTER_BODY, "char_flags", true); + assertFalse(prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); + assertFalse(prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); + assertFalse(prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); + } } /** @@ -132,30 +143,32 @@ public final class TestSlideMaster { */ @Test void testTitleMaster() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - HSLFSlide slide = ppt.getSlides().get(2); - HSLFMasterSheet masterSheet = slide.getMasterSheet(); - assertTrue(masterSheet instanceof HSLFTitleMaster); - - for (List<HSLFTextParagraph> txt : slide.getTextParagraphs()) { - HSLFTextRun rt = txt.get(0).getTextRuns().get(0); - switch(TextPlaceholder.fromNativeId(txt.get(0).getRunType())){ - case CENTER_TITLE: - assertEquals("Arial", rt.getFontFamily()); - assertEquals(32, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isUnderlined()); - break; - case CENTER_BODY: - assertEquals("Courier New", rt.getFontFamily()); - assertEquals(20, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertFalse(rt.isUnderlined()); - break; + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + HSLFSlide slide = ppt.getSlides().get(2); + HSLFMasterSheet masterSheet = slide.getMasterSheet(); + assertTrue(masterSheet instanceof HSLFTitleMaster); + + for (List<HSLFTextParagraph> txt : slide.getTextParagraphs()) { + HSLFTextRun rt = txt.get(0).getTextRuns().get(0); + assertNotNull(rt.getFontSize()); + TextPlaceholder tp = TextPlaceholder.fromNativeId(txt.get(0).getRunType()); + assertNotNull(tp); + switch (tp) { + case CENTER_TITLE: + assertEquals("Arial", rt.getFontFamily()); + assertEquals(32, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertTrue(rt.isUnderlined()); + break; + case CENTER_BODY: + assertEquals("Courier New", rt.getFontFamily()); + assertEquals(20, rt.getFontSize(), 0); + assertTrue(rt.isBold()); + assertFalse(rt.isUnderlined()); + break; + } } - } - ppt.close(); } /** @@ -163,48 +176,46 @@ public final class TestSlideMaster { */ @Test void testMasterAttributes() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List<HSLFSlide> slide = ppt.getSlides(); - assertEquals(3, slide.size()); - for (List<HSLFTextParagraph> tparas : slide.get(0).getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TITLE.nativeId){ - HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(40, rt.getFontSize(), 0); - assertTrue(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - } else if (tpara.getRunType() == BODY.nativeId){ + try (HSLFSlideShow ppt = getSlideShow("slide_master.ppt")) { + List<HSLFSlide> slide = ppt.getSlides(); + assertEquals(3, slide.size()); + for (List<HSLFTextParagraph> tparas : slide.get(0).getTextParagraphs()) { + HSLFTextParagraph tpara = tparas.get(0); HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(0, tpara.getIndentLevel()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals("Arial", rt.getFontFamily()); - - tpara = tparas.get(1); - rt = tpara.getTextRuns().get(0); - assertEquals(1, tpara.getIndentLevel()); - assertEquals(28, rt.getFontSize(), 0); - assertEquals("Arial", rt.getFontFamily()); + assertNotNull(rt.getFontSize()); + if (tpara.getRunType() == TITLE.nativeId) { + assertEquals(40, rt.getFontSize(), 0); + assertTrue(rt.isUnderlined()); + assertEquals("Arial", rt.getFontFamily()); + } else if (tpara.getRunType() == BODY.nativeId) { + assertEquals(0, tpara.getIndentLevel()); + assertEquals(32, rt.getFontSize(), 0); + assertEquals("Arial", rt.getFontFamily()); + tpara = tparas.get(1); + rt = tpara.getTextRuns().get(0); + assertEquals(1, tpara.getIndentLevel()); + assertNotNull(rt.getFontSize()); + assertEquals(28, rt.getFontSize(), 0); + assertEquals("Arial", rt.getFontFamily()); + } } - } - for (List<HSLFTextParagraph> tparas : slide.get(1).getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TITLE.nativeId){ + for (List<HSLFTextParagraph> tparas : slide.get(1).getTextParagraphs()) { + HSLFTextParagraph tpara = tparas.get(0); HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(48, rt.getFontSize(), 0); - assertTrue(rt.isItalic()); - assertEquals("Georgia", rt.getFontFamily()); - } else if (tpara.getRunType() == BODY.nativeId){ - HSLFTextRun rt; - rt = tpara.getTextRuns().get(0); - assertEquals(0, tpara.getIndentLevel()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals("Courier New", rt.getFontFamily()); + assertNotNull(rt.getFontSize()); + if (tpara.getRunType() == TITLE.nativeId) { + assertEquals(48, rt.getFontSize(), 0); + assertTrue(rt.isItalic()); + assertEquals("Georgia", rt.getFontFamily()); + } else if (tpara.getRunType() == BODY.nativeId) { + assertEquals(0, tpara.getIndentLevel()); + assertEquals(32, rt.getFontSize(), 0); + assertEquals("Courier New", rt.getFontFamily()); + } } } - - ppt.close(); } /** @@ -212,35 +223,32 @@ public final class TestSlideMaster { */ @Test void testChangeSlideMaster() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List<HSLFSlideMaster> master = ppt.getSlideMasters(); - List<HSLFSlide> slide = ppt.getSlides(); - int sheetNo; - - //each slide uses its own master - assertEquals(slide.get(0).getMasterSheet()._getSheetNumber(), master.get(0)._getSheetNumber()); - assertEquals(slide.get(1).getMasterSheet()._getSheetNumber(), master.get(1)._getSheetNumber()); - - //all slides use the first master slide - sheetNo = master.get(0)._getSheetNumber(); - for (HSLFSlide s : slide) { - s.setMasterSheet(master.get(0)); - } - - ByteArrayOutputStream out; - - out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - master = ppt.getSlideMasters(); - slide = ppt.getSlides(); - for (HSLFSlide s : slide) { - assertEquals(sheetNo, s.getMasterSheet()._getSheetNumber()); + try (HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt"))) { + int[] masterIds = IntStream.concat( + ppt.getSlideMasters().stream().mapToInt(HSLFSlideMaster::_getSheetNumber), + ppt.getTitleMasters().stream().mapToInt(HSLFTitleMaster::_getSheetNumber) + ).toArray(); + //each slide uses its own master + int[] slideMasters = ppt.getSlides().stream().mapToInt(s -> { + HSLFMasterSheet m = s.getMasterSheet(); + assertNotNull(m); + return m._getSheetNumber(); + }).toArray(); + assertArrayEquals(masterIds, slideMasters); + + //all slides use the first master slide + HSLFSlideMaster master0 = ppt.getSlideMasters().get(0); + int sheetNo = master0._getSheetNumber(); + ppt.getSlides().forEach(s -> s.setMasterSheet(master0)); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + for (HSLFSlide s : ppt2.getSlides()) { + HSLFMasterSheet ms = s.getMasterSheet(); + assertNotNull(ms); + assertEquals(sheetNo, ms._getSheetNumber()); + } + } } - - ppt.close(); } /** @@ -256,6 +264,7 @@ public final class TestSlideMaster { HSLFTextParagraph tpara = tparas.get(0); if (tpara.getRunType() == TITLE.nativeId){ HSLFTextRun rt = tpara.getTextRuns().get(0); + assertNotNull(rt.getFontSize()); assertEquals(40, rt.getFontSize(), 0); assertTrue(rt.isUnderlined()); assertEquals("Arial", rt.getFontFamily()); @@ -263,6 +272,7 @@ public final class TestSlideMaster { int[] indents = {32, 28, 24}; for (HSLFTextRun rt : tpara.getTextRuns()) { int indent = tpara.getIndentLevel(); + assertNotNull(rt.getFontSize()); assertEquals(indents[indent], rt.getFontSize(), 0); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java index 31713bae88..15850e6047 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestSlides.java @@ -17,14 +17,13 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.*; +import org.apache.poi.hslf.usermodel.HSLFSlide; +import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.junit.jupiter.api.Test; /** @@ -36,105 +35,96 @@ public final class TestSlides { /** * Add 1 slide to an empty ppt. - * @throws Exception */ @Test void testAddSlides1() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(1, ppt.getSlides().size()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + assertTrue(ppt1.getSlides().isEmpty()); + + HSLFSlide s1 = ppt1.createSlide(); + assertEquals(1, ppt1.getSlides().size()); + assertEquals(3, s1._getSheetRefId()); + assertEquals(256, s1._getSheetNumber()); + assertEquals(1, s1.getSlideNumber()); + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)){ + assertEquals(1, ppt2.getSlides().size()); + } + } } /** * Add 2 slides to an empty ppt - * @throws Exception */ @Test void testAddSlides2() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - HSLFSlide s2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(2, s2.getSlideNumber()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(2, ppt.getSlides().size()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + assertTrue(ppt1.getSlides().isEmpty()); + + HSLFSlide s1 = ppt1.createSlide(); + assertEquals(1, ppt1.getSlides().size()); + assertEquals(3, s1._getSheetRefId()); + assertEquals(256, s1._getSheetNumber()); + assertEquals(1, s1.getSlideNumber()); + + HSLFSlide s2 = ppt1.createSlide(); + assertEquals(2, ppt1.getSlides().size()); + assertEquals(4, s2._getSheetRefId()); + assertEquals(257, s2._getSheetNumber()); + assertEquals(2, s2.getSlideNumber()); + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + assertEquals(2, ppt2.getSlides().size()); + } + } } /** * Add 3 slides to an empty ppt - * @throws Exception */ @Test void testAddSlides3() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - HSLFSlide s2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(2, s2.getSlideNumber()); - - HSLFSlide s3 = ppt.createSlide(); - assertEquals(3, ppt.getSlides().size()); - assertEquals(5, s3._getSheetRefId()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(3, s3.getSlideNumber()); - - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(3, ppt.getSlides().size()); - - // Check IDs are still right - s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(4, s2._getSheetRefId()); - s3 = ppt.getSlides().get(2); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(5, s3._getSheetRefId()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + assertTrue(ppt1.getSlides().isEmpty()); + + HSLFSlide s1 = ppt1.createSlide(); + assertEquals(1, ppt1.getSlides().size()); + assertEquals(3, s1._getSheetRefId()); + assertEquals(256, s1._getSheetNumber()); + assertEquals(1, s1.getSlideNumber()); + + HSLFSlide s2 = ppt1.createSlide(); + assertEquals(2, ppt1.getSlides().size()); + assertEquals(4, s2._getSheetRefId()); + assertEquals(257, s2._getSheetNumber()); + assertEquals(2, s2.getSlideNumber()); + + HSLFSlide s3 = ppt1.createSlide(); + assertEquals(3, ppt1.getSlides().size()); + assertEquals(5, s3._getSheetRefId()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(3, s3.getSlideNumber()); + + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + assertEquals(3, ppt2.getSlides().size()); + + // Check IDs are still right + s1 = ppt2.getSlides().get(0); + assertEquals(256, s1._getSheetNumber()); + assertEquals(3, s1._getSheetRefId()); + s2 = ppt2.getSlides().get(1); + assertEquals(257, s2._getSheetNumber()); + assertEquals(4, s2._getSheetRefId()); + s3 = ppt2.getSlides().get(2); + assertEquals(3, ppt2.getSlides().size()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(5, s3._getSheetRefId()); + } + } } /** @@ -142,48 +132,42 @@ public final class TestSlides { */ @Test void testAddSlides2to3() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - HSLFSlideShow ppt = new HSLFSlideShow(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - - assertEquals(2, ppt.getSlides().size()); - - // First slide is 256 / 4 - HSLFSlide s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - - // Last slide is 257 / 6 - HSLFSlide s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - - // Add another slide, goes in at the end - HSLFSlide s3 = ppt.createSlide(); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); - - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(3, ppt.getSlides().size()); - - - // Check IDs are still right - s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - s3 = ppt.getSlides().get(2); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); + try (HSLFSlideShow ppt1 = getSlideShow("basic_test_ppt_file.ppt")) { + + assertEquals(2, ppt1.getSlides().size()); + + // First slide is 256 / 4 + HSLFSlide s1 = ppt1.getSlides().get(0); + assertEquals(256, s1._getSheetNumber()); + assertEquals(4, s1._getSheetRefId()); + + // Last slide is 257 / 6 + HSLFSlide s2 = ppt1.getSlides().get(1); + assertEquals(257, s2._getSheetNumber()); + assertEquals(6, s2._getSheetRefId()); + + // Add another slide, goes in at the end + HSLFSlide s3 = ppt1.createSlide(); + assertEquals(3, ppt1.getSlides().size()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(8, s3._getSheetRefId()); + + // Serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + assertEquals(3, ppt2.getSlides().size()); + + // Check IDs are still right + s1 = ppt2.getSlides().get(0); + assertEquals(256, s1._getSheetNumber()); + assertEquals(4, s1._getSheetRefId()); + s2 = ppt2.getSlides().get(1); + assertEquals(257, s2._getSheetNumber()); + assertEquals(6, s2._getSheetRefId()); + s3 = ppt2.getSlides().get(2); + assertEquals(3, ppt2.getSlides().size()); + assertEquals(258, s3._getSheetNumber()); + assertEquals(8, s3._getSheetRefId()); + } + } } - } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java index 1777ffed2c..b97dcef413 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTable.java @@ -17,18 +17,17 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; -import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; @@ -42,18 +41,15 @@ import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; import org.junit.jupiter.api.Test; /** - * Test <code>Table</code> object. + * Test {@code Table} object. */ public final class TestTable { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - /** - * Test that ShapeFactory works properly and returns <code>Table</code> + * Test that ShapeFactory works properly and returns {@code Table} */ @Test void testShapeFactory() throws IOException { final int noColumns, noRows; - ByteArrayOutputStream out = new ByteArrayOutputStream(); try (HSLFSlideShow ppt = new HSLFSlideShow()) { HSLFSlide slide = ppt.createSlide(); @@ -73,16 +69,15 @@ public final class TestTable { assertEquals(noColumns, tbl2.getNumberOfColumns()); assertEquals(noRows, tbl2.getNumberOfRows()); - ppt.write(out); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt)) { + HSLFSlide slide2 = ppt2.getSlides().get(0); + assertTrue(slide2.getShapes().get(0) instanceof HSLFTable); + HSLFTable tbl3 = (HSLFTable) slide2.getShapes().get(0); + assertEquals(noColumns, tbl3.getNumberOfColumns()); + assertEquals(noRows, tbl3.getNumberOfRows()); + } } - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray()))) { - HSLFSlide slide = ppt.getSlides().get(0); - assertTrue(slide.getShapes().get(0) instanceof HSLFTable); - HSLFTable tbl3 = (HSLFTable) slide.getShapes().get(0); - assertEquals(noColumns, tbl3.getNumberOfColumns()); - assertEquals(noRows, tbl3.getNumberOfRows()); - } } /** @@ -132,7 +127,7 @@ public final class TestTable { */ @Test void test57820() throws IOException { - try (SlideShow<?,?> ppt = new HSLFSlideShow(_slTests.openResourceAsStream("bug57820-initTableNullRefrenceException.ppt"))) { + try (SlideShow<?,?> ppt = getSlideShow("bug57820-initTableNullRefrenceException.ppt")) { List<? extends Slide<?, ?>> slides = ppt.getSlides(); assertEquals(1, slides.size()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java index f6f7fe6f7c..9509ca6c94 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestTextRunReWrite.java @@ -17,22 +17,20 @@ package org.apache.poi.hslf.model; +import static org.apache.poi.POIDataSamples.writeOutAndReadBack; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; -import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFTextParagraph; import org.apache.poi.hslf.usermodel.HSLFTextRun; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -41,137 +39,111 @@ import org.junit.jupiter.api.Test; * that we don't break anything in the process. */ public final class TestTextRunReWrite { - // HSLFSlideShow primed on the test data - private HSLFSlideShow ss; - - /** - * Load up a test PPT file with rich data - */ - @BeforeEach - void setUp() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - String filename = "Single_Coloured_Page_With_Fonts_and_Alignments.ppt"; - ss = new HSLFSlideShow(slTests.openResourceAsStream(filename)); - } - @Test void testWritesOutTheSameNonRich() throws IOException { - // Ensure the text lengths are as we'd expect to start with - assertEquals(1, ss.getSlides().size()); - assertEquals(2, ss.getSlides().get(0).getTextParagraphs().size()); - - // Grab the first text run on the first sheet - List<HSLFTextParagraph> tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - List<HSLFTextParagraph> tr2 = ss.getSlides().get(0).getTextParagraphs().get(1); - - - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); - - assertEquals(1, tr1.size()); - assertEquals(30, HSLFTextParagraph.getText(tr1).length()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - // Set the text to be as it is now - HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1)); - tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - - // Check the text lengths are still right - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); - - assertEquals(1, tr1.size()); - assertEquals(30, HSLFTextParagraph.getText(tr1).length()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - - // Write the slideshow out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DirectoryNode oDir = ss.getSlideShowImpl().getDirectory(); - - DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); - npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); - assertArrayEquals(_oData, _nData); - - npfs.close(); + try (HSLFSlideShow ppt1 = getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt")) { + // Ensure the text lengths are as we'd expect to start with + assertEquals(1, ppt1.getSlides().size()); + assertEquals(2, ppt1.getSlides().get(0).getTextParagraphs().size()); + + // Grab the first text run on the first sheet + List<HSLFTextParagraph> tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0); + List<HSLFTextParagraph> tr2 = ppt1.getSlides().get(0).getTextParagraphs().get(1); + + + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); + + assertEquals(1, tr1.size()); + assertEquals(30, HSLFTextParagraph.getText(tr1).length()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Set the text to be as it is now + HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1)); + tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0); + + // Check the text lengths are still right + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); + + assertEquals(1, tr1.size()); + assertEquals(30, HSLFTextParagraph.getText(tr1).length()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Use POIFS to query that lot + try (POIFSFileSystem npfs = writeOutAndReadBack(ppt1.getDirectory().getFileSystem())) { + // Check that the "PowerPoint Document" sections have the same size + DirectoryNode oDir = ppt1.getSlideShowImpl().getDirectory(); + + DocumentEntry oProps = (DocumentEntry) oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + DocumentEntry nProps = (DocumentEntry) npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + assertEquals(oProps.getSize(), nProps.getSize()); + + // Check that they contain the same data + byte[] _oData = new byte[oProps.getSize()]; + byte[] _nData = new byte[nProps.getSize()]; + int oLen = oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); + int nLen = npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); + assertEquals(_oData.length, oLen); + assertEquals(_nData.length, nLen); + assertArrayEquals(_oData, _nData); + } + } } @Test void testWritesOutTheSameRich() throws IOException { - // Grab the first text run on the first sheet - List<HSLFTextParagraph> tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - - // Get the first rich text run - HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0); - - - // Check that the text sizes are as expected - assertEquals(1, tr1.get(0).getTextRuns().size()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(30, rtr1.getLength()); - assertEquals(30, rtr1.getRawText().length()); - assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - // Set the text to be as it is now - rtr1.setText( rtr1.getRawText() ); - rtr1 = tr1.get(0).getTextRuns().get(0); - - // Check that the text sizes are still as expected - assertEquals(1, tr1.get(0).getTextRuns().size()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length()); - assertEquals(30, rtr1.getLength()); - assertEquals(30, rtr1.getRawText().length()); - assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - - // Write the slideshow out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DirectoryNode oDir = ss.getSlideShowImpl().getDirectory(); - - DocumentEntry oProps = (DocumentEntry)oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - - oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); - npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); - assertArrayEquals(_oData, _nData); - - npfs.close(); + try (HSLFSlideShow ppt1 = getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt")) { + // Grab the first text run on the first sheet + List<HSLFTextParagraph> tr1 = ppt1.getSlides().get(0).getTextParagraphs().get(0); + + // Get the first rich text run + HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0); + + // Check that the text sizes are as expected + assertEquals(1, tr1.get(0).getTextRuns().size()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(30, rtr1.getLength()); + assertEquals(30, rtr1.getRawText().length()); + assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Set the text to be as it is now + rtr1.setText(rtr1.getRawText()); + rtr1 = tr1.get(0).getTextRuns().get(0); + + // Check that the text sizes are still as expected + assertEquals(1, tr1.get(0).getTextRuns().size()); + assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); + assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length()); + assertEquals(30, rtr1.getLength()); + assertEquals(30, rtr1.getRawText().length()); + assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); + assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); + + // Use POIFS to query that lot + try (POIFSFileSystem npfs = writeOutAndReadBack(ppt1.getDirectory().getFileSystem())) { + // Check that the "PowerPoint Document" sections have the same size + DirectoryNode oDir = ppt1.getSlideShowImpl().getDirectory(); + + DocumentEntry oProps = (DocumentEntry) oDir.getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + DocumentEntry nProps = (DocumentEntry) npfs.getRoot().getEntry(HSLFSlideShow.POWERPOINT_DOCUMENT); + assertEquals(oProps.getSize(), nProps.getSize()); + + // Check that they contain the same data + byte[] _oData = new byte[oProps.getSize()]; + byte[] _nData = new byte[nProps.getSize()]; + + int oLen = oDir.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_oData); + int nLen = npfs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT).read(_nData); + assertEquals(_oData.length, oLen); + assertEquals(_nData.length, nLen); + assertArrayEquals(_oData, _nData); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java index 21d25007db..dac20b569b 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestAnimationInfoAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -66,7 +65,7 @@ public final class TestAnimationInfoAtom { @Test void testWrite() throws Exception { AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); @@ -82,7 +81,7 @@ public final class TestAnimationInfoAtom { record.setFlag(AnimationInfoAtom.Play, true); record.setFlag(AnimationInfoAtom.Synchronous, true); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java index a117037832..054b5c9790 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCString.java @@ -18,11 +18,11 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -70,24 +70,16 @@ public final class TestCString { @Test void testWrite() throws Exception { CString ca = new CString(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); CString cb = new CString(data_b, 0, data_a.length); - ByteArrayOutputStream baosB = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baosB = new UnsynchronizedByteArrayOutputStream(); cb.writeOut(baosB); b = baosB.toByteArray(); - - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, b); } // Turn data_a into data_b @@ -107,14 +99,9 @@ public final class TestCString { } assertFalse(equals, "Arrays should not be equals"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - // Should now be the same - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, b); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java index 768ca20623..fc74f17613 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestColorSchemeAtom.java @@ -18,10 +18,10 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -81,13 +81,10 @@ public final class TestColorSchemeAtom { @Test void testWrite() throws Exception { ColorSchemeAtom csa = new ColorSchemeAtom(data_a,0,data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); csa.writeOut(baos); byte[] b = baos.toByteArray(); - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java index f518b9ffee..ffff00f289 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000.java @@ -18,16 +18,17 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LocaleUtil; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -143,14 +144,10 @@ public final class TestComment2000 { @Test void testWrite() throws Exception { Comment2000 ca = new Comment2000(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } // Change a few things @@ -199,22 +196,16 @@ public final class TestComment2000 { assertFalse(equals, "Arrays should not be equals"); // Check bytes are now the same - ByteArrayOutputStream baosa = new ByteArrayOutputStream(); - ByteArrayOutputStream baosn = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baosa = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baosn = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baosa); cn.writeOut(baosn); byte[] ba = baosa.toByteArray(); byte[] bn = baosn.toByteArray(); // Should now be the same - assertEquals(data_b.length, ba.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],ba[i]); - } - assertEquals(data_b.length, bn.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],bn[i]); - } + assertArrayEquals(data_b, ba); + assertArrayEquals(data_b, bn); } /** diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java index 59660e4947..f3bbdcaa8f 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestComment2000Atom.java @@ -18,13 +18,14 @@ package org.apache.poi.hslf.record; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.util.LocaleUtil; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -35,18 +36,18 @@ import org.junit.jupiter.api.Test; public final class TestComment2000Atom { // From a real file private final byte[] data_a = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 01, 00, 00, 00, 0xD6-256, 07, 01, 00, - 02, 00, 0x18, 00, 0x0A, 00, 0x1A, 00, - 0x0F, 00, 0xCD-256, 00, 0x92-256, 00, - 00, 00, 0x92-256, 00, 00, 00 + 0, 0, 0xE1-256, 0x2E, 0x1C, 0, 0, 0, + 1, 0, 0, 0, 0xD6-256, 7, 1, 0, + 2, 0, 0x18, 0, 0x0A, 0, 0x1A, 0, + 0x0F, 0, 0xCD-256, 0, 0x92-256, 0, + 0, 0, 0x92-256, 0, 0, 0 }; private final byte[] data_b = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 05, 00, 00, 00, 0xD6-256, 0x07, 01, 00, - 02, 00, 0x18, 00, 0x15, 00, 0x19, 00, 03, - 00, 0xD5-256, 02, 0x0A, 00, 00, 00, - 0x0E, 00, 00, 00 + 0, 0, 0xE1-256, 0x2E, 0x1C, 0, 0, 0, + 5, 0, 0, 0, 0xD6-256, 0x07, 1, 0, + 2, 0, 0x18, 0, 0x15, 0, 0x19, 0, 3, + 0, 0xD5-256, 2, 0x0A, 0, 0, 0, + 0x0E, 0, 0, 0 }; private static SimpleDateFormat sdf; @@ -60,7 +61,7 @@ public final class TestComment2000Atom { @Test void testRecordType() { Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - assertEquals(12001l, ca.getRecordType()); + assertEquals(12001L, ca.getRecordType()); } @Test @@ -105,14 +106,10 @@ public final class TestComment2000Atom { @Test void testWrite() throws Exception { Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } // Create A from scratch @@ -130,14 +127,10 @@ public final class TestComment2000Atom { a.setDate(date_a); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); a.writeOut(baos); byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, b); } // Try to turn a into b @@ -157,14 +150,9 @@ public final class TestComment2000Atom { ca.setYOffset(0x0E); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(baos); byte[] b = baos.toByteArray(); - - // Should now be the same - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, b); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java index 138e127024..b21e0d8b67 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestCurrentUserAtom.java @@ -21,9 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.ByteArrayOutputStream; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -89,7 +89,7 @@ public final class TestCurrentUserAtom { cu.setCurrentEditOffset(0x2942); // Check it matches - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); cu.writeOut(baos); byte[] out = baos.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java index 06bca9df9b..c831a478c6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -41,7 +40,7 @@ public final class TestDocumentAtom { @Test void testRecordType() { DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(1001l, da.getRecordType()); + assertEquals(1001L, da.getRecordType()); } @Test @@ -67,7 +66,7 @@ public final class TestDocumentAtom { void testSlideDetails() { DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); assertEquals(1, da.getFirstSlideNum()); - assertEquals(0, da.getSlideSizeType()); + assertEquals(DocumentAtom.SlideSize.ON_SCREEN, da.getSlideSizeTypeEnum()); } @Test @@ -82,7 +81,7 @@ public final class TestDocumentAtom { @Test void testWrite() throws Exception { DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); da.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java index 55944a5246..34945764f2 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestDocumentEncryption.java @@ -23,12 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.security.MessageDigest; import java.util.List; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.PropertySet; @@ -44,7 +44,6 @@ import org.apache.poi.poifs.crypt.CryptoFunctions; import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIDecryptor; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -86,12 +85,12 @@ public class TestDocumentEncryption { DocumentEncryptionAtom documentEncryptionAtom = hss.getDocumentEncryptionAtom(); assertNotNull(documentEncryptionAtom); EncryptionInfo ei = documentEncryptionAtom.getEncryptionInfo(); - ((CryptoAPIEncryptionHeader) ei.getHeader()).setKeySize(0x78); + ei.getHeader().setKeySize(0x78); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); hss.write(bos); - try (POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); + try (POIFSFileSystem fs2 = new POIFSFileSystem(bos.toInputStream()); HSLFSlideShowImpl hss2 = new HSLFSlideShowImpl(fs2)) { List<HSLFPictureData> picsActual = hss2.getPictureData(); @@ -109,9 +108,9 @@ public class TestDocumentEncryption { void cryptoAPIEncryption() throws Exception { /* documents with multiple edits need to be normalized for encryption */ String pptFile = "57272_corrupted_usereditatom.ppt"; - ByteArrayOutputStream encrypted = new ByteArrayOutputStream(); - ByteArrayOutputStream expected = new ByteArrayOutputStream(); - ByteArrayOutputStream actual = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream encrypted = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream expected = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream actual = new UnsynchronizedByteArrayOutputStream(); try { try (POIFSFileSystem fs = new POIFSFileSystem(slTests.getFile(pptFile), true); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) { @@ -126,8 +125,9 @@ public class TestDocumentEncryption { } // decrypted - ByteArrayInputStream bis = new ByteArrayInputStream(encrypted.toByteArray()); - try (POIFSFileSystem fs = new POIFSFileSystem(bis); + + try (InputStream bis = encrypted.toInputStream(); + POIFSFileSystem fs = new POIFSFileSystem(bis); HSLFSlideShowImpl hss = new HSLFSlideShowImpl(fs)) { Biff8EncryptionKey.setCurrentUserPassword(null); hss.write(actual); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java index c7bd84e116..2faa7ebfd8 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java @@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -93,7 +92,7 @@ public final class TestExControl { @Test void testWrite() throws Exception { ExControl record = new ExControl(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -116,7 +115,7 @@ public final class TestExControl { record.setProgId("ShockwaveFlash.ShockwaveFlash.9"); record.setClipboardName("Shockwave Flash Object"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java index 13fea4a83a..42a9867560 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlink.java @@ -22,11 +22,11 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; @@ -46,14 +46,14 @@ public final class TestExHyperlink { ExHyperlink exHyperlink = new ExHyperlink(exHyperlinkBytes, 0, exHyperlinkBytes.length); - assertEquals(4055l, exHyperlink.getRecordType()); + assertEquals(4055L, exHyperlink.getRecordType()); assertEquals(3, exHyperlink.getExHyperlinkAtom().getNumber()); String expURL = "http://jakarta.apache.org/poi/hssf/"; assertEquals(expURL, exHyperlink.getLinkURL()); assertEquals(expURL, exHyperlink._getDetailsA()); assertEquals(expURL, exHyperlink._getDetailsB()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); exHyperlink.writeOut(baos); assertArrayEquals(exHyperlinkBytes, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java index fb8072bd44..f868d96b16 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExHyperlinkAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -57,7 +56,7 @@ public class TestExHyperlinkAtom { @Test void testWrite() throws Exception { ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eha.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -71,7 +70,7 @@ public class TestExHyperlinkAtom { eha.setNumber(1); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eha.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -85,7 +84,7 @@ public class TestExHyperlinkAtom { eha.setNumber(4); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eha.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java index 5b961d5816..606f0ac827 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExMediaAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -50,7 +49,7 @@ public final class TestExMediaAtom { @Test void testWrite() throws Exception { ExMediaAtom record = new ExMediaAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); @@ -68,7 +67,7 @@ public final class TestExMediaAtom { record.setFlag(HeadersFootersAtom.fHasTodayDate, false); record.setFlag(HeadersFootersAtom.fHasFooter, false); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java index 9256b01b9f..97d3ef1707 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExObjListAtom.java @@ -20,8 +20,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.ss.formula.functions.BaseTestNumeric; import org.junit.jupiter.api.Test; @@ -57,7 +56,7 @@ public class TestExObjListAtom { @Test void testWrite() throws Exception { ExObjListAtom eoa = new ExObjListAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eoa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -71,7 +70,7 @@ public class TestExObjListAtom { eoa.setObjectIDSeed(1); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eoa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -85,7 +84,7 @@ public class TestExObjListAtom { eoa.setObjectIDSeed(4); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); eoa.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java index 4c7771cac8..a0860abbbe 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java @@ -20,8 +20,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -50,7 +49,7 @@ public final class TestExOleObjAtom { @Test void testWrite() throws Exception { ExOleObjAtom record = new ExOleObjAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -65,7 +64,7 @@ public final class TestExOleObjAtom { record.setObjStgDataRef(2); record.setOptions(1283584); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java index fcdadfe211..f9d282a095 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjStg.java @@ -22,12 +22,12 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.IOUtils; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -58,7 +58,7 @@ public final class TestExOleObjStg { assertEquals(RecordTypes.ExOleObjStg.typeID, record.getRecordType()); int len = record.getDataLength(); - byte[] oledata = readAll(record.getData()); + byte[] oledata = IOUtils.toByteArray(record.getData()); assertEquals(len, oledata.length); try (POIFSFileSystem fs = new POIFSFileSystem(record.getData())) { @@ -70,7 +70,7 @@ public final class TestExOleObjStg { @Test void testWrite() throws Exception { ExOleObjStg record = new ExOleObjStg(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); byte[] b = baos.toByteArray(); @@ -80,7 +80,7 @@ public final class TestExOleObjStg { @Test void testNewRecord() throws Exception { ExOleObjStg src = new ExOleObjStg(data, 0, data.length); - byte[] oledata = readAll(src.getData()); + byte[] oledata = IOUtils.toByteArray(src.getData()); ExOleObjStg tgt = new ExOleObjStg(); tgt.setData(oledata); @@ -88,22 +88,11 @@ public final class TestExOleObjStg { assertEquals(src.getDataLength(), tgt.getDataLength()); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); tgt.writeOut(out); byte[] b = out.toByteArray(); assertEquals(data.length, b.length); assertArrayEquals(data, b); } - - private byte[] readAll(InputStream is) throws IOException { - int pos; - byte[] chunk = new byte[1024]; - ByteArrayOutputStream out = new ByteArrayOutputStream(); - while((pos = is.read(chunk)) > 0){ - out.write(chunk, 0, pos); - } - return out.toByteArray(); - - } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java index 3933965ac2..ce02202335 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExVideoContainer.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -68,7 +67,7 @@ public final class TestExVideoContainer { @Test void testWrite() throws Exception { ExVideoContainer record = new ExVideoContainer(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -79,7 +78,7 @@ public final class TestExVideoContainer { record.getExMediaAtom().setObjectId(1); record.getPathAtom().setText("D:\\projects\\SchulerAG\\mcom_v_1_0_4\\view\\data\\tests\\images\\cards.mpg"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java index f5b64da586..3592100af6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java @@ -19,12 +19,13 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hslf.usermodel.HSLFFontInfo; import org.apache.poi.hslf.usermodel.HSLFFontInfoPredefined; @@ -78,16 +79,22 @@ public final class TestFontCollection { assertEquals(child.length, 3); // Check we get the right font name for the indicies - assertEquals("Times New Roman", fonts.getFontInfo(0).getTypeface()); - assertEquals("Helvetica", fonts.getFontInfo(1).getTypeface()); - assertEquals("Arial", fonts.getFontInfo(2).getTypeface()); + fi = fonts.getFontInfo(0); + assertNotNull(fi); + assertEquals("Times New Roman", fi.getTypeface()); + fi = fonts.getFontInfo(1); + assertNotNull(fi); + assertEquals("Helvetica", fi.getTypeface()); + fi = fonts.getFontInfo(2); + assertNotNull(fi); + assertEquals("Arial", fi.getTypeface()); assertNull(fonts.getFontInfo(3)); } @Test void testWrite() throws Exception { FontCollection fonts = new FontCollection(data, 0, data.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); fonts.writeOut(out); byte[] recdata = out.toByteArray(); assertArrayEquals(recdata, data); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java index 3edfadb3de..7277fc4790 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersAtom.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -55,7 +54,7 @@ public final class TestHeadersFootersAtom { @Test void testWrite() throws Exception { HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -67,7 +66,7 @@ public final class TestHeadersFootersAtom { record.setFlag(HeadersFootersAtom.fHasTodayDate, true); record.setFlag(HeadersFootersAtom.fHasFooter, true); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java index f6a25739b2..5d6d15b798 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestHeadersFootersContainer.java @@ -23,8 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -76,7 +75,7 @@ public final class TestHeadersFootersContainer { @Test void testWriteSlideHeadersFootersContainer() throws Exception { HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(slideData, baos.toByteArray()); } @@ -100,7 +99,7 @@ public final class TestHeadersFootersContainer { assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); csFooter.setText("My Footer - 1"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(slideData, baos.toByteArray()); } @@ -129,7 +128,7 @@ public final class TestHeadersFootersContainer { @Test void testWriteNotesHeadersFootersContainer() throws Exception { HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(notesData, baos.toByteArray()); } @@ -161,7 +160,7 @@ public final class TestHeadersFootersContainer { assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); csFooter.setText("Note Footer"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); record.writeOut(baos); assertArrayEquals(notesData, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java index 7da5ee6f5c..1b1ab55491 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfo.java @@ -24,8 +24,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -57,7 +56,7 @@ public class TestInteractiveInfo { @Test void testWrite() throws Exception { InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ii.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -75,7 +74,7 @@ public class TestInteractiveInfo { ia.setHyperlinkType((byte)8); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ii.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java index 7f9bcde86e..9eeab59618 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestInteractiveInfoAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -74,7 +73,7 @@ public class TestInteractiveInfoAtom { @Test void testWrite() throws Exception { InteractiveInfoAtom ia = new InteractiveInfoAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -91,7 +90,7 @@ public class TestInteractiveInfoAtom { ia.setHyperlinkType((byte)8); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -105,7 +104,7 @@ public class TestInteractiveInfoAtom { ia.setHyperlinkID(4); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java index e2852088dc..d122f019dd 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestNotesAtom.java @@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -52,7 +51,7 @@ public final class TestNotesAtom { @Test void testWrite() throws Exception { NotesAtom na = new NotesAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); na.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java index ef3c7b84b4..7f67088716 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlideAtom.java @@ -22,9 +22,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.hslf.record.SlideAtomLayout.SlideLayoutType; import org.apache.poi.hslf.usermodel.HSLFSlide; @@ -43,7 +43,7 @@ public final class TestSlideAtom { @Test void testRecordType() { SlideAtom sa = new SlideAtom(data_a, 0, data_a.length); - assertEquals(1007l, sa.getRecordType()); + assertEquals(1007L, sa.getRecordType()); } @Test @@ -75,23 +75,23 @@ public final class TestSlideAtom { @Test void testWrite() throws IOException { SlideAtom sa = new SlideAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); sa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @Test void testSSSlideInfoAtom() throws IOException { - HSLFSlideShow ss1 = new HSLFSlideShow(); - HSLFSlide slide1 = ss1.createSlide(), slide2 = ss1.createSlide(); - slide2.setHidden(true); - - HSLFSlideShow ss2 = HSLFTestDataSamples.writeOutAndReadBack(ss1); - slide1 = ss2.getSlides().get(0); - slide2 = ss2.getSlides().get(1); - assertFalse(slide1.isHidden()); - assertTrue(slide2.isHidden()); - ss2.close(); - ss1.close(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide1 = ppt1.createSlide(), slide2 = ppt1.createSlide(); + slide2.setHidden(true); + + try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) { + slide1 = ppt2.getSlides().get(0); + slide2 = ppt2.getSlides().get(1); + assertFalse(slide1.isHidden()); + assertTrue(slide2.isHidden()); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java index 2a638d5a9a..d5f1105f47 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestSlidePersistAtom.java @@ -22,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -53,7 +52,7 @@ public final class TestSlidePersistAtom { @Test void testWrite() throws Exception { SlidePersistAtom spa = new SlidePersistAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); spa.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java index 3de5c8d131..1e57798caf 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestStyleTextPropAtom.java @@ -26,15 +26,14 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.exceptions.HSLFException; import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp; import org.apache.poi.hslf.model.textproperties.TextProp; import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.util.HexDump; import org.junit.jupiter.api.Test; /** @@ -467,14 +466,9 @@ public final class TestStyleTextPropAtom { tpc.setValue(0xFE0033FF); // Should now be the same as data_a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); stpa.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i<data_a.length; i++) { - assertEquals(data_a[i],b[i]); - } + assertArrayEquals(data_a, baos.toByteArray()); } /** @@ -621,34 +615,20 @@ public final class TestStyleTextPropAtom { assertEquals(tpa.getValue(), tpb.getValue()); } - ByteArrayOutputStream ba = new ByteArrayOutputStream(); - ByteArrayOutputStream bb = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream ba = new UnsynchronizedByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream bb = new UnsynchronizedByteArrayOutputStream(); ca.writeOut(ba); cb.writeOut(bb); - byte[] cab = ba.toByteArray(); - byte[] cbb = bb.toByteArray(); - assertEquals(cbb.length, cab.length); - for(int j=0; j<cab.length; j++) { - //System.out.println("On tp " + z + " " + i + " " + j + "\t" + cab[j] + "\t" + cbb[j]); - assertEquals(cbb[j], cab[j]); - } + assertArrayEquals(bb.toByteArray(), ba.toByteArray()); } } - - // Check byte level with b - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); stpa.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_b.length, b.length); - for(int i=0; i<data_b.length; i++) { - //System.out.println(i + "\t" + b[i] + "\t" + data_b[i] + "\t" + Integer.toHexString(b[i]) ); - assertEquals(data_b[i],b[i]); - } + assertArrayEquals(data_b, baos.toByteArray()); } @Test @@ -694,13 +674,9 @@ public final class TestStyleTextPropAtom { StyleTextPropAtom stpb = new StyleTextPropAtom(data, 0,data.length); if(textlen != -1) stpb.setParentTextSize(textlen); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); stpb.writeOut(out); - byte[] bytes = out.toByteArray(); - - assertEquals(expected.length, bytes.length); - assertArrayEquals(expected, bytes, - "Had: " + HexDump.toHex(expected) + "\nand: " + HexDump.toHex(bytes)); + assertArrayEquals(expected, out.toByteArray()); } @Test @@ -759,12 +735,14 @@ public final class TestStyleTextPropAtom { * * From the test file attached to the bug: * + * {@code * <StyleTextPropAtom info="0" type="4001" size="94" offset="114782" header="00 00 A1 0F 5E 00 00 00 "> * 14 00 00 00 00 00 41 00 0A 00 06 00 50 00 07 00 01 00 00 00 00 00 00 00 02 * 00 00 00 01 04 00 00 01 04 01 00 00 00 01 08 00 00 01 08 0C 00 00 00 01 0C * 00 00 01 0C 01 00 00 00 01 10 00 00 01 10 01 00 00 00 01 14 00 00 01 14 01 * 00 00 00 01 18 00 00 01 18 01 00 00 00 01 1C 00 00 01 1C * </StyleTextPropAtom> + * } */ @Test void test45815() throws IOException { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java index 44f2dc4617..c06eff77d1 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextBytesAtom.java @@ -21,9 +21,9 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -64,7 +64,7 @@ public final class TestTextBytesAtom { TextBytesAtom tba = new TextBytesAtom(data,0,data.length); tba.setText(alt_text.getBytes(StandardCharsets.ISO_8859_1)); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tba.writeOut(baos); assertArrayEquals(alt_data, baos.toByteArray()); } @@ -72,7 +72,7 @@ public final class TestTextBytesAtom { @Test void testWrite() throws Exception { TextBytesAtom tba = new TextBytesAtom(data,0,data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tba.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java index 4c1a71daa0..382719cdfc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextCharsAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -60,7 +59,7 @@ public final class TestTextCharsAtom { TextCharsAtom tca = new TextCharsAtom(data,0,data.length); tca.setText(alt_text); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tca.writeOut(baos); assertArrayEquals(alt_data, baos.toByteArray()); } @@ -68,7 +67,7 @@ public final class TestTextCharsAtom { @Test void testWrite() throws Exception { TextCharsAtom tca = new TextCharsAtom(data,0,data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tca.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } @@ -82,7 +81,7 @@ public final class TestTextCharsAtom { assertEquals(data_text, tca.getText()); // Check it's now like data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tca.writeOut(baos); assertArrayEquals(data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java index 4935940afb..6eddf527af 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextHeaderAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; import org.junit.jupiter.api.Test; @@ -54,7 +53,7 @@ public final class TestTextHeaderAtom { @Test void testWrite() throws Exception { TextHeaderAtom tha = new TextHeaderAtom(notes_data,0,12); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); tha.writeOut(baos); assertArrayEquals(notes_data, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java index e50419c410..a24402ec2a 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java @@ -21,9 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayOutputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.model.textproperties.HSLFTabStop; import org.junit.jupiter.api.Test; @@ -61,7 +61,7 @@ public final class TestTextRulerAtom { @Test void testWriteRuler() throws Exception { TextRulerAtom ruler = new TextRulerAtom(data_1, 0, data_1.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ruler.writeOut(out); byte[] result = out.toByteArray(); @@ -72,7 +72,7 @@ public final class TestTextRulerAtom { void testRead2() throws Exception { TextRulerAtom ruler = TextRulerAtom.getParagraphInstance(); ruler.setParagraphIndent((short)249, (short)321); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); ruler.writeOut(out); byte[] result = out.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java index 77ded7d795..93e8b5e420 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextSpecInfoAtom.java @@ -20,8 +20,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -54,7 +53,7 @@ public final class TestTextSpecInfoAtom { @Test void testWrite() throws Exception { TextSpecInfoAtom spec = new TextSpecInfoAtom(data_1, 0, data_1.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); spec.writeOut(out); assertArrayEquals(data_1, out.toByteArray()); } @@ -70,7 +69,7 @@ public final class TestTextSpecInfoAtom { assertEquals(32, run[0].getLength()); //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(); spec.writeOut(out); byte[] result = out.toByteArray(); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java index 12874ec041..601baf0dc6 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTxInteractiveInfoAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -58,7 +57,7 @@ public final class TestTxInteractiveInfoAtom { @Test void testWrite() throws Exception { TxInteractiveInfoAtom atom = new TxInteractiveInfoAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); atom.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -73,7 +72,7 @@ public final class TestTxInteractiveInfoAtom { ia.setEndIndex(56); // Check it's now the same as a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } @@ -88,7 +87,7 @@ public final class TestTxInteractiveInfoAtom { ia.setEndIndex(78); // Check bytes are now the same - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); ia.writeOut(baos); assertArrayEquals(data_b, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java index c09e1e55b3..42b34157d9 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestUserEditAtom.java @@ -21,8 +21,7 @@ package org.apache.poi.hslf.record; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayOutputStream; - +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.Test; /** @@ -57,7 +56,7 @@ public final class TestUserEditAtom { @Test void testWrite() throws Exception { UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); uea.writeOut(baos); assertArrayEquals(data_a, baos.toByteArray()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java index e1f453327d..343c1117d9 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java @@ -18,10 +18,10 @@ package org.apache.poi.hslf.usermodel; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.sl.usermodel.BaseTestSlideShow; import org.apache.poi.sl.usermodel.SlideShow; import org.junit.jupiter.api.Test; @@ -38,15 +38,13 @@ public class TestHSLFSlideShow extends BaseTestSlideShow<HSLFShape, HSLFTextPara assertNotNull(createSlideShow()); } + @Override public HSLFSlideShow reopen(SlideShow<HSLFShape, HSLFTextParagraph> show) throws IOException { - BufAccessBAOS bos = new BufAccessBAOS(); - show.write(bos); - return new HSLFSlideShow(new ByteArrayInputStream(bos.getBuf())); - } - - private static class BufAccessBAOS extends ByteArrayOutputStream { - byte[] getBuf() { - return buf; + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + show.write(bos); + try (InputStream is = bos.toInputStream()) { + return new HSLFSlideShow(is); + } } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java index 5e50aa9c1f..65a2716711 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestPictures.java @@ -17,13 +17,18 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.awt.Dimension; +import java.awt.geom.Dimension2D; +import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.util.Arrays; @@ -31,12 +36,13 @@ import java.util.Collections; import java.util.List; import java.util.Random; +import javax.imageio.ImageIO; + +import org.apache.commons.io.output.CountingOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.ddf.EscherBSERecord; import org.apache.poi.ddf.EscherContainerRecord; import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.blip.DIB; import org.apache.poi.hslf.blip.EMF; import org.apache.poi.hslf.blip.JPEG; import org.apache.poi.hslf.blip.PICT; @@ -50,6 +56,8 @@ import org.apache.poi.sl.usermodel.PictureData.PictureType; import org.apache.poi.util.Units; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Test adding/reading pictures @@ -58,302 +66,101 @@ public final class TestPictures { private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); /** - * Test read/write Macintosh PICT - */ - @Test - void testPICT() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("cow.pict"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PICT); - ImageHeaderPICT nHeader = new ImageHeaderPICT(src_bytes, 512); - final int expWidth = 197, expHeight = 137; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.PICT, pd.getType()); - assertTrue(pd instanceof PICT); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertEquals(src_bytes.length, ppt_bytes.length); - //in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them - byte[] b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); - byte[] b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); - assertArrayEquals(b1, b2); - } - - /** - * Test read/write WMF - */ - @Test - void testWMF() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("santa.wmf"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.WMF); - ImageHeaderWMF nHeader = new ImageHeaderWMF(src_bytes, 0); - final int expWidth = 136, expHeight = 146; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(PictureType.WMF, pd.getType()); - assertTrue(pd instanceof WMF); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertEquals(src_bytes.length, ppt_bytes.length); - //in WMF the first 22 bytes - is a metafile header - byte[] b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); - byte[] b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); - assertArrayEquals(b1, b2); - } - - /** - * Test read/write EMF + * Test add/read/write images */ - @Test - void testEMF() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("wrench.emf"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.EMF); - ImageHeaderEMF nHeader = new ImageHeaderEMF(src_bytes, 0); - final int expWidth = 190, expHeight = 115; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can get this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.EMF, pd.getType()); - assertTrue(pd instanceof EMF); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write PNG - */ - @Test - void testPNG() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("tomcat.png"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PNG); - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.PNG, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof PNG); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write JPEG - */ - @Test - void testJPEG() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("clock.jpg"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.JPEG); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.JPEG, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof JPEG); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write DIB - */ - @Test - void testDIB() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("clock.dib"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.DIB); - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List<HSLFShape> sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List<HSLFPictureData> pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.DIB, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof DIB); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); + @ParameterizedTest() + @CsvSource(value = { + // in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them + "PICT, cow.pict, 197, 137, 512, org.apache.poi.hslf.blip.PICT", + // in WMF the first 22 bytes - is a metafile header + "WMF, santa.wmf, 136, 146, 22, org.apache.poi.hslf.blip.WMF", + "EMF, wrench.emf, 190, 115, 0, org.apache.poi.hslf.blip.EMF", + "PNG, tomcat.png, 129, 92, 0, org.apache.poi.hslf.blip.PNG", + "JPEG, clock.jpg, 192, 176, 0, org.apache.poi.hslf.blip.JPEG", + "DIB, clock.dib, 192, 176, 0, org.apache.poi.hslf.blip.DIB" + }) + void testAddPictures(PictureType pictureType, String imgFile, int expWidth, int expHeight, int headerOffset, Class<?> imgClazz) throws IOException { + byte[] src_bytes = slTests.readFile(imgFile); + + int dataIndex; + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + + HSLFSlide slide1 = ppt1.createSlide(); + HSLFPictureData data1 = ppt1.addPicture(src_bytes, pictureType); + dataIndex = data1.getIndex(); + + // TODO: Fix the differences in the frame sizes + Dimension2D dimN, dimFrame1, dimFrame2; + switch (pictureType) { + case PICT: + dimN = new ImageHeaderPICT(src_bytes, headerOffset).getSize(); + dimFrame1 = Units.pointsToPixel(dimN); + dimFrame2 = dimN; + break; + case WMF: + dimN = new ImageHeaderWMF(src_bytes, 0).getSize(); + dimFrame1 = Units.pointsToPixel(dimN); + dimFrame2 = dimN; + break; + case EMF: + dimN = new ImageHeaderEMF(src_bytes, 0).getSize(); + dimFrame1 = Units.pointsToPixel(dimN); + dimFrame2 = dimN; + break; + case JPEG: + case DIB: + case PNG: { + BufferedImage png = ImageIO.read(new ByteArrayInputStream(src_bytes)); + dimN = new Dimension(png.getWidth(), png.getHeight()); + dimFrame1 = dimN; + dimFrame2 = Units.pixelToPoints(dimN); + break; + } + default: + fail(); + return; + } + assertEquals(expWidth, dimN.getWidth(), 1); + assertEquals(expHeight, dimN.getHeight(), 1); + + Dimension dim1 = data1.getImageDimensionInPixels(); + assertEquals(dimFrame1.getWidth(), dim1.getWidth(), 1); + assertEquals(dimFrame1.getHeight(), dim1.getHeight(), 1); + + HSLFPictureShape pict1 = new HSLFPictureShape(data1); + assertEquals(data1.getIndex(), pict1.getPictureIndex()); + slide1.addShape(pict1); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + //make sure we can read this picture shape and it refers to the correct picture data + List<HSLFShape> sh2 = ppt2.getSlides().get(0).getShapes(); + assertEquals(1, sh2.size()); + HSLFPictureShape pict2 = (HSLFPictureShape) sh2.get(0); + assertEquals(dataIndex, pict2.getPictureIndex()); + + //check picture data + List<HSLFPictureData> pictures2 = ppt2.getPictureData(); + assertEquals(1, pictures2.size()); + + HSLFPictureData pd2 = pictures2.get(0); + Dimension dim2 = pd2.getImageDimension(); + assertEquals(dimFrame2.getWidth(), dim2.width, 1); + assertEquals(dimFrame2.getHeight(), dim2.height, 1); + + //the Picture shape refers to the PictureData object in the Presentation + assertEquals(pict2.getPictureData(), pd2); + + assertEquals(1, pictures2.size()); + assertEquals(pictureType, pd2.getType()); + assertTrue(imgClazz.isInstance(pd2)); + //compare the content of the initial file with what is stored in the PictureData + byte[] ppt_bytes = pd2.getData(); + assertEquals(src_bytes.length, ppt_bytes.length); + byte[] b1 = Arrays.copyOfRange(src_bytes, headerOffset, src_bytes.length); + byte[] b2 = Arrays.copyOfRange(ppt_bytes, headerOffset, ppt_bytes.length); + assertArrayEquals(b1, b2); + } + } } /** @@ -366,60 +173,59 @@ public final class TestPictures { HSLFPictureShape pict; HSLFPictureData pdata; - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt"); - List<HSLFSlide> slides = ppt.getSlides(); - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(5, pictures.size()); - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(0); //the first slide contains JPEG - pdata = pict.getPictureData(); - assertTrue(pdata instanceof JPEG); - assertEquals(PictureType.JPEG, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("clock.jpg"); - assertArrayEquals(src_bytes, ppt_bytes); - - pict = (HSLFPictureShape)slides.get(1).getShapes().get(0); //the second slide contains PNG - pdata = pict.getPictureData(); - assertTrue(pdata instanceof PNG); - assertEquals(PictureType.PNG, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("tomcat.png"); - assertArrayEquals(src_bytes, ppt_bytes); - - pict = (HSLFPictureShape)slides.get(2).getShapes().get(0); //the third slide contains WMF - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("santa.wmf"); - assertEquals(src_bytes.length, ppt_bytes.length); - //ignore the first 22 bytes - it is a WMF metafile header - b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); - b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); - assertArrayEquals(b1, b2); - - pict = (HSLFPictureShape)slides.get(3).getShapes().get(0); //the forth slide contains PICT - pdata = pict.getPictureData(); - assertTrue(pdata instanceof PICT); - assertEquals(PictureType.PICT, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("cow.pict"); - assertEquals(src_bytes.length, ppt_bytes.length); - //ignore the first 512 bytes - it is a MAC specific crap - b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); - b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); - assertArrayEquals(b1, b2); - - pict = (HSLFPictureShape)slides.get(4).getShapes().get(0); //the fifth slide contains EMF - pdata = pict.getPictureData(); - assertTrue(pdata instanceof EMF); - assertEquals(PictureType.EMF, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("wrench.emf"); - assertArrayEquals(src_bytes, ppt_bytes); - - ppt.close(); + try (HSLFSlideShow ppt = getSlideShow("pictures.ppt")) { + List<HSLFSlide> slides = ppt.getSlides(); + List<HSLFPictureData> pictures = ppt.getPictureData(); + assertEquals(5, pictures.size()); + + pict = (HSLFPictureShape) slides.get(0).getShapes().get(0); //the first slide contains JPEG + pdata = pict.getPictureData(); + assertTrue(pdata instanceof JPEG); + assertEquals(PictureType.JPEG, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("clock.jpg"); + assertArrayEquals(src_bytes, ppt_bytes); + + pict = (HSLFPictureShape) slides.get(1).getShapes().get(0); //the second slide contains PNG + pdata = pict.getPictureData(); + assertTrue(pdata instanceof PNG); + assertEquals(PictureType.PNG, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("tomcat.png"); + assertArrayEquals(src_bytes, ppt_bytes); + + pict = (HSLFPictureShape) slides.get(2).getShapes().get(0); //the third slide contains WMF + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("santa.wmf"); + assertEquals(src_bytes.length, ppt_bytes.length); + //ignore the first 22 bytes - it is a WMF metafile header + b1 = Arrays.copyOfRange(src_bytes, 22, src_bytes.length); + b2 = Arrays.copyOfRange(ppt_bytes, 22, ppt_bytes.length); + assertArrayEquals(b1, b2); + + pict = (HSLFPictureShape) slides.get(3).getShapes().get(0); //the forth slide contains PICT + pdata = pict.getPictureData(); + assertTrue(pdata instanceof PICT); + assertEquals(PictureType.PICT, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("cow.pict"); + assertEquals(src_bytes.length, ppt_bytes.length); + //ignore the first 512 bytes - it is a MAC specific crap + b1 = Arrays.copyOfRange(src_bytes, 512, src_bytes.length); + b2 = Arrays.copyOfRange(ppt_bytes, 512, ppt_bytes.length); + assertArrayEquals(b1, b2); + + pict = (HSLFPictureShape) slides.get(4).getShapes().get(0); //the fifth slide contains EMF + pdata = pict.getPictureData(); + assertTrue(pdata instanceof EMF); + assertEquals(PictureType.EMF, pdata.getType()); + src_bytes = pdata.getData(); + ppt_bytes = slTests.readFile("wrench.emf"); + assertArrayEquals(src_bytes, ppt_bytes); + } } /** @@ -428,35 +234,34 @@ public final class TestPictures { */ @Test void testZeroPictureType() throws IOException { - HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt")); - - // Should still have 2 real pictures - assertEquals(2, hslf.getPictureData().size()); - // Both are real pictures, both WMF - assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); - assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); - - // Now test what happens when we use the SlideShow interface - HSLFSlideShow ppt = new HSLFSlideShow(hslf); - List<HSLFSlide> slides = ppt.getSlides(); - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(12, slides.size()); - assertEquals(2, pictures.size()); - - HSLFPictureShape pict; - HSLFPictureData pdata; - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(1); // 2nd object on 1st slide - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(2); // 3rd object on 1st slide - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - ppt.close(); + try (HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt"))) { + + // Should still have 2 real pictures + assertEquals(2, hslf.getPictureData().size()); + // Both are real pictures, both WMF + assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); + assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); + + // Now test what happens when we use the SlideShow interface + HSLFSlideShow ppt = new HSLFSlideShow(hslf); + List<HSLFSlide> slides = ppt.getSlides(); + List<HSLFPictureData> pictures = ppt.getPictureData(); + assertEquals(12, slides.size()); + assertEquals(2, pictures.size()); + + HSLFPictureShape pict; + HSLFPictureData pdata; + + pict = (HSLFPictureShape) slides.get(0).getShapes().get(1); // 2nd object on 1st slide + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + + pict = (HSLFPictureShape) slides.get(0).getShapes().get(2); // 3rd object on 1st slide + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + } } /** @@ -490,75 +295,70 @@ public final class TestPictures { assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); // Now test what happens when we use the SlideShow interface - HSLFSlideShow ppt = new HSLFSlideShow(hslf); - List<HSLFSlide> slides = ppt.getSlides(); - List<HSLFPictureData> pictures = ppt.getPictureData(); - assertEquals(27, slides.size()); - assertEquals(2, pictures.size()); - - HSLFPictureShape pict; - HSLFPictureData pdata; - - pict = (HSLFPictureShape)slides.get(6).getShapes().get(13); - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - pict = (HSLFPictureShape)slides.get(7).getShapes().get(13); - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - //add a new picture, it should be correctly appended to the Pictures stream - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(HSLFPictureData p : pictures) p.write(out); - out.close(); - - int streamSize = out.size(); - - HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG); - int offset = data.getOffset(); - assertEquals(streamSize, offset); - assertEquals(3, ppt.getPictureData().size()); - - ppt.close(); + try (HSLFSlideShow ppt = new HSLFSlideShow(hslf)) { + List<HSLFSlide> slides = ppt.getSlides(); + List<HSLFPictureData> pictures = ppt.getPictureData(); + assertEquals(27, slides.size()); + assertEquals(2, pictures.size()); + + HSLFPictureShape pict; + HSLFPictureData pdata; + + pict = (HSLFPictureShape) slides.get(6).getShapes().get(13); + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + + pict = (HSLFPictureShape) slides.get(7).getShapes().get(13); + pdata = pict.getPictureData(); + assertTrue(pdata instanceof WMF); + assertEquals(PictureType.WMF, pdata.getType()); + + //add a new picture, it should be correctly appended to the Pictures stream + CountingOutputStream out = new CountingOutputStream(NULL_OUTPUT_STREAM); + for (HSLFPictureData p : pictures) p.write(out); + + int streamSize = out.getCount(); + + HSLFPictureData data = ppt.addPicture(new byte[100], PictureType.JPEG); + int offset = data.getOffset(); + assertEquals(streamSize, offset); + assertEquals(3, ppt.getPictureData().size()); + } } @Test void testGetPictureName() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt"); - HSLFSlide slide = ppt.getSlides().get(0); + try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) { + HSLFSlide slide = ppt.getSlides().get(0); - HSLFPictureShape p = (HSLFPictureShape)slide.getShapes().get(0); //the first slide contains JPEG - assertEquals("test", p.getPictureName()); - ppt.close(); + HSLFPictureShape p = (HSLFPictureShape) slide.getShapes().get(0); //the first slide contains JPEG + assertEquals("test", p.getPictureName()); + } } @Test void testSetPictureName() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] img = slTests.readFile("tomcat.png"); - HSLFPictureData data = ppt.addPicture(img, PictureType.PNG); - HSLFPictureShape pict = new HSLFPictureShape(data); - pict.setPictureName("tomcat.png"); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - - HSLFPictureShape p = (HSLFPictureShape)ppt.getSlides().get(0).getShapes().get(0); - assertEquals("tomcat.png", p.getPictureName()); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + + HSLFSlide slide = ppt1.createSlide(); + byte[] img = slTests.readFile("tomcat.png"); + HSLFPictureData data = ppt1.addPicture(img, PictureType.PNG); + HSLFPictureShape pict = new HSLFPictureShape(data); + pict.setPictureName("tomcat.png"); + slide.addShape(pict); + + //serialize and read again + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + HSLFPictureShape p = (HSLFPictureShape) ppt2.getSlides().get(0).getShapes().get(0); + assertEquals("tomcat.png", p.getPictureName()); + } + } } @Test void testPictureIndexIsOneBased() throws IOException { - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt")) { + try (HSLFSlideShow ppt = getSlideShow("ppt_with_png.ppt")) { HSLFPictureData picture = ppt.getPictureData().get(0); assertEquals(1, picture.getIndex()); } @@ -571,20 +371,18 @@ public final class TestPictures { @Test void testEditPictureData() throws IOException { byte[] newImage = slTests.readFile("tomcat.png"); - ByteArrayOutputStream modifiedSlideShow = new ByteArrayOutputStream(); // Load an existing slideshow and modify the image - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png.ppt")) { - HSLFPictureData picture = ppt.getPictureData().get(0); - picture.setData(newImage); - ppt.write(modifiedSlideShow); - } + try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png.ppt")) { + HSLFPictureData picture1 = ppt1.getPictureData().get(0); + picture1.setData(newImage); - // Load the modified slideshow and verify the image content - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(modifiedSlideShow.toByteArray()))) { - HSLFPictureData picture = ppt.getPictureData().get(0); - byte[] modifiedImageData = picture.getData(); - assertArrayEquals(newImage, modifiedImageData); + // Load the modified slideshow and verify the image content + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + HSLFPictureData picture2 = ppt2.getPictureData().get(0); + byte[] modifiedImageData = picture2.getData(); + assertArrayEquals(newImage, modifiedImageData); + } } } @@ -595,22 +393,20 @@ public final class TestPictures { @Test void testEditPictureDataEncrypted() throws IOException { byte[] newImage = slTests.readFile("tomcat.png"); - ByteArrayOutputStream modifiedSlideShow = new ByteArrayOutputStream(); Biff8EncryptionKey.setCurrentUserPassword("password"); try { // Load an existing slideshow and modify the image - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ppt_with_png_encrypted.ppt")) { - HSLFPictureData picture = ppt.getPictureData().get(0); - picture.setData(newImage); - ppt.write(modifiedSlideShow); - } - - // Load the modified slideshow and verify the image content - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(modifiedSlideShow.toByteArray()))) { - HSLFPictureData picture = ppt.getPictureData().get(0); - byte[] modifiedImageData = picture.getData(); - assertArrayEquals(newImage, modifiedImageData); + try (HSLFSlideShow ppt1 = getSlideShow("ppt_with_png_encrypted.ppt")) { + HSLFPictureData picture1 = ppt1.getPictureData().get(0); + picture1.setData(newImage); + + // Load the modified slideshow and verify the image content + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + HSLFPictureData picture2 = ppt2.getPictureData().get(0); + byte[] modifiedImageData = picture2.getData(); + assertArrayEquals(newImage, modifiedImageData); + } } } finally { Biff8EncryptionKey.setCurrentUserPassword(null); @@ -626,27 +422,23 @@ public final class TestPictures { int[] originalOffsets = {0, 12013, 15081, 34162, 59563}; int[] modifiedOffsets = {0, 35, 3103, 22184, 47585}; - ByteArrayOutputStream inMemory = new ByteArrayOutputStream(); - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) { - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(originalOffsets, offsets); + try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { + int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(originalOffsets, offsets1); - HSLFPictureData imageBeingChanged = ppt.getPictureData().get(0); + HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0); // It doesn't matter that this isn't a valid image. We are just testing offsets here. imageBeingChanged.setData(new byte[10]); // Verify that the in-memory representations have all been updated - offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(modifiedOffsets, offsets); - - ppt.write(inMemory); - } - - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) { + offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(modifiedOffsets, offsets1); - // Verify that the persisted representations have all been updated - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(modifiedOffsets, offsets); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // Verify that the persisted representations have all been updated + int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(modifiedOffsets, offsets2); + } } } @@ -662,11 +454,9 @@ public final class TestPictures { void testEditPictureDataOutOfOrderRecords() throws IOException { int[] modifiedOffsets = {0, 35, 3103, 22184, 47585}; - ByteArrayOutputStream inMemory = new ByteArrayOutputStream(); - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) { - + try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { // For this test we're going to intentionally manipulate the records into a shuffled order. - EscherContainerRecord container = ppt.getPictureData().get(0).bStore; + EscherContainerRecord container = ppt1.getPictureData().get(0).bStore; List<EscherRecord> children = container.getChildRecords(); for (EscherRecord child : children) { container.removeChildRecord(child); @@ -676,25 +466,21 @@ public final class TestPictures { container.addChildRecord(child); } - HSLFPictureData imageBeingChanged = ppt.getPictureData().get(0); + HSLFPictureData imageBeingChanged = ppt1.getPictureData().get(0); // It doesn't matter that this isn't a valid image. We are just testing offsets here. imageBeingChanged.setData(new byte[10]); // Verify that the in-memory representations have all been updated - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - Arrays.sort(offsets); - assertArrayEquals(modifiedOffsets, offsets); + int[] offsets1 = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray(); + assertArrayEquals(modifiedOffsets, offsets1); - ppt.write(inMemory); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // Verify that the persisted representations have all been updated + int[] offsets2 = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).sorted().toArray(); + assertArrayEquals(modifiedOffsets, offsets2); + } } - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) { - - // Verify that the persisted representations have all been updated - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - Arrays.sort(offsets); - assertArrayEquals(modifiedOffsets, offsets); - } } /** @@ -707,28 +493,25 @@ public final class TestPictures { int originalNumberOfRecords; // Create a presentation that has records with unmatched offsets, but with matched UIDs. - ByteArrayOutputStream inMemory = new ByteArrayOutputStream(); - try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("pictures.ppt")) { - originalOffsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - originalNumberOfRecords = ppt.getPictureData().get(0).bStore.getChildCount(); + try (HSLFSlideShow ppt1 = getSlideShow("pictures.ppt")) { + originalOffsets = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + originalNumberOfRecords = ppt1.getPictureData().get(0).bStore.getChildCount(); Random random = new Random(); - for (HSLFPictureData picture : ppt.getPictureData()) { + for (HSLFPictureData picture : ppt1.getPictureData()) { // Bound is arbitrary and irrelevant to the test. picture.bse.setOffset(random.nextInt(500_000)); } - ppt.write(inMemory); - } - try (HSLFSlideShow ppt = new HSLFSlideShow(new ByteArrayInputStream(inMemory.toByteArray()))) { + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + // Verify that the offsets all got fixed. + int[] offsets = ppt2.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); + assertArrayEquals(originalOffsets, offsets); - // Verify that the offsets all got fixed. - int[] offsets = ppt.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray(); - assertArrayEquals(originalOffsets, offsets); - - // Verify that there are the same number of records as in the original slideshow. - int numberOfRecords = ppt.getPictureData().get(0).bStore.getChildCount(); - assertEquals(originalNumberOfRecords, numberOfRecords); + // Verify that there are the same number of records as in the original slideshow. + int numberOfRecords = ppt2.getPictureData().get(0).bStore.getChildCount(); + assertEquals(originalNumberOfRecords, numberOfRecords); + } } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java index 8081528a9f..90a84b815e 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestRichTextRun.java @@ -24,12 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.hslf.record.Record; import org.apache.poi.hslf.record.SlideListWithText; @@ -230,30 +229,30 @@ public final class TestRichTextRun { assertEquals("Courier", rtr.getFontFamily()); // Write out and back in - HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h); - - // Tweak existing one again, to ensure really worked - rtr.setBold(false); - rtr.setFontSize(17d); - rtr.setFontFamily("CourierZZ"); - - // Check it took those changes - assertFalse(rtr.isBold()); - assertEquals(17., rtr.getFontSize(), 0); - assertEquals("CourierZZ", rtr.getFontFamily()); - - - // Now, look at the one we changed, wrote out, and read back in - // Ensure it does contain our original modifications - HSLFSlide slideOneRR = readS.getSlides().get(0); - List<List<HSLFTextParagraph>> textParassRR = slideOneRR.getTextParagraphs(); - HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0); - - assertTrue(rtrRRa.isBold()); - assertNotNull(rtrRRa.getFontSize()); - assertEquals(18., rtrRRa.getFontSize(), 0); - assertEquals("Courier", rtrRRa.getFontFamily()); - readS.close(); + try (HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h)) { + + // Tweak existing one again, to ensure really worked + rtr.setBold(false); + rtr.setFontSize(17d); + rtr.setFontFamily("CourierZZ"); + + // Check it took those changes + assertFalse(rtr.isBold()); + assertEquals(17., rtr.getFontSize(), 0); + assertEquals("CourierZZ", rtr.getFontFamily()); + + + // Now, look at the one we changed, wrote out, and read back in + // Ensure it does contain our original modifications + HSLFSlide slideOneRR = readS.getSlides().get(0); + List<List<HSLFTextParagraph>> textParassRR = slideOneRR.getTextParagraphs(); + HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0); + + assertTrue(rtrRRa.isBold()); + assertNotNull(rtrRRa.getFontSize()); + assertEquals(18., rtrRRa.getFontSize(), 0); + assertEquals("Courier", rtrRRa.getFontFamily()); + } } } @@ -370,29 +369,30 @@ public final class TestRichTextRun { */ private void assertMatchesSLTWC(HSLFSlideShow s) throws IOException { // Grab a new copy of slideshow C - HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC); + try (HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC)) { - // Write out the 2nd SLWT in the active document - SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1]; - byte[] raw_slwt = writeRecord(refSLWT); + // Write out the 2nd SLWT in the active document + SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1]; + byte[] raw_slwt = writeRecord(refSLWT); - // Write out the same for the supplied slideshow - SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1]; - byte[] s_slwt = writeRecord(s_SLWT); + // Write out the same for the supplied slideshow + SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1]; + byte[] s_slwt = writeRecord(s_SLWT); - // Check the records are the same - assertEquals(refSLWT.getChildRecords().length, s_SLWT.getChildRecords().length); - for(int i=0; i<refSLWT.getChildRecords().length; i++) { - Record ref_r = refSLWT.getChildRecords()[i]; - Record s_r = s_SLWT.getChildRecords()[i]; + // Check the records are the same + assertEquals(refSLWT.getChildRecords().length, s_SLWT.getChildRecords().length); + for (int i = 0; i < refSLWT.getChildRecords().length; i++) { + Record ref_r = refSLWT.getChildRecords()[i]; + Record s_r = s_SLWT.getChildRecords()[i]; - byte[] r_rb = writeRecord(ref_r); - byte[] s_rb = writeRecord(s_r); - assertArrayEquals(r_rb, s_rb); - } + byte[] r_rb = writeRecord(ref_r); + byte[] s_rb = writeRecord(s_r); + assertArrayEquals(r_rb, s_rb); + } - // Check the bytes are the same - assertArrayEquals(raw_slwt, s_slwt); + // Check the bytes are the same + assertArrayEquals(raw_slwt, s_slwt); + } } /** @@ -401,20 +401,20 @@ public final class TestRichTextRun { */ private static void assertMatchesFileC(HSLFSlideShow s) throws IOException { // Grab the bytes of the file - POIFSFileSystem fs = new POIFSFileSystem(HSLFTestDataSamples.openSampleFileStream(filenameC)); - InputStream is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT); - byte[] raw_file = IOUtils.toByteArray(is); - is.close(); - fs.close(); + byte[] raw_file; + try (POIFSFileSystem fs = new POIFSFileSystem(HSLFTestDataSamples.openSampleFileStream(filenameC)); + InputStream is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT)) { + raw_file = IOUtils.toByteArray(is); + } // Now write out the slideshow - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] raw_ss; + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); s.write(baos); - fs = new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); - is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT); - byte[] raw_ss = IOUtils.toByteArray(is); - is.close(); - fs.close(); + try (POIFSFileSystem fs = new POIFSFileSystem(baos.toInputStream()); + InputStream is = fs.createDocumentInputStream(HSLFSlideShow.POWERPOINT_DOCUMENT)) { + raw_ss = IOUtils.toByteArray(is); + } // different paragraph mask, because of sanitizing raw_ss[169030] = 0x0a; @@ -424,24 +424,24 @@ public final class TestRichTextRun { } private byte[] writeRecord( org.apache.poi.hslf.record.Record r) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); r.writeOut(baos); return baos.toByteArray(); } @Test void testIndentationLevel() throws Exception { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ParagraphStylesShorterThanCharStyles.ppt"); - for (HSLFSlide sl : ppt.getSlides()) { - for (List<HSLFTextParagraph> txt : sl.getTextParagraphs()) { - for (HSLFTextParagraph p : txt) { - int indent = p.getIndentLevel(); - assertTrue(indent >= 0 && indent <= 4 ); - } + try (HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("ParagraphStylesShorterThanCharStyles.ppt")) { + for (HSLFSlide sl : ppt.getSlides()) { + for (List<HSLFTextParagraph> txt : sl.getTextParagraphs()) { + for (HSLFTextParagraph p : txt) { + int indent = p.getIndentLevel(); + assertTrue(indent >= 0 && indent <= 4); + } + } } } - ppt.close(); } @Test @@ -502,54 +502,54 @@ public final class TestRichTextRun { @Test void testSetParagraphStyles() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { - HSLFSlide slide = ppt1.createSlide(); + HSLFSlide slide = ppt1.createSlide(); - HSLFTextBox shape = new HSLFTextBox(); - shape.setText( + HSLFTextBox shape = new HSLFTextBox(); + shape.setText( "Hello, World!\r" + - "This should be\r" + - "Multiline text"); - HSLFTextParagraph rt = shape.getTextParagraphs().get(0); - HSLFTextRun tr = rt.getTextRuns().get(0); - tr.setFontSize(42d); - rt.setBullet(true); - rt.setLeftMargin(50d); - rt.setIndent(0d); - rt.setBulletChar('\u263A'); - slide.addShape(shape); - - assertNotNull(tr.getFontSize()); - assertEquals(42.0, tr.getFontSize(), 0); - assertTrue(rt.isBullet()); - assertNotNull(rt.getLeftMargin()); - assertEquals(50.0, rt.getLeftMargin(), 0); - assertNotNull(rt.getIndent()); - assertEquals(0, rt.getIndent(), 0); - assertNotNull(rt.getBulletChar()); - assertEquals('\u263A', (char)rt.getBulletChar()); - - shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); - slide.addShape(shape); - - //serialize and read again - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - slide = ppt2.getSlides().get(0); - shape = (HSLFTextBox)slide.getShapes().get(0); - rt = shape.getTextParagraphs().get(0); - tr = rt.getTextRuns().get(0); - assertNotNull(tr.getFontSize()); - assertEquals(42.0, tr.getFontSize(), 0); - assertTrue(rt.isBullet()); - assertNotNull(rt.getLeftMargin()); - assertEquals(50.0, rt.getLeftMargin(), 0); - assertNotNull(rt.getIndent()); - assertEquals(0, rt.getIndent(), 0); - assertNotNull(rt.getBulletChar()); - assertEquals('\u263A', (char)rt.getBulletChar()); - ppt2.close(); - ppt1.close(); + "This should be\r" + + "Multiline text"); + HSLFTextParagraph rt = shape.getTextParagraphs().get(0); + HSLFTextRun tr = rt.getTextRuns().get(0); + tr.setFontSize(42d); + rt.setBullet(true); + rt.setLeftMargin(50d); + rt.setIndent(0d); + rt.setBulletChar('\u263A'); + slide.addShape(shape); + + assertNotNull(tr.getFontSize()); + assertEquals(42.0, tr.getFontSize(), 0); + assertTrue(rt.isBullet()); + assertNotNull(rt.getLeftMargin()); + assertEquals(50.0, rt.getLeftMargin(), 0); + assertNotNull(rt.getIndent()); + assertEquals(0, rt.getIndent(), 0); + assertNotNull(rt.getBulletChar()); + assertEquals('\u263A', (char) rt.getBulletChar()); + + shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); + slide.addShape(shape); + + //serialize and read again + try (HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + shape = (HSLFTextBox) slide.getShapes().get(0); + rt = shape.getTextParagraphs().get(0); + tr = rt.getTextRuns().get(0); + assertNotNull(tr.getFontSize()); + assertEquals(42.0, tr.getFontSize(), 0); + assertTrue(rt.isBullet()); + assertNotNull(rt.getLeftMargin()); + assertEquals(50.0, rt.getLeftMargin(), 0); + assertNotNull(rt.getIndent()); + assertEquals(0, rt.getIndent(), 0); + assertNotNull(rt.getBulletChar()); + assertEquals('\u263A', (char) rt.getBulletChar()); + } + } } @Test diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java index 1176003e7a..437cb592ff 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTable.java @@ -19,6 +19,7 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -26,8 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; @@ -108,58 +107,49 @@ public class TestTable { @Test void testAddText() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlide slide = ppt1.createSlide(); - HSLFTable tab = slide.createTable(4, 5); - - int rows = tab.getNumberOfRows(); - int cols = tab.getNumberOfColumns(); - for (int row=0; row<rows; row++) { - for (int col=0; col<cols; col++) { - HSLFTableCell c = tab.getCell(row, col); - assertNotNull(c); - c.setText("r"+(row+1)+"c"+(col+1)); + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide = ppt1.createSlide(); + HSLFTable tab = slide.createTable(4, 5); + + int rows = tab.getNumberOfRows(); + int cols = tab.getNumberOfColumns(); + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + HSLFTableCell c = tab.getCell(row, col); + assertNotNull(c); + c.setText("r" + (row + 1) + "c" + (col + 1)); + } } - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt1.write(bos); - ppt1.close(); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - HSLFSlideShow ppt2 = new HSLFSlideShow(bis); - slide = ppt2.getSlides().get(0); - tab = (HSLFTable)slide.getShapes().get(0); - - rows = tab.getNumberOfRows(); - cols = tab.getNumberOfColumns(); - for (int row=0; row<rows; row++) { - for (int col=0; col<cols; col++) { - HSLFTableCell c = tab.getCell(row, col); - assertNotNull(c); - c.setText(c.getText()+"..."); + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + tab = (HSLFTable) slide.getShapes().get(0); + + rows = tab.getNumberOfRows(); + cols = tab.getNumberOfColumns(); + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + HSLFTableCell c = tab.getCell(row, col); + assertNotNull(c); + c.setText(c.getText() + "..."); + } + } + + try (HSLFSlideShow ppt3 = writeOutAndReadBack(ppt2)) { + slide = ppt3.getSlides().get(0); + tab = (HSLFTable) slide.getShapes().get(0); + + rows = tab.getNumberOfRows(); + cols = tab.getNumberOfColumns(); + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + HSLFTableCell c = tab.getCell(row, col); + assertNotNull(c); + assertEquals("r" + (row + 1) + "c" + (col + 1) + "...", c.getText()); + } + } + } } } - - bos.reset(); - ppt2.write(bos); - ppt2.close(); - - bis = new ByteArrayInputStream(bos.toByteArray()); - HSLFSlideShow ppt3 = new HSLFSlideShow(bis); - slide = ppt3.getSlides().get(0); - tab = (HSLFTable)slide.getShapes().get(0); - - rows = tab.getNumberOfRows(); - cols = tab.getNumberOfColumns(); - for (int row=0; row<rows; row++) { - for (int col=0; col<cols; col++) { - HSLFTableCell c = tab.getCell(row, col); - assertNotNull(c); - assertEquals("r"+(row+1)+"c"+(col+1)+"...", c.getText()); - } - } - - ppt3.close(); } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java index 1b577eb273..10493a6998 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/usermodel/TestTextShape.java @@ -17,27 +17,26 @@ package org.apache.poi.hslf.usermodel; +import static org.apache.poi.hslf.HSLFTestDataSamples.getSlideShow; +import static org.apache.poi.hslf.HSLFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.poi.hslf.HSLFTestDataSamples; import org.apache.poi.sl.usermodel.ShapeType; import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; import org.junit.jupiter.api.Test; /** - * Verify behavior of <code>TextShape</code> and its sub-classes + * Verify behavior of {@code TextShape} and its sub-classes */ public final class TestTextShape { @Test @@ -72,153 +71,146 @@ public final class TestTextShape { */ @Test void read() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text_shapes.ppt"); - - List<String> lst1 = new ArrayList<>(); - HSLFSlide slide = ppt.getSlides().get(0); - for (HSLFShape shape : slide.getShapes()) { - assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName()); - HSLFTextShape tx = (HSLFTextShape)shape; - List<HSLFTextParagraph> paras = tx.getTextParagraphs(); - assertNotNull(paras); - int runType = paras.get(0).getRunType(); - - ShapeType type = shape.getShapeType(); - String rawText = HSLFTextParagraph.getRawText(paras); - switch (type){ - case TEXT_BOX: - assertEquals("Text in a TextBox", rawText); - break; - case RECT: - if(runType == TextPlaceholder.OTHER.nativeId) { - assertEquals("Rectangle", rawText); - } else if(runType == TextPlaceholder.TITLE.nativeId) { - assertEquals("Title Placeholder", rawText); - } - break; - case OCTAGON: - assertEquals("Octagon", rawText); - break; - case ELLIPSE: - assertEquals("Ellipse", rawText); - break; - case ROUND_RECT: - assertEquals("RoundRectangle", rawText); - break; - default: - fail("Unexpected shape: " + shape.getShapeName()); + try (HSLFSlideShow ppt = getSlideShow("text_shapes.ppt")) { + + List<String> lst1 = new ArrayList<>(); + HSLFSlide slide = ppt.getSlides().get(0); + for (HSLFShape shape : slide.getShapes()) { + assertTrue(shape instanceof HSLFTextShape, "Expected TextShape but found " + shape.getClass().getName()); + HSLFTextShape tx = (HSLFTextShape) shape; + List<HSLFTextParagraph> paras = tx.getTextParagraphs(); + assertNotNull(paras); + int runType = paras.get(0).getRunType(); + + ShapeType type = shape.getShapeType(); + String rawText = HSLFTextParagraph.getRawText(paras); + switch (type) { + case TEXT_BOX: + assertEquals("Text in a TextBox", rawText); + break; + case RECT: + if (runType == TextPlaceholder.OTHER.nativeId) { + assertEquals("Rectangle", rawText); + } else if (runType == TextPlaceholder.TITLE.nativeId) { + assertEquals("Title Placeholder", rawText); + } + break; + case OCTAGON: + assertEquals("Octagon", rawText); + break; + case ELLIPSE: + assertEquals("Ellipse", rawText); + break; + case ROUND_RECT: + assertEquals("RoundRectangle", rawText); + break; + default: + fail("Unexpected shape: " + shape.getShapeName()); + + } + lst1.add(rawText); + } + List<String> lst2 = new ArrayList<>(); + for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) { + lst2.add(HSLFTextParagraph.getRawText(paras)); } - lst1.add(rawText); - } - List<String> lst2 = new ArrayList<>(); - for (List<HSLFTextParagraph> paras : slide.getTextParagraphs()) { - lst2.add(HSLFTextParagraph.getRawText(paras)); + assertTrue(lst1.containsAll(lst2)); } - - assertTrue(lst1.containsAll(lst2)); - ppt.close(); } @Test void readWrite() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - - HSLFTextShape shape1 = new HSLFTextBox(); - shape1.setText("Hello, World!"); - slide.addShape(shape1); - - shape1.moveTo(100, 100); - - HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW); - shape2.setText("Testing TextShape"); - slide.addShape(shape2); - shape2.moveTo(300, 300); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - slide = ppt.getSlides().get(0); - List<HSLFShape> shape = slide.getShapes(); - - assertTrue(shape.get(0) instanceof HSLFTextShape); - shape1 = (HSLFTextShape)shape.get(0); - assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType()); - assertEquals("Hello, World!", shape1.getText()); - - assertTrue(shape.get(1) instanceof HSLFTextShape); - shape1 = (HSLFTextShape)shape.get(1); - assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType()); - assertEquals("Testing TextShape", shape1.getText()); - ppt.close(); - } + try (HSLFSlideShow ppt1 = new HSLFSlideShow()) { + HSLFSlide slide = ppt1.createSlide(); - @Test - void margins() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text-margins.ppt"); + HSLFTextShape shape1 = new HSLFTextBox(); + shape1.setText("Hello, World!"); + slide.addShape(shape1); + + shape1.moveTo(100, 100); + + HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW); + shape2.setText("Testing TextShape"); + slide.addShape(shape2); + shape2.moveTo(300, 300); + + try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) { + slide = ppt2.getSlides().get(0); + List<HSLFShape> shape = slide.getShapes(); - HSLFSlide slide = ppt.getSlides().get(0); + assertTrue(shape.get(0) instanceof HSLFTextShape); + shape1 = (HSLFTextShape) shape.get(0); + assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType()); + assertEquals("Hello, World!", shape1.getText()); - Map<String,HSLFTextShape> map = new HashMap<>(); - for (HSLFShape shape : slide.getShapes()) { - if(shape instanceof HSLFTextShape){ - HSLFTextShape tx = (HSLFTextShape)shape; - map.put(tx.getText(), tx); + assertTrue(shape.get(1) instanceof HSLFTextShape); + shape1 = (HSLFTextShape) shape.get(1); + assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType()); + assertEquals("Testing TextShape", shape1.getText()); } } - - HSLFTextShape tx; - - tx = map.get("TEST1"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(28.34, tx.getTopInset(), 0.01); - assertEquals(3.6, tx.getBottomInset(), 0); - - tx = map.get("TEST2"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(28.34, tx.getBottomInset(), 0.01); - - tx = map.get("TEST3"); - assertEquals(28.34, tx.getLeftInset(), 0.01); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(3.6, tx.getBottomInset(), 0); - - tx = map.get("TEST4"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(28.34, tx.getRightInset(), 0.01); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(3.6, tx.getBottomInset(), 0); - - ppt.close(); } @Test - void bug52599() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("52599.ppt"); + void margins() throws IOException { + try (HSLFSlideShow ppt = getSlideShow("text-margins.ppt")) { - HSLFSlide slide = ppt.getSlides().get(0); - List<HSLFShape> sh = slide.getShapes(); - assertEquals(3, sh.size()); + HSLFSlide slide = ppt.getSlides().get(0); - HSLFTextShape sh0 = (HSLFTextShape)sh.get(0); - assertNotNull(sh0.getTextParagraphs()); - assertEquals("", sh0.getText()); + Map<String, HSLFTextShape> map = new HashMap<>(); + for (HSLFShape shape : slide.getShapes()) { + if (shape instanceof HSLFTextShape) { + HSLFTextShape tx = (HSLFTextShape) shape; + map.put(tx.getText(), tx); + } + } - HSLFTextShape sh1 = (HSLFTextShape)sh.get(1); - assertNotNull(sh1.getTextParagraphs()); - assertEquals("", sh1.getText()); + HSLFTextShape tx = map.get("TEST1"); + assertEquals(7.2, tx.getLeftInset(), 0); + assertEquals(7.2, tx.getRightInset(), 0); + assertEquals(28.34, tx.getTopInset(), 0.01); + assertEquals(3.6, tx.getBottomInset(), 0); + + tx = map.get("TEST2"); + assertEquals(7.2, tx.getLeftInset(), 0); + assertEquals(7.2, tx.getRightInset(), 0); + assertEquals(3.6, tx.getTopInset(), 0); + assertEquals(28.34, tx.getBottomInset(), 0.01); + + tx = map.get("TEST3"); + assertEquals(28.34, tx.getLeftInset(), 0.01); + assertEquals(7.2, tx.getRightInset(), 0); + assertEquals(3.6, tx.getTopInset(), 0); + assertEquals(3.6, tx.getBottomInset(), 0); + + tx = map.get("TEST4"); + assertEquals(7.2, tx.getLeftInset(), 0); + assertEquals(28.34, tx.getRightInset(), 0.01); + assertEquals(3.6, tx.getTopInset(), 0); + assertEquals(3.6, tx.getBottomInset(), 0); + } + } - HSLFTextShape sh2 = (HSLFTextShape)sh.get(2); - assertEquals("this box should be shown just once", sh2.getText()); - assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex()); - ppt.close(); + @Test + void bug52599() throws IOException { + try (HSLFSlideShow ppt = getSlideShow("52599.ppt")) { + HSLFSlide slide = ppt.getSlides().get(0); + List<HSLFShape> sh = slide.getShapes(); + assertEquals(3, sh.size()); + + HSLFTextShape sh0 = (HSLFTextShape) sh.get(0); + assertNotNull(sh0.getTextParagraphs()); + assertEquals("", sh0.getText()); + + HSLFTextShape sh1 = (HSLFTextShape) sh.get(1); + assertNotNull(sh1.getTextParagraphs()); + assertEquals("", sh1.getText()); + + HSLFTextShape sh2 = (HSLFTextShape) sh.get(2); + assertEquals("this box should be shown just once", sh2.getText()); + assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex()); + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java index 4f0322b806..a11ba12c90 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java @@ -21,12 +21,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Map; import java.util.TimeZone; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.AttachmentChunks; import org.apache.poi.hsmf.datatypes.Chunk; @@ -54,8 +54,6 @@ public class TestExtractEmbeddedMSG { /** * Initialize this test, load up the attachment_msg_pdf.msg mapi message. - * - * @throws Exception */ @BeforeAll public static void setUp() throws IOException { @@ -71,9 +69,6 @@ public class TestExtractEmbeddedMSG { /** * Test to see if embedded message properties can be read, extracted, and * re-parsed - * - * @throws ChunkNotFoundException - * */ @Test void testEmbeddedMSGProperties() throws IOException, ChunkNotFoundException { @@ -86,11 +81,9 @@ public class TestExtractEmbeddedMSG { testFixedAndVariableLengthPropertiesOfAttachedMSG(attachedMsg); // rebuild top level message from embedded message try (POIFSFileSystem extractedAttachedMsg = rebuildFromAttached(attachedMsg)) { - try (ByteArrayOutputStream extractedAttachedMsgOut = new ByteArrayOutputStream()) { + try (UnsynchronizedByteArrayOutputStream extractedAttachedMsgOut = new UnsynchronizedByteArrayOutputStream()) { extractedAttachedMsg.writeFilesystem(extractedAttachedMsgOut); - byte[] extratedAttachedMsgRaw = extractedAttachedMsgOut.toByteArray(); - MAPIMessage extractedMsgTopLevel = new MAPIMessage( - new ByteArrayInputStream(extratedAttachedMsgRaw)); + MAPIMessage extractedMsgTopLevel = new MAPIMessage(extractedAttachedMsgOut.toInputStream()); // test properties of rebuilt embedded message testFixedAndVariableLengthPropertiesOfAttachedMSG(extractedMsgTopLevel); } @@ -104,7 +97,7 @@ public class TestExtractEmbeddedMSG { Calendar messageDate = msg.getMessageDate(); assertNotNull(messageDate); Calendar expectedMessageDate = LocaleUtil.getLocaleCalendar(); - expectedMessageDate.set(2010, 05, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT + expectedMessageDate.set(2010, Calendar.JUNE, 17, 23, 52, 19); // 2010/06/17 23:52:19 GMT expectedMessageDate.setTimeZone(TimeZone.getTimeZone("GMT")); expectedMessageDate.set(Calendar.MILLISECOND, 0); assertEquals(expectedMessageDate.getTimeInMillis(), messageDate.getTimeInMillis()); @@ -178,7 +171,7 @@ public class TestExtractEmbeddedMSG { MAPIType type = Types.getById(iType); if (type != null && type != Types.UNKNOWN) { MAPIProperty mprop = MAPIProperty.createCustom(chunk.getChunkId(), type, chunk.getEntryName()); - ByteArrayOutputStream data = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream data = new UnsynchronizedByteArrayOutputStream(); chunk.writeValue(data); PropertyValue pval = new PropertyValue(mprop, MessagePropertiesChunk.PROPERTIES_FLAG_READABLE | MessagePropertiesChunk.PROPERTIES_FLAG_WRITEABLE, data.toByteArray(), type); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java index 1d8cc9f98a..068fa10883 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java @@ -22,14 +22,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.AttachmentChunks; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Tests to verify that we can read attachments from msg file @@ -74,32 +76,21 @@ public class TestFileWithAttachmentsRead { /** * Bug 60550: Test to see if we get the correct Content-IDs of inline images`. */ - @Test - void testReadContentIDField() throws IOException { - AttachmentChunks[] attachments = inlineImgMsgAttachments.getAttachmentFiles(); - - AttachmentChunks attachment; - - // Check in Content-ID field - attachment = inlineImgMsgAttachments.getAttachmentFiles()[0]; - assertEquals("image001.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image001.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[1]; - assertEquals("image002.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image002.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[2]; - assertEquals("image003.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image003.png@01D0A526.B4C739C0", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[3]; - assertEquals("image006.jpg", attachment.getAttachFileName().getValue()); - assertEquals(".jpg", attachment.getAttachExtension().getValue()); - assertEquals("image006.jpg@01D0A526.B649E220", attachment.getAttachContentId().getValue()); + @ParameterizedTest + @CsvSource({ + "0, image001.png@01D0A524.96D40F30", + "1, image002.png@01D0A524.96D40F30", + "2, image003.png@01D0A526.B4C739C0", + "3, image006.jpg@01D0A526.B649E220" + }) + void testReadContentIDField(int index, String contentId) { + AttachmentChunks attachment = inlineImgMsgAttachments.getAttachmentFiles()[index]; + String fileName = contentId.substring(0, contentId.indexOf("@")); + String extension = fileName.substring(fileName.lastIndexOf(".")); + + assertEquals(fileName, attachment.getAttachFileName().getValue()); + assertEquals(extension, attachment.getAttachExtension().getValue()); + assertEquals(contentId, attachment.getAttachContentId().getValue()); } @@ -128,7 +119,7 @@ public class TestFileWithAttachmentsRead { assertEquals("test-unicode.doc", attachment.getAttachLongFileName().getValue()); assertEquals(".doc", attachment.getAttachExtension().getValue()); assertNull(attachment.getAttachMimeTag()); - ByteArrayOutputStream attachmentstream = new ByteArrayOutputStream(); + UnsynchronizedByteArrayOutputStream attachmentstream = new UnsynchronizedByteArrayOutputStream(); attachment.getAttachData().writeValue(attachmentstream); assertEquals(24064, attachmentstream.size()); // or compare the hashes of the attachment data @@ -141,7 +132,7 @@ public class TestFileWithAttachmentsRead { assertNull(attachment.getAttachMimeTag()); // or compare the hashes of the attachment data assertEquals(89, attachment.getAttachData().getValue().length); - attachmentstream = new ByteArrayOutputStream(); + attachmentstream.reset(); attachment.getAttachData().writeValue(attachmentstream); assertEquals(89, attachmentstream.size()); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java index 04131f3a23..74d6d27ec2 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestFixedSizedProperties.java @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashSet; @@ -33,6 +32,7 @@ import java.util.Locale; import java.util.Map; import java.util.TimeZone; +import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hsmf.datatypes.ChunkBasedPropertyValue; import org.apache.poi.hsmf.datatypes.Chunks; @@ -44,7 +44,6 @@ import org.apache.poi.hsmf.dev.HSMFDump; import org.apache.poi.hsmf.extractor.OutlookTextExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NullPrintStream; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -167,7 +166,7 @@ public final class TestFixedSizedProperties { * Test to see if we can read the Date Chunk with HSMFDump. */ @Test - void testReadMessageDateSucceedsWithHSMFDump() throws IOException { + void testReadMessageDateSucceedsWithHSMFDump() { HSMFDump dump = new HSMFDump(fsMessageSucceeds); assertDoesNotThrow(() -> dump.dump(new NullPrintStream())); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java index 937bb5367d..fba8bc97c0 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestCase.java @@ -17,10 +17,10 @@ package org.apache.poi.hwpf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -29,7 +29,7 @@ public abstract class HWPFTestCase { @BeforeEach void setUp() throws Exception { - /** @todo verify the constructors */ + // @TODO verify the constructors _hWPFDocFixture = new HWPFDocFixture(this, getTestFile()); _hWPFDocFixture.setUp(); @@ -40,7 +40,7 @@ public abstract class HWPFTestCase { } @AfterEach - void tearDown() throws Exception { + void tearDown() { if (_hWPFDocFixture != null) { _hWPFDocFixture.tearDown(); } @@ -49,15 +49,13 @@ public abstract class HWPFTestCase { } public HWPFDocument writeOutAndRead(HWPFDocument doc) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - HWPFDocument newDoc; - try { + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) { doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - newDoc = new HWPFDocument(bais); + try (InputStream is = baos.toInputStream()) { + return new HWPFDocument(is); + } } catch (IOException e) { throw new RuntimeException(e); } - return newDoc; } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java index b8f11dc40f..0d6ce9bc8c 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/HWPFTestDataSamples.java @@ -16,74 +16,24 @@ ==================================================================== */ package org.apache.poi.hwpf; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.zip.ZipInputStream; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; - -import static org.apache.logging.log4j.util.Unbox.box; public class HWPFTestDataSamples { - - private static final Logger LOG = LogManager.getLogger(HWPFTestDataSamples.class); + private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); public static HWPFDocument openSampleFile(String sampleFileName) { - try { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); - try { - return new HWPFDocument(is); - } catch (Throwable e) { - is.close(); - throw e; - } + try (InputStream is = SAMPLES.openResourceAsStream(sampleFileName)) { + return new HWPFDocument(is); } catch (IOException e) { throw new RuntimeException(e); } } - public static HWPFDocument openSampleFileFromArchive( String sampleFileName ) - { - final long start = System.currentTimeMillis(); - try - { - try (ZipInputStream is = new ZipInputStream(POIDataSamples - .getDocumentInstance() - .openResourceAsStream(sampleFileName))) { - is.getNextEntry(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - IOUtils.copy(is, baos); - } finally { - baos.close(); - } - - final long endUnzip = System.currentTimeMillis(); - byte[] byteArray = baos.toByteArray(); - - LOG.atDebug().log("Unzipped in {} ms -- {} byte(s)", box(endUnzip - start),box(byteArray.length)); - - ByteArrayInputStream bais = new ByteArrayInputStream(byteArray); - HWPFDocument doc = new HWPFDocument(bais); - final long endParse = System.currentTimeMillis(); - - LOG.atDebug().log("Parsed in {} ms", box(endParse - start)); - - return doc; - } - } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - } - public static HWPFOldDocument openOldSampleFile(String sampleFileName) { try { InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); @@ -98,11 +48,9 @@ public class HWPFTestDataSamples { * Useful for verifying that the serialisation round trip */ public static HWPFDocument writeOutAndReadBack(HWPFDocument original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(4096)) { original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HWPFDocument(bais); + return new HWPFDocument(baos.toInputStream()); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java index 3a94a3efb4..c7cd45c1cc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/dev/TestHWPFLister.java @@ -22,7 +22,7 @@ import java.io.PrintStream; import java.util.Arrays; import org.apache.poi.POIDataSamples; -import org.apache.poi.util.NullPrintStream; +import org.apache.commons.io.output.NullPrintStream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -38,7 +38,7 @@ public class TestHWPFLister { "", " --dop --textPieces --textPiecesText --chpx --chpxProperties --chpxSprms --papx --papxProperties --papxSprms --paragraphs --paragraphsText --bookmarks --escher --fields --pictures --officeDrawings --styles --writereadback" }) - void main(String args) throws Exception { + void main(String args) { String fileArgs = SAMPLES.getFile("SampleDoc.doc").getAbsolutePath() + args; PrintStream oldStdOut = System.out; diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java index 0ae2e4a87a..b98f5208a0 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestSavedByTable.java @@ -17,17 +17,15 @@ package org.apache.poi.hwpf.model; +import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; +import static org.apache.poi.hwpf.HWPFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Arrays; import java.util.List; import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; import org.junit.jupiter.api.Test; /** @@ -53,29 +51,21 @@ public final class TestSavedByTable { * Tests reading in the entries, comparing them against the expected * entries. Then tests writing the document out and reading the entries yet * again. - * - * @throws Exception if an unexpected error occurs. */ @Test void testReadWrite() throws IOException { // This document is widely available on the internet as "blair.doc". // I tried stripping the content and saving the document but my version // of Word (from Office XP) strips this table out. - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc"); + try (HWPFDocument doc = openSampleFile("saved-by-table.doc")) { + // Check what we just read. + assertEquals(expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected"); - // Check what we just read. - assertEquals( expected, doc.getSavedByTable().getEntries(), "List of saved-by entries was not as expected" ); - - // Now write the entire document out, and read it back in... - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - doc.write(byteStream); - InputStream copyStream = new ByteArrayInputStream(byteStream.toByteArray()); - doc.close(); - HWPFDocument copy = new HWPFDocument(copyStream); - - // And check again. - assertEquals( expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing" ); - - copy.close(); + // Now write the entire document out, and read it back in... + try (HWPFDocument copy = writeOutAndReadBack(doc)) { + // And check again. + assertEquals(expected, copy.getSavedByTable().getEntries(), "List of saved-by entries was incorrect after writing"); + } + } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java index 65c5dac5a8..d8cbba82c8 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/sprm/TestSprms.java @@ -19,43 +19,29 @@ package org.apache.poi.hwpf.sprm; +import static org.apache.poi.hwpf.HWPFTestDataSamples.openSampleFile; +import static org.apache.poi.hwpf.HWPFTestDataSamples.writeOutAndReadBack; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Locale; -import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Paragraph; import org.apache.poi.hwpf.usermodel.Range; import org.junit.jupiter.api.Test; public class TestSprms { - private static HWPFDocument reload( HWPFDocument hwpfDocument ) - throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hwpfDocument.write( baos ); - return new HWPFDocument( new ByteArrayInputStream( baos.toByteArray() ) ); - } - /** * Test correct processing of "sprmPItap" (0x6649) and "sprmPFInTable" * (0x2416) */ @Test void testInnerTable() throws Exception { - InputStream resourceAsStream = POIDataSamples.getDocumentInstance() - .openResourceAsStream( "innertable.doc" ); - try (HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream )) { - resourceAsStream.close(); - + try (HWPFDocument hwpfDocument = openSampleFile("innertable.doc")) { testInnerTable(hwpfDocument); - try (HWPFDocument hwpfDocument2 = reload(hwpfDocument)) { + try (HWPFDocument hwpfDocument2 = writeOutAndReadBack(hwpfDocument)) { testInnerTable(hwpfDocument2); } } @@ -87,20 +73,12 @@ public class TestSprms { */ @Test void testSprmPJc() throws IOException { - try (InputStream resourceAsStream = POIDataSamples.getDocumentInstance() - .openResourceAsStream( "Bug49820.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream )) { - resourceAsStream.close(); + try (HWPFDocument hwpfDocument = openSampleFile( "Bug49820.doc" )) { + assertEquals(1, hwpfDocument.getStyleSheet().getParagraphStyle(8).getJustification()); - assertEquals(1, hwpfDocument.getStyleSheet().getParagraphStyle(8) - .getJustification()); - - try (HWPFDocument hwpfDocument2 = reload(hwpfDocument)) { - - assertEquals(1, hwpfDocument2.getStyleSheet().getParagraphStyle(8) - .getJustification()); + try (HWPFDocument hwpfDocument2 = writeOutAndReadBack(hwpfDocument)) { + assertEquals(1, hwpfDocument2.getStyleSheet().getParagraphStyle(8).getJustification()); } } - } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java index 3f0f8b7ce0..36ad393a51 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java @@ -20,14 +20,13 @@ package org.apache.poi.hwpf.usermodel; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.POIDataSamples; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.HWPFTestCase; @@ -48,20 +47,17 @@ public final class TestHWPFWrite extends HWPFTestCase { */ @Test void testWriteStream() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); - - Range r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - doc.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(); + try (HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc")) { + Range r = doc.getRange(); + assertEquals("I am a test document\r", r.getParagraph(0).text()); + doc.write(baos); + } - doc = new HWPFDocument(bais); - r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - doc.close(); + try (HWPFDocument doc = new HWPFDocument(baos.toInputStream())) { + Range r = doc.getRange(); + assertEquals("I am a test document\r", r.getParagraph(0).text()); + } } /** |