aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAndreas Beeker <kiwiwings@apache.org>2020-10-24 21:25:52 +0000
committerAndreas Beeker <kiwiwings@apache.org>2020-10-24 21:25:52 +0000
commit90bfac52d607c6a8499bfefe17d12d74253e5b7a (patch)
tree5fa940937c99a62fd667f8629d384496079b67da
parentebdd3c37d42166c1318f819b37af23eb1ebb6a2e (diff)
downloadpoi-90bfac52d607c6a8499bfefe17d12d74253e5b7a.tar.gz
poi-90bfac52d607c6a8499bfefe17d12d74253e5b7a.zip
Sonar fixes - a few "Try-with-resources should be used"
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1882820 13f79535-47bb-0310-9956-ffa450edef68
-rw-r--r--src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java31
-rw-r--r--src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java16
-rw-r--r--src/java/org/apache/poi/poifs/macros/VBAMacroReader.java52
-rw-r--r--src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java17
-rw-r--r--src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java80
-rw-r--r--src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java13
6 files changed, 86 insertions, 123 deletions
diff --git a/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java b/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java
index 361d8a8c1c..a586c73211 100644
--- a/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java
+++ b/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java
@@ -44,7 +44,7 @@ final class StaticFontMetrics {
private static final Map<String, FontDetails> fontDetailsMap = new HashMap<>();
private StaticFontMetrics() {}
-
+
/**
* Retrieves the fake font details for a given font.
*
@@ -84,7 +84,7 @@ final class StaticFontMetrics {
// If not, check with the font style added
String fontHeight = FontDetails.buildFontHeightProperty(fontName);
String styleHeight = FontDetails.buildFontHeightProperty(fontName + "." + fontStyle);
-
+
if (fontMetricsProps.get(fontHeight) == null
&& fontMetricsProps.get(styleHeight) != null) {
// Need to add on the style to the font name
@@ -99,7 +99,7 @@ final class StaticFontMetrics {
}
return fontDetails;
}
-
+
private static Properties loadMetrics() throws IOException {
// Check to see if the font metric file was specified
// as a system property
@@ -117,26 +117,19 @@ final class StaticFontMetrics {
LOGGER.log(POILogger.WARN, "Can't access font.metrics.filename system property", e);
}
- InputStream metricsIn = null;
- try {
- if (propFile != null) {
- metricsIn = new FileInputStream(propFile);
- } else {
- // Use the built-in font metrics file off the classpath
- metricsIn = FontDetails.class.getResourceAsStream("/font_metrics.properties");
- if (metricsIn == null) {
- String err = "font_metrics.properties not found in classpath";
- throw new IOException(err);
- }
- }
+ try (InputStream metricsIn = (propFile != null)
+ ? new FileInputStream(propFile)
+ : FontDetails.class.getResourceAsStream("/font_metrics.properties")
+ ) {
+ // Use the built-in font metrics file off the classpath
+ if (metricsIn == null) {
+ String err = "font_metrics.properties not found in classpath";
+ throw new IOException(err);
+ }
Properties props = new Properties();
props.load(metricsIn);
return props;
- } finally {
- if (metricsIn != null) {
- metricsIn.close();
- }
}
}
}
diff --git a/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java b/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
index affadffdc2..df2a51bc38 100644
--- a/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
+++ b/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
@@ -175,10 +175,11 @@ public class CryptoAPIDecryptor extends Decryptor {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copy(dis, bos);
dis.close();
- CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray());
- LittleEndianInputStream leis = new LittleEndianInputStream(sbis);
POIFSFileSystem fsOut = null;
- try {
+ try (
+ CryptoAPIDocumentInputStream sbis = new CryptoAPIDocumentInputStream(this, bos.toByteArray());
+ LittleEndianInputStream leis = new LittleEndianInputStream(sbis)
+ ) {
int streamDescriptorArrayOffset = (int) leis.readUInt();
/* int streamDescriptorArraySize = (int) */ leis.readUInt();
long skipN = streamDescriptorArrayOffset - 8L;
@@ -207,9 +208,9 @@ public class CryptoAPIDecryptor extends Decryptor {
for (StreamDescriptorEntry entry : entries) {
sbis.seek(entry.streamOffset);
sbis.setBlock(entry.block);
- InputStream is = new BoundedInputStream(sbis, entry.streamSize);
- fsOut.createDocument(is, entry.streamName);
- is.close();
+ try (InputStream is = new BoundedInputStream(sbis, entry.streamSize)) {
+ fsOut.createDocument(is, entry.streamName);
+ }
}
} catch (Exception e) {
IOUtils.closeQuietly(fsOut);
@@ -220,9 +221,6 @@ public class CryptoAPIDecryptor extends Decryptor {
} else {
throw new IOException("summary entries can't be read", e);
}
- } finally {
- IOUtils.closeQuietly(leis);
- IOUtils.closeQuietly(sbis);
}
return fsOut;
}
diff --git a/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java b/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java
index 783ab9fdfa..624a5fd360 100644
--- a/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java
+++ b/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java
@@ -42,8 +42,8 @@ import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.DocumentNode;
import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.FileMagic;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.macros.Module.ModuleType;
import org.apache.poi.util.CodePageUtil;
import org.apache.poi.util.HexDump;
@@ -64,7 +64,7 @@ import org.apache.poi.util.StringUtil;
* module for an example of how to do this. Patches that make macro
* extraction from .ppt more elegant are welcomed!
* </p>
- *
+ *
* @since 3.15-beta2
*/
public class VBAMacroReader implements Closeable {
@@ -76,7 +76,7 @@ public class VBAMacroReader implements Closeable {
protected static final String VBA_PROJECT_POIFS = "VBA";
private POIFSFileSystem fs;
-
+
public VBAMacroReader(InputStream rstream) throws IOException {
InputStream is = FileMagic.prepareToCheckMagic(rstream);
FileMagic fm = FileMagic.valueOf(is);
@@ -86,7 +86,7 @@ public class VBAMacroReader implements Closeable {
openOOXML(is);
}
}
-
+
public VBAMacroReader(File file) throws IOException {
try {
this.fs = new POIFSFileSystem(file);
@@ -97,7 +97,7 @@ public class VBAMacroReader implements Closeable {
public VBAMacroReader(POIFSFileSystem fs) {
this.fs = fs;
}
-
+
private void openOOXML(InputStream zipFile) throws IOException {
try(ZipInputStream zis = new ZipInputStream(zipFile)) {
ZipEntry zipEntry;
@@ -119,7 +119,7 @@ public class VBAMacroReader implements Closeable {
}
throw new IllegalArgumentException("No VBA project found");
}
-
+
public void close() throws IOException {
fs.close();
fs = null;
@@ -145,7 +145,7 @@ public class VBAMacroReader implements Closeable {
}
/**
- * Reads all macros from all modules of the opened office file.
+ * Reads all macros from all modules of the opened office file.
* @return All the macros and their contents
*
* @since 3.15-beta2
@@ -158,7 +158,7 @@ public class VBAMacroReader implements Closeable {
}
return moduleSources;
}
-
+
protected static class ModuleImpl implements Module {
Integer offset;
byte[] buf;
@@ -180,7 +180,7 @@ public class VBAMacroReader implements Closeable {
protected static class ModuleMap extends HashMap<String, ModuleImpl> {
Charset charset = StringUtil.WIN_1252; // default charset
}
-
+
/**
* Recursively traverses directory structure rooted at <tt>dir</tt>.
* For each macro module that is found, the module's name and code are
@@ -204,13 +204,13 @@ public class VBAMacroReader implements Closeable {
}
}
}
-
-
+
+
/**
* reads module from DIR node in input stream and adds it to the modules map for decompression later
* on the second pass through this function, the module will be decompressed
- *
+ *
* Side-effects: adds a new module to the module map or sets the buf field on the module
* to the decompressed stream contents (the VBA code for one module)
*
@@ -237,7 +237,7 @@ public class VBAMacroReader implements Closeable {
stream.close();
}
}
-
+
private static void readModuleFromDocumentStream(DocumentNode documentNode, String name, ModuleMap modules) throws IOException {
ModuleImpl module = modules.get(name);
// TODO Refactor this to fetch dir then do the rest
@@ -256,34 +256,28 @@ public class VBAMacroReader implements Closeable {
}
//try the general case, where module.offset is accurate
- InputStream decompressed = null;
- InputStream compressed = new DocumentInputStream(documentNode);
- try {
+ try (InputStream compressed = new DocumentInputStream(documentNode)) {
// we know the offset already, so decompress immediately on-the-fly
trySkip(compressed, module.offset);
- decompressed = new RLEDecompressingInputStream(compressed);
- module.read(decompressed);
+ try (InputStream decompressed = new RLEDecompressingInputStream(compressed)) {
+ module.read(decompressed);
+ }
return;
} catch (IllegalArgumentException | IllegalStateException e) {
- } finally {
- IOUtils.closeQuietly(compressed);
- IOUtils.closeQuietly(decompressed);
}
//bad module.offset, try brute force
- compressed = new DocumentInputStream(documentNode);
+ ;
byte[] decompressedBytes;
- try {
+ try (InputStream compressed = new DocumentInputStream(documentNode)) {
decompressedBytes = findCompressedStreamWBruteForce(compressed);
- } finally {
- IOUtils.closeQuietly(compressed);
}
if (decompressedBytes != null) {
module.read(new ByteArrayInputStream(decompressedBytes));
}
}
-
+
}
/**
@@ -305,7 +299,7 @@ public class VBAMacroReader implements Closeable {
}
}
}
-
+
// Constants from MS-OVBA: https://msdn.microsoft.com/en-us/library/office/cc313094(v=office.12).aspx
private static final int STREAMNAME_RESERVED = 0x0032;
private static final int PROJECT_CONSTANTS_RESERVED = 0x003C;
@@ -319,7 +313,7 @@ public class VBAMacroReader implements Closeable {
* <tt>macroDir</tt> into <tt>modules</tt>.
*
* @since 3.15-beta2
- */
+ */
protected void readMacros(DirectoryNode macroDir, ModuleMap modules) throws IOException {
//bug59858 shows that dirstream may not be in this directory (\MBD00082648\_VBA_PROJECT_CUR\VBA ENTRY NAME)
//but may be in another directory (\_VBA_PROJECT_CUR\VBA ENTRY NAME)
@@ -333,7 +327,7 @@ public class VBAMacroReader implements Closeable {
for (Entry entry : macroDir) {
if (! (entry instanceof DocumentNode)) { continue; }
-
+
String name = entry.getName();
DocumentNode document = (DocumentNode)entry;
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
index 5e1ee2fbe4..3c70649b97 100644
--- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
+++ b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
@@ -50,7 +50,6 @@ import javax.xml.crypto.MarshalException;
import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
import org.apache.poi.poifs.crypt.dsig.SignatureInfo;
import org.apache.poi.poifs.crypt.dsig.services.RevocationData;
-import org.apache.poi.util.IOUtils;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.xml.security.c14n.Canonicalizer;
@@ -315,18 +314,12 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
return null;
}
- try {
- ASN1InputStream asn1IS1 = null, asn1IS2 = null;
- try {
- asn1IS1 = new ASN1InputStream(crlNumberExtensionValue);
- ASN1OctetString octetString = (ASN1OctetString)asn1IS1.readObject();
- byte[] octets = octetString.getOctets();
- asn1IS2 = new ASN1InputStream(octets);
- ASN1Integer integer = (ASN1Integer)asn1IS2.readObject();
+ try (ASN1InputStream asn1IS1 = new ASN1InputStream(crlNumberExtensionValue)) {
+ ASN1OctetString octetString = (ASN1OctetString)asn1IS1.readObject();
+ byte[] octets = octetString.getOctets();
+ try (ASN1InputStream asn1IS2 = new ASN1InputStream(octets)) {
+ ASN1Integer integer = (ASN1Integer) asn1IS2.readObject();
return integer.getPositiveValue();
- } finally {
- IOUtils.closeQuietly(asn1IS2);
- IOUtils.closeQuietly(asn1IS1);
}
} catch (IOException e) {
throw new RuntimeException("I/O error: " + e.getMessage(), e);
diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java
index 5ebda3841d..9c5087350e 100644
--- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java
+++ b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java
@@ -72,55 +72,45 @@ public final class ChunkFactory {
* of all the different possible chunk commands.
*/
private void processChunkParseCommands() throws IOException {
- String line;
- InputStream cpd = null;
- BufferedReader inp = null;
- try {
- cpd = ChunkFactory.class.getResourceAsStream(chunkTableName);
+ try (InputStream cpd = ChunkFactory.class.getResourceAsStream(chunkTableName)) {
if(cpd == null) {
throw new IllegalStateException("Unable to find HDGF chunk definition on the classpath - " + chunkTableName);
}
- inp = new BufferedReader(new InputStreamReader(cpd, LocaleUtil.CHARSET_1252));
-
- while( (line = inp.readLine()) != null ) {
- if (line.isEmpty() || "# \t".contains(line.substring(0,1))) {
- continue;
- }
-
- // Start xxx
- if(!line.matches("^start [0-9]+$")) {
- throw new IllegalStateException("Expecting start xxx, found " + line);
- }
- int chunkType = Integer.parseInt(line.substring(6));
- ArrayList<CommandDefinition> defsL = new ArrayList<>();
-
- // Data entries
- while( (line = inp.readLine()) != null ) {
- if (line.startsWith("end")) {
- break;
- }
- StringTokenizer st = new StringTokenizer(line, " ");
- int defType = Integer.parseInt(st.nextToken());
- int offset = Integer.parseInt(st.nextToken());
- String name = st.nextToken("\uffff").substring(1);
-
- CommandDefinition def = new CommandDefinition(defType,offset,name);
- defsL.add(def);
- }
-
- CommandDefinition[] defs = defsL.toArray(new CommandDefinition[0]);
-
- // Add to the map
- chunkCommandDefinitions.put(chunkType, defs);
- }
- } finally {
- if (inp != null) {
- inp.close();
- }
- if (cpd != null) {
- cpd.close();
- }
+ try (BufferedReader inp = new BufferedReader(new InputStreamReader(cpd, LocaleUtil.CHARSET_1252))) {
+ String line;
+ while ((line = inp.readLine()) != null) {
+ if (line.isEmpty() || "# \t".contains(line.substring(0, 1))) {
+ continue;
+ }
+
+ // Start xxx
+ if (!line.matches("^start [0-9]+$")) {
+ throw new IllegalStateException("Expecting start xxx, found " + line);
+ }
+ int chunkType = Integer.parseInt(line.substring(6));
+ ArrayList<CommandDefinition> defsL = new ArrayList<>();
+
+ // Data entries
+ while ((line = inp.readLine()) != null) {
+ if (line.startsWith("end")) {
+ break;
+ }
+ StringTokenizer st = new StringTokenizer(line, " ");
+ int defType = Integer.parseInt(st.nextToken());
+ int offset = Integer.parseInt(st.nextToken());
+ String name = st.nextToken("\uffff").substring(1);
+
+ CommandDefinition def = new CommandDefinition(defType, offset, name);
+ defsL.add(def);
+ }
+
+ CommandDefinition[] defs = defsL.toArray(new CommandDefinition[0]);
+
+ // Add to the map
+ chunkCommandDefinitions.put(chunkType, defs);
+ }
+ }
}
}
diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
index d616180245..b6453cab80 100644
--- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
+++ b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
@@ -173,16 +173,11 @@ public final class HSLFSlideShowImpl extends POIDocument implements Closeable {
* Constructs a new, empty, Powerpoint document.
*/
public static HSLFSlideShowImpl create() {
- InputStream is = HSLFSlideShowImpl.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt");
- if (is == null) {
- throw new HSLFException("Missing resource 'empty.ppt'");
- }
- try {
- try {
- return new HSLFSlideShowImpl(is);
- } finally {
- is.close();
+ try (InputStream is = HSLFSlideShowImpl.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt")) {
+ if (is == null) {
+ throw new HSLFException("Missing resource 'empty.ppt'");
}
+ return new HSLFSlideShowImpl(is);
} catch (IOException e) {
throw new HSLFException(e);
}