diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2018-08-26 11:55:00 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2018-08-26 11:55:00 +0000 |
commit | 96d5fab4836225c0aebb0d71bff4a04ae98858e0 (patch) | |
tree | 9d00b62a855d26156f70ed40ee0805083b999e1b /src/java | |
parent | 636d9495a52686df0f570db57d56a72f12274e3c (diff) | |
download | poi-96d5fab4836225c0aebb0d71bff4a04ae98858e0.tar.gz poi-96d5fab4836225c0aebb0d71bff4a04ae98858e0.zip |
#62649 - Remove OPOIFS
Fix HPSF UTF-8 encoding error with Bug52311.doc while refactoring CopyCompare/EntryUtils
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1839201 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/java')
44 files changed, 697 insertions, 3222 deletions
diff --git a/src/java/org/apache/poi/POIDocument.java b/src/java/org/apache/poi/POIDocument.java index 4d86f13927..c2c19fcea6 100644 --- a/src/java/org/apache/poi/POIDocument.java +++ b/src/java/org/apache/poi/POIDocument.java @@ -40,7 +40,6 @@ import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptor; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.IOUtils; import org.apache.poi.util.Internal; @@ -80,14 +79,6 @@ public abstract class POIDocument implements Closeable { * * @param fs the filesystem the document is read from */ - protected POIDocument(OPOIFSFileSystem fs) { - this(fs.getRoot()); - } - /** - * Constructs from an old-style OPOIFS - * - * @param fs the filesystem the document is read from - */ protected POIDocument(NPOIFSFileSystem fs) { this(fs.getRoot()); } @@ -195,6 +186,7 @@ public abstract class POIDocument implements Closeable { * @param setName The property to read * @return The value of the given property or null if it wasn't found. */ + @SuppressWarnings("WeakerAccess") protected PropertySet getPropertySet(String setName) throws IOException { return getPropertySet(setName, getEncryptionInfo()); } @@ -207,6 +199,7 @@ public abstract class POIDocument implements Closeable { * @param encryptionInfo the encryption descriptor in case of cryptoAPI encryption * @return The value of the given property or null if it wasn't found. */ + @SuppressWarnings("WeakerAccess") protected PropertySet getPropertySet(String setName, EncryptionInfo encryptionInfo) throws IOException { DirectoryNode dirNode = directory; @@ -329,7 +322,7 @@ public abstract class POIDocument implements Closeable { * @throws IOException if an error when writing to the * {@link NPOIFSFileSystem} occurs */ - protected void writePropertySet(String name, PropertySet set, NPOIFSFileSystem outFS) throws IOException { + private void writePropertySet(String name, PropertySet set, NPOIFSFileSystem outFS) throws IOException { try { PropertySet mSet = new PropertySet(set); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); @@ -420,8 +413,9 @@ public abstract class POIDocument implements Closeable { /** * Closes the underlying {@link NPOIFSFileSystem} from which * the document was read, if any. Has no effect on documents - * opened from an InputStream, or newly created ones. - * <p>Once close() has been called, no further operations + * opened from an InputStream, or newly created ones.<p> + * + * Once {@code close()} has been called, no further operations * should be called on the document. */ @Override @@ -468,13 +462,10 @@ public abstract class POIDocument implements Closeable { * to a new POIFSFileSystem * * @param newDirectory the new directory - * @return the old/previous directory */ @Internal - protected DirectoryNode replaceDirectory(DirectoryNode newDirectory) { - DirectoryNode dn = directory; + protected void replaceDirectory(DirectoryNode newDirectory) { directory = newDirectory; - return dn; } /** diff --git a/src/java/org/apache/poi/POIReadOnlyDocument.java b/src/java/org/apache/poi/POIReadOnlyDocument.java index 3b3eca588d..ef4956f525 100644 --- a/src/java/org/apache/poi/POIReadOnlyDocument.java +++ b/src/java/org/apache/poi/POIReadOnlyDocument.java @@ -21,8 +21,6 @@ import java.io.OutputStream; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** @@ -32,16 +30,10 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem; * @since POI 3.15 beta 3 */ public abstract class POIReadOnlyDocument extends POIDocument { - public POIReadOnlyDocument(DirectoryNode dir) { + protected POIReadOnlyDocument(DirectoryNode dir) { super(dir); } - public POIReadOnlyDocument(NPOIFSFileSystem fs) { - super(fs); - } - public POIReadOnlyDocument(OPOIFSFileSystem fs) { - super(fs); - } - public POIReadOnlyDocument(POIFSFileSystem fs) { + protected POIReadOnlyDocument(NPOIFSFileSystem fs) { super(fs); } diff --git a/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java b/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java index fda090729e..8b2e7bba2c 100644 --- a/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java +++ b/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java @@ -26,20 +26,14 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.apache.poi.EncryptedDocumentException; import org.apache.poi.hssf.OldExcelFormatException; import org.apache.poi.hssf.extractor.EventBasedExcelExtractor; import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; @@ -50,24 +44,24 @@ import org.apache.poi.util.POILogger; * <p>Note 1 - will fail for many file formats if the POI Scratchpad jar is * not present on the runtime classpath</p> * <p>Note 2 - for text extractor creation across all formats, use - * {@link org.apache.poi.extractor.ExtractorFactory} contained within + * {@link org.apache.poi.ooxml.extractor.ExtractorFactory} contained within * the OOXML jar.</p> * <p>Note 3 - rather than using this, for most cases you would be better * off switching to <a href="http://tika.apache.org">Apache Tika</a> instead!</p> */ @SuppressWarnings("WeakerAccess") -public class OLE2ExtractorFactory { +public final class OLE2ExtractorFactory { private static final POILogger LOGGER = POILogFactory.getLogger(OLE2ExtractorFactory.class); /** Should this thread prefer event based over usermodel based extractors? */ - private static final ThreadLocal<Boolean> threadPreferEventExtractors = new ThreadLocal<Boolean>() { - @Override - protected Boolean initialValue() { return Boolean.FALSE; } - }; + private static final ThreadLocal<Boolean> threadPreferEventExtractors = ThreadLocal.withInitial(() -> Boolean.FALSE); /** Should all threads prefer event based over usermodel based extractors? */ private static Boolean allPreferEventExtractors; + private OLE2ExtractorFactory() { + } + /** * Should this thread prefer event based over usermodel based extractors? * (usermodel extractors tend to be more accurate, but use more memory) @@ -113,16 +107,16 @@ public class OLE2ExtractorFactory { return threadPreferEventExtractors.get(); } + @SuppressWarnings("unchecked") public static <T extends POITextExtractor> T createExtractor(POIFSFileSystem fs) throws IOException { return (T)createExtractor(fs.getRoot()); } + @SuppressWarnings("unchecked") public static <T extends POITextExtractor> T createExtractor(NPOIFSFileSystem fs) throws IOException { return (T)createExtractor(fs.getRoot()); } - public static <T extends POITextExtractor> T createExtractor(OPOIFSFileSystem fs) throws IOException { - return (T)createExtractor(fs.getRoot()); - } + @SuppressWarnings("unchecked") public static <T extends POITextExtractor> T createExtractor(InputStream input) throws IOException { Class<?> cls = getOOXMLClass(); if (cls != null) { @@ -165,7 +159,7 @@ public class OLE2ExtractorFactory { /** * Create the Extractor, if possible. Generally needs the Scratchpad jar. * Note that this won't check for embedded OOXML resources either, use - * {@link org.apache.poi.extractor.ExtractorFactory} for that. + * {@link org.apache.poi.ooxml.extractor.ExtractorFactory} for that. */ public static POITextExtractor createExtractor(DirectoryNode poifsDir) throws IOException { // Look for certain entries in the stream, to figure it @@ -205,6 +199,7 @@ public class OLE2ExtractorFactory { * empty array. Otherwise, you'll get one open * {@link POITextExtractor} for each embedded file. */ + @SuppressWarnings("unused") public static POITextExtractor[] getEmbededDocsTextExtractors(POIOLE2TextExtractor ext) throws IOException { @@ -254,40 +249,11 @@ public class OLE2ExtractorFactory { for (InputStream nonPOIF : nonPOIFS) { try { e.add(createExtractor(nonPOIF)); - } catch (IllegalArgumentException ie) { - // Ignore, just means it didn't contain - // a format we support as yet - LOGGER.log(POILogger.WARN, ie); } catch (Exception xe) { // Ignore, invalid format LOGGER.log(POILogger.WARN, xe); } } - return e.toArray(new POITextExtractor[e.size()]); - } - - private static POITextExtractor createEncyptedOOXMLExtractor(DirectoryNode poifsDir) - throws IOException { - String pass = Biff8EncryptionKey.getCurrentUserPassword(); - if (pass == null) { - pass = Decryptor.DEFAULT_PASSWORD; - } - - EncryptionInfo ei = new EncryptionInfo(poifsDir); - Decryptor dec = ei.getDecryptor(); - InputStream is = null; - try { - if (!dec.verifyPassword(pass)) { - throw new EncryptedDocumentException("Invalid password specified - use Biff8EncryptionKey.setCurrentUserPassword() before calling extractor"); - } - is = dec.getDataStream(poifsDir); - return createExtractor(is); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new IOException(e); - } finally { - IOUtils.closeQuietly(is); - } + return e.toArray(new POITextExtractor[0]); } } diff --git a/src/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java b/src/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java index 3f6731c51d..868f1bf36e 100644 --- a/src/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java +++ b/src/java/org/apache/poi/hpsf/HPSFPropertiesOnlyDocument.java @@ -26,7 +26,6 @@ import org.apache.poi.POIDocument; import org.apache.poi.poifs.filesystem.EntryUtils; import org.apache.poi.poifs.filesystem.FilteringDirectoryNode; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; /** @@ -39,9 +38,6 @@ public class HPSFPropertiesOnlyDocument extends POIDocument { public HPSFPropertiesOnlyDocument(NPOIFSFileSystem fs) { super(fs.getRoot()); } - public HPSFPropertiesOnlyDocument(OPOIFSFileSystem fs) { - super(fs); - } public HPSFPropertiesOnlyDocument(POIFSFileSystem fs) { super(fs); } @@ -60,24 +56,18 @@ public class HPSFPropertiesOnlyDocument extends POIDocument { * Write out, with any properties changes, but nothing else */ public void write(File newFile) throws IOException { - POIFSFileSystem fs = POIFSFileSystem.create(newFile); - try { + try (POIFSFileSystem fs = POIFSFileSystem.create(newFile)) { write(fs); fs.writeFilesystem(); - } finally { - fs.close(); } } /** * Write out, with any properties changes, but nothing else */ public void write(OutputStream out) throws IOException { - NPOIFSFileSystem fs = new NPOIFSFileSystem(); - try { + try (NPOIFSFileSystem fs = new NPOIFSFileSystem()) { write(fs); fs.writeFilesystem(out); - } finally { - fs.close(); } } diff --git a/src/java/org/apache/poi/hpsf/Property.java b/src/java/org/apache/poi/hpsf/Property.java index df38d7a597..8878497dc3 100644 --- a/src/java/org/apache/poi/hpsf/Property.java +++ b/src/java/org/apache/poi/hpsf/Property.java @@ -345,9 +345,13 @@ public class Property { * @return the truncated size with a maximum of 4 bytes shorter (3 bytes + trailing 0 of strings) */ private static int unpaddedLength(byte[] buf) { - int len; - for (len = buf.length; len > 0 && len > buf.length-4 && buf[len-1] == 0; len--); - return len; + final int end = (buf.length-(buf.length+3)%4); + for (int i = buf.length; i>end; i--) { + if (buf[i-1] != 0) { + return i; + } + } + return end; } diff --git a/src/java/org/apache/poi/hpsf/PropertySet.java b/src/java/org/apache/poi/hpsf/PropertySet.java index 77621419ba..70c0a1bf16 100644 --- a/src/java/org/apache/poi/hpsf/PropertySet.java +++ b/src/java/org/apache/poi/hpsf/PropertySet.java @@ -34,8 +34,11 @@ import org.apache.poi.poifs.filesystem.Entry; import org.apache.poi.util.CodePageUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; +import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianConsts; +import org.apache.poi.util.LittleEndianOutputStream; import org.apache.poi.util.NotImplemented; +import org.apache.poi.util.Removal; /** * Represents a property set in the Horrible Property Set Format @@ -175,8 +178,6 @@ public class PropertySet { * * @param stream Holds the data making out the property set * stream. - * @throws MarkUnsupportedException - * if the stream does not support the {@link InputStream#markSupported} method. * @throws IOException * if the {@link InputStream} cannot be accessed as needed. * @exception NoPropertySetStreamException @@ -185,8 +186,7 @@ public class PropertySet { * if a character encoding is not supported. */ public PropertySet(final InputStream stream) - throws NoPropertySetStreamException, MarkUnsupportedException, - IOException, UnsupportedEncodingException { + throws NoPropertySetStreamException, IOException { if (!isPropertySetStream(stream)) { throw new NoPropertySetStreamException(); } @@ -266,6 +266,7 @@ public class PropertySet { * * @param byteOrder The property set stream's low-level "byte order" field. */ + @SuppressWarnings("WeakerAccess") public void setByteOrder(int byteOrder) { this.byteOrder = byteOrder; } @@ -298,6 +299,7 @@ public class PropertySet { * * @param osVersion The property set stream's low-level "OS version" field. */ + @SuppressWarnings("WeakerAccess") public void setOSVersion(int osVersion) { this.osVersion = osVersion; } @@ -315,6 +317,7 @@ public class PropertySet { * * @param classID The property set stream's low-level "class ID" field. */ + @SuppressWarnings("WeakerAccess") public void setClassID(ClassID classID) { this.classID = classID; } @@ -374,12 +377,10 @@ public class PropertySet { * {@link InputStream#mark} method. * @return {@code true} if the stream is a property set * stream, else {@code false}. - * @throws MarkUnsupportedException if the {@link InputStream} - * does not support the {@link InputStream#mark} method. * @exception IOException if an I/O error occurs */ public static boolean isPropertySetStream(final InputStream stream) - throws MarkUnsupportedException, IOException { + throws IOException { /* * Read at most this many bytes. */ @@ -408,30 +409,34 @@ public class PropertySet { * @return {@code true} if the byte array is a property set * stream, {@code false} if not. */ + @SuppressWarnings({"unused", "WeakerAccess"}) public static boolean isPropertySetStream(final byte[] src, final int offset, final int length) { - /* FIXME (3): Ensure that at most "length" bytes are read. */ + LittleEndianByteArrayInputStream leis = new LittleEndianByteArrayInputStream(src, offset, length); /* * Read the header fields of the stream. They must always be * there. */ - int o = offset; - final int byteOrder = LittleEndian.getUShort(src, o); - o += LittleEndianConsts.SHORT_SIZE; - if (byteOrder != BYTE_ORDER_ASSERTION) { - return false; - } - final int format = LittleEndian.getUShort(src, o); - o += LittleEndianConsts.SHORT_SIZE; - if (format != FORMAT_ASSERTION) { + try { + final int byteOrder = leis.readUShort(); + if (byteOrder != BYTE_ORDER_ASSERTION) { + return false; + } + final int format = leis.readUShort(); + if (format != FORMAT_ASSERTION) { + return false; + } + final long osVersion = leis.readUInt(); + byte[] clsBuf = new byte[ClassID.LENGTH]; + leis.readFully(clsBuf); + + final ClassID classID = new ClassID(clsBuf, 0); + + final long sectionCount = leis.readUInt(); + return (sectionCount >= 0); + } catch (RuntimeException e) { return false; } - // final long osVersion = LittleEndian.getUInt(src, offset); - o += LittleEndianConsts.INT_SIZE; - // final ClassID classID = new ClassID(src, offset); - o += ClassID.LENGTH; - final long sectionCount = LittleEndian.getUInt(src, o); - return (sectionCount >= 0); } @@ -452,7 +457,7 @@ public class PropertySet { private void init(final byte[] src, final int offset, final int length) throws UnsupportedEncodingException { /* FIXME (3): Ensure that at most "length" bytes are read. */ - + /* * Read the stream's header fields. */ @@ -504,50 +509,60 @@ public class PropertySet { * @exception WritingNotSupportedException if HPSF does not yet support * writing a property's variant type. */ - public void write(final OutputStream out) - throws WritingNotSupportedException, IOException { + public void write(final OutputStream out) throws IOException, WritingNotSupportedException { + + out.write(toBytes()); + + /* Indicate that we're done */ + out.close(); + } + + private byte[] toBytes() throws WritingNotSupportedException, IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); + /* Write the number of sections in this property set stream. */ final int nrSections = getSectionCount(); /* Write the property set's header. */ - LittleEndian.putShort(out, (short) getByteOrder()); - LittleEndian.putShort(out, (short) getFormat()); - LittleEndian.putInt(getOSVersion(), out); - putClassId(out, getClassID()); - LittleEndian.putInt(nrSections, out); - int offset = OFFSET_HEADER; + leos.writeShort(getByteOrder()); + leos.writeShort(getFormat()); + leos.writeInt(getOSVersion()); + putClassId(bos, getClassID()); + leos.writeInt(nrSections); + + assert(bos.size() == OFFSET_HEADER); + + final int[][] offsets = new int[getSectionCount()][2]; /* Write the section list, i.e. the references to the sections. Each * entry in the section list consist of the section's class ID and the * section's offset relative to the beginning of the stream. */ - offset += nrSections * (ClassID.LENGTH + LittleEndianConsts.INT_SIZE); - final int sectionsBegin = offset; + int secCnt = 0; for (final Section section : getSections()) { final ClassID formatID = section.getFormatID(); if (formatID == null) { throw new NoFormatIDException(); } - putClassId(out, formatID); - LittleEndian.putUInt(offset, out); - try { - offset += section.getSize(); - } catch (HPSFRuntimeException ex) { - final Throwable cause = ex.getReason(); - if (cause instanceof UnsupportedEncodingException) { - throw new IllegalPropertySetDataException(cause); - } - throw ex; - } + putClassId(bos, formatID); + offsets[secCnt++][0] = bos.size(); + // offset dummy - filled later + leos.writeInt(-1); } /* Write the sections themselves. */ - offset = sectionsBegin; + secCnt = 0; for (final Section section : getSections()) { - offset += section.write(out); + offsets[secCnt++][1] = bos.size(); + section.write(bos); } - - /* Indicate that we're done */ - out.close(); + + byte[] result = bos.toByteArray(); + for (int[] off : offsets) { + LittleEndian.putInt(result, off[0], off[1]); + } + + return result; } /** @@ -586,15 +601,8 @@ public class PropertySet { * of a property's variant type. * @throws IOException if an I/O exception occurs. */ - public InputStream toInputStream() throws IOException, WritingNotSupportedException { - final ByteArrayOutputStream psStream = new ByteArrayOutputStream(); - try { - write(psStream); - } finally { - psStream.close(); - } - final byte[] streamData = psStream.toByteArray(); - return new ByteArrayInputStream(streamData); + public InputStream toInputStream() throws WritingNotSupportedException, IOException { + return new ByteArrayInputStream(toBytes()); } /** @@ -605,7 +613,7 @@ public class PropertySet { * * @return The property as a String, or null if unavailable */ - protected String getPropertyStringValue(final int propertyId) { + String getPropertyStringValue(final int propertyId) { Object propertyValue = getProperty(propertyId); return getPropertyStringValue(propertyValue); } @@ -724,7 +732,7 @@ public class PropertySet { * @throws NoSingleSectionException if the {@link PropertySet} has * more or less than one {@link Section}. */ - protected boolean getPropertyBooleanValue(final int id) throws NoSingleSectionException { + boolean getPropertyBooleanValue(final int id) throws NoSingleSectionException { return getFirstSection().getPropertyBooleanValue(id); } @@ -742,7 +750,7 @@ public class PropertySet { * @throws NoSingleSectionException if the {@link PropertySet} has * more or less than one {@link Section}. */ - protected int getPropertyIntValue(final int id) throws NoSingleSectionException { + int getPropertyIntValue(final int id) throws NoSingleSectionException { return getFirstSection().getPropertyIntValue(id); } @@ -774,6 +782,7 @@ public class PropertySet { * * @return The {@link PropertySet}'s first section. */ + @SuppressWarnings("WeakerAccess") public Section getFirstSection() { if (sections.isEmpty()) { throw new MissingSectionException("Property set does not contain any sections."); @@ -787,7 +796,11 @@ public class PropertySet { * If the {@link PropertySet} has only a single section this method returns it. * * @return The singleSection value + * + * @deprecated superfluous convenience method */ + @Deprecated + @Removal(version="5.0.0") public Section getSingleSection() { final int sectionCount = getSectionCount(); if (sectionCount != 1) { @@ -809,7 +822,7 @@ public class PropertySet { */ @Override public boolean equals(final Object o) { - if (o == null || !(o instanceof PropertySet)) { + if (!(o instanceof PropertySet)) { return false; } final PropertySet ps = (PropertySet) o; @@ -877,27 +890,28 @@ public class PropertySet { } - protected void remove1stProperty(long id) { + void remove1stProperty(long id) { getFirstSection().removeProperty(id); } - protected void set1stProperty(long id, String value) { + void set1stProperty(long id, String value) { getFirstSection().setProperty((int)id, value); } - protected void set1stProperty(long id, int value) { + void set1stProperty(long id, int value) { getFirstSection().setProperty((int)id, value); } - protected void set1stProperty(long id, boolean value) { + void set1stProperty(long id, boolean value) { getFirstSection().setProperty((int)id, value); } - protected void set1stProperty(long id, byte[] value) { + @SuppressWarnings("SameParameterValue") + void set1stProperty(long id, byte[] value) { getFirstSection().setProperty((int)id, value); } - private static void putClassId(final OutputStream out, final ClassID n) throws IOException { + private static void putClassId(final ByteArrayOutputStream out, final ClassID n) { byte[] b = new byte[16]; n.write(b, 0); out.write(b, 0, b.length); diff --git a/src/java/org/apache/poi/hpsf/Section.java b/src/java/org/apache/poi/hpsf/Section.java index bcacfb3348..1411d0490f 100644 --- a/src/java/org/apache/poi/hpsf/Section.java +++ b/src/java/org/apache/poi/hpsf/Section.java @@ -36,6 +36,7 @@ import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndianByteArrayInputStream; import org.apache.poi.util.LittleEndianConsts; +import org.apache.poi.util.LittleEndianOutputStream; import org.apache.poi.util.POILogFactory; import org.apache.poi.util.POILogger; @@ -81,7 +82,7 @@ public class Section { * #getPropertyIntValue} or {@link #getProperty} tried to access a * property that was not available, else {@code false}. */ - private boolean wasNull; + private transient boolean wasNull; /** * Creates an empty {@link Section}. @@ -292,6 +293,7 @@ public class Section { * @param formatID The section's format ID as a byte array. It components * are in big-endian format. */ + @SuppressWarnings("WeakerAccess") public void setFormatID(final byte[] formatID) { ClassID fid = getFormatID(); if (fid == null) { @@ -325,7 +327,7 @@ public class Section { * @return This section's properties. */ public Property[] getProperties() { - return properties.values().toArray(new Property[properties.size()]); + return properties.values().toArray(new Property[0]); } /** @@ -375,7 +377,7 @@ public class Section { * @see #getProperty */ public void setProperty(final int id, final int value) { - setProperty(id, Variant.VT_I4, Integer.valueOf(value)); + setProperty(id, Variant.VT_I4, value); } @@ -390,7 +392,7 @@ public class Section { * @see #getProperty */ public void setProperty(final int id, final long value) { - setProperty(id, Variant.VT_I8, Long.valueOf(value)); + setProperty(id, Variant.VT_I8, value); } @@ -405,7 +407,7 @@ public class Section { * @see #getProperty */ public void setProperty(final int id, final boolean value) { - setProperty(id, Variant.VT_BOOL, Boolean.valueOf(value)); + setProperty(id, Variant.VT_BOOL, value); } @@ -487,7 +489,7 @@ public class Section { * * @return The property's value */ - protected int getPropertyIntValue(final long id) { + int getPropertyIntValue(final long id) { final Number i; final Object o = getProperty(id); if (o == null) { @@ -513,9 +515,9 @@ public class Section { * * @return The property's value */ - protected boolean getPropertyBooleanValue(final int id) { + boolean getPropertyBooleanValue(final int id) { final Boolean b = (Boolean) getProperty(id); - return b != null && b.booleanValue(); + return b != null && b; } /** @@ -529,8 +531,9 @@ public class Section { * @see #getProperty * @see Variant */ + @SuppressWarnings("unused") protected void setPropertyBooleanValue(final int id, final boolean value) { - setProperty(id, Variant.VT_BOOL, Boolean.valueOf(value)); + setProperty(id, Variant.VT_BOOL, value); } /** @@ -588,6 +591,7 @@ public class Section { * #getPropertyIntValue} or {@link #getProperty} tried to access a * property that was not available, else {@code false}. */ + @SuppressWarnings("WeakerAccess") public boolean wasNull() { return wasNull; } @@ -674,7 +678,7 @@ public class Section { for (Long id : propIds) { Property p1 = properties.get(id); Property p2 = s.properties.get(id); - if (p1 == null || p2 == null || !p1.equals(p2)) { + if (p1 == null || !p1.equals(p2)) { return false; } } @@ -683,7 +687,7 @@ public class Section { Map<Long,String> d1 = getDictionary(); Map<Long,String> d2 = s.getDictionary(); - return (d1 == null && d2 == null) || (d1 != null && d2 != null && d1.equals(d2)); + return (d1 == null && d2 == null) || (d1 != null && d1.equals(d2)); } /** @@ -691,6 +695,7 @@ public class Section { * * @param id The ID of the property to be removed */ + @SuppressWarnings("WeakerAccess") public void removeProperty(final long id) { if (properties.remove(id) != null) { sectionBytes.reset(); @@ -731,60 +736,54 @@ public class Section { codepage = Property.DEFAULT_CODEPAGE; } - /* The properties are written to this stream. */ - final ByteArrayOutputStream propertyStream = new ByteArrayOutputStream(); + final int[][] offsets = new int[properties.size()][2]; + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); - /* The property list is established here. After each property that has - * been written to "propertyStream", a property list entry is written to - * "propertyListStream". */ - final ByteArrayOutputStream propertyListStream = new ByteArrayOutputStream(); + /* Write the section's length - dummy value, fixed later */ + leos.writeInt(-1); - /* Maintain the current position in the list. */ - int position = 0; + /* Write the section's number of properties: */ + leos.writeInt(properties.size()); + + int propCnt = 0; + for (Property p : properties.values()) { + /* Write the property list entry. */ + leos.writeUInt(p.getID()); + // dummy offset to be fixed later + offsets[propCnt++][0] = bos.size(); + leos.writeInt(-1); + } - /* Increase the position variable by the size of the property list so - * that it points behind the property list and to the beginning of the - * properties themselves. */ - position += 2 * LittleEndianConsts.INT_SIZE + getPropertyCount() * 2 * LittleEndianConsts.INT_SIZE; /* Write the properties and the property list into their respective * streams: */ + propCnt = 0; for (Property p : properties.values()) { - final long id = p.getID(); - - /* Write the property list entry. */ - LittleEndian.putUInt(id, propertyListStream); - LittleEndian.putUInt(position, propertyListStream); - + offsets[propCnt++][1] = bos.size(); /* If the property ID is not equal 0 we write the property and all * is fine. However, if it equals 0 we have to write the section's * dictionary which has an implicit type only and an explicit * value. */ - if (id != 0) { + if (p.getID() != 0) { /* Write the property and update the position to the next * property. */ - position += p.write(propertyStream, codepage); + p.write(bos, codepage); } else { - position += writeDictionary(propertyStream, codepage); + writeDictionary(bos, codepage); } } - /* Write the section: */ - int streamLength = LittleEndianConsts.INT_SIZE * 2 + propertyListStream.size() + propertyStream.size(); - - /* Write the section's length: */ - LittleEndian.putInt(streamLength, out); + byte[] result = bos.toByteArray(); + LittleEndian.putInt(result, 0, bos.size()); - /* Write the section's number of properties: */ - LittleEndian.putInt(getPropertyCount(), out); - - /* Write the property list: */ - propertyListStream.writeTo(out); + for (int[] off : offsets) { + LittleEndian.putUInt(result, off[0], off[1]); + } - /* Write the properties: */ - propertyStream.writeTo(out); + out.write(result); - return streamLength; + return bos.size(); } /** @@ -795,12 +794,8 @@ public class Section { * @param codepage The codepage of the string values. * * @return {@code true} if dictionary was read successful, {@code false} otherwise - * - * @throws UnsupportedEncodingException if the dictionary's codepage is not - * (yet) supported. */ - private boolean readDictionary(LittleEndianByteArrayInputStream leis, final int length, final int codepage) - throws UnsupportedEncodingException { + private boolean readDictionary(LittleEndianByteArrayInputStream leis, final int length, final int codepage) { Map<Long,String> dic = new HashMap<>(); /* @@ -863,13 +858,12 @@ public class Section { * * @param out The output stream to write to. * @param codepage The codepage to be used to write the dictionary items. - * @return The number of bytes written * @exception IOException if an I/O exception occurs. */ - private int writeDictionary(final OutputStream out, final int codepage) + private void writeDictionary(final OutputStream out, final int codepage) throws IOException { final byte padding[] = new byte[4]; - Map<Long,String> dic = getDictionary(); + final Map<Long,String> dic = getDictionary(); LittleEndian.putUInt(dic.size(), out); int length = LittleEndianConsts.INT_SIZE; @@ -878,26 +872,23 @@ public class Section { LittleEndian.putUInt(ls.getKey(), out); length += LittleEndianConsts.INT_SIZE; - String value = ls.getValue()+"\0"; - LittleEndian.putUInt( value.length(), out ); + final String value = ls.getValue()+"\0"; + final byte bytes[] = CodePageUtil.getBytesInCodePage(value, codepage); + final int len = (codepage == CodePageUtil.CP_UNICODE) ? value.length() : bytes.length; + + LittleEndian.putUInt( len, out ); length += LittleEndianConsts.INT_SIZE; - byte bytes[] = CodePageUtil.getBytesInCodePage(value, codepage); out.write(bytes); length += bytes.length; - if (codepage == CodePageUtil.CP_UNICODE) { - int pad = (4 - (length & 0x3)) & 0x3; - out.write(padding, 0, pad); - length += pad; - } + final int pad = (codepage == CodePageUtil.CP_UNICODE) ? ((4 - (length & 0x3)) & 0x3) : 0; + out.write(padding, 0, pad); + length += pad; } - int pad = (4 - (length & 0x3)) & 0x3; + final int pad = (4 - (length & 0x3)) & 0x3; out.write(padding, 0, pad); - length += pad; - - return length; } /** diff --git a/src/java/org/apache/poi/poifs/storage/SmallDocumentBlockList.java b/src/java/org/apache/poi/poifs/common/package-info.java index cc6bb7c17f..2df44254bd 100644 --- a/src/java/org/apache/poi/poifs/storage/SmallDocumentBlockList.java +++ b/src/java/org/apache/poi/poifs/common/package-info.java @@ -1,4 +1,3 @@ - /* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -15,27 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ - - -package org.apache.poi.poifs.storage; - -import java.util.*; /** - * A list of SmallDocumentBlocks instances, and methods to manage the list + * common package contains constants and other classes shared across all POIFS subpackages */ -public class SmallDocumentBlockList - extends BlockListImpl -{ - /** - * Constructor SmallDocumentBlockList - * - * @param blocks a list of SmallDocumentBlock instances - */ - - public SmallDocumentBlockList(final List<SmallDocumentBlock> blocks) - { - setBlocks(blocks.toArray(new SmallDocumentBlock[blocks.size()])); - } -} - +package org.apache.poi.poifs.common;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/crypt/Decryptor.java b/src/java/org/apache/poi/poifs/crypt/Decryptor.java index da746d896e..0af59dce3d 100644 --- a/src/java/org/apache/poi/poifs/crypt/Decryptor.java +++ b/src/java/org/apache/poi/poifs/crypt/Decryptor.java @@ -27,7 +27,6 @@ import javax.crypto.spec.SecretKeySpec; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public abstract class Decryptor implements Cloneable { @@ -87,7 +86,7 @@ public abstract class Decryptor implements Cloneable { * @param cipher may be null, otherwise the given instance is reset to the new block index * @param block the block index, e.g. the persist/slide id (hslf) * @return a new cipher object, if cipher was null, otherwise the reinitialized cipher - * @throws GeneralSecurityException + * @throws GeneralSecurityException if the cipher can't be initialized */ public Cipher initCipherForBlock(Cipher cipher, int block) throws GeneralSecurityException { @@ -126,10 +125,6 @@ public abstract class Decryptor implements Cloneable { return getDataStream(fs.getRoot()); } - public InputStream getDataStream(OPOIFSFileSystem fs) throws IOException, GeneralSecurityException { - return getDataStream(fs.getRoot()); - } - public InputStream getDataStream(POIFSFileSystem fs) throws IOException, GeneralSecurityException { return getDataStream(fs.getRoot()); } @@ -147,6 +142,7 @@ public abstract class Decryptor implements Cloneable { return integrityHmacKey; } + @SuppressWarnings("unused") public byte[] getIntegrityHmacValue() { return integrityHmacValue; } @@ -167,6 +163,7 @@ public abstract class Decryptor implements Cloneable { this.integrityHmacValue = (integrityHmacValue == null) ? null : integrityHmacValue.clone(); } + @SuppressWarnings("unused") protected int getBlockSizeInBytes() { return encryptionInfo.getHeader().getBlockSize(); } diff --git a/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java b/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java index df08b3cf5b..eee1531622 100644 --- a/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java +++ b/src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java @@ -27,7 +27,6 @@ import java.io.IOException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; @@ -59,12 +58,14 @@ public class EncryptionInfo implements Cloneable { * A value that MUST be 0 if document properties are encrypted. * The encryption of document properties is specified in section 2.3.5.4. */ + @SuppressWarnings("WeakerAccess") public static final BitField flagDocProps = BitFieldFactory.getInstance(0x08); /** * A value that MUST be 1 if extensible encryption is used. If this value is 1, * the value of every other field in this structure MUST be 0. */ + @SuppressWarnings("WeakerAccess") public static final BitField flagExternal = BitFieldFactory.getInstance(0x10); /** @@ -84,13 +85,6 @@ public class EncryptionInfo implements Cloneable { /** * Opens for decryption */ - public EncryptionInfo(OPOIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - - /** - * Opens for decryption - */ public EncryptionInfo(NPOIFSFileSystem fs) throws IOException { this(fs.getRoot()); } @@ -167,11 +161,11 @@ public class EncryptionInfo implements Cloneable { * * @param encryptionMode see {@link EncryptionMode} for values, {@link EncryptionMode#cryptoAPI} is for * internal use only, as it's record based - * @param cipherAlgorithm - * @param hashAlgorithm - * @param keyBits - * @param blockSize - * @param chainingMode + * @param cipherAlgorithm the cipher algorithm + * @param hashAlgorithm the hash algorithm + * @param keyBits the bit count of the key + * @param blockSize the size of a cipher block + * @param chainingMode the chaining mode * * @throws EncryptedDocumentException if the given parameters mismatch, e.g. only certain combinations * of keyBits, blockSize are allowed for a given {@link CipherAlgorithm} @@ -211,10 +205,11 @@ public class EncryptionInfo implements Cloneable { * * @param encryptionMode the encryption mode * @return an encryption info builder - * @throws ClassNotFoundException - * @throws IllegalAccessException - * @throws InstantiationException + * @throws ClassNotFoundException if the builder class is not on the classpath + * @throws IllegalAccessException if the builder class can't be loaded + * @throws InstantiationException if the builder class can't be loaded */ + @SuppressWarnings("WeakerAccess") protected static EncryptionInfoBuilder getBuilder(EncryptionMode encryptionMode) throws ClassNotFoundException, IllegalAccessException, InstantiationException { ClassLoader cl = EncryptionInfo.class.getClassLoader(); diff --git a/src/java/org/apache/poi/poifs/crypt/Encryptor.java b/src/java/org/apache/poi/poifs/crypt/Encryptor.java index ff954ab6b1..386b8a8747 100644 --- a/src/java/org/apache/poi/poifs/crypt/Encryptor.java +++ b/src/java/org/apache/poi/poifs/crypt/Encryptor.java @@ -26,7 +26,6 @@ import javax.crypto.spec.SecretKeySpec; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem; public abstract class Encryptor implements Cloneable { @@ -55,9 +54,6 @@ public abstract class Encryptor implements Cloneable { public OutputStream getDataStream(NPOIFSFileSystem fs) throws IOException, GeneralSecurityException { return getDataStream(fs.getRoot()); } - public OutputStream getDataStream(OPOIFSFileSystem fs) throws IOException, GeneralSecurityException { - return getDataStream(fs.getRoot()); - } public OutputStream getDataStream(POIFSFileSystem fs) throws IOException, GeneralSecurityException { return getDataStream(fs.getRoot()); } diff --git a/src/java/org/apache/poi/poifs/crypt/package-info.java b/src/java/org/apache/poi/poifs/crypt/package-info.java new file mode 100644 index 0000000000..924b54ec15 --- /dev/null +++ b/src/java/org/apache/poi/poifs/crypt/package-info.java @@ -0,0 +1,35 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +/** + * Implementation of the ECMA-376 and MS-propritary document encryptions<p> + * + * The implementation is split into the following packages:<p> + * + * <ul> + * <li>This package contains common functions for both current implemented cipher modes.</li> + * <li>the {@link org.apache.poi.poifs.crypt.agile agile} package is part of the poi ooxml jar and the provides agile encryption support.</li> + * <li>the {@link org.apache.poi.poifs.crypt.binaryrc4 binaryrc} package is used for the fixed length RC4 encryption of biff/H**F formats</li> + * <li>the {@link org.apache.poi.poifs.crypt.cryptoapi cryptoapi} package is used for the variable length RC encryption of biff/H**F formats</li> + * <li>the {@link org.apache.poi.poifs.crypt.standard standard} package contains classes for the standard encryption ...</li> + * <li>the {@link org.apache.poi.poifs.crypt.xor xor} package contains classes for the xor obfuscation of biff/H**F formats</li> + * </ul> + * + * @see <a href="http://poi.apache.org/encryption.html">Apache POI - Encryption support</a> + * @see <a href="http://msdn.microsoft.com/en-us/library/dd952186(v=office.12).aspx">ECMA-376 Document Encryption</a> + */ +package org.apache.poi.poifs.crypt;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/crypt/package.html b/src/java/org/apache/poi/poifs/crypt/package.html deleted file mode 100644 index 977cf8b5a9..0000000000 --- a/src/java/org/apache/poi/poifs/crypt/package.html +++ /dev/null @@ -1,44 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> - -<p>Implementation of the <a href="http://msdn.microsoft.com/en-us/library/dd952186(v=office.12).aspx">ECMA-376 Document Encryption</a></p> -<p>The implementation is split into three packages:</p> -<ul> -<li>This package contains common functions for both current implemented cipher modes.</li> -<li>the {@link org.apache.poi.poifs.crypt.standard standard} package is part of the base poi jar and contains classes for the standard encryption ...</li> -<li>the {@link org.apache.poi.poifs.crypt.agile agile} package is part of the poi ooxml jar and the provides agile encryption support.</li> -</ul> - -<h2>Related Documentation</h2> - -Some implementations informations can be found under: -<ul> -<li><a href="http://poi.apache.org/encryption.html">Apache POI - Encryption support</a> -</ul> - -<!-- Put @see and @since tags down here. --> -@see org.apache.poi.poifs.crypt.standard -@see org.apache.poi.poifs.crypt.agile -</body> -</html> diff --git a/src/java/org/apache/poi/poifs/dev/POIFSHeaderDumper.java b/src/java/org/apache/poi/poifs/dev/POIFSHeaderDumper.java deleted file mode 100644 index 642ffa0f98..0000000000 --- a/src/java/org/apache/poi/poifs/dev/POIFSHeaderDumper.java +++ /dev/null @@ -1,181 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.dev; - -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.Property; -import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.poifs.storage.BlockAllocationTableReader; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.poifs.storage.ListManagedBlock; -import org.apache.poi.poifs.storage.RawDataBlockList; -import org.apache.poi.poifs.storage.SmallBlockTableReader; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.IntList; - -/** - * A very low level debugging tool, for printing out core - * information on the headers and FAT blocks. - * You probably only want to use this if you're trying - * to understand POIFS, or if you're trying to track - * down the source of corruption in a file. - */ -public class POIFSHeaderDumper { - /** - * Display the entries of multiple POIFS files - * - * @param args the names of the files to be displayed - */ - public static void main(final String args[]) throws Exception { - if (args.length == 0) { - System.err.println("Must specify at least one file to view"); - System.exit(1); - } - - for (int j = 0; j < args.length; j++) { - viewFile(args[j]); - } - } - - public static void viewFile(final String filename) throws Exception { - System.out.println("Dumping headers from: " + filename); - InputStream inp = new FileInputStream(filename); - - // Header - HeaderBlock header_block = new HeaderBlock(inp); - displayHeader(header_block); - - // Raw blocks - POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize(); - RawDataBlockList data_blocks = new RawDataBlockList(inp, bigBlockSize); - displayRawBlocksSummary(data_blocks); - - // Main FAT Table - BlockAllocationTableReader batReader = - new BlockAllocationTableReader( - header_block.getBigBlockSize(), - header_block.getBATCount(), - header_block.getBATArray(), - header_block.getXBATCount(), - header_block.getXBATIndex(), - data_blocks); - displayBATReader("Big Blocks", batReader); - - // Properties Table - PropertyTable properties = - new PropertyTable(header_block, data_blocks); - - // Mini Fat - BlockAllocationTableReader sbatReader = - SmallBlockTableReader._getSmallDocumentBlockReader( - bigBlockSize, data_blocks, properties.getRoot(), - header_block.getSBATStart() - ); - displayBATReader("Small Blocks", sbatReader); - - // Summary of the properties - displayPropertiesSummary(properties); - } - - public static void displayHeader(HeaderBlock header_block) throws Exception { - System.out.println("Header Details:"); - System.out.println(" Block size: " + header_block.getBigBlockSize().getBigBlockSize()); - System.out.println(" BAT (FAT) header blocks: " + header_block.getBATArray().length); - System.out.println(" BAT (FAT) block count: " + header_block.getBATCount()); - if (header_block.getBATCount() > 0) - System.out.println(" BAT (FAT) block 1 at: " + header_block.getBATArray()[0]); - System.out.println(" XBAT (FAT) block count: " + header_block.getXBATCount()); - System.out.println(" XBAT (FAT) block 1 at: " + header_block.getXBATIndex()); - System.out.println(" SBAT (MiniFAT) block count: " + header_block.getSBATCount()); - System.out.println(" SBAT (MiniFAT) block 1 at: " + header_block.getSBATStart()); - System.out.println(" Property table at: " + header_block.getPropertyStart()); - System.out.println(""); - } - - public static void displayRawBlocksSummary(RawDataBlockList data_blocks) throws Exception { - System.out.println("Raw Blocks Details:"); - System.out.println(" Number of blocks: " + data_blocks.blockCount()); - - for(int i=0; i<Math.min(16, data_blocks.blockCount()); i++) { - ListManagedBlock block = data_blocks.get(i); - byte[] data = new byte[Math.min(48, block.getData().length)]; - System.arraycopy(block.getData(), 0, data, 0, data.length); - - System.out.println(" Block #" + i + ":"); - System.out.println(HexDump.dump(data, 0, 0)); - } - - System.out.println(""); - } - - public static void displayBATReader(String type, BlockAllocationTableReader batReader) throws Exception { - System.out.println("Sectors, as referenced from the "+type+" FAT:"); - IntList entries = batReader.getEntries(); - - for(int i=0; i<entries.size(); i++) { - int bn = entries.get(i); - String bnS = Integer.toString(bn); - if(bn == POIFSConstants.END_OF_CHAIN) { - bnS = "End Of Chain"; - } else if(bn == POIFSConstants.DIFAT_SECTOR_BLOCK) { - bnS = "DI Fat Block"; - } else if(bn == POIFSConstants.FAT_SECTOR_BLOCK) { - bnS = "Normal Fat Block"; - } else if(bn == POIFSConstants.UNUSED_BLOCK) { - bnS = "Block Not Used (Free)"; - } - - System.out.println(" Block # " + i + " -> " + bnS); - } - - System.out.println(""); - } - - public static void displayPropertiesSummary(PropertyTable properties) { - System.out.println("Mini Stream starts at " + properties.getRoot().getStartBlock()); - System.out.println("Mini Stream length is " + properties.getRoot().getSize()); - System.out.println(); - - System.out.println("Properties and their block start:"); - displayProperties(properties.getRoot(), ""); - System.out.println(""); - } - public static void displayProperties(DirectoryProperty prop, String indent) { - String nextIndent = indent + " "; - System.out.println(indent + "-> " + prop.getName()); - for (Property cp : prop) { - if (cp instanceof DirectoryProperty) { - displayProperties((DirectoryProperty)cp, nextIndent); - } else { - System.out.println(nextIndent + "=> " + cp.getName()); - System.out.print(nextIndent + " " + cp.getSize() + " bytes in "); - if (cp.shouldUseSmallBlocks()) { - System.out.print("mini"); - } else { - System.out.print("main"); - } - System.out.println(" stream, starts at " + cp.getStartBlock()); - } - } - } -} diff --git a/src/java/org/apache/poi/poifs/common/package.html b/src/java/org/apache/poi/poifs/dev/package-info.java index da2edf1959..4d04219f88 100644 --- a/src/java/org/apache/poi/poifs/common/package.html +++ b/src/java/org/apache/poi/poifs/dev/package-info.java @@ -1,6 +1,4 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== +/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. @@ -15,21 +13,14 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> +==================================================================== */ -common package contains constants and other classes shared across all POIFS subpackages - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -</body> -</html> +/** + * DEV package serves two purposes. + * + * <ol> + * <li>Examples for how to use POIFS</li> + * <li>tools for developing and validating POIFS</li> + * </ol> + */ +package org.apache.poi.poifs.dev;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReader.java b/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReader.java index e61039360d..abb90acc26 100644 --- a/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReader.java +++ b/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReader.java @@ -19,23 +19,19 @@ package org.apache.poi.poifs.eventfilesystem; -import java.io.FileInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.Iterator; import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.OPOIFSDocument; +import org.apache.poi.poifs.filesystem.NPOIFSDocument; +import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSDocumentPath; import org.apache.poi.poifs.property.DirectoryProperty; +import org.apache.poi.poifs.property.DocumentProperty; +import org.apache.poi.poifs.property.NPropertyTable; import org.apache.poi.poifs.property.Property; -import org.apache.poi.poifs.property.PropertyTable; import org.apache.poi.poifs.property.RootProperty; -import org.apache.poi.poifs.storage.BlockAllocationTableReader; -import org.apache.poi.poifs.storage.BlockList; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.poifs.storage.RawDataBlockList; -import org.apache.poi.poifs.storage.SmallBlockTableReader; import org.apache.poi.util.IOUtils; /** @@ -49,62 +45,54 @@ import org.apache.poi.util.IOUtils; public class POIFSReader { - private final POIFSReaderRegistry registry; - private boolean registryClosed; + private final POIFSReaderRegistry registry = new POIFSReaderRegistry(); + private boolean registryClosed = false; private boolean notifyEmptyDirectories; +// private NPOIFSFileSystem poifs; /** - * Create a POIFSReader + * Read from an InputStream and process the documents we get + * + * @param stream the InputStream from which to read the data + * + * @exception IOException on errors reading, or on invalid data */ - public POIFSReader() - { - registry = new POIFSReaderRegistry(); - registryClosed = false; + public void read(final InputStream stream) throws IOException { + try (NPOIFSFileSystem poifs = new NPOIFSFileSystem(stream)) { + read(poifs); + } } /** - * Read from an InputStream and process the documents we get + * Read from a File and process the documents we get * - * @param stream the InputStream from which to read the data + * @param poifsFile the file from which to read the data * * @exception IOException on errors reading, or on invalid data */ + public void read(final File poifsFile) throws IOException { + try (NPOIFSFileSystem poifs = new NPOIFSFileSystem(poifsFile, true)) { + read(poifs); + } + } - public void read(final InputStream stream) - throws IOException - { + /** + * Read from a NPOIFSFileSystem and process the documents we get + * + * @param poifs the NPOIFSFileSystem from which to read the data + * + * @exception IOException on errors reading, or on invalid data + */ + public void read(final NPOIFSFileSystem poifs) throws IOException { registryClosed = true; - // read the header block from the stream - HeaderBlock header_block = new HeaderBlock(stream); - - // read the rest of the stream into blocks - RawDataBlockList data_blocks = new RawDataBlockList(stream, header_block.getBigBlockSize()); - - // set up the block allocation table (necessary for the - // data_blocks to be manageable - new BlockAllocationTableReader(header_block.getBigBlockSize(), - header_block.getBATCount(), - header_block.getBATArray(), - header_block.getXBATCount(), - header_block.getXBATIndex(), - data_blocks); - // get property table from the document - PropertyTable properties = - new PropertyTable(header_block, data_blocks); + NPropertyTable properties = poifs.getPropertyTable(); // process documents RootProperty root = properties.getRoot(); - processProperties(SmallBlockTableReader - .getSmallDocumentBlocks( - header_block.getBigBlockSize(), - data_blocks, root, - header_block.getSBATStart() - ), - data_blocks, root.getChildren(), new POIFSDocumentPath() - ); + processProperties(poifs, root, new POIFSDocumentPath()); } /** @@ -117,14 +105,11 @@ public class POIFSReader * called */ - public void registerListener(final POIFSReaderListener listener) - { - if (listener == null) - { + public void registerListener(final POIFSReaderListener listener) { + if (listener == null) { throw new NullPointerException(); } - if (registryClosed) - { + if (registryClosed) { throw new IllegalStateException(); } registry.registerListener(listener); @@ -143,9 +128,7 @@ public class POIFSReader * called */ - public void registerListener(final POIFSReaderListener listener, - final String name) - { + public void registerListener(final POIFSReaderListener listener, final String name) { registerListener(listener, null, name); } @@ -166,19 +149,14 @@ public class POIFSReader public void registerListener(final POIFSReaderListener listener, final POIFSDocumentPath path, - final String name) - { - if ((listener == null) || (name == null) || (name.length() == 0)) - { + final String name) { + if ((listener == null) || (name == null) || (name.length() == 0)) { throw new NullPointerException(); } - if (registryClosed) - { + if (registryClosed) { throw new IllegalStateException(); } - registry.registerListener(listener, - (path == null) ? new POIFSDocumentPath() - : path, name); + registry.registerListener(listener, (path == null) ? new POIFSDocumentPath() : path, name); } /** @@ -186,7 +164,7 @@ public class POIFSReader * If this flag is activated, the {@link POIFSReaderListener listener} receives * {@link POIFSReaderEvent POIFSReaderEvents} with nulled {@code name} and {@code stream} * - * @param notifyEmptyDirectories + * @param notifyEmptyDirectories if {@code true}, empty directories will be notified */ public void setNotifyEmptyDirectories(boolean notifyEmptyDirectories) { this.notifyEmptyDirectories = notifyEmptyDirectories; @@ -198,139 +176,72 @@ public class POIFSReader * * @param args names of the files * - * @exception IOException + * @exception IOException if the files can't be read or have invalid content */ - public static void main(String args[]) - throws IOException - { - if (args.length == 0) - { + public static void main(String args[]) throws IOException { + if (args.length == 0) { System.err.println("at least one argument required: input filename(s)"); System.exit(1); } // register for all - for (String arg : args) - { - POIFSReader reader = new POIFSReader(); - POIFSReaderListener listener = new SampleListener(); - - reader.registerListener(listener); + for (String arg : args) { + POIFSReader reader = new POIFSReader(); + reader.registerListener(POIFSReader::readEntry); System.out.println("reading " + arg); - FileInputStream istream = new FileInputStream(arg); - reader.read(istream); - istream.close(); + reader.read(new File(arg)); } } - private void processProperties(final BlockList small_blocks, - final BlockList big_blocks, - final Iterator<Property> properties, - final POIFSDocumentPath path) - throws IOException { - if (!properties.hasNext() && notifyEmptyDirectories) { - Iterator<POIFSReaderListener> listeners = registry.getListeners(path, "."); - while (listeners.hasNext()) { - POIFSReaderListener pl = listeners.next(); - POIFSReaderEvent pe = new POIFSReaderEvent(null, path, null); - pl.processPOIFSReaderEvent(pe); + private static void readEntry(POIFSReaderEvent event) { + POIFSDocumentPath path = event.getPath(); + StringBuilder sb = new StringBuilder(); + + try (DocumentInputStream istream = event.getStream()) { + sb.setLength(0); + int pathLength = path.length(); + for (int k = 0; k < pathLength; k++) { + sb.append("/").append(path.getComponent(k)); } - return; + byte[] data = IOUtils.toByteArray(istream); + sb.append("/").append(event.getName()).append(": ").append(data.length).append(" bytes read"); + System.out.println(sb); + } catch (IOException ignored) { } + } - while (properties.hasNext()) - { - Property property = properties.next(); - String name = property.getName(); + private void processProperties(final NPOIFSFileSystem poifs, DirectoryProperty dir, final POIFSDocumentPath path) { + boolean hasChildren = false; + for (final Property property : dir) { + hasChildren = true; + String name = property.getName(); if (property.isDirectory()) { POIFSDocumentPath new_path = new POIFSDocumentPath(path,new String[]{name}); - DirectoryProperty dp = (DirectoryProperty) property; - processProperties(small_blocks, big_blocks, dp.getChildren(), new_path); + processProperties(poifs, (DirectoryProperty) property, new_path); } else { - int startBlock = property.getStartBlock(); - Iterator<POIFSReaderListener> listeners = registry.getListeners(path, name); - - if (listeners.hasNext()) - { - int size = property.getSize(); - OPOIFSDocument document = null; - - if (property.shouldUseSmallBlocks()) - { - document = - new OPOIFSDocument(name, small_blocks - .fetchBlocks(startBlock, -1), size); - } - else - { - document = - new OPOIFSDocument(name, big_blocks - .fetchBlocks(startBlock, -1), size); - } - while (listeners.hasNext()) - { - POIFSReaderListener listener = listeners.next(); - try (DocumentInputStream dis = new DocumentInputStream(document)) { - listener.processPOIFSReaderEvent(new POIFSReaderEvent(dis, path, name)); - } - } - } - else - { - - // consume the document's data and discard it - if (property.shouldUseSmallBlocks()) - { - small_blocks.fetchBlocks(startBlock, -1); + NPOIFSDocument document = null; + for (POIFSReaderListener rl : registry.getListeners(path, name)) { + if (document == null) { + document = new NPOIFSDocument((DocumentProperty)property, poifs); } - else - { - big_blocks.fetchBlocks(startBlock, -1); + try (DocumentInputStream dis = new DocumentInputStream(document)) { + POIFSReaderEvent pe = new POIFSReaderEvent(dis, path, name); + rl.processPOIFSReaderEvent(pe); } } } } - } - - private static class SampleListener - implements POIFSReaderListener - { - - /** - * Constructor SampleListener - */ - SampleListener() - { + if (hasChildren || !notifyEmptyDirectories) { + return; } - /** - * Method processPOIFSReaderEvent - * - * @param event - */ - - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) { - DocumentInputStream istream = event.getStream(); - POIFSDocumentPath path = event.getPath(); - String name = event.getName(); - - try { - byte[] data = IOUtils.toByteArray(istream); - int pathLength = path.length(); - - for (int k = 0; k < pathLength; k++) { - System.out.print("/" + path.getComponent(k)); - } - System.out.println("/" + name + ": " + data.length + " bytes read"); - } catch (IOException ignored) { - } finally { - IOUtils.closeQuietly(istream); - } + for (POIFSReaderListener rl : registry.getListeners(path, ".")) { + POIFSReaderEvent pe = new POIFSReaderEvent(null, path, null); + rl.processPOIFSReaderEvent(pe); } } } diff --git a/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.java b/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.java index 0a6c29bd9f..9ffac63120 100644 --- a/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.java +++ b/src/java/org/apache/poi/poifs/eventfilesystem/POIFSReaderRegistry.java @@ -79,34 +79,21 @@ class POIFSReaderRegistry // not an omnivorous listener (if it was, this method is a // no-op) - Set<DocumentDescriptor> descriptors = selectiveListeners.get(listener); + Set<DocumentDescriptor> descriptors = + selectiveListeners.computeIfAbsent(listener, k -> new HashSet<>()); - if (descriptors == null) - { + // this listener has not registered before + DocumentDescriptor descriptor = new DocumentDescriptor(path, documentName); - // this listener has not registered before - descriptors = new HashSet<>(); - selectiveListeners.put(listener, descriptors); - } - DocumentDescriptor descriptor = new DocumentDescriptor(path, - documentName); - - if (descriptors.add(descriptor)) - { + if (descriptors.add(descriptor)) { // this listener wasn't already listening for this // document -- add the listener to the set of // listeners for this document Set<POIFSReaderListener> listeners = - chosenDocumentDescriptors.get(descriptor); - - if (listeners == null) - { + chosenDocumentDescriptors.computeIfAbsent(descriptor, k -> new HashSet<>()); - // nobody was listening for this document before - listeners = new HashSet<>(); - chosenDocumentDescriptors.put(descriptor, listeners); - } + // nobody was listening for this document before listeners.add(listener); } } @@ -141,7 +128,7 @@ class POIFSReaderRegistry * @return an Iterator POIFSReaderListeners; may be empty */ - Iterator<POIFSReaderListener> getListeners(final POIFSDocumentPath path, final String name) + Iterable<POIFSReaderListener> getListeners(final POIFSDocumentPath path, final String name) { Set<POIFSReaderListener> rval = new HashSet<>(omnivorousListeners); Set<POIFSReaderListener> selectiveListenersInner = @@ -151,20 +138,16 @@ class POIFSReaderRegistry { rval.addAll(selectiveListenersInner); } - return rval.iterator(); + return rval; } private void removeSelectiveListener(final POIFSReaderListener listener) { Set<DocumentDescriptor> selectedDescriptors = selectiveListeners.remove(listener); - if (selectedDescriptors != null) - { - Iterator<DocumentDescriptor> iter = selectedDescriptors.iterator(); - - while (iter.hasNext()) - { - dropDocument(listener, iter.next()); + if (selectedDescriptors != null) { + for (DocumentDescriptor selectedDescriptor : selectedDescriptors) { + dropDocument(listener, selectedDescriptor); } } } diff --git a/src/java/org/apache/poi/poifs/dev/package.html b/src/java/org/apache/poi/poifs/eventfilesystem/package-info.java index e4e60cece0..34760da4d4 100644 --- a/src/java/org/apache/poi/poifs/dev/package.html +++ b/src/java/org/apache/poi/poifs/eventfilesystem/package-info.java @@ -1,6 +1,4 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== +/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. @@ -15,22 +13,11 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> +==================================================================== */ -DEV package serves two purposes. 1. Examples for how to use POIFS and 2. tools for developing -and validating POIFS. - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -</body> -</html> +/** + * The eventfilesystem is an efficient method for reading OLE 2 CDF files. It is to OLE 2 CDF what SAX is to XML. + * + * @see org.apache.poi.poifs.filesystem + */ +package org.apache.poi.poifs.eventfilesystem;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/eventfilesystem/package.html b/src/java/org/apache/poi/poifs/eventfilesystem/package.html deleted file mode 100644 index 472a0d93ef..0000000000 --- a/src/java/org/apache/poi/poifs/eventfilesystem/package.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> - -The eventfilesystem is an efficient method for reading OLE 2 CDF files. It is to OLE 2 CDF what SAX is to XML. - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -<!-- Put @see and @since tags down here. --> -@see org.apache.poi.poifs.filesystem -</body> -</html> diff --git a/src/java/org/apache/poi/poifs/filesystem/DirectoryNode.java b/src/java/org/apache/poi/poifs/filesystem/DirectoryNode.java index dfeb7d2c03..b6af88babe 100644 --- a/src/java/org/apache/poi/poifs/filesystem/DirectoryNode.java +++ b/src/java/org/apache/poi/poifs/filesystem/DirectoryNode.java @@ -44,33 +44,16 @@ public class DirectoryNode { // Map of Entry instances, keyed by their names - private Map<String,Entry> _byname; + private final Map<String,Entry> _byname = new HashMap<>(); + // Our list of entries, kept sorted to preserve order - private ArrayList<Entry> _entries; + private final ArrayList<Entry> _entries = new ArrayList<>(); - // Only one of these two will exist - // the OPOIFSFileSystem we belong to - private OPOIFSFileSystem _ofilesystem; // the NPOIFSFileSytem we belong to - private NPOIFSFileSystem _nfilesystem; + private final NPOIFSFileSystem _nfilesystem; // the path described by this document - private POIFSDocumentPath _path; - - /** - * create a DirectoryNode. This method is not public by design; it - * is intended strictly for the internal use of this package - * - * @param property the DirectoryProperty for this DirectoryEntry - * @param filesystem the OPOIFSFileSystem we belong to - * @param parent the parent of this entry - */ - DirectoryNode(final DirectoryProperty property, - final OPOIFSFileSystem filesystem, - final DirectoryNode parent) - { - this(property, parent, filesystem, null); - } + private final POIFSDocumentPath _path; /** * create a DirectoryNode. This method is not public by design; it @@ -84,16 +67,7 @@ public class DirectoryNode final NPOIFSFileSystem nfilesystem, final DirectoryNode parent) { - this(property, parent, null, nfilesystem); - } - - private DirectoryNode(final DirectoryProperty property, - final DirectoryNode parent, - final OPOIFSFileSystem ofilesystem, - final NPOIFSFileSystem nfilesystem) - { super(property, parent); - this._ofilesystem = ofilesystem; this._nfilesystem = nfilesystem; if (parent == null) @@ -103,12 +77,10 @@ public class DirectoryNode else { _path = new POIFSDocumentPath(parent._path, new String[] - { - property.getName() - }); + { + property.getName() + }); } - _byname = new HashMap<>(); - _entries = new ArrayList<>(); Iterator<Property> iter = property.getChildren(); while (iter.hasNext()) @@ -119,11 +91,7 @@ public class DirectoryNode if (child.isDirectory()) { DirectoryProperty childDir = (DirectoryProperty) child; - if(_ofilesystem != null) { - childNode = new DirectoryNode(childDir, _ofilesystem, this); - } else { - childNode = new DirectoryNode(childDir, _nfilesystem, this); - } + childNode = new DirectoryNode(childDir, _nfilesystem, this); } else { @@ -151,15 +119,6 @@ public class DirectoryNode return _nfilesystem; } - /** - * If this is OPOIFS based, return the NPOIFSFileSystem - * that this belong to, otherwise Null if NPOIFS based - * @return the filesystem that this belongs to - */ - public OPOIFSFileSystem getOFileSystem() - { - return _ofilesystem; - } /** * If this is NPOIFS based, return the NPOIFSFileSystem @@ -218,30 +177,7 @@ public class DirectoryNode * * @return the new DocumentEntry * - * @exception IOException - */ - DocumentEntry createDocument(final OPOIFSDocument document) - throws IOException - { - DocumentProperty property = document.getDocumentProperty(); - DocumentNode rval = new DocumentNode(property, this); - - (( DirectoryProperty ) getProperty()).addChild(property); - _ofilesystem.addDocument(document); - - _entries.add(rval); - _byname.put(property.getName(), rval); - return rval; - } - - /** - * create a new DocumentEntry - * - * @param document the new document - * - * @return the new DocumentEntry - * - * @exception IOException + * @exception IOException if the document can't be created */ DocumentEntry createDocument(final NPOIFSDocument document) throws IOException @@ -302,14 +238,11 @@ public class DirectoryNode _entries.remove(entry); _byname.remove(entry.getName()); - if(_ofilesystem != null) { - _ofilesystem.remove(entry); - } else { - try { - _nfilesystem.remove(entry); - } catch (IOException e) { - // TODO Work out how to report this, given we can't change the method signature... - } + try { + _nfilesystem.remove(entry); + } catch (IOException e) { + // TODO Work out how to report this, given we can't change the method signature... + throw new RuntimeException(e); } } return rval; @@ -411,18 +344,14 @@ public class DirectoryNode * * @return the new DocumentEntry * - * @exception IOException + * @exception IOException if the document can't be created */ public DocumentEntry createDocument(final String name, final InputStream stream) throws IOException { - if(_nfilesystem != null) { - return createDocument(new NPOIFSDocument(name, _nfilesystem, stream)); - } else { - return createDocument(new OPOIFSDocument(name, stream)); - } + return createDocument(new NPOIFSDocument(name, _nfilesystem, stream)); } /** @@ -434,18 +363,14 @@ public class DirectoryNode * * @return the new DocumentEntry * - * @exception IOException + * @exception IOException if the document can't be created */ public DocumentEntry createDocument(final String name, final int size, final POIFSWriterListener writer) throws IOException { - if(_nfilesystem != null) { - return createDocument(new NPOIFSDocument(name, size, _nfilesystem, writer)); - } else { - return createDocument(new OPOIFSDocument(name, size, _path, writer)); - } + return createDocument(new NPOIFSDocument(name, size, _nfilesystem, writer)); } /** @@ -455,22 +380,16 @@ public class DirectoryNode * * @return the new DirectoryEntry * - * @exception IOException + * @exception IOException if the directory can't be created */ public DirectoryEntry createDirectory(final String name) throws IOException { - DirectoryNode rval; DirectoryProperty property = new DirectoryProperty(name); - if(_ofilesystem != null) { - rval = new DirectoryNode(property, _ofilesystem, this); - _ofilesystem.addDirectory(property); - } else { - rval = new DirectoryNode(property, _nfilesystem, this); - _nfilesystem.addDirectory(property); - } + DirectoryNode rval = new DirectoryNode(property, _nfilesystem, this); + _nfilesystem.addDirectory(property); (( DirectoryProperty ) getProperty()).addChild(property); _entries.add(rval); @@ -487,9 +406,9 @@ public class DirectoryNode * * @return the new or updated DocumentEntry * - * @exception IOException + * @exception IOException if the document can't be created or its content be replaced */ - + @SuppressWarnings("WeakerAccess") public DocumentEntry createOrUpdateDocument(final String name, final InputStream stream) throws IOException @@ -498,15 +417,9 @@ public class DirectoryNode return createDocument(name, stream); } else { DocumentNode existing = (DocumentNode)getEntry(name); - if (_nfilesystem != null) { - NPOIFSDocument nDoc = new NPOIFSDocument(existing); - nDoc.replaceContents(stream); - return existing; - } else { - // Do it the hard way for Old POIFS... - deleteEntry(existing); - return createDocument(name, stream); - } + NPOIFSDocument nDoc = new NPOIFSDocument(existing); + nDoc.replaceContents(stream); + return existing; } } diff --git a/src/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java b/src/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java index 314cae0ee2..3aeaa19320 100644 --- a/src/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java +++ b/src/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java @@ -20,7 +20,6 @@ package org.apache.poi.poifs.filesystem; import java.io.IOException; import java.io.InputStream; -import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndianInput; import org.apache.poi.util.SuppressForbidden; @@ -34,10 +33,6 @@ public class DocumentInputStream extends InputStream implements LittleEndianInpu /** returned by read operations if we're at end of document */ protected static final int EOF = -1; - protected static final int SIZE_SHORT = 2; - protected static final int SIZE_INT = 4; - protected static final int SIZE_LONG = 8; - private DocumentInputStream delegate; /** For use by downstream implementations */ @@ -55,27 +50,7 @@ public class DocumentInputStream extends InputStream implements LittleEndianInpu if (!(document instanceof DocumentNode)) { throw new IOException("Cannot open internal document storage"); } - DocumentNode documentNode = (DocumentNode)document; - DirectoryNode parentNode = (DirectoryNode)document.getParent(); - - if(documentNode.getDocument() != null) { - delegate = new ODocumentInputStream(document); - } else if(parentNode.getOFileSystem() != null) { - delegate = new ODocumentInputStream(document); - } else if(parentNode.getNFileSystem() != null) { - delegate = new NDocumentInputStream(document); - } else { - throw new IOException("No FileSystem bound on the parent, can't read contents"); - } - } - - /** - * Create an InputStream from the specified Document - * - * @param document the Document to be read - */ - public DocumentInputStream(OPOIFSDocument document) { - delegate = new ODocumentInputStream(document); + delegate = new NDocumentInputStream(document); } /** diff --git a/src/java/org/apache/poi/poifs/filesystem/DocumentNode.java b/src/java/org/apache/poi/poifs/filesystem/DocumentNode.java index 19143fd745..f60c1dc5da 100644 --- a/src/java/org/apache/poi/poifs/filesystem/DocumentNode.java +++ b/src/java/org/apache/poi/poifs/filesystem/DocumentNode.java @@ -35,7 +35,7 @@ public class DocumentNode { // underlying POIFSDocument instance - private OPOIFSDocument _document; + private NPOIFSDocument _document; /** * create a DocumentNode. This method is not public by design; it @@ -56,7 +56,7 @@ public class DocumentNode * * @return the internal POIFSDocument */ - OPOIFSDocument getDocument() + NPOIFSDocument getDocument() { return _document; } diff --git a/src/java/org/apache/poi/poifs/filesystem/EntryUtils.java b/src/java/org/apache/poi/poifs/filesystem/EntryUtils.java index e2ba3dc3bd..1fdf2e4770 100644 --- a/src/java/org/apache/poi/poifs/filesystem/EntryUtils.java +++ b/src/java/org/apache/poi/poifs/filesystem/EntryUtils.java @@ -16,27 +16,31 @@ ==================================================================== */ package org.apache.poi.poifs.filesystem; -import java.io.FileNotFoundException; +import java.io.EOFException; import java.io.IOException; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; +import org.apache.poi.hpsf.MarkUnsupportedException; +import org.apache.poi.hpsf.NoPropertySetStreamException; +import org.apache.poi.hpsf.PropertySet; +import org.apache.poi.hpsf.PropertySetFactory; import org.apache.poi.util.Internal; @Internal -public class EntryUtils -{ +public final class EntryUtils { + private EntryUtils() {} /** * Copies an Entry into a target POIFS directory, recursively */ @Internal public static void copyNodeRecursively( Entry entry, DirectoryEntry target ) - throws IOException { - // logger.log( POILogger.ERROR, "copyNodeRecursively called with "+entry.getName()+ - // ","+target.getName()); + throws IOException { if ( entry.isDirectoryEntry() ) { DirectoryEntry dirEntry = (DirectoryEntry)entry; DirectoryEntry newTarget = target.createDirectory( entry.getName() ); @@ -62,8 +66,8 @@ public class EntryUtils * @param targetRoot * is the target Directory to copy to */ - public static void copyNodes(DirectoryEntry sourceRoot, - DirectoryEntry targetRoot) throws IOException { + public static void copyNodes(DirectoryEntry sourceRoot, DirectoryEntry targetRoot) + throws IOException { for (Entry entry : sourceRoot) { copyNodeRecursively( entry, targetRoot ); } @@ -77,22 +81,8 @@ public class EntryUtils * @param target * is the target POIFS to copy to */ - public static void copyNodes( OPOIFSFileSystem source, - OPOIFSFileSystem target ) throws IOException - { - copyNodes( source.getRoot(), target.getRoot() ); - } - /** - * Copies all nodes from one POIFS to the other - * - * @param source - * is the source POIFS to copy from - * @param target - * is the target POIFS to copy to - */ - public static void copyNodes( NPOIFSFileSystem source, - NPOIFSFileSystem target ) throws IOException - { + public static void copyNodes( NPOIFSFileSystem source, NPOIFSFileSystem target ) + throws IOException { copyNodes( source.getRoot(), target.getRoot() ); } @@ -106,27 +96,8 @@ public class EntryUtils * @param target is the target POIFS to copy to * @param excepts is a list of Entry Names to be excluded from the copy */ - public static void copyNodes( OPOIFSFileSystem source, - OPOIFSFileSystem target, List<String> excepts ) throws IOException - { - copyNodes( - new FilteringDirectoryNode(source.getRoot(), excepts), - new FilteringDirectoryNode(target.getRoot(), excepts) - ); - } - /** - * Copies nodes from one POIFS to the other, minus the excepts. - * This delegates the filtering work to {@link FilteringDirectoryNode}, - * so excepts can be of the form "NodeToExclude" or - * "FilteringDirectory/ExcludedChildNode" - * - * @param source is the source POIFS to copy from - * @param target is the target POIFS to copy to - * @param excepts is a list of Entry Names to be excluded from the copy - */ - public static void copyNodes( NPOIFSFileSystem source, - NPOIFSFileSystem target, List<String> excepts ) throws IOException - { + public static void copyNodes( NPOIFSFileSystem source, NPOIFSFileSystem target, List<String> excepts ) + throws IOException { copyNodes( new FilteringDirectoryNode(source.getRoot(), excepts), new FilteringDirectoryNode(target.getRoot(), excepts) @@ -142,114 +113,137 @@ public class EntryUtils * use a {@link FilteringDirectoryNode} */ public static boolean areDirectoriesIdentical(DirectoryEntry dirA, DirectoryEntry dirB) { - // First, check names - if (! dirA.getName().equals(dirB.getName())) { - return false; - } - - // Next up, check they have the same number of children - if (dirA.getEntryCount() != dirB.getEntryCount()) { - return false; - } - - // Next, check entries and their types/sizes - Map<String,Integer> aSizes = new HashMap<>(); - final int isDirectory = -12345; - for (Entry a : dirA) { - String aName = a.getName(); - if (a.isDirectoryEntry()) { - aSizes.put(aName, isDirectory); - } else { - aSizes.put(aName, ((DocumentNode)a).getSize()); - } - } - for (Entry b : dirB) { - String bName = b.getName(); - if (! aSizes.containsKey(bName)) { - // In B but not A - return false; - } - - int size; - if (b.isDirectoryEntry()) { - size = isDirectory; - } else { - size = ((DocumentNode)b).getSize(); - } - if (size != aSizes.get(bName)) { - // Either the wrong type, or they're different sizes - return false; - } - - // Track it as checked - aSizes.remove(bName); - } - if (!aSizes.isEmpty()) { - // Nodes were in A but not B - return false; - } - - // If that passed, check entry contents - for (Entry a : dirA) { - try { - Entry b = dirB.getEntry(a.getName()); - boolean match; - if (a.isDirectoryEntry()) { - match = areDirectoriesIdentical( - (DirectoryEntry)a, (DirectoryEntry)b); - } else { - match = areDocumentsIdentical( - (DocumentEntry)a, (DocumentEntry)b); - } - if (!match) return false; - } catch(FileNotFoundException e) { - // Shouldn't really happen... - return false; - } catch(IOException e) { - // Something's messed up with one document, not a match - return false; - } - } - - // If we get here, they match! - return true; + return new DirectoryDelegate(dirA).equals(new DirectoryDelegate(dirB)); } /** - * Checks to see if two Documents have the same name - * and the same contents. (Their parent directories are - * not checked) + * Compares two {@link DocumentEntry} instances of a POI file system. + * Documents that are not property set streams must be bitwise identical. + * Property set streams must be logically equal.<p> + * + * (Their parent directories are not checked) */ - public static boolean areDocumentsIdentical(DocumentEntry docA, DocumentEntry docB) throws IOException { - if (! docA.getName().equals(docB.getName())) { - // Names don't match, not the same - return false; - } - if (docA.getSize() != docB.getSize()) { - // Wrong sizes, can't have the same contents - return false; - } - - boolean matches = true; - DocumentInputStream inpA = null, inpB = null; - try { - inpA = new DocumentInputStream(docA); - inpB = new DocumentInputStream(docB); - - int readA, readB; - do { - readA = inpA.read(); - readB = inpB.read(); - if (readA != readB) { - matches = false; - break; - } - } while(readA != -1 && readB != -1); - } finally { - if (inpA != null) inpA.close(); - if (inpB != null) inpB.close(); - } - - return matches; + @SuppressWarnings("WeakerAccess") + public static boolean areDocumentsIdentical(DocumentEntry docA, DocumentEntry docB) + throws IOException { + try { + return new DocumentDelegate(docA).equals(new DocumentDelegate(docB)); + } catch (RuntimeException e) { + if (e.getCause() instanceof IOException) { + throw (IOException)e.getCause(); + } else { + throw e; + } + } + } + + private interface POIDelegate { + } + + private static class DirectoryDelegate implements POIDelegate { + final DirectoryEntry dir; + + DirectoryDelegate(DirectoryEntry dir) { + this.dir = dir; + } + + private Map<String,POIDelegate> entries() { + return StreamSupport.stream(dir.spliterator(), false) + .collect(Collectors.toMap(Entry::getName, DirectoryDelegate::toDelegate)); + } + + private static POIDelegate toDelegate(Entry entry) { + return (entry.isDirectoryEntry()) + ? new DirectoryDelegate((DirectoryEntry)entry) + : new DocumentDelegate((DocumentEntry)entry); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof DirectoryDelegate)) { + return false; + } + + DirectoryDelegate dd = (DirectoryDelegate)other; + + if (this == dd) { + return true; + } + + // First, check names + if (!Objects.equals(dir.getName(),dd.dir.getName())) { + return false; + } + + // Next up, check they have the same number of children + if (dir.getEntryCount() != dd.dir.getEntryCount()) { + return false; + } + + return entries().equals(dd.entries()); + } + } + + private static class DocumentDelegate implements POIDelegate { + final DocumentEntry doc; + + DocumentDelegate(DocumentEntry doc) { + this.doc = doc; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof DocumentDelegate)) { + return false; + } + + DocumentDelegate dd = (DocumentDelegate)other; + + if (this == dd) { + return true; + } + + + if (!Objects.equals(doc.getName(), dd.doc.getName())) { + // Names don't match, not the same + return false; + } + + try (DocumentInputStream inpA = new DocumentInputStream(doc); + DocumentInputStream inpB = new DocumentInputStream(dd.doc)) { + + if (PropertySet.isPropertySetStream(inpA) && + PropertySet.isPropertySetStream(inpB)) { + final PropertySet ps1 = PropertySetFactory.create(inpA); + final PropertySet ps2 = PropertySetFactory.create(inpB); + return ps1.equals(ps2); + } else { + return isEqual(inpA, inpB); + } + } catch (MarkUnsupportedException | NoPropertySetStreamException | IOException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean isEqual(DocumentInputStream i1, DocumentInputStream i2) + throws IOException { + final byte[] buf1 = new byte[4*1024]; + final byte[] buf2 = new byte[4*1024]; + try { + int len; + while ((len = i1.read(buf1)) > 0) { + i2.readFully(buf2,0,len); + for(int i=0;i<len;i++) { + if (buf1[i] != buf2[i]) { + return false; + } + } + } + // is the end of the second file also. + return i2.read() < 0; + } catch(EOFException | RuntimeException ioe) { + return false; + } + } } } diff --git a/src/java/org/apache/poi/poifs/filesystem/NDocumentInputStream.java b/src/java/org/apache/poi/poifs/filesystem/NDocumentInputStream.java index b32166ac1c..3a944f7281 100644 --- a/src/java/org/apache/poi/poifs/filesystem/NDocumentInputStream.java +++ b/src/java/org/apache/poi/poifs/filesystem/NDocumentInputStream.java @@ -17,6 +17,10 @@ package org.apache.poi.poifs.filesystem; +import static org.apache.poi.util.LittleEndianConsts.INT_SIZE; +import static org.apache.poi.util.LittleEndianConsts.LONG_SIZE; +import static org.apache.poi.util.LittleEndianConsts.SHORT_SIZE; + import java.io.IOException; import java.nio.ByteBuffer; import java.util.Iterator; @@ -71,9 +75,9 @@ public final class NDocumentInputStream extends DocumentInputStream { _document_size = document.getSize(); _closed = false; - if (_document_size < 0) { - //throw new RecordFormatException("Document size can't be < 0"); - } + // can't be asserted ... see bug 61300 + // assert (_document_size >= 0) : "Document size can't be < 0"; + DocumentNode doc = (DocumentNode)document; DocumentProperty property = (DocumentProperty)doc.getProperty(); _document = new NPOIFSDocument( @@ -284,33 +288,33 @@ public final class NDocumentInputStream extends DocumentInputStream { @Override public long readLong() { - checkAvaliable(SIZE_LONG); - byte[] data = new byte[SIZE_LONG]; - readFully(data, 0, SIZE_LONG); + checkAvaliable(LONG_SIZE); + byte[] data = new byte[LONG_SIZE]; + readFully(data, 0, LONG_SIZE); return LittleEndian.getLong(data, 0); } @Override public short readShort() { - checkAvaliable(SIZE_SHORT); - byte[] data = new byte[SIZE_SHORT]; - readFully(data, 0, SIZE_SHORT); + checkAvaliable(SHORT_SIZE); + byte[] data = new byte[SHORT_SIZE]; + readFully(data, 0, SHORT_SIZE); return LittleEndian.getShort(data); } @Override public int readInt() { - checkAvaliable(SIZE_INT); - byte[] data = new byte[SIZE_INT]; - readFully(data, 0, SIZE_INT); + checkAvaliable(INT_SIZE); + byte[] data = new byte[INT_SIZE]; + readFully(data, 0, INT_SIZE); return LittleEndian.getInt(data); } @Override public int readUShort() { - checkAvaliable(SIZE_SHORT); - byte[] data = new byte[SIZE_SHORT]; - readFully(data, 0, SIZE_SHORT); + checkAvaliable(SHORT_SIZE); + byte[] data = new byte[SHORT_SIZE]; + readFully(data, 0, SHORT_SIZE); return LittleEndian.getUShort(data); } diff --git a/src/java/org/apache/poi/poifs/filesystem/NPOIFSDocument.java b/src/java/org/apache/poi/poifs/filesystem/NPOIFSDocument.java index 22e4106962..f25838b570 100644 --- a/src/java/org/apache/poi/poifs/filesystem/NPOIFSDocument.java +++ b/src/java/org/apache/poi/poifs/filesystem/NPOIFSDocument.java @@ -17,6 +17,8 @@ package org.apache.poi.poifs.filesystem; +import static java.util.Collections.emptyList; + import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; @@ -25,7 +27,6 @@ import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; -import java.util.List; import org.apache.poi.poifs.common.POIFSConstants; import org.apache.poi.poifs.dev.POIFSViewable; @@ -37,7 +38,7 @@ import org.apache.poi.util.IOUtils; * This class manages a document in the NIO POIFS filesystem. * This is the {@link NPOIFSFileSystem} version. */ -public final class NPOIFSDocument implements POIFSViewable { +public final class NPOIFSDocument implements POIFSViewable, Iterable<ByteBuffer> { //arbitrarily selected; may need to increase private static final int MAX_RECORD_LENGTH = 100_000; @@ -51,7 +52,7 @@ public final class NPOIFSDocument implements POIFSViewable { /** * Constructor for an existing Document */ - public NPOIFSDocument(DocumentNode document) throws IOException { + public NPOIFSDocument(DocumentNode document) { this((DocumentProperty)document.getProperty(), ((DirectoryNode)document.getParent()).getNFileSystem()); } @@ -59,9 +60,7 @@ public final class NPOIFSDocument implements POIFSViewable { /** * Constructor for an existing Document */ - public NPOIFSDocument(DocumentProperty property, NPOIFSFileSystem filesystem) - throws IOException - { + public NPOIFSDocument(DocumentProperty property, NPOIFSFileSystem filesystem) { this._property = property; this._filesystem = filesystem; @@ -90,7 +89,8 @@ public final class NPOIFSDocument implements POIFSViewable { // Build the property for it this._property = new DocumentProperty(name, length); - _property.setStartBlock(_stream.getStartBlock()); + _property.setStartBlock(_stream.getStartBlock()); + _property.setDocument(this); } public NPOIFSDocument(String name, int size, NPOIFSFileSystem filesystem, POIFSWriterListener writer) @@ -116,7 +116,8 @@ public final class NPOIFSDocument implements POIFSViewable { // And build the property for it this._property = new DocumentProperty(name, size); - _property.setStartBlock(_stream.getStartBlock()); + _property.setStartBlock(_stream.getStartBlock()); + _property.setDocument(this); } /** @@ -128,7 +129,8 @@ public final class NPOIFSDocument implements POIFSViewable { bis.mark(bigBlockSize); // Do we need to store as a mini stream or a full one? - if(bis.skip(bigBlockSize) < bigBlockSize) { + long streamBlockSize = IOUtils.skipFully(bis, bigBlockSize); + if (streamBlockSize < bigBlockSize) { _stream = new NPOIFSStream(_filesystem.getMiniStore()); _block_size = _filesystem.getMiniStore().getBlockStoreBlockSize(); } else { @@ -140,26 +142,21 @@ public final class NPOIFSDocument implements POIFSViewable { bis.reset(); // Store it - OutputStream os = _stream.getOutputStream(); - byte buf[] = new byte[1024]; - int length = 0; - - for (int readBytes; (readBytes = bis.read(buf)) != -1; length += readBytes) { - os.write(buf, 0, readBytes); - } - - // Pad to the end of the block with -1s - int usedInBlock = length % _block_size; - if (usedInBlock != 0 && usedInBlock != _block_size) { - int toBlockEnd = _block_size - usedInBlock; - byte[] padding = IOUtils.safelyAllocate(toBlockEnd, MAX_RECORD_LENGTH); - Arrays.fill(padding, (byte)0xFF); - os.write(padding); + final long length; + try (OutputStream os = _stream.getOutputStream()) { + length = IOUtils.copy(bis, os); + + // Pad to the end of the block with -1s + int usedInBlock = (int) (length % _block_size); + if (usedInBlock != 0 && usedInBlock != _block_size) { + int toBlockEnd = _block_size - usedInBlock; + byte[] padding = IOUtils.safelyAllocate(toBlockEnd, MAX_RECORD_LENGTH); + Arrays.fill(padding, (byte) 0xFF); + os.write(padding); + } } - - // Tidy and return the length - os.close(); - return length; + + return (int)length; } /** @@ -178,15 +175,15 @@ public final class NPOIFSDocument implements POIFSViewable { int getDocumentBlockSize() { return _block_size; } - - Iterator<ByteBuffer> getBlockIterator() { - if(getSize() > 0) { - return _stream.getBlockIterator(); - } else { - List<ByteBuffer> empty = Collections.emptyList(); - return empty.iterator(); - } - } + + @Override + public Iterator<ByteBuffer> iterator() { + return getBlockIterator(); + } + + Iterator<ByteBuffer> getBlockIterator() { + return (getSize() > 0 ? _stream : Collections.<ByteBuffer>emptyList()).iterator(); + } /** * @return size of the document @@ -240,7 +237,7 @@ public final class NPOIFSDocument implements POIFSViewable { * store */ public Iterator<Object> getViewableIterator() { - return Collections.emptyList().iterator(); + return emptyList().iterator(); } /** @@ -261,10 +258,7 @@ public final class NPOIFSDocument implements POIFSViewable { * @return short description */ public String getShortDescription() { - StringBuffer buffer = new StringBuffer(); - buffer.append("Document: \"").append(_property.getName()).append("\""); - buffer.append(" size = ").append(getSize()); - return buffer.toString(); + return "Document: \"" + _property.getName() + "\" size = " + getSize(); } } diff --git a/src/java/org/apache/poi/poifs/filesystem/ODocumentInputStream.java b/src/java/org/apache/poi/poifs/filesystem/ODocumentInputStream.java deleted file mode 100644 index 944e3f322f..0000000000 --- a/src/java/org/apache/poi/poifs/filesystem/ODocumentInputStream.java +++ /dev/null @@ -1,341 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.IOException; -import java.util.function.Function; - -import org.apache.poi.poifs.storage.DataInputBlock; -import org.apache.poi.util.RecordFormatException; - -/** - * This class provides methods to read a DocumentEntry managed by a - * {@link OPOIFSFileSystem} instance. - */ -public final class ODocumentInputStream extends DocumentInputStream { - /** current offset into the Document */ - private int _current_offset; - - /** current marked offset into the Document (used by mark and reset) */ - private int _marked_offset; - - /** the Document's size */ - private final int _document_size; - - /** have we been closed? */ - private boolean _closed; - - /** the actual Document */ - private final OPOIFSDocument _document; - - /** the data block containing the current stream pointer */ - private DataInputBlock _currentBlock; - - /** - * Create an InputStream from the specified DocumentEntry - * - * @param document the DocumentEntry to be read - * - * @exception IOException if the DocumentEntry cannot be opened (like, maybe it has - * been deleted?) - */ - public ODocumentInputStream(DocumentEntry document) throws IOException { - if (!(document instanceof DocumentNode)) { - throw new IOException("Cannot open internal document storage"); - } - DocumentNode documentNode = (DocumentNode)document; - if (documentNode.getDocument() == null) { - throw new IOException("Cannot open internal document storage"); - } - - _current_offset = 0; - _marked_offset = 0; - _document_size = document.getSize(); - if (_document_size < 0) { - throw new RecordFormatException("document_size cannot be < 0"); - } - _closed = false; - _document = documentNode.getDocument(); - _currentBlock = getDataInputBlock(0); - } - - /** - * Create an InputStream from the specified Document - * - * @param document the Document to be read - */ - public ODocumentInputStream(OPOIFSDocument document) { - _current_offset = 0; - _marked_offset = 0; - _document_size = document.getSize(); - _closed = false; - _document = document; - _currentBlock = getDataInputBlock(0); - } - - @Override - public int available() { - if (_closed) { - throw new IllegalStateException("cannot perform requested operation on a closed stream"); - } - return _document_size - _current_offset; - } - - @Override - public void close() { - _closed = true; - } - - @Override - public void mark(int ignoredReadlimit) { - _marked_offset = _current_offset; - } - - private DataInputBlock getDataInputBlock(int offset) { - return _document.getDataInputBlock(offset); - } - - @Override - public int read() throws IOException { - dieIfClosed(); - if (atEOD()) { - return EOF; - } - int result = _currentBlock.readUByte(); - _current_offset++; - if (_currentBlock.available() < 1) { - _currentBlock = getDataInputBlock(_current_offset); - } - return result; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - dieIfClosed(); - if (b == null) { - throw new IllegalArgumentException("buffer must not be null"); - } - if (off < 0 || len < 0 || b.length < off + len) { - throw new IndexOutOfBoundsException("can't read past buffer boundaries"); - } - if (len == 0) { - return 0; - } - if (atEOD()) { - return EOF; - } - int limit = Math.min(_document_size - _current_offset, len); - readFully(b, off, limit); - return limit; - } - - /** - * Repositions this stream to the position at the time the mark() method was - * last called on this input stream. If mark() has not been called this - * method repositions the stream to its beginning. - */ - @Override - public void reset() { - _current_offset = _marked_offset; - _currentBlock = getDataInputBlock(_current_offset); - } - - @Override - public long skip(long n) throws IOException { - dieIfClosed(); - if (n < 0) { - return 0; - } - int new_offset = _current_offset + (int) n; - - if (new_offset < _current_offset) { - - // wrap around in converting a VERY large long to an int - new_offset = _document_size; - } else if (new_offset > _document_size) { - new_offset = _document_size; - } - long rval = new_offset - _current_offset; - - _current_offset = new_offset; - _currentBlock = getDataInputBlock(_current_offset); - return rval; - } - - private void dieIfClosed() throws IOException { - if (_closed) { - throw new IOException("cannot perform requested operation on a closed stream"); - } - } - - private boolean atEOD() { - return _current_offset == _document_size; - } - - private void checkAvaliable(int requestedSize) { - if (_closed) { - throw new IllegalStateException("cannot perform requested operation on a closed stream"); - } - if (requestedSize > _document_size - _current_offset) { - throw new RuntimeException("Buffer underrun - requested " + requestedSize - + " bytes but " + (_document_size - _current_offset) + " was available"); - } - } - - @Override - public byte readByte() { - return (byte) readUByte(); - } - - @Override - public double readDouble() { - return Double.longBitsToDouble(readLong()); - } - - @Override - public short readShort() { - return (short) readUShort(); - } - - @Override - public void readFully(byte[] buf, int off, int len) { - checkAvaliable(len); - - Function<Integer,DataInputBlock> nextDataInputBlock = (offset) -> { - if (offset >= _document_size) { - _currentBlock = null; - } else if (offset != _current_offset) { - _currentBlock = getDataInputBlock(offset); - } - return _currentBlock; - }; - - _current_offset = readFullyInternal(buf, off, len, _current_offset, _document_size, nextDataInputBlock); - } - - /* package */ static int readFullyInternal(byte[] buf, int off, int len, int currentOffset, int maxSize, Function<Integer,DataInputBlock> nextDataInputBlock) { - DataInputBlock currentBlock = nextDataInputBlock.apply(currentOffset); - if (currentBlock == null) { - throw new IllegalStateException("reached end of document stream unexpectedly"); - } - int blockAvailable = currentBlock.available(); - if (blockAvailable > len) { - currentBlock.readFully(buf, off, len); - return currentOffset + len; - } - // else read big amount in chunks - int remaining = len; - int writePos = off; - int offset = currentOffset; - while (remaining > 0) { - final boolean blockIsExpiring = remaining >= blockAvailable; - final int reqSize = (blockIsExpiring) ? blockAvailable : remaining; - currentBlock.readFully(buf, writePos, reqSize); - remaining -= reqSize; - writePos += reqSize; - offset += reqSize; - if (blockIsExpiring) { - if (offset >= maxSize) { - if (remaining > 0) { - throw new IllegalStateException( - "reached end of document stream unexpectedly"); - } - break; - } - currentBlock = nextDataInputBlock.apply(offset); - if (currentBlock == null) { - throw new IllegalStateException( - "reached end of document stream unexpectedly"); - } - blockAvailable = currentBlock.available(); - } - } - return offset; - } - - @Override - public long readLong() { - checkAvaliable(SIZE_LONG); - int blockAvailable = _currentBlock.available(); - long result; - if (blockAvailable > SIZE_LONG) { - result = _currentBlock.readLongLE(); - } else { - DataInputBlock nextBlock = getDataInputBlock(_current_offset + blockAvailable); - if (blockAvailable == SIZE_LONG) { - result = _currentBlock.readLongLE(); - } else { - result = nextBlock.readLongLE(_currentBlock, blockAvailable); - } - _currentBlock = nextBlock; - } - _current_offset += SIZE_LONG; - return result; - } - - @Override - public int readInt() { - checkAvaliable(SIZE_INT); - int blockAvailable = _currentBlock.available(); - int result; - if (blockAvailable > SIZE_INT) { - result = _currentBlock.readIntLE(); - } else { - DataInputBlock nextBlock = getDataInputBlock(_current_offset + blockAvailable); - if (blockAvailable == SIZE_INT) { - result = _currentBlock.readIntLE(); - } else { - result = nextBlock.readIntLE(_currentBlock, blockAvailable); - } - _currentBlock = nextBlock; - } - _current_offset += SIZE_INT; - return result; - } - - @Override - public int readUShort() { - checkAvaliable(SIZE_SHORT); - int blockAvailable = _currentBlock.available(); - int result; - if (blockAvailable > SIZE_SHORT) { - result = _currentBlock.readUShortLE(); - } else { - DataInputBlock nextBlock = getDataInputBlock(_current_offset + blockAvailable); - if (blockAvailable == SIZE_SHORT) { - result = _currentBlock.readUShortLE(); - } else { - result = nextBlock.readUShortLE(_currentBlock); - } - _currentBlock = nextBlock; - } - _current_offset += SIZE_SHORT; - return result; - } - - @Override - public int readUByte() { - checkAvaliable(1); - int result = _currentBlock.readUByte(); - _current_offset++; - if (_currentBlock.available() < 1) { - _currentBlock = getDataInputBlock(_current_offset); - } - return result; - } -} diff --git a/src/java/org/apache/poi/poifs/filesystem/OPOIFSDocument.java b/src/java/org/apache/poi/poifs/filesystem/OPOIFSDocument.java deleted file mode 100644 index 43820ab532..0000000000 --- a/src/java/org/apache/poi/poifs/filesystem/OPOIFSDocument.java +++ /dev/null @@ -1,516 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.function.Function; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.dev.POIFSViewable; -import org.apache.poi.poifs.property.DocumentProperty; -import org.apache.poi.poifs.property.Property; -import org.apache.poi.poifs.storage.BlockWritable; -import org.apache.poi.poifs.storage.DataInputBlock; -import org.apache.poi.poifs.storage.DocumentBlock; -import org.apache.poi.poifs.storage.ListManagedBlock; -import org.apache.poi.poifs.storage.RawDataBlock; -import org.apache.poi.poifs.storage.SmallDocumentBlock; -import org.apache.poi.util.HexDump; - -/** - * This class manages a document in a old-style - * OPOIFS filesystem. - */ -public final class OPOIFSDocument implements BATManaged, BlockWritable, POIFSViewable { - private static final DocumentBlock[] EMPTY_BIG_BLOCK_ARRAY = { }; - private static final SmallDocumentBlock[] EMPTY_SMALL_BLOCK_ARRAY = { }; - private DocumentProperty _property; - private int _size; - - private final POIFSBigBlockSize _bigBigBlockSize; - - // one of these stores will be valid - private SmallBlockStore _small_store; - private BigBlockStore _big_store; - - /** - * Constructor from large blocks - * - * @param name the name of the POIFSDocument - * @param blocks the big blocks making up the POIFSDocument - * @param length the actual length of the POIFSDocument - */ - public OPOIFSDocument(String name, RawDataBlock[] blocks, int length) throws IOException { - _size = length; - if(blocks.length == 0) { - _bigBigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - } else { - _bigBigBlockSize = (blocks[0].getBigBlockSize() == POIFSConstants.SMALLER_BIG_BLOCK_SIZE ? - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS : - POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS - ); - } - - _big_store = new BigBlockStore(_bigBigBlockSize, convertRawBlocksToBigBlocks(blocks)); - _property = new DocumentProperty(name, _size); - _small_store = new SmallBlockStore(_bigBigBlockSize, EMPTY_SMALL_BLOCK_ARRAY); - _property.setDocument(this); - } - - // TODO - awkward typing going on here - private static DocumentBlock[] convertRawBlocksToBigBlocks(ListManagedBlock[] blocks) throws IOException { - DocumentBlock[] result = new DocumentBlock[blocks.length]; - for (int i = 0; i < result.length; i++) { - result[i] = new DocumentBlock((RawDataBlock)blocks[i]); - } - return result; - } - private static SmallDocumentBlock[] convertRawBlocksToSmallBlocks(ListManagedBlock[] blocks) { - if (blocks instanceof SmallDocumentBlock[]) { - return (SmallDocumentBlock[]) blocks; - } - SmallDocumentBlock[] result = new SmallDocumentBlock[blocks.length]; - System.arraycopy(blocks, 0, result, 0, blocks.length); - return result; - } - - /** - * Constructor from small blocks - * - * @param name the name of the POIFSDocument - * @param blocks the small blocks making up the POIFSDocument - * @param length the actual length of the POIFSDocument - */ - public OPOIFSDocument(String name, SmallDocumentBlock[] blocks, int length) { - _size = length; - - if(blocks.length == 0) { - _bigBigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - } else { - _bigBigBlockSize = blocks[0].getBigBlockSize(); - } - - _big_store = new BigBlockStore(_bigBigBlockSize, EMPTY_BIG_BLOCK_ARRAY); - _property = new DocumentProperty(name, _size); - _small_store = new SmallBlockStore(_bigBigBlockSize, blocks); - _property.setDocument(this); - } - - /** - * Constructor from small blocks - * - * @param name the name of the POIFSDocument - * @param blocks the small blocks making up the POIFSDocument - * @param length the actual length of the POIFSDocument - */ - public OPOIFSDocument(String name, POIFSBigBlockSize bigBlockSize, ListManagedBlock[] blocks, int length) throws IOException { - _size = length; - _bigBigBlockSize = bigBlockSize; - _property = new DocumentProperty(name, _size); - _property.setDocument(this); - if (Property.isSmall(_size)) { - _big_store = new BigBlockStore(bigBlockSize,EMPTY_BIG_BLOCK_ARRAY); - _small_store = new SmallBlockStore(bigBlockSize,convertRawBlocksToSmallBlocks(blocks)); - } else { - _big_store = new BigBlockStore(bigBlockSize,convertRawBlocksToBigBlocks(blocks)); - _small_store = new SmallBlockStore(bigBlockSize,EMPTY_SMALL_BLOCK_ARRAY); - } - } - public OPOIFSDocument(String name, ListManagedBlock[] blocks, int length) throws IOException { - this(name, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, blocks, length); - } - - /** - * Constructor - * - * @param name the name of the POIFSDocument - * @param stream the InputStream we read data from - */ - public OPOIFSDocument(String name, POIFSBigBlockSize bigBlockSize, InputStream stream) throws IOException { - List<DocumentBlock> blocks = new ArrayList<>(); - - _size = 0; - _bigBigBlockSize = bigBlockSize; - while (true) { - DocumentBlock block = new DocumentBlock(stream, bigBlockSize); - int blockSize = block.size(); - - if (blockSize > 0) { - blocks.add(block); - _size += blockSize; - } - if (block.partiallyRead()) { - break; - } - } - DocumentBlock[] bigBlocks = blocks.toArray(new DocumentBlock[blocks.size()]); - - _big_store = new BigBlockStore(bigBlockSize,bigBlocks); - _property = new DocumentProperty(name, _size); - _property.setDocument(this); - if (_property.shouldUseSmallBlocks()) { - _small_store = new SmallBlockStore(bigBlockSize,SmallDocumentBlock.convert(bigBlockSize,bigBlocks, _size)); - _big_store = new BigBlockStore(bigBlockSize,new DocumentBlock[0]); - } else { - _small_store = new SmallBlockStore(bigBlockSize,EMPTY_SMALL_BLOCK_ARRAY); - } - } - public OPOIFSDocument(String name, InputStream stream) throws IOException { - this(name, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, stream); - } - - /** - * Constructor - * - * @param name the name of the POIFSDocument - * @param size the length of the POIFSDocument - * @param path the path of the POIFSDocument - * @param writer the writer who will eventually write the document contents - */ - public OPOIFSDocument(String name, int size, POIFSBigBlockSize bigBlockSize, POIFSDocumentPath path, POIFSWriterListener writer) { - _size = size; - _bigBigBlockSize = bigBlockSize; - _property = new DocumentProperty(name, _size); - _property.setDocument(this); - if (_property.shouldUseSmallBlocks()) { - _small_store = new SmallBlockStore(_bigBigBlockSize, path, name, size, writer); - _big_store = new BigBlockStore(_bigBigBlockSize, EMPTY_BIG_BLOCK_ARRAY); - } else { - _small_store = new SmallBlockStore(_bigBigBlockSize, EMPTY_SMALL_BLOCK_ARRAY); - _big_store = new BigBlockStore(_bigBigBlockSize, path, name, size, writer); - } - } - public OPOIFSDocument(String name, int size, POIFSDocumentPath path, POIFSWriterListener writer) { - this(name, size, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, path, writer); - } - - /** - * @return array of SmallDocumentBlocks; may be empty, cannot be null - */ - public SmallDocumentBlock[] getSmallBlocks() { - return _small_store.getBlocks(); - } - - /** - * @return size of the document - */ - public int getSize() { - return _size; - } - - /** - * read data from the internal stores - * - * @param buffer the buffer to write to - * @param offset the offset into our storage to read from - * This method is currently (Oct 2008) only used by test code. Perhaps it can be deleted - */ - void read(byte[] buffer, int offset) { - ODocumentInputStream.readFullyInternal(buffer, 0, buffer.length, offset, _size, this::getDataInputBlock); - } - - /** - * @return <code>null</code> if <tt>offset</tt> points to the end of the document stream - */ - DataInputBlock getDataInputBlock(int offset) { - if (offset >= _size) { - if (offset > _size) { - throw new RuntimeException("Request for Offset " + offset + " doc size is " + _size); - } - return null; - } - if (_property.shouldUseSmallBlocks()) { - return SmallDocumentBlock.getDataInputBlock(_small_store.getBlocks(), offset); - } - return DocumentBlock.getDataInputBlock(_big_store.getBlocks(), offset); - } - - /** - * @return the instance's DocumentProperty - */ - - DocumentProperty getDocumentProperty() { - return _property; - } - - /* ********** START implementation of BlockWritable ********** */ - - /** - * Write the storage to an OutputStream - * - * @param stream the OutputStream to which the stored data should be written - */ - public void writeBlocks(OutputStream stream) throws IOException { - _big_store.writeBlocks(stream); - } - - /* ********** END implementation of BlockWritable ********** */ - /* ********** START implementation of BATManaged ********** */ - - /** - * Return the number of BigBlock's this instance uses - * - * @return count of BigBlock instances - */ - public int countBlocks() { - return _big_store.countBlocks(); - } - - /** - * Set the start block for this instance - * - * @param index index into the array of blocks making up the filesystem - */ - public void setStartBlock(int index) { - _property.setStartBlock(index); - } - - /* ********** END implementation of BATManaged ********** */ - /* ********** START begin implementation of POIFSViewable ********** */ - - /** - * Get an array of objects, some of which may implement POIFSViewable - * - * @return an array of Object; may not be null, but may be empty - */ - public Object[] getViewableArray() { - String result = "<NO DATA>"; - - try { - BlockWritable[] blocks = null; - - if (_big_store.isValid()) { - blocks = _big_store.getBlocks(); - } else if (_small_store.isValid()) { - blocks = _small_store.getBlocks(); - } - if (blocks != null) { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - for (BlockWritable bw : blocks) { - bw.writeBlocks(output); - } - int length = Math.min(output.size(), _property.getSize()); - result = HexDump.dump(output.toByteArray(), 0, 0, length); - } - } catch (IOException e) { - result = e.getMessage(); - } - return new String[]{ result }; - } - - /** - * Get an Iterator of objects, some of which may implement POIFSViewable - * - * @return an Iterator; may not be null, but may have an empty back end - * store - */ - public Iterator<Object> getViewableIterator() { - return Collections.emptyList().iterator(); - } - - /** - * Give viewers a hint as to whether to call getViewableArray or - * getViewableIterator - * - * @return <code>true</code> if a viewer should call getViewableArray, - * <code>false</code> if a viewer should call getViewableIterator - */ - public boolean preferArray() { - return true; - } - - /** - * Provides a short description of the object, to be used when a - * POIFSViewable object has not provided its contents. - * - * @return short description - */ - public String getShortDescription() { - return "Document: \"" + _property.getName() + "\"" + - " size = " + getSize(); - } - - /* ********** END begin implementation of POIFSViewable ********** */ - private static final class SmallBlockStore { - private SmallDocumentBlock[] _smallBlocks; - private final POIFSDocumentPath _path; - private final String _name; - private final int _size; - private final POIFSWriterListener _writer; - private final POIFSBigBlockSize _bigBlockSize; - - /** - * Constructor - * - * @param blocks blocks to construct the store from - */ - SmallBlockStore(POIFSBigBlockSize bigBlockSize, SmallDocumentBlock[] blocks) { - _bigBlockSize = bigBlockSize; - _smallBlocks = blocks.clone(); - this._path = null; - this._name = null; - this._size = -1; - this._writer = null; - } - - /** - * Constructor for a small block store that will be written later - * - * @param path path of the document - * @param name name of the document - * @param size length of the document - * @param writer the object that will eventually write the document - */ - SmallBlockStore(POIFSBigBlockSize bigBlockSize, POIFSDocumentPath path, - String name, int size, POIFSWriterListener writer) { - _bigBlockSize = bigBlockSize; - _smallBlocks = new SmallDocumentBlock[0]; - this._path = path; - this._name = name; - this._size = size; - this._writer = writer; - } - - /** - * @return <code>true</code> if this store is a valid source of data - */ - boolean isValid() { - return _smallBlocks.length > 0 || _writer != null; - } - - /** - * @return the SmallDocumentBlocks - */ - SmallDocumentBlock[] getBlocks() { - if (isValid() && _writer != null) { - ByteArrayOutputStream stream = new ByteArrayOutputStream(_size); - DocumentOutputStream dstream = new DocumentOutputStream(stream, _size); - - _writer.processPOIFSWriterEvent(new POIFSWriterEvent(dstream, _path, _name, _size)); - _smallBlocks = SmallDocumentBlock.convert(_bigBlockSize, stream.toByteArray(), _size); - } - return _smallBlocks; - } - } // end private class SmallBlockStore - - private static final class BigBlockStore { - private DocumentBlock[] bigBlocks; - private final POIFSDocumentPath _path; - private final String _name; - private final int _size; - private final POIFSWriterListener _writer; - private final POIFSBigBlockSize _bigBlockSize; - - /** - * Constructor - * - * @param blocks the blocks making up the store - */ - BigBlockStore(POIFSBigBlockSize bigBlockSize, DocumentBlock[] blocks) { - _bigBlockSize = bigBlockSize; - bigBlocks = blocks.clone(); - _path = null; - _name = null; - _size = -1; - _writer = null; - } - - /** - * Constructor for a big block store that will be written later - * - * @param path path of the document - * @param name name of the document - * @param size length of the document - * @param writer the object that will eventually write the document - */ - BigBlockStore(POIFSBigBlockSize bigBlockSize, POIFSDocumentPath path, - String name, int size, POIFSWriterListener writer) { - _bigBlockSize = bigBlockSize; - bigBlocks = new DocumentBlock[0]; - _path = path; - _name = name; - _size = size; - _writer = writer; - } - - /** - * @return <code>true</code> if this store is a valid source of data - */ - boolean isValid() { - return bigBlocks.length > 0 || _writer != null; - } - - /** - * @return the DocumentBlocks - */ - DocumentBlock[] getBlocks() { - if (isValid() && _writer != null) { - ByteArrayOutputStream stream = new ByteArrayOutputStream(_size); - DocumentOutputStream dstream = new DocumentOutputStream(stream, _size); - - _writer.processPOIFSWriterEvent(new POIFSWriterEvent(dstream, _path, _name, _size)); - bigBlocks = DocumentBlock.convert(_bigBlockSize, stream.toByteArray(), _size); - } - return bigBlocks; - } - - /** - * write the blocks to a stream - * - * @param stream the stream to which the data is to be written - */ - void writeBlocks(OutputStream stream) throws IOException { - if (isValid()) { - if (_writer != null) { - DocumentOutputStream dstream = new DocumentOutputStream(stream, _size); - - _writer.processPOIFSWriterEvent(new POIFSWriterEvent(dstream, _path, _name, _size)); - dstream.writeFiller(countBlocks() * _bigBlockSize.getBigBlockSize(), - DocumentBlock.getFillByte()); - } else { - for (DocumentBlock bigBlock : bigBlocks) { - bigBlock.writeBlocks(stream); - } - } - } - } - - /** - * @return number of big blocks making up this document - */ - int countBlocks() { - - if (isValid()) { - if (_writer == null) { - return bigBlocks.length; - } - return (_size + _bigBlockSize.getBigBlockSize() - 1) - / _bigBlockSize.getBigBlockSize(); - } - return 0; - } - } // end private class BigBlockStore -} diff --git a/src/java/org/apache/poi/poifs/filesystem/OPOIFSFileSystem.java b/src/java/org/apache/poi/poifs/filesystem/OPOIFSFileSystem.java deleted file mode 100644 index 18bc8be0bb..0000000000 --- a/src/java/org/apache/poi/poifs/filesystem/OPOIFSFileSystem.java +++ /dev/null @@ -1,570 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.dev.POIFSViewable; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.Property; -import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.poifs.storage.BATBlock; -import org.apache.poi.poifs.storage.BlockAllocationTableReader; -import org.apache.poi.poifs.storage.BlockAllocationTableWriter; -import org.apache.poi.poifs.storage.BlockList; -import org.apache.poi.poifs.storage.BlockWritable; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.poifs.storage.HeaderBlockWriter; -import org.apache.poi.poifs.storage.RawDataBlockList; -import org.apache.poi.poifs.storage.SmallBlockTableReader; -import org.apache.poi.poifs.storage.SmallBlockTableWriter; -import org.apache.poi.util.CloseIgnoringInputStream; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * <p>This is the main class of the POIFS system; it manages the entire - * life cycle of the filesystem.</p> - * <p>This is the older version, which uses more memory, and doesn't - * support in-place writes.</p> - */ -public class OPOIFSFileSystem - implements POIFSViewable -{ - private static final POILogger _logger = - POILogFactory.getLogger(OPOIFSFileSystem.class); - - /** - * Convenience method for clients that want to avoid the auto-close behaviour of the constructor. - */ - public static InputStream createNonClosingInputStream(InputStream is) { - return new CloseIgnoringInputStream(is); - } - - private PropertyTable _property_table; - private List<OPOIFSDocument> _documents; - private DirectoryNode _root; - - /** - * What big block size the file uses. Most files - * use 512 bytes, but a few use 4096 - */ - private POIFSBigBlockSize bigBlockSize = - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - - /** - * Constructor, intended for writing - */ - public OPOIFSFileSystem() - { - HeaderBlock header_block = new HeaderBlock(bigBlockSize); - _property_table = new PropertyTable(header_block); - _documents = new ArrayList<>(); - _root = null; - } - - /** - * Create a OPOIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until - * EOF. The stream is always closed.<p> - * - * Some streams are usable after reaching EOF (typically those that return <code>true</code> - * for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream - * <i>and</i> needs to use it after this constructor completes, a work around is to wrap the - * stream in order to trap the <tt>close()</tt> call. A convenience method ( - * <tt>createNonClosingInputStream()</tt>) has been provided for this purpose: - * <pre> - * InputStream wrappedStream = OPOIFSFileSystem.createNonClosingInputStream(is); - * HSSFWorkbook wb = new HSSFWorkbook(wrappedStream); - * is.reset(); - * doSomethingElse(is); - * </pre> - * Note also the special case of <tt>ByteArrayInputStream</tt> for which the <tt>close()</tt> - * method does nothing. - * <pre> - * ByteArrayInputStream bais = ... - * HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.close() ! - * bais.reset(); // no problem - * doSomethingElse(bais); - * </pre> - * - * @param stream the InputStream from which to read the data - * - * @exception IOException on errors reading, or on invalid data - */ - - public OPOIFSFileSystem(InputStream stream) - throws IOException - { - this(); - boolean success = false; - - HeaderBlock header_block; - RawDataBlockList data_blocks; - try { - // read the header block from the stream - header_block = new HeaderBlock(stream); - bigBlockSize = header_block.getBigBlockSize(); - - // read the rest of the stream into blocks - data_blocks = new RawDataBlockList(stream, bigBlockSize); - success = true; - } finally { - closeInputStream(stream, success); - } - - - // set up the block allocation table (necessary for the - // data_blocks to be manageable - new BlockAllocationTableReader(header_block.getBigBlockSize(), - header_block.getBATCount(), - header_block.getBATArray(), - header_block.getXBATCount(), - header_block.getXBATIndex(), - data_blocks); - - // get property table from the document - PropertyTable properties = - new PropertyTable(header_block, data_blocks); - - // init documents - processProperties( - SmallBlockTableReader.getSmallDocumentBlocks( - bigBlockSize, data_blocks, properties.getRoot(), - header_block.getSBATStart() - ), - data_blocks, - properties.getRoot().getChildren(), - null, - header_block.getPropertyStart() - ); - - // For whatever reason CLSID of root is always 0. - getRoot().setStorageClsid(properties.getRoot().getStorageClsid()); - } - /** - * @param stream the stream to be closed - * @param success <code>false</code> if an exception is currently being thrown in the calling method - */ - protected void closeInputStream(InputStream stream, boolean success) { - - if(stream.markSupported() && !(stream instanceof ByteArrayInputStream)) { - String msg = "POIFS is closing the supplied input stream of type (" - + stream.getClass().getName() + ") which supports mark/reset. " - + "This will be a problem for the caller if the stream will still be used. " - + "If that is the case the caller should wrap the input stream to avoid this close logic. " - + "This warning is only temporary and will not be present in future versions of POI."; - _logger.log(POILogger.WARN, msg); - } - try { - stream.close(); - } catch (IOException e) { - if(success) { - throw new RuntimeException(e); - } - // else not success? Try block did not complete normally - // just print stack trace and leave original ex to be thrown - _logger.log(POILogger.ERROR, "can't close input stream", e); - } - } - - /** - * Create a new document to be added to the root directory - * - * @param stream the InputStream from which the document's data - * will be obtained - * @param name the name of the new POIFSDocument - * - * @return the new DocumentEntry - * - * @exception IOException on error creating the new POIFSDocument - */ - - public DocumentEntry createDocument(final InputStream stream, - final String name) - throws IOException - { - return getRoot().createDocument(name, stream); - } - - /** - * create a new DocumentEntry in the root entry; the data will be - * provided later - * - * @param name the name of the new DocumentEntry - * @param size the size of the new DocumentEntry - * @param writer the writer of the new DocumentEntry - * - * @return the new DocumentEntry - * - * @exception IOException - */ - public DocumentEntry createDocument(final String name, final int size, - final POIFSWriterListener writer) - throws IOException - { - return getRoot().createDocument(name, size, writer); - } - - /** - * create a new DirectoryEntry in the root directory - * - * @param name the name of the new DirectoryEntry - * - * @return the new DirectoryEntry - * - * @exception IOException on name duplication - */ - - public DirectoryEntry createDirectory(final String name) - throws IOException - { - return getRoot().createDirectory(name); - } - - /** - * Write the filesystem out - * - * @param stream the OutputStream to which the filesystem will be - * written - * - * @exception IOException thrown on errors writing to the stream - */ - - public void writeFilesystem(final OutputStream stream) - throws IOException - { - - // get the property table ready - _property_table.preWrite(); - - // create the small block store, and the SBAT - SmallBlockTableWriter sbtw = - new SmallBlockTableWriter(bigBlockSize, _documents, _property_table.getRoot()); - - // create the block allocation table - BlockAllocationTableWriter bat = - new BlockAllocationTableWriter(bigBlockSize); - - // create a list of BATManaged objects: the documents plus the - // property table and the small block table - List<Object> bm_objects = new ArrayList<>(); - - bm_objects.addAll(_documents); - bm_objects.add(_property_table); - bm_objects.add(sbtw); - bm_objects.add(sbtw.getSBAT()); - - // walk the list, allocating space for each and assigning each - // a starting block number - Iterator<Object> iter = bm_objects.iterator(); - - while (iter.hasNext()) - { - BATManaged bmo = ( BATManaged ) iter.next(); - int block_count = bmo.countBlocks(); - - if (block_count != 0) { - bmo.setStartBlock(bat.allocateSpace(block_count)); - } /*else { - // Either the BATManaged object is empty or its data - // is composed of SmallBlocks; in either case, - // allocating space in the BAT is inappropriate - }*/ - } - - // allocate space for the block allocation table and take its - // starting block - int batStartBlock = bat.createBlocks(); - - // get the extended block allocation table blocks - HeaderBlockWriter header_block_writer = new HeaderBlockWriter(bigBlockSize); - BATBlock[] xbat_blocks = - header_block_writer.setBATBlocks(bat.countBlocks(), - batStartBlock); - - // set the property table start block - header_block_writer.setPropertyStart(_property_table.getStartBlock()); - - // set the small block allocation table start block - header_block_writer.setSBATStart(sbtw.getSBAT().getStartBlock()); - - // set the small block allocation table block count - header_block_writer.setSBATBlockCount(sbtw.getSBATBlockCount()); - - // the header is now properly initialized. Make a list of - // writers (the header block, followed by the documents, the - // property table, the small block store, the small block - // allocation table, the block allocation table, and the - // extended block allocation table blocks) - List<Object> writers = new ArrayList<>(); - - writers.add(header_block_writer); - writers.addAll(_documents); - writers.add(_property_table); - writers.add(sbtw); - writers.add(sbtw.getSBAT()); - writers.add(bat); - Collections.addAll(writers, xbat_blocks); - - // now, write everything out - iter = writers.iterator(); - while (iter.hasNext()) - { - BlockWritable writer = ( BlockWritable ) iter.next(); - - writer.writeBlocks(stream); - } - } - - /** - * read in a file and write it back out again - * - * @param args names of the files; arg[ 0 ] is the input file, - * arg[ 1 ] is the output file - * - * @exception IOException - */ - public static void main(String args[]) - throws IOException - { - if (args.length != 2) - { - System.err.println( - "two arguments required: input filename and output filename"); - System.exit(1); - } - FileInputStream istream = new FileInputStream(args[ 0 ]); - FileOutputStream ostream = new FileOutputStream(args[ 1 ]); - - new OPOIFSFileSystem(istream).writeFilesystem(ostream); - istream.close(); - ostream.close(); - } - - /** - * get the root entry - * - * @return the root entry - */ - - public DirectoryNode getRoot() - { - if (_root == null) - { - _root = new DirectoryNode(_property_table.getRoot(), this, null); - } - return _root; - } - - /** - * open a document in the root entry's list of entries - * - * @param documentName the name of the document to be opened - * - * @return a newly opened DocumentInputStream - * - * @exception IOException if the document does not exist or the - * name is that of a DirectoryEntry - */ - - public DocumentInputStream createDocumentInputStream( - final String documentName) - throws IOException - { - return getRoot().createDocumentInputStream(documentName); - } - - /** - * add a new POIFSDocument - * - * @param document the POIFSDocument being added - */ - - void addDocument(final OPOIFSDocument document) - { - _documents.add(document); - _property_table.addProperty(document.getDocumentProperty()); - } - - /** - * add a new DirectoryProperty - * - * @param directory the DirectoryProperty being added - */ - - void addDirectory(final DirectoryProperty directory) - { - _property_table.addProperty(directory); - } - - /** - * remove an entry - * - * @param entry to be removed - */ - - void remove(EntryNode entry) - { - _property_table.removeProperty(entry.getProperty()); - if (entry.isDocumentEntry()) - { - _documents.remove((( DocumentNode ) entry).getDocument()); - } - } - - private void processProperties(final BlockList small_blocks, - final BlockList big_blocks, - final Iterator<Property> properties, - final DirectoryNode dir, - final int headerPropertiesStartAt) - throws IOException - { - while (properties.hasNext()) - { - Property property = properties.next(); - String name = property.getName(); - DirectoryNode parent = (dir == null) - ? getRoot() - : dir; - - if (property.isDirectory()) - { - DirectoryNode new_dir = - ( DirectoryNode ) parent.createDirectory(name); - - new_dir.setStorageClsid( property.getStorageClsid() ); - - processProperties( - small_blocks, big_blocks, - (( DirectoryProperty ) property).getChildren(), - new_dir, headerPropertiesStartAt); - } - else - { - int startBlock = property.getStartBlock(); - int size = property.getSize(); - OPOIFSDocument document; - - if (property.shouldUseSmallBlocks()) - { - document = - new OPOIFSDocument(name, - small_blocks.fetchBlocks(startBlock, headerPropertiesStartAt), - size); - } - else - { - document = - new OPOIFSDocument(name, - big_blocks.fetchBlocks(startBlock, headerPropertiesStartAt), - size); - } - parent.createDocument(document); - } - } - } - - /* ********** START begin implementation of POIFSViewable ********** */ - - /** - * Get an array of objects, some of which may implement - * POIFSViewable - * - * @return an array of Object; may not be null, but may be empty - */ - - public Object [] getViewableArray() - { - if (preferArray()) - { - return getRoot().getViewableArray(); - } - return new Object[ 0 ]; - } - - /** - * Get an Iterator of objects, some of which may implement - * POIFSViewable - * - * @return an Iterator; may not be null, but may have an empty - * back end store - */ - - public Iterator<Object> getViewableIterator() - { - if (!preferArray()) - { - return getRoot().getViewableIterator(); - } - return Collections.emptyList().iterator(); - } - - /** - * Give viewers a hint as to whether to call getViewableArray or - * getViewableIterator - * - * @return true if a viewer should call getViewableArray, false if - * a viewer should call getViewableIterator - */ - - public boolean preferArray() - { - return getRoot().preferArray(); - } - - /** - * Provides a short description of the object, to be used when a - * POIFSViewable object has not provided its contents. - * - * @return short description - */ - - public String getShortDescription() - { - return "POIFS FileSystem"; - } - - /** - * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes - */ - public int getBigBlockSize() { - return bigBlockSize.getBigBlockSize(); - } - /** - * @return The Big Block size, normally 512 bytes, sometimes 4096 bytes - */ - public POIFSBigBlockSize getBigBlockSizeDetails() { - return bigBlockSize; - } - - /* ********** END begin implementation of POIFSViewable ********** */ -} // end public class OPOIFSFileSystem - diff --git a/src/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java b/src/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java index a12a9369d8..39065c24a2 100644 --- a/src/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java +++ b/src/java/org/apache/poi/poifs/filesystem/POIFSFileSystem.java @@ -141,6 +141,6 @@ public class POIFSFileSystem * arg[ 1 ] is the output file */ public static void main(String args[]) throws IOException { - OPOIFSFileSystem.main(args); + NPOIFSFileSystem.main(args); } } diff --git a/src/java/org/apache/poi/poifs/storage/package.html b/src/java/org/apache/poi/poifs/filesystem/package-info.java index b098350c27..84c2d9f35d 100644 --- a/src/java/org/apache/poi/poifs/storage/package.html +++ b/src/java/org/apache/poi/poifs/filesystem/package-info.java @@ -1,6 +1,4 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== +/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. @@ -15,22 +13,11 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> +==================================================================== */ -storage package contains low level binary structures for POIFS's implementation of the OLE 2 -Compound Document Format. - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -</body> -</html> +/** + * filesystem package maps OLE 2 Compound document files to a more familiar filesystem interface. + * + * @see org.apache.poi.poifs.eventfilesystem + */ +package org.apache.poi.poifs.filesystem;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/filesystem/package.html b/src/java/org/apache/poi/poifs/filesystem/package.html deleted file mode 100644 index d673ed5934..0000000000 --- a/src/java/org/apache/poi/poifs/filesystem/package.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> - -filesystem package maps OLE 2 Compound document files to a more familiar filesystem interface. - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -<!-- Put @see and @since tags down here. --> -@see org.apache.poi.poifs.eventfilesystem -</body> -</html> diff --git a/src/java/org/apache/poi/poifs/package-info.java b/src/java/org/apache/poi/poifs/package-info.java new file mode 100644 index 0000000000..78420021c9 --- /dev/null +++ b/src/java/org/apache/poi/poifs/package-info.java @@ -0,0 +1,25 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +/** + * Poor Obfuscation Implementation FileSystem APIs implement the OLE 2 Compound Document format in + * pure Java. All POI subprojects are based upon this API. + * + * @see org.apache.poi.hssf + * @see org.apache.poi.hpsf + */ +package org.apache.poi.poifs;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/package.html b/src/java/org/apache/poi/poifs/package.html deleted file mode 100644 index f86821c8a8..0000000000 --- a/src/java/org/apache/poi/poifs/package.html +++ /dev/null @@ -1,39 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> - -Poor Obfuscation Implementation FileSystem APIs implement the OLE 2 Compound Document format in -pure Java. All POI subprojects are based upon this API. - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -<!-- Put @see and @since tags down here. --> -@see org.apache.poi.hssf -@see org.apache.poi.hpsf -</body> -</html> diff --git a/src/java/org/apache/poi/poifs/property/DirectoryProperty.java b/src/java/org/apache/poi/poifs/property/DirectoryProperty.java index 12d0cc855d..07846736c2 100644 --- a/src/java/org/apache/poi/poifs/property/DirectoryProperty.java +++ b/src/java/org/apache/poi/poifs/property/DirectoryProperty.java @@ -30,7 +30,7 @@ import java.util.Set; /** * Directory property */ -public class DirectoryProperty extends Property implements Parent, Iterable<Property> { // TODO - fix instantiable superclass +public class DirectoryProperty extends Property implements Parent, Iterable<Property> { /** List of Property instances */ private List<Property> _children; diff --git a/src/java/org/apache/poi/poifs/property/DocumentProperty.java b/src/java/org/apache/poi/poifs/property/DocumentProperty.java index ea693d8871..38d196975e 100644 --- a/src/java/org/apache/poi/poifs/property/DocumentProperty.java +++ b/src/java/org/apache/poi/poifs/property/DocumentProperty.java @@ -19,14 +19,14 @@ package org.apache.poi.poifs.property; -import org.apache.poi.poifs.filesystem.OPOIFSDocument; +import org.apache.poi.poifs.filesystem.NPOIFSDocument; /** * Trivial extension of Property for POIFSDocuments */ public class DocumentProperty extends Property { // the POIFSDocument this property is associated with - private OPOIFSDocument _document; + private NPOIFSDocument _document; /** * Constructor @@ -64,7 +64,7 @@ public class DocumentProperty extends Property { * * @param doc the associated POIFSDocument */ - public void setDocument(OPOIFSDocument doc) + public void setDocument(NPOIFSDocument doc) { _document = doc; } @@ -74,7 +74,7 @@ public class DocumentProperty extends Property { * * @return the associated document */ - public OPOIFSDocument getDocument() + public NPOIFSDocument getDocument() { return _document; } diff --git a/src/java/org/apache/poi/poifs/property/RootProperty.java b/src/java/org/apache/poi/poifs/property/RootProperty.java index 5a8f3d52ef..3cb4a6e43b 100644 --- a/src/java/org/apache/poi/poifs/property/RootProperty.java +++ b/src/java/org/apache/poi/poifs/property/RootProperty.java @@ -18,7 +18,6 @@ package org.apache.poi.poifs.property; import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.SmallDocumentBlock; /** * Root property @@ -43,9 +42,7 @@ public final class RootProperty extends DirectoryProperty { * @param array byte data * @param offset offset into byte data */ - protected RootProperty(final int index, final byte [] array, - final int offset) - { + RootProperty(final int index, final byte [] array, final int offset) { super(index, array, offset); } @@ -56,7 +53,9 @@ public final class RootProperty extends DirectoryProperty { */ public void setSize(int size) { - super.setSize(SmallDocumentBlock.calcSize(size)); + final int BLOCK_SHIFT = 6; + final int _block_size = 1 << BLOCK_SHIFT; + super.setSize(size * _block_size); } /** diff --git a/src/java/org/apache/poi/poifs/property/package-info.java b/src/java/org/apache/poi/poifs/property/package-info.java new file mode 100644 index 0000000000..9ffa4aebc7 --- /dev/null +++ b/src/java/org/apache/poi/poifs/property/package-info.java @@ -0,0 +1,23 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +/** + * property package contains high and low level Property structures for POIFS. + * + * @see org.apache.poi.poifs.filesystem + */ +package org.apache.poi.poifs.property;
\ No newline at end of file diff --git a/src/java/org/apache/poi/poifs/property/package.html b/src/java/org/apache/poi/poifs/property/package.html deleted file mode 100644 index ff11a205aa..0000000000 --- a/src/java/org/apache/poi/poifs/property/package.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> -<!-- - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== ---> -<html> -<head> -</head> -<body bgcolor="white"> - -property package contains high and low level Property structures for POIFS. - -<h2>Related Documentation</h2> - -For overviews, tutorials, examples, guides, and tool documentation, please see: -<ul> -<li><a href="http://poi.apache.org">Apache POI Project</a> -</ul> - -<!-- Put @see and @since tags down here. --> -@see org.apache.poi.poifs.filesystem -</body> -</html> diff --git a/src/java/org/apache/poi/poifs/storage/HeaderBlockConstants.java b/src/java/org/apache/poi/poifs/storage/HeaderBlockConstants.java index 27e4b41e87..5470bde5b8 100644 --- a/src/java/org/apache/poi/poifs/storage/HeaderBlockConstants.java +++ b/src/java/org/apache/poi/poifs/storage/HeaderBlockConstants.java @@ -27,9 +27,9 @@ import org.apache.poi.util.LittleEndianConsts; */ public interface HeaderBlockConstants { - public static final long _signature = 0xE11AB1A1E011CFD0L; - public static final int _bat_array_offset = 0x4c; - public static final int _max_bats_in_header = + long _signature = 0xE11AB1A1E011CFD0L; + int _bat_array_offset = 0x4c; + int _max_bats_in_header = (POIFSConstants.SMALLER_BIG_BLOCK_SIZE - _bat_array_offset) / LittleEndianConsts.INT_SIZE; // If 4k blocks, rest is blank @@ -39,12 +39,12 @@ public interface HeaderBlockConstants // XBAT ~= DIFat // useful offsets - public static final int _signature_offset = 0; - public static final int _bat_count_offset = 0x2C; - public static final int _property_start_offset = 0x30; - public static final int _sbat_start_offset = 0x3C; - public static final int _sbat_block_count_offset = 0x40; - public static final int _xbat_start_offset = 0x44; - public static final int _xbat_count_offset = 0x48; -} // end public interface HeaderBlockConstants + int _signature_offset = 0; + int _bat_count_offset = 0x2C; + int _property_start_offset = 0x30; + int _sbat_start_offset = 0x3C; + int _sbat_block_count_offset = 0x40; + int _xbat_start_offset = 0x44; + int _xbat_count_offset = 0x48; +} diff --git a/src/java/org/apache/poi/poifs/storage/SmallBlockTableReader.java b/src/java/org/apache/poi/poifs/storage/SmallBlockTableReader.java deleted file mode 100644 index 605b749af6..0000000000 --- a/src/java/org/apache/poi/poifs/storage/SmallBlockTableReader.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.IOException; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.property.RootProperty; - -/** - * This class implements reading the small document block list from an - * existing file - */ -public final class SmallBlockTableReader { - private static BlockList prepareSmallDocumentBlocks( - final POIFSBigBlockSize bigBlockSize, - final RawDataBlockList blockList, final RootProperty root, - final int sbatStart) - throws IOException - { - // Fetch the blocks which hold the Small Blocks stream - ListManagedBlock [] smallBlockBlocks = - blockList.fetchBlocks(root.getStartBlock(), -1); - - // Turn that into a list - - return new SmallDocumentBlockList( - SmallDocumentBlock.extract(bigBlockSize, smallBlockBlocks)); - } - private static BlockAllocationTableReader prepareReader( - final POIFSBigBlockSize bigBlockSize, - final RawDataBlockList blockList, final BlockList list, - final RootProperty root, final int sbatStart) - throws IOException - { - // Process the SBAT and blocks - return new BlockAllocationTableReader(bigBlockSize, - blockList.fetchBlocks(sbatStart, -1), - list); - } - - /** - * Fetch the small document block reader from an existing file, normally - * needed for debugging and low level dumping. You should typically call - * {@link #getSmallDocumentBlocks(POIFSBigBlockSize, RawDataBlockList, RootProperty, int)} - * instead. - * - * @param blockList the raw data from which the small block table - * will be extracted - * @param root the root property (which contains the start block - * and small block table size) - * @param sbatStart the start block of the SBAT - * - * @return the small document block reader - * - * @exception IOException - */ - public static BlockAllocationTableReader _getSmallDocumentBlockReader( - final POIFSBigBlockSize bigBlockSize, - final RawDataBlockList blockList, final RootProperty root, - final int sbatStart) - throws IOException - { - BlockList list = prepareSmallDocumentBlocks( - bigBlockSize, blockList, root, sbatStart); - return prepareReader( - bigBlockSize, blockList, list, root, sbatStart); - } - - /** - * Fetch the small document block list from an existing file - * - * @param blockList the raw data from which the small block table - * will be extracted - * @param root the root property (which contains the start block - * and small block table size) - * @param sbatStart the start block of the SBAT - * - * @return the small document block list - * - * @exception IOException - */ - public static BlockList getSmallDocumentBlocks( - final POIFSBigBlockSize bigBlockSize, - final RawDataBlockList blockList, final RootProperty root, - final int sbatStart) - throws IOException - { - BlockList list = prepareSmallDocumentBlocks( - bigBlockSize, blockList, root, sbatStart); - prepareReader(bigBlockSize, blockList, list, root, sbatStart); - return list; - } -} diff --git a/src/java/org/apache/poi/poifs/storage/SmallBlockTableWriter.java b/src/java/org/apache/poi/poifs/storage/SmallBlockTableWriter.java deleted file mode 100644 index 3d2b16fe5b..0000000000 --- a/src/java/org/apache/poi/poifs/storage/SmallBlockTableWriter.java +++ /dev/null @@ -1,149 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.storage; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.filesystem.BATManaged; -import org.apache.poi.poifs.filesystem.OPOIFSDocument; -import org.apache.poi.poifs.property.RootProperty; - -import java.util.*; - -import java.io.*; - -/** - * This class implements storage for writing the small blocks used by - * small documents. - * - * @author Marc Johnson (mjohnson at apache dot org) - */ - -public class SmallBlockTableWriter - implements BlockWritable, BATManaged -{ - private BlockAllocationTableWriter _sbat; - private List<SmallDocumentBlock> _small_blocks; - private int _big_block_count; - private RootProperty _root; - - /** - * Creates new SmallBlockTable - * - * @param documents a List of POIFSDocument instances - * @param root the Filesystem's root property - */ - public SmallBlockTableWriter(final POIFSBigBlockSize bigBlockSize, - final List<OPOIFSDocument> documents, - final RootProperty root) - { - _sbat = new BlockAllocationTableWriter(bigBlockSize); - _small_blocks = new ArrayList<>(); - _root = root; - - for (OPOIFSDocument doc : documents) - { - SmallDocumentBlock[] blocks = doc.getSmallBlocks(); - - if (blocks.length != 0) - { - doc.setStartBlock(_sbat.allocateSpace(blocks.length)); - for (int j = 0; j < blocks.length; j++) - { - _small_blocks.add(blocks[ j ]); - } - } else { - doc.setStartBlock(POIFSConstants.END_OF_CHAIN); - } - } - _sbat.simpleCreateBlocks(); - _root.setSize(_small_blocks.size()); - _big_block_count = SmallDocumentBlock.fill(bigBlockSize,_small_blocks); - } - - /** - * Get the number of SBAT blocks - * - * @return number of SBAT big blocks - */ - - public int getSBATBlockCount() - { - return (_big_block_count + 15) / 16; - } - - /** - * Get the SBAT - * - * @return the Small Block Allocation Table - */ - - public BlockAllocationTableWriter getSBAT() - { - return _sbat; - } - - /* ********** START implementation of BATManaged ********** */ - - /** - * Return the number of BigBlock's this instance uses - * - * @return count of BigBlock instances - */ - - public int countBlocks() - { - return _big_block_count; - } - - /** - * Set the start block for this instance - * - * @param start_block - */ - - public void setStartBlock(int start_block) - { - _root.setStartBlock(start_block); - } - - /* ********** END implementation of BATManaged ********** */ - /* ********** START implementation of BlockWritable ********** */ - - /** - * Write the storage to an OutputStream - * - * @param stream the OutputStream to which the stored data should - * be written - * - * @exception IOException on problems writing to the specified - * stream - */ - - public void writeBlocks(final OutputStream stream) - throws IOException - { - for (BlockWritable block : _small_blocks) { - block.writeBlocks(stream); - } - } - - /* ********** END implementation of BlockWritable ********** */ -} diff --git a/src/java/org/apache/poi/poifs/storage/SmallDocumentBlock.java b/src/java/org/apache/poi/poifs/storage/SmallDocumentBlock.java deleted file mode 100644 index 711a2d56a3..0000000000 --- a/src/java/org/apache/poi/poifs/storage/SmallDocumentBlock.java +++ /dev/null @@ -1,253 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; - -/** - * Storage for documents that are too small to use regular - * DocumentBlocks for their data - */ -public final class SmallDocumentBlock implements BlockWritable, ListManagedBlock { - private static final int BLOCK_SHIFT = 6; - - private byte[] _data; - private static final byte _default_fill = ( byte ) 0xff; - private static final int _block_size = 1 << BLOCK_SHIFT; - private static final int BLOCK_MASK = _block_size-1; - - private final int _blocks_per_big_block; - private final POIFSBigBlockSize _bigBlockSize; - - private SmallDocumentBlock(final POIFSBigBlockSize bigBlockSize, final byte [] data, final int index) - { - this(bigBlockSize); - System.arraycopy(data, index * _block_size, _data, 0, _block_size); - } - - protected SmallDocumentBlock(final POIFSBigBlockSize bigBlockSize) - { - _bigBlockSize = bigBlockSize; - _blocks_per_big_block = getBlocksPerBigBlock(bigBlockSize); - _data = new byte[ _block_size ]; - } - - private static int getBlocksPerBigBlock(final POIFSBigBlockSize bigBlockSize) - { - return bigBlockSize.getBigBlockSize() / _block_size; - } - - /** - * convert a single long array into an array of SmallDocumentBlock - * instances - * - * @param array the byte array to be converted - * @param size the intended size of the array (which may be smaller) - * - * @return an array of SmallDocumentBlock instances, filled from - * the array - */ - public static SmallDocumentBlock [] convert(POIFSBigBlockSize bigBlockSize, - byte [] array, - int size) - { - SmallDocumentBlock[] rval = - new SmallDocumentBlock[ (size + _block_size - 1) / _block_size ]; - int offset = 0; - - for (int k = 0; k < rval.length; k++) - { - rval[ k ] = new SmallDocumentBlock(bigBlockSize); - if (offset < array.length) - { - int length = Math.min(_block_size, array.length - offset); - - System.arraycopy(array, offset, rval[ k ]._data, 0, length); - if (length != _block_size) - { - Arrays.fill(rval[ k ]._data, length, _block_size, - _default_fill); - } - } - else - { - Arrays.fill(rval[ k ]._data, _default_fill); - } - offset += _block_size; - } - return rval; - } - - /** - * fill out a List of SmallDocumentBlocks so that it fully occupies - * a set of big blocks - * - * @param blocks the List to be filled out - * - * @return number of big blocks the list encompasses - */ - public static int fill(POIFSBigBlockSize bigBlockSize, List<SmallDocumentBlock> blocks) - { - int _blocks_per_big_block = getBlocksPerBigBlock(bigBlockSize); - - int count = blocks.size(); - int big_block_count = (count + _blocks_per_big_block - 1) - / _blocks_per_big_block; - int full_count = big_block_count * _blocks_per_big_block; - - for (; count < full_count; count++) - { - blocks.add(makeEmptySmallDocumentBlock(bigBlockSize)); - } - return big_block_count; - } - - /** - * Factory for creating SmallDocumentBlocks from DocumentBlocks - * - * @param store the original DocumentBlocks - * @param size the total document size - * - * @return an array of new SmallDocumentBlocks instances - * - * @exception IOException on errors reading from the DocumentBlocks - * @exception ArrayIndexOutOfBoundsException if, somehow, the store - * contains less data than size indicates - */ - public static SmallDocumentBlock [] convert(POIFSBigBlockSize bigBlockSize, - BlockWritable [] store, - int size) - throws IOException, ArrayIndexOutOfBoundsException - { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - for (int j = 0; j < store.length; j++) - { - store[ j ].writeBlocks(stream); - } - byte[] data = stream.toByteArray(); - SmallDocumentBlock[] rval = - new SmallDocumentBlock[ convertToBlockCount(size) ]; - - for (int index = 0; index < rval.length; index++) - { - rval[ index ] = new SmallDocumentBlock(bigBlockSize, data, index); - } - return rval; - } - - /** - * create a list of SmallDocumentBlock's from raw data - * - * @param blocks the raw data containing the SmallDocumentBlock - * data - * - * @return a List of SmallDocumentBlock's extracted from the input - */ - public static List<SmallDocumentBlock> extract(POIFSBigBlockSize bigBlockSize, ListManagedBlock [] blocks) - throws IOException - { - int _blocks_per_big_block = getBlocksPerBigBlock(bigBlockSize); - - List<SmallDocumentBlock> sdbs = new ArrayList<>(); - - for (int j = 0; j < blocks.length; j++) - { - byte[] data = blocks[ j ].getData(); - - for (int k = 0; k < _blocks_per_big_block; k++) - { - sdbs.add(new SmallDocumentBlock(bigBlockSize, data, k)); - } - } - return sdbs; - } - - public static DataInputBlock getDataInputBlock(SmallDocumentBlock[] blocks, int offset) { - int firstBlockIndex = offset >> BLOCK_SHIFT; - int firstBlockOffset= offset & BLOCK_MASK; - return new DataInputBlock(blocks[firstBlockIndex]._data, firstBlockOffset); - } - - /** - * Calculate the storage size of a set of SmallDocumentBlocks - * - * @param size number of SmallDocumentBlocks - * - * @return total size - */ - public static int calcSize(int size) - { - return size * _block_size; - } - - protected int getSmallBlocksPerBigBlock() - { - return _blocks_per_big_block; - } - - private static SmallDocumentBlock makeEmptySmallDocumentBlock(POIFSBigBlockSize bigBlockSize) - { - SmallDocumentBlock block = new SmallDocumentBlock(bigBlockSize); - - Arrays.fill(block._data, _default_fill); - return block; - } - - private static int convertToBlockCount(int size) - { - return (size + _block_size - 1) / _block_size; - } - - /** - * Write the storage to an OutputStream - * - * @param stream the OutputStream to which the stored data should - * be written - * - * @exception IOException on problems writing to the specified - * stream - */ - public void writeBlocks(OutputStream stream) - throws IOException - { - stream.write(_data); - } - - /** - * Get the data from the block - * - * @return the block's data as a byte array - * - * @exception IOException if there is no data - */ - public byte [] getData() { - return _data; - } - - public POIFSBigBlockSize getBigBlockSize() { - return _bigBlockSize; - } -} diff --git a/src/java/org/apache/poi/poifs/storage/package-info.java b/src/java/org/apache/poi/poifs/storage/package-info.java new file mode 100644 index 0000000000..9fadf9df91 --- /dev/null +++ b/src/java/org/apache/poi/poifs/storage/package-info.java @@ -0,0 +1,22 @@ +/* ==================================================================== + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +==================================================================== */ + +/** + * storage package contains low level binary structures for POIFS's implementation of the OLE 2 + * Compound Document Format. + */ +package org.apache.poi.poifs.storage;
\ No newline at end of file diff --git a/src/java/org/apache/poi/util/LittleEndianOutputStream.java b/src/java/org/apache/poi/util/LittleEndianOutputStream.java index fa4f9d1abe..920ff40519 100644 --- a/src/java/org/apache/poi/util/LittleEndianOutputStream.java +++ b/src/java/org/apache/poi/util/LittleEndianOutputStream.java @@ -21,10 +21,6 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; -/** - * - * @author Josh Micich - */ public final class LittleEndianOutputStream extends FilterOutputStream implements LittleEndianOutput { public LittleEndianOutputStream(OutputStream out) { super(out); @@ -49,7 +45,7 @@ public final class LittleEndianOutputStream extends FilterOutputStream implement int b3 = (v >>> 24) & 0xFF; int b2 = (v >>> 16) & 0xFF; int b1 = (v >>> 8) & 0xFF; - int b0 = (v/* >>> 0*/) & 0xFF; + int b0 = (v) & 0xFF; try { out.write(b0); out.write(b1); @@ -69,7 +65,7 @@ public final class LittleEndianOutputStream extends FilterOutputStream implement @Override public void writeShort(int v) { int b1 = (v >>> 8) & 0xFF; - int b0 = (v/* >>> 0*/) & 0xFF; + int b0 = (v) & 0xFF; try { out.write(b0); out.write(b1); @@ -95,4 +91,37 @@ public final class LittleEndianOutputStream extends FilterOutputStream implement throw new RuntimeException(e); } } + + + /** + * Put unsigned int into output stream + * + * @param value + * the int (32-bit) value + */ + public void writeUInt( long value ) { + try { + out.write( (byte) ( ( value ) & 0xFF ) ); + out.write( (byte) ( ( value >>> 8 ) & 0xFF ) ); + out.write( (byte) ( ( value >>> 16 ) & 0xFF ) ); + out.write( (byte) ( ( value >>> 24 ) & 0xFF ) ); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Put unsigned short into output stream + * + * @param value + * the unsigned short (16-bit) value + */ + public void putUShort( int value ) { + try { + out.write( (byte) ( ( value ) & 0xFF ) ); + out.write( (byte) ( ( value >>> 8 ) & 0xFF ) ); + } catch (IOException e) { + throw new RuntimeException(e); + } + } } |