You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@poi.apache.org by ki...@apache.org on 2020/10/24 21:25:52 UTC

svn commit: r1882820 - in /poi/trunk/src: java/org/apache/poi/hssf/usermodel/ java/org/apache/poi/poifs/crypt/cryptoapi/ java/org/apache/poi/poifs/macros/ ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/ scratchpad/src/org/apache/poi/hdgf/chunks/ scr...

Author: kiwiwings
Date: Sat Oct 24 21:25:52 2020
New Revision: 1882820

URL: http://svn.apache.org/viewvc?rev=1882820&view=rev
Log:
Sonar fixes - a few "Try-with-resources should be used"

Modified:
    poi/trunk/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java
    poi/trunk/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
    poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java
    poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
    poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java
    poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java

Modified: poi/trunk/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java?rev=1882820&r1=1882819&r2=1882820&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java (original)
+++ poi/trunk/src/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java Sat Oct 24 21:25:52 2020
@@ -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();
-            }
         }
 	}
 }

Modified: poi/trunk/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java?rev=1882820&r1=1882819&r2=1882820&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java (original)
+++ poi/trunk/src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java Sat Oct 24 21:25:52 2020
@@ -175,10 +175,11 @@ public class CryptoAPIDecryptor extends
         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
             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
             } else {
                 throw new IOException("summary entries can't be read", e);
             }
-        } finally {
-            IOUtils.closeQuietly(leis);
-            IOUtils.closeQuietly(sbis);
         }
         return fsOut;
     }

Modified: poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java?rev=1882820&r1=1882819&r2=1882820&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java (original)
+++ poi/trunk/src/java/org/apache/poi/poifs/macros/VBAMacroReader.java Sat Oct 24 21:25:52 2020
@@ -42,8 +42,8 @@ import org.apache.poi.poifs.filesystem.D
 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 C
     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 C
             openOOXML(is);
         }
     }
-    
+
     public VBAMacroReader(File file) throws IOException {
         try {
             this.fs = new POIFSFileSystem(file);
@@ -97,7 +97,7 @@ public class VBAMacroReader implements C
     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 C
         }
         throw new IllegalArgumentException("No VBA project found");
     }
-    
+
     public void close() throws IOException {
         fs.close();
         fs = null;
@@ -145,7 +145,7 @@ public class VBAMacroReader implements C
     }
 
     /**
-     * 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 C
         }
         return moduleSources;
     }
-    
+
     protected static class ModuleImpl implements Module {
         Integer offset;
         byte[] buf;
@@ -180,7 +180,7 @@ public class VBAMacroReader implements C
     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 C
             }
         }
     }
-    
 
-    
+
+
     /**
      * 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 C
             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 C
             }
 
             //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 C
             }
         }
     }
-    
+
     // 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 C
      * <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 C
 
         for (Entry entry : macroDir) {
             if (! (entry instanceof DocumentNode)) { continue; }
-            
+
             String name = entry.getName();
             DocumentNode document = (DocumentNode)entry;
 

Modified: poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java?rev=1882820&r1=1882819&r2=1882820&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java Sat Oct 24 21:25:52 2020
@@ -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 imple
             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);

Modified: poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java?rev=1882820&r1=1882819&r2=1882820&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java (original)
+++ poi/trunk/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkFactory.java Sat Oct 24 21:25:52 2020
@@ -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);
+				}
+			}
 		}
 	}
 

Modified: poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java?rev=1882820&r1=1882819&r2=1882820&view=diff
==============================================================================
--- poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java (original)
+++ poi/trunk/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java Sat Oct 24 21:25:52 2020
@@ -173,16 +173,11 @@ public final class HSLFSlideShowImpl ext
      * 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);
         }



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org