diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2021-08-28 23:48:48 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2021-08-28 23:48:48 +0000 |
commit | f71cebcce5ed809ee15cd69524f8cb0b0b2ea47c (patch) | |
tree | 4f9f798ae3acd7a3e50a675becbe85055d1beff6 /poi/src/main/java | |
parent | 6d9b450ce31209014d945a13c65fc23cb29a351c (diff) | |
download | poi-f71cebcce5ed809ee15cd69524f8cb0b0b2ea47c.tar.gz poi-f71cebcce5ed809ee15cd69524f8cb0b0b2ea47c.zip |
sonar fixes
close resources in tests
fix gradle warnings
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1892683 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'poi/src/main/java')
14 files changed, 222 insertions, 205 deletions
diff --git a/poi/src/main/java/org/apache/poi/hpsf/ClassID.java b/poi/src/main/java/org/apache/poi/hpsf/ClassID.java index aaf45554ae..21aba376b0 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/ClassID.java +++ b/poi/src/main/java/org/apache/poi/hpsf/ClassID.java @@ -49,7 +49,7 @@ public class ClassID implements Duplicatable, GenericRecord { private final byte[] bytes = new byte[LENGTH]; /** - * Creates a {@link ClassID} and reads its value from a byte array. + * Creates a ClassID and reads its value from a byte array. * * @param src The byte array to read from. * @param offset The offset of the first byte to read. @@ -60,7 +60,7 @@ public class ClassID implements Duplicatable, GenericRecord { /** - * Creates a {@link ClassID} and initializes its value with 0x00 bytes. + * Creates a ClassID and initializes its value with 0x00 bytes. */ public ClassID() { Arrays.fill(bytes, (byte)0); @@ -77,7 +77,7 @@ public class ClassID implements Duplicatable, GenericRecord { /** - * Creates a {@link ClassID} from a human-readable representation of the Class ID in standard + * Creates a ClassID from a human-readable representation of the Class ID in standard * format {@code "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"}. * * @param externalForm representation of the Class ID represented by this object. @@ -102,12 +102,11 @@ public class ClassID implements Duplicatable, GenericRecord { /** * @return The number of bytes occupied by this object in the byte stream. */ + @SuppressWarnings("java:S1845") public int length() { return LENGTH; } - - /** * Gets the bytes making out the class ID. They are returned in correct order, i.e. big-endian. * @@ -117,8 +116,6 @@ public class ClassID implements Duplicatable, GenericRecord { return bytes; } - - /** * Sets the bytes making out the class ID. * @@ -129,8 +126,6 @@ public class ClassID implements Duplicatable, GenericRecord { System.arraycopy(bytes, 0, this.bytes, 0, LENGTH); } - - /** * Reads the class ID's value from a byte array by turning little-endian into big-endian. * @@ -249,10 +244,6 @@ public class ClassID implements Duplicatable, GenericRecord { ; } - - /** - * @see Object#hashCode() - */ @Override public int hashCode() { return toString().hashCode(); diff --git a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java index 5237309c9c..eed2a7d4c8 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java +++ b/poi/src/main/java/org/apache/poi/hpsf/PropertySet.java @@ -514,51 +514,52 @@ public class PropertySet { } private byte[] toBytes() throws WritingNotSupportedException, IOException { - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - 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. */ - 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. */ - int secCnt = 0; - for (final Section section : getSections()) { - final ClassID formatID = section.getFormatID(); - if (formatID == null) { - throw new NoFormatIDException(); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + 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. */ + 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. */ + int secCnt = 0; + for (final Section section : getSections()) { + final ClassID formatID = section.getFormatID(); + if (formatID == null) { + throw new NoFormatIDException(); + } + putClassId(bos, formatID); + offsets[secCnt++][0] = bos.size(); + // offset dummy - filled later + leos.writeInt(-1); } - putClassId(bos, formatID); - offsets[secCnt++][0] = bos.size(); - // offset dummy - filled later - leos.writeInt(-1); - } - /* Write the sections themselves. */ - secCnt = 0; - for (final Section section : getSections()) { - offsets[secCnt++][1] = bos.size(); - section.write(bos); - } + /* Write the sections themselves. */ + secCnt = 0; + for (final Section section : getSections()) { + offsets[secCnt++][1] = bos.size(); + section.write(bos); + } - byte[] result = bos.toByteArray(); - for (int[] off : offsets) { - LittleEndian.putInt(result, off[0], off[1]); - } + byte[] result = bos.toByteArray(); + for (int[] off : offsets) { + LittleEndian.putInt(result, off[0], off[1]); + } - return result; + return result; + } } /** diff --git a/poi/src/main/java/org/apache/poi/hpsf/Section.java b/poi/src/main/java/org/apache/poi/hpsf/Section.java index 90d20cf448..13ae9af603 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/Section.java +++ b/poi/src/main/java/org/apache/poi/hpsf/Section.java @@ -735,53 +735,54 @@ public class Section { } final int[][] offsets = new int[properties.size()][2]; - final UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - final LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + LittleEndianOutputStream leos = new LittleEndianOutputStream(bos)) { - /* Write the section's length - dummy value, fixed later */ - leos.writeInt(-1); + /* Write the section's length - dummy value, fixed later */ + leos.writeInt(-1); - /* Write the section's number of properties: */ - leos.writeInt(properties.size()); + /* 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); - } + 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); + } - /* Write the properties and the property list into their respective - * streams: */ - propCnt = 0; - for (Property p : properties.values()) { - 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 (p.getID() != 0) { - /* Write the property and update the position to the next - * property. */ - p.write(bos, codepage); - } else { - writeDictionary(bos, codepage); + /* Write the properties and the property list into their respective + * streams: */ + propCnt = 0; + for (Property p : properties.values()) { + 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 (p.getID() != 0) { + /* Write the property and update the position to the next + * property. */ + p.write(bos, codepage); + } else { + writeDictionary(bos, codepage); + } } - } - byte[] result = bos.toByteArray(); - LittleEndian.putInt(result, 0, bos.size()); + byte[] result = bos.toByteArray(); + LittleEndian.putInt(result, 0, bos.size()); - for (int[] off : offsets) { - LittleEndian.putUInt(result, off[0], off[1]); - } + for (int[] off : offsets) { + LittleEndian.putUInt(result, off[0], off[1]); + } - out.write(result); + out.write(result); - return bos.size(); + return bos.size(); + } } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java index 94fc4070c7..5b7b114cdb 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java @@ -459,17 +459,20 @@ public final class RecordInputStream implements LittleEndianInput { */ @Deprecated public byte[] readAllContinuedRemainder() { - UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE); + try (UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(2 * MAX_RECORD_DATA_SIZE)) { - while (true) { - byte[] b = readRemainder(); - out.write(b, 0, b.length); - if (!isContinueNext()) { - break; + while (true) { + byte[] b = readRemainder(); + out.write(b, 0, b.length); + if (!isContinueNext()) { + break; + } + nextRecord(); } - nextRecord(); + return out.toByteArray(); + } catch (IOException ex) { + throw new RecordFormatException(ex); } - return out.toByteArray(); } /** The remaining number of bytes in the <i>current</i> record. diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java index 29506743f6..af688471fd 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingRule.java @@ -64,8 +64,8 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin * Only newer style formatting rules have priorities. For older ones, * we don't know priority for these, other than definition/model order, * which appears to be what Excel uses. - * @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getPriority() */ + @Override public int getPriority() { CFRule12Record rule12 = getCFRule12Record(false); if (rule12 == null) return 0; @@ -74,8 +74,8 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin /** * Always true for HSSF files, per Microsoft Excel documentation - * @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getStopIfTrue() */ + @Override public boolean getStopIfTrue() { return true; } @@ -95,8 +95,8 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin /** * Always null for HSSF records, until someone figures out where to find it - * @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getNumberFormat() */ + @Override public ExcelNumberFormat getNumberFormat() { return null; } @@ -112,16 +112,18 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin } /** - * @return - font formatting object if defined, <code>null</code> otherwise + * @return - font formatting object if defined, {@code null} otherwise */ + @Override public HSSFFontFormatting getFontFormatting() { return getFontFormatting(false); } /** * create a new font formatting structure if it does not exist, * otherwise just return existing object. - * @return - font formatting object, never returns <code>null</code>. + * @return - font formatting object, never returns {@code null}. */ + @Override public HSSFFontFormatting createFontFormatting() { return getFontFormatting(true); } @@ -137,16 +139,18 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin } /** - * @return - border formatting object if defined, <code>null</code> otherwise + * @return - border formatting object if defined, {@code null} otherwise */ + @Override public HSSFBorderFormatting getBorderFormatting() { return getBorderFormatting(false); } /** * create a new border formatting structure if it does not exist, * otherwise just return existing object. - * @return - border formatting object, never returns <code>null</code>. + * @return - border formatting object, never returns {@code null}. */ + @Override public HSSFBorderFormatting createBorderFormatting() { return getBorderFormatting(true); } @@ -162,8 +166,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin } /** - * @return - pattern formatting object if defined, <code>null</code> otherwise + * @return - pattern formatting object if defined, {@code null} otherwise */ + @Override public HSSFPatternFormatting getPatternFormatting() { return getPatternFormatting(false); @@ -171,8 +176,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin /** * create a new pattern formatting structure if it does not exist, * otherwise just return existing object. - * @return - pattern formatting object, never returns <code>null</code>. + * @return - pattern formatting object, never returns {@code null}. */ + @Override public HSSFPatternFormatting createPatternFormatting() { return getPatternFormatting(true); @@ -192,8 +198,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin } /** - * @return databar / data-bar formatting object if defined, <code>null</code> otherwise + * @return databar / data-bar formatting object if defined, {@code null} otherwise */ + @Override public HSSFDataBarFormatting getDataBarFormatting() { return getDataBarFormatting(false); } @@ -218,8 +225,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin } /** - * @return icon / multi-state formatting object if defined, <code>null</code> otherwise + * @return icon / multi-state formatting object if defined, {@code null} otherwise */ + @Override public HSSFIconMultiStateFormatting getMultiStateFormatting() { return getMultiStateFormatting(false); } @@ -245,8 +253,9 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin } /** - * @return color scale / gradient formatting object if defined, <code>null</code> otherwise + * @return color scale / gradient formatting object if defined, {@code null} otherwise */ + @Override public HSSFColorScaleFormatting getColorScaleFormatting() { return getColorScaleFormatting(false); } @@ -270,12 +279,13 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin /** * always null (not a filter condition) or {@link ConditionFilterType#FILTER} if it is. - * @see org.apache.poi.ss.usermodel.ConditionalFormattingRule#getConditionFilterType() */ + @Override public ConditionFilterType getConditionFilterType() { return getConditionType() == ConditionType.FILTER ? ConditionFilterType.FILTER : null; } + @Override public ConditionFilterData getFilterConfiguration() { return null; } @@ -288,11 +298,13 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin return cfRuleRecord.getComparisonOperation(); } + @Override public String getFormula1() { return toFormulaString(cfRuleRecord.getParsedExpression1()); } + @Override public String getFormula2() { byte conditionType = cfRuleRecord.getConditionType(); if (conditionType == CELL_COMPARISON) { @@ -306,6 +318,7 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin return null; } + @Override public String getText() { return null; // not available here, unless it exists and is unimplemented in cfRuleRecord } @@ -325,6 +338,7 @@ public final class HSSFConditionalFormattingRule implements ConditionalFormattin * Conditional format rules don't define stripes, so always 0 * @see org.apache.poi.ss.usermodel.DifferentialStyleProvider#getStripeSize() */ + @Override public int getStripeSize() { return 0; } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingThreshold.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingThreshold.java index 4ab124c05c..987d9f47f3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingThreshold.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFConditionalFormattingThreshold.java @@ -31,32 +31,40 @@ public final class HSSFConditionalFormattingThreshold implements org.apache.poi. private final HSSFSheet sheet; private final HSSFWorkbook workbook; - protected HSSFConditionalFormattingThreshold(Threshold threshold, HSSFSheet sheet) { + HSSFConditionalFormattingThreshold(Threshold threshold, HSSFSheet sheet) { this.threshold = threshold; this.sheet = sheet; this.workbook = sheet.getWorkbook(); } - protected Threshold getThreshold() { + + Threshold getThreshold() { return threshold; } + @Override public RangeType getRangeType() { return RangeType.byId(threshold.getType()); } + @Override public void setRangeType(RangeType type) { threshold.setType((byte)type.id); } + @Override public String getFormula() { return toFormulaString(threshold.getParsedExpression(), workbook); } + @Override public void setFormula(String formula) { threshold.setParsedExpression(parseFormula(formula, sheet)); } + @Override public Double getValue() { return threshold.getValue(); } + + @Override public void setValue(Double value) { threshold.setValue(value); } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFIconMultiStateFormatting.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFIconMultiStateFormatting.java index cabfad2f80..110612e8bb 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFIconMultiStateFormatting.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFIconMultiStateFormatting.java @@ -24,41 +24,46 @@ import org.apache.poi.hssf.record.cf.Threshold; import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold; /** - * High level representation for Icon / Multi-State Formatting + * High level representation for Icon / Multi-State Formatting * component of Conditional Formatting settings */ public final class HSSFIconMultiStateFormatting implements org.apache.poi.ss.usermodel.IconMultiStateFormatting { private final HSSFSheet sheet; - private final CFRule12Record cfRule12Record; private final IconMultiStateFormatting iconFormatting; - protected HSSFIconMultiStateFormatting(CFRule12Record cfRule12Record, HSSFSheet sheet) { + HSSFIconMultiStateFormatting(CFRule12Record cfRule12Record, HSSFSheet sheet) { this.sheet = sheet; - this.cfRule12Record = cfRule12Record; - this.iconFormatting = this.cfRule12Record.getMultiStateFormatting(); + this.iconFormatting = cfRule12Record.getMultiStateFormatting(); } + @Override public IconSet getIconSet() { return iconFormatting.getIconSet(); } + @Override public void setIconSet(IconSet set) { iconFormatting.setIconSet(set); } + @Override public boolean isIconOnly() { return iconFormatting.isIconOnly(); } + @Override public void setIconOnly(boolean only) { iconFormatting.setIconOnly(only); } + @Override public boolean isReversed() { return iconFormatting.isReversed(); } + @Override public void setReversed(boolean reversed) { iconFormatting.setReversed(reversed); } + @Override public HSSFConditionalFormattingThreshold[] getThresholds() { Threshold[] t = iconFormatting.getThresholds(); HSSFConditionalFormattingThreshold[] ht = new HSSFConditionalFormattingThreshold[t.length]; @@ -68,6 +73,7 @@ public final class HSSFIconMultiStateFormatting implements org.apache.poi.ss.use return ht; } + @Override public void setThresholds(ConditionalFormattingThreshold[] thresholds) { Threshold[] t = new Threshold[thresholds.length]; for (int i=0; i<t.length; i++) { @@ -76,6 +82,7 @@ public final class HSSFIconMultiStateFormatting implements org.apache.poi.ss.use iconFormatting.setThresholds(t); } + @Override public HSSFConditionalFormattingThreshold createThreshold() { return new HSSFConditionalFormattingThreshold(new IconMultiStateThreshold(), sheet); } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java index b43a45de6a..b9fdbb9727 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbookFactory.java @@ -48,6 +48,7 @@ public class HSSFWorkbookFactory implements WorkbookProvider { * * @return The created workbook */ + @Override public HSSFWorkbook create() { return new HSSFWorkbook(); } @@ -66,6 +67,7 @@ public class HSSFWorkbookFactory implements WorkbookProvider { * Note that in order to properly release resources the * Workbook should be closed after use. */ + @Override public HSSFWorkbook create(final DirectoryNode root, String password) throws IOException { boolean passwordSet = false; if (password != null) { @@ -93,6 +95,7 @@ public class HSSFWorkbookFactory implements WorkbookProvider { } @Override + @SuppressWarnings("java:S2095") public Workbook create(File file, String password, boolean readOnly) throws IOException { boolean passwordSet = false; if (password != null) { @@ -104,11 +107,8 @@ public class HSSFWorkbookFactory implements WorkbookProvider { try { return new HSSFWorkbook(fs, true); } catch (RuntimeException e) { - // we need to close the filesystem - // if we encounter an exception to - // not leak file handles + // we need to close the filesystem if we encounter an exception to not leak file handles fs.close(); - throw e; } } finally { diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java index 36b44efbcc..4f229e9a18 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java @@ -28,7 +28,7 @@ import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; -import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.commons.io.input.BoundedInputStream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.poifs.crypt.ChunkedCipherInputStream; import org.apache.poi.poifs.crypt.CryptoFunctions; @@ -39,11 +39,9 @@ import org.apache.poi.poifs.crypt.EncryptionVerifier; import org.apache.poi.poifs.crypt.HashAlgorithm; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.DocumentNode; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; -import org.apache.commons.io.input.BoundedInputStream; import org.apache.poi.util.IOUtils; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.LittleEndianInputStream; @@ -170,14 +168,10 @@ public class CryptoAPIDecryptor extends Decryptor { */ public POIFSFileSystem getSummaryEntries(DirectoryNode root, String encryptedStream) throws IOException, GeneralSecurityException { - DocumentNode es = (DocumentNode) root.getEntry(encryptedStream); - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - try (DocumentInputStream dis = root.createDocumentInputStream(es)) { - IOUtils.copy(dis, bos); - } POIFSFileSystem fsOut = null; try ( - CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray()); + DocumentInputStream dis = root.createDocumentInputStream(root.getEntry(encryptedStream)); + CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, IOUtils.toByteArray(dis)); LittleEndianInputStream leis = new LittleEndianInputStream(sbis) ) { int streamDescriptorArrayOffset = (int) leis.readUInt(); diff --git a/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java b/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java index 71d6a4b405..789bfbb702 100644 --- a/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java +++ b/poi/src/main/java/org/apache/poi/poifs/macros/VBAMacroReader.java @@ -68,6 +68,7 @@ import org.apache.poi.util.StringUtil; * * @since 3.15-beta2 */ +@SuppressWarnings("unused") public class VBAMacroReader implements Closeable { private static final Logger LOGGER = LogManager.getLogger(VBAMacroReader.class); @@ -667,35 +668,36 @@ public class VBAMacroReader implements Closeable { private static String readUnicode(InputStream is) throws IOException { //reads null-terminated unicode string - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - int b0 = IOUtils.readByte(is); - int b1 = IOUtils.readByte(is); - - int read = 2; - while ((b0 + b1) != 0 && read < MAX_STRING_LENGTH) { - - bos.write(b0); - bos.write(b1); - b0 = IOUtils.readByte(is); - b1 = IOUtils.readByte(is); - read += 2; - } - if (read >= MAX_STRING_LENGTH) { - LOGGER.atWarn().log("stopped reading unicode name after {} bytes", box(read)); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + int b0 = IOUtils.readByte(is); + int b1 = IOUtils.readByte(is); + + int read = 2; + while ((b0 + b1) != 0 && read < MAX_STRING_LENGTH) { + bos.write(b0); + bos.write(b1); + b0 = IOUtils.readByte(is); + b1 = IOUtils.readByte(is); + read += 2; + } + if (read >= MAX_STRING_LENGTH) { + LOGGER.atWarn().log("stopped reading unicode name after {} bytes", box(read)); + } + return bos.toString(StandardCharsets.UTF_16LE); } - return bos.toString(StandardCharsets.UTF_16LE); } private static String readMBCS(int firstByte, InputStream is, Charset charset) throws IOException { - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - int len = 0; - int b = firstByte; - while (b > 0 && len < MAX_STRING_LENGTH) { - ++len; - bos.write(b); - b = IOUtils.readByte(is); - } - return bos.toString(charset); + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { + int len = 0; + int b = firstByte; + while (b > 0 && len < MAX_STRING_LENGTH) { + ++len; + bos.write(b); + b = IOUtils.readByte(is); + } + return bos.toString(charset); + } } /** @@ -792,9 +794,7 @@ public class VBAMacroReader implements Closeable { */ private static byte[] findCompressedStreamWBruteForce(InputStream is) throws IOException { //buffer to memory for multiple tries - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - IOUtils.copy(is, bos); - byte[] compressed = bos.toByteArray(); + byte[] compressed = IOUtils.toByteArray(is); byte[] decompressed = null; for (int i = 0; i < compressed.length; i++) { if (compressed[i] == 0x01 && i < compressed.length-1) { @@ -821,12 +821,10 @@ public class VBAMacroReader implements Closeable { } private static byte[] tryToDecompress(InputStream is) { - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - try { - IOUtils.copy(new RLEDecompressingInputStream(is), bos); + try (RLEDecompressingInputStream ris = new RLEDecompressingInputStream(is)) { + return IOUtils.toByteArray(ris); } catch (IllegalArgumentException | IOException | IllegalStateException e){ return null; } - return bos.toByteArray(); } } diff --git a/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java b/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java index 18eef73108..47793a14c1 100644 --- a/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java +++ b/poi/src/main/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java @@ -162,14 +162,13 @@ public class EmbeddedExtractor implements Iterable<EmbeddedExtractor> { protected EmbeddedData extract(DirectoryNode dn) throws IOException { assert(canExtract(dn)); - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(20000); - try (POIFSFileSystem dest = new POIFSFileSystem()) { + try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(20000); + POIFSFileSystem dest = new POIFSFileSystem()) { copyNodes(dn, dest.getRoot()); // start with a reasonable big size dest.writeFilesystem(bos); + return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES); } - - return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES); } protected EmbeddedData extract(Picture source) throws IOException { diff --git a/poi/src/main/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java b/poi/src/main/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java index c70e3d1d24..69cc1887c5 100644 --- a/poi/src/main/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java +++ b/poi/src/main/java/org/apache/poi/ss/usermodel/ConditionalFormattingThreshold.java @@ -27,7 +27,7 @@ package org.apache.poi.ss.usermodel; * icon and which Yellow or Red.</p> */ public interface ConditionalFormattingThreshold { - public enum RangeType { + enum RangeType { /** Number / Parameter */ NUMBER(1, "num"), /** The minimum value from the range */ @@ -41,16 +41,16 @@ public interface ConditionalFormattingThreshold { UNALLOCATED(6, null), /** Formula result */ FORMULA(7, "formula"); - + /** Numeric ID of the type */ public final int id; /** Name (system) of the type */ public final String name; - + public String toString() { return id + " - " + name; } - + public static RangeType byId(int id) { return values()[id-1]; // 1-based IDs } @@ -60,51 +60,51 @@ public interface ConditionalFormattingThreshold { } return null; } - - private RangeType(int id, String name) { + + RangeType(int id, String name) { this.id = id; this.name = name; } } - + /** * Get the Range Type used */ RangeType getRangeType(); - + /** * Changes the Range Type used - * + * * <p>If you change the range type, you need to * ensure that the Formula and Value parameters * are compatible with it before saving</p> */ void setRangeType(RangeType type); - + /** * Formula to use to calculate the threshold, - * or <code>null</code> if no formula + * or {@code null} if no formula */ String getFormula(); /** * Sets the formula used to calculate the threshold, - * or unsets it if <code>null</code> is given. + * or unsets it if {@code null} is given. */ void setFormula(String formula); - + /** - * Gets the value used for the threshold, or - * <code>null</code> if there isn't one. + * Gets the value used for the threshold, or + * {@code null} if there isn't one. */ Double getValue(); - + /** - * Sets the value used for the threshold. - * <p>If the type is {@link RangeType#PERCENT} or + * Sets the value used for the threshold. + * <p>If the type is {@link RangeType#PERCENT} or * {@link RangeType#PERCENTILE} it must be between 0 and 100. * <p>If the type is {@link RangeType#MIN} or {@link RangeType#MAX} * or {@link RangeType#FORMULA} it shouldn't be set. - * <p>Use <code>null</code> to unset + * <p>Use {@code null} to unset */ void setValue(Double value); } diff --git a/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java b/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java index 281b8180b0..f282907c94 100644 --- a/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java +++ b/poi/src/main/java/org/apache/poi/util/GenericRecordJsonWriter.java @@ -265,6 +265,7 @@ public class GenericRecordJsonWriter implements Closeable { return true; } + @SuppressWarnings("java:S3516") protected boolean printNumber(String name, Object o) { Number n = (Number)o; printName(name); diff --git a/poi/src/main/java/org/apache/poi/util/IOUtils.java b/poi/src/main/java/org/apache/poi/util/IOUtils.java index 279b56974c..09bb25a9cb 100644 --- a/poi/src/main/java/org/apache/poi/util/IOUtils.java +++ b/poi/src/main/java/org/apache/poi/util/IOUtils.java @@ -178,29 +178,29 @@ public final class IOUtils { } final int len = Math.min(length, maxLength); - UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len); + try (UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(len == Integer.MAX_VALUE ? 4096 : len)) { + byte[] buffer = new byte[4096]; + int totalBytes = 0, readBytes; + do { + readBytes = stream.read(buffer, 0, Math.min(buffer.length, len - totalBytes)); + totalBytes += Math.max(readBytes, 0); + if (readBytes > 0) { + baos.write(buffer, 0, readBytes); + } - byte[] buffer = new byte[4096]; - int totalBytes = 0, readBytes; - do { - readBytes = stream.read(buffer, 0, Math.min(buffer.length, len-totalBytes)); - totalBytes += Math.max(readBytes,0); - if (readBytes > 0) { - baos.write(buffer, 0, readBytes); - } + checkByteSizeLimit(totalBytes); + } while (totalBytes < len && readBytes > -1); - checkByteSizeLimit(totalBytes); - } while (totalBytes < len && readBytes > -1); + if (maxLength != Integer.MAX_VALUE && totalBytes == maxLength) { + throw new IOException("MaxLength (" + maxLength + ") reached - stream seems to be invalid."); + } - if (maxLength != Integer.MAX_VALUE && totalBytes == maxLength) { - throw new IOException("MaxLength ("+maxLength+") reached - stream seems to be invalid."); - } + if (len != Integer.MAX_VALUE && totalBytes < len) { + throw new EOFException("unexpected EOF - expected len: " + len + " - actual len: " + totalBytes); + } - if (len != Integer.MAX_VALUE && totalBytes < len) { - throw new EOFException("unexpected EOF - expected len: "+len+" - actual len: "+totalBytes); + return baos.toByteArray(); } - - return baos.toByteArray(); } private static void checkLength(long length, int maxLength) { |