]> source.dussan.org Git - poi.git/commitdiff
SonarQube fixes
authorAndreas Beeker <kiwiwings@apache.org>
Fri, 6 Jan 2017 17:51:22 +0000 (17:51 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Fri, 6 Jan 2017 17:51:22 +0000 (17:51 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1777669 13f79535-47bb-0310-9956-ffa450edef68

15 files changed:
src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java
src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIDecryptor.java
src/java/org/apache/poi/poifs/crypt/cryptoapi/CryptoAPIEncryptor.java
src/java/org/apache/poi/poifs/eventfilesystem/POIFSReader.java
src/java/org/apache/poi/sl/draw/DrawSimpleShape.java
src/java/org/apache/poi/sl/usermodel/SlideShowFactory.java
src/java/org/apache/poi/ss/formula/FormulaUsedBlankCellSet.java
src/java/org/apache/poi/ss/formula/PlainCellCache.java
src/java/org/apache/poi/ss/formula/atp/YearFracCalculator.java
src/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationSheet.java
src/java/org/apache/poi/ss/formula/functions/Countif.java
src/java/org/apache/poi/ss/formula/ptg/Ptg.java
src/java/org/apache/poi/ss/util/CellReference.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
src/ooxml/java/org/apache/poi/ss/usermodel/WorkbookFactory.java

index bf4018f3d64c9ce16a208a0965e326f77fd42f68..b9e1f2d37bbf5b2b9d87c77c3cae3acbc5e2266b 100644 (file)
 \r
 package org.apache.poi.ss.examples.formula;\r
 \r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.util.HashMap;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+\r
 import org.apache.poi.ss.formula.OperationEvaluationContext;\r
 import org.apache.poi.ss.formula.eval.ErrorEval;\r
 import org.apache.poi.ss.formula.eval.ValueEval;\r
@@ -29,19 +35,11 @@ import org.apache.poi.ss.usermodel.Sheet;
 import org.apache.poi.ss.usermodel.Workbook;\r
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;\r
 \r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-import java.util.HashMap;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-\r
 /**\r
  * Demonstrates how to use functions provided by third-party add-ins, e.g. Bloomberg Excel Add-in.\r
  *\r
  * There can be situations when you are not interested in formula evaluation,\r
  * you just need to set the formula  and the workbook will be evaluation by the client.\r
- *\r
- * @author Yegor Kozlov\r
  */\r
 public class SettingExternalFunction {\r
 \r
@@ -90,7 +88,8 @@ public class SettingExternalFunction {
         FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");\r
         wb.write(out);\r
         out.close();\r
-\r
+        \r
+        wb.close();\r
     }\r
 \r
 }\r
index af9d62b85b39effcbd60dfed677ecbb61a9cb0b4..669931f9e9df75d1ef9aa52c5fc5757c32b332ac 100644 (file)
@@ -194,7 +194,7 @@ public class CryptoAPIDecryptor extends Decryptor implements Cloneable {
                 assert(entry.streamName.length() == nameSize);\r
             }\r
 \r
-            fsOut = new POIFSFileSystem();\r
+            fsOut = new POIFSFileSystem(); // NOSONAR\r
             for (StreamDescriptorEntry entry : entries) {\r
                 sbis.seek(entry.streamOffset);\r
                 sbis.setBlock(entry.block);\r
index d04096c3970d7fc394f861c9c1795937cd26c9b0..5740380d0fbc1e12ee1596e8df145a5bf4fdb9af 100644 (file)
@@ -126,7 +126,7 @@ public class CryptoAPIEncryptor extends Encryptor implements Cloneable {
      */\r
     public OutputStream getSummaryEntries(DirectoryNode dir)\r
     throws IOException, GeneralSecurityException {\r
-        CryptoAPIDocumentOutputStream bos = new CryptoAPIDocumentOutputStream(this);\r
+        CryptoAPIDocumentOutputStream bos = new CryptoAPIDocumentOutputStream(this); // NOSONAR\r
         byte buf[] = new byte[8];\r
         \r
         bos.write(buf, 0, 8); // skip header\r
index 80151146ad94882c91a7e078374c79df9779d7a4..b82e61a934d16c10398430731f9a425be1993796 100644 (file)
 
 package org.apache.poi.poifs.eventfilesystem;
 
-import java.io.*;
-
-import java.util.*;
+import java.io.FileInputStream;
+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;
@@ -34,6 +35,7 @@ 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;
 
 /**
  * An event-driven reader for POIFS file systems. Users of this class
@@ -42,8 +44,6 @@ import org.apache.poi.poifs.storage.SmallBlockTableReader;
  * documents. Once all the listeners have been registered, the read()
  * method is called, which results in the listeners being notified as
  * their documents are read.
- *
- * @author Marc Johnson (mjohnson at apache dot org)
  */
 
 public class POIFSReader
@@ -190,20 +190,19 @@ public class POIFSReader
     {
         if (args.length == 0)
         {
-            System.err
-                .println("at least one argument required: input filename(s)");
+            System.err.println("at least one argument required: input filename(s)");
             System.exit(1);
         }
 
         // register for all
-        for (int j = 0; j < args.length; j++)
+        for (String arg : args)
         {
             POIFSReader         reader   = new POIFSReader();
             POIFSReaderListener listener = new SampleListener();
 
             reader.registerListener(listener);
-            System.out.println("reading " + args[ j ]);
-            FileInputStream istream = new FileInputStream(args[ j ]);
+            System.out.println("reading " + arg);
+            FileInputStream istream = new FileInputStream(arg);
 
             reader.read(istream);
             istream.close();
@@ -300,31 +299,25 @@ public class POIFSReader
          * @param event
          */
 
-        public void processPOIFSReaderEvent(final POIFSReaderEvent event)
-        {
-            @SuppressWarnings("resource")
+        @Override
+        public void processPOIFSReaderEvent(final POIFSReaderEvent event) {
             DocumentInputStream istream = event.getStream();
             POIFSDocumentPath   path    = event.getPath();
             String              name    = event.getName();
 
-            try
-            {
-                byte[] data = new byte[ istream.available() ];
-
-                istream.read(data);
+            try {
+                byte[] data = IOUtils.toByteArray(istream);
                 int pathLength = path.length();
 
-                for (int k = 0; k < pathLength; k++)
-                {
+                for (int k = 0; k < pathLength; k++) {
                     System.out.print("/" + path.getComponent(k));
                 }
-                System.out.println("/" + name + ": " + data.length
-                                   + " bytes read");
-            }
-            catch (IOException ignored)
-            {
+                System.out.println("/" + name + ": " + data.length + " bytes read");
+            } catch (IOException ignored) {
+            } finally {
+                IOUtils.closeQuietly(istream);
             }
         }
-    }   // end private class SampleListener
-}       // end public class POIFSReader
+    }
+}
 
index cfd6cf991b8c7027b710f32342098f7736a64d76..ef0cc08478b9a2cfff8cdd49e4cfc0713fd30ec5 100644 (file)
@@ -25,7 +25,6 @@ import java.awt.geom.AffineTransform;
 import java.awt.geom.Ellipse2D;\r
 import java.awt.geom.Path2D;\r
 import java.awt.geom.Rectangle2D;\r
-import java.io.IOException;\r
 import java.io.InputStream;\r
 import java.util.ArrayList;\r
 import java.util.Collection;\r
@@ -53,6 +52,7 @@ import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize;
 import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint;\r
 import org.apache.poi.sl.usermodel.Shadow;\r
 import org.apache.poi.sl.usermodel.SimpleShape;\r
+import org.apache.poi.util.IOUtils;\r
 import org.apache.poi.util.Units;\r
 \r
 \r
@@ -110,15 +110,21 @@ public class DrawSimpleShape extends DrawShape {
     }\r
 \r
     protected void drawDecoration(Graphics2D graphics, Paint line, BasicStroke stroke) {\r
-        if(line == null) return;\r
+        if(line == null) {\r
+            return;\r
+        }\r
         graphics.setPaint(line);\r
 \r
         List<Outline> lst = new ArrayList<Outline>();\r
         LineDecoration deco = getShape().getLineDecoration();\r
         Outline head = getHeadDecoration(graphics, deco, stroke);\r
-        if (head != null) lst.add(head);\r
+        if (head != null) {\r
+            lst.add(head);\r
+        }\r
         Outline tail = getTailDecoration(graphics, deco, stroke);\r
-        if (tail != null) lst.add(tail);\r
+        if (tail != null) {\r
+            lst.add(tail);\r
+        }\r
 \r
 \r
         for(Outline o : lst){\r
@@ -126,8 +132,12 @@ public class DrawSimpleShape extends DrawShape {
             Path p = o.getPath();\r
             graphics.setRenderingHint(Drawable.GRADIENT_SHAPE, s);\r
 \r
-            if(p.isFilled()) graphics.fill(s);\r
-            if(p.isStroked()) graphics.draw(s);\r
+            if(p.isFilled()) {\r
+                graphics.fill(s);\r
+            }\r
+            if(p.isStroked()) {\r
+                graphics.draw(s);\r
+            }\r
         }\r
     }\r
 \r
@@ -221,8 +231,7 @@ public class DrawSimpleShape extends DrawShape {
         double lineWidth = Math.max(2.5, stroke.getLineWidth());\r
 \r
         Rectangle2D anchor = getAnchor(graphics, getShape());\r
-        double x1 = anchor.getX(),\r
-                y1 = anchor.getY();\r
+        double x1 = anchor.getX(), y1 = anchor.getY();\r
 \r
         double alpha = Math.atan(anchor.getHeight() / anchor.getWidth());\r
 \r
@@ -283,13 +292,15 @@ public class DrawSimpleShape extends DrawShape {
     }\r
 \r
     protected void drawShadow(\r
-            Graphics2D graphics\r
-          , Collection<Outline> outlines\r
-          , Paint fill\r
-          , Paint line\r
+        Graphics2D graphics\r
+      , Collection<Outline> outlines\r
+      , Paint fill\r
+      , Paint line\r
     ) {\r
           Shadow<?,?> shadow = getShape().getShadow();\r
-          if (shadow == null || (fill == null && line == null)) return;\r
+          if (shadow == null || (fill == null && line == null)) {\r
+              return;\r
+          }\r
 \r
           SolidPaint shadowPaint = shadow.getFillStyle();\r
           Color shadowColor = DrawPaint.applyColorTransform(shadowPaint.getSolidColor());\r
@@ -373,11 +384,7 @@ public class DrawSimpleShape extends DrawShape {
             } catch (Exception e) {\r
                 throw new RuntimeException("Unable to load preset geometries.", e);\r
             } finally {\r
-                try {\r
-                    presetIS.close();\r
-                } catch (IOException e) {\r
-                    throw new RuntimeException("Unable to load preset geometries.", e);\r
-                }\r
+                IOUtils.closeQuietly(presetIS);\r
             }\r
         }\r
 \r
index db23e1de086d3166f632d1847c8a2d34a1278367..b61d55daf0f94ae3af6dbc0bee0668b526376efd 100644 (file)
 ==================================================================== */\r
 package org.apache.poi.sl.usermodel;\r
 \r
-import java.io.*;\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.PushbackInputStream;\r
 import java.lang.reflect.InvocationTargetException;\r
 import java.lang.reflect.Method;\r
 \r
 import org.apache.poi.EncryptedDocumentException;\r
 import org.apache.poi.OldFileFormatException;\r
-import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;\r
 import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;\r
 import org.apache.poi.poifs.crypt.Decryptor;\r
 import org.apache.poi.poifs.filesystem.DirectoryNode;\r
+import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;\r
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;\r
 import org.apache.poi.poifs.filesystem.OfficeXmlFileException;\r
 import org.apache.poi.util.IOUtils;\r
@@ -66,7 +70,7 @@ public class SlideShowFactory {
 \r
                 return createXSLFSlideShow(stream);\r
             } finally {\r
-                if (stream != null) stream.close();\r
+                IOUtils.closeQuietly(stream);\r
             }\r
         }\r
 \r
@@ -211,14 +215,10 @@ public class SlideShowFactory {
             fs = new NPOIFSFileSystem(file, readOnly);\r
             return create(fs, password);\r
         } catch(OfficeXmlFileException e) {\r
-            if(fs != null) {\r
-                fs.close();\r
-            }\r
+            IOUtils.closeQuietly(fs);\r
             return createXSLFSlideShow(file, readOnly);\r
         } catch(RuntimeException e) {\r
-            if(fs != null) {\r
-                fs.close();\r
-            }\r
+            IOUtils.closeQuietly(fs);\r
             throw e;\r
         }\r
     }\r
index e054f125da26652d3c4c233853b3b84bda11827e..a07cb9c70ba0071826d09e89872fd8b74b2fd153 100644 (file)
@@ -25,9 +25,7 @@ import java.util.Map;
 import org.apache.poi.ss.util.CellReference;
 
 /**
- * Optimisation - compacts many blank cell references used by a single formula.
- *
- * @author Josh Micich
+ * Optimization - compacts many blank cell references used by a single formula.
  */
 final class FormulaUsedBlankCellSet {
        public static final class BookSheetKey {
@@ -39,11 +37,15 @@ final class FormulaUsedBlankCellSet {
                        _bookIndex = bookIndex;
                        _sheetIndex = sheetIndex;
                }
-               public int hashCode() {
+               @Override
+        public int hashCode() {
                        return _bookIndex * 17 + _sheetIndex;
                }
-               public boolean equals(Object obj) {
-                       assert obj instanceof BookSheetKey : "these private cache key instances are only compared to themselves";
+               @Override
+        public boolean equals(Object obj) {
+                   if (!(obj instanceof BookSheetKey)) {
+                       return false;
+                   }
                        BookSheetKey other = (BookSheetKey) obj;
                        return _bookIndex == other._bookIndex && _sheetIndex == other._sheetIndex;
                }
@@ -148,7 +150,8 @@ final class FormulaUsedBlankCellSet {
                        _lastRowIndex = rowIndex;
                        return true;
                }
-               public String toString() {
+               @Override
+        public String toString() {
                        StringBuffer sb = new StringBuffer(64);
                        CellReference crA = new CellReference(_firstRowIndex, _firstColumnIndex, false, false);
                        CellReference crB = new CellReference(_lastRowIndex, _lastColumnIndex, false, false);
index f422b9604e9396a74f318824bae020ee7a5c4b06..2514c0711ff71161e999368bd08449b7c0d2abce 100644 (file)
@@ -20,10 +20,6 @@ package org.apache.poi.ss.formula;
 import java.util.HashMap;
 import java.util.Map;
 
-/**
- *
- * @author Josh Micich
- */
 final class PlainCellCache {
 
        public static final class Loc {
@@ -48,12 +44,16 @@ final class PlainCellCache {
                        _rowIndex = rowIndex;
                }
 
-               public int hashCode() {
+               @Override
+        public int hashCode() {
                        return (int)(_bookSheetColumn ^ (_bookSheetColumn >>> 32)) + 17 * _rowIndex;
                }
 
-               public boolean equals(Object obj) {
-                       assert obj instanceof Loc : "these package-private cache key instances are only compared to themselves";
+               @Override
+        public boolean equals(Object obj) {
+                   if (!(obj instanceof Loc)) {
+                       return false;
+                   }
                        Loc other = (Loc) obj;
                        return _bookSheetColumn == other._bookSheetColumn && _rowIndex == other._rowIndex;
                }
index 42bd9aed10d31090e2cb1c63feeca2f0c445ce9c..473c22536322216480c6e8be6452aa073880935c 100644 (file)
@@ -29,8 +29,6 @@ import org.apache.poi.util.LocaleUtil;
  * Internal calculation methods for Excel 'Analysis ToolPak' function YEARFRAC()<br/>
  *  
  * Algorithm inspired by www.dwheeler.com/yearfrac
- * 
- * @author Josh Micich
  */
 final class YearFracCalculator {
        private static final int MS_PER_HOUR = 60 * 60 * 1000;
@@ -212,25 +210,21 @@ final class YearFracCalculator {
         * @return <code>true</code> if dates both within a leap year, or span a period including Feb 29
         */
        private static boolean shouldCountFeb29(SimpleDate start, SimpleDate end) {
-               boolean startIsLeapYear = isLeapYear(start.year);
-               if (startIsLeapYear && start.year == end.year) {
-                       // note - dates may not actually span Feb-29, but it gets counted anyway in this case
-                       return true;
-               }
+               if (isLeapYear(start.year)) {
+               if (start.year == end.year) {
+                   // note - dates may not actually span Feb-29, but it gets counted anyway in this case
+                   return true;
+               }
 
-               boolean endIsLeapYear = isLeapYear(end.year);
-               if (!startIsLeapYear && !endIsLeapYear) {
-                       return false;
-               }
-               if (startIsLeapYear) {
-                       switch (start.month) {
+               switch (start.month) {
                                case SimpleDate.JANUARY:
                                case SimpleDate.FEBRUARY:
                                        return true;
                        }
                        return false;
                }
-               if (endIsLeapYear) {
+               
+               if (isLeapYear(end.year)) {
                        switch (end.month) {
                                case SimpleDate.JANUARY:
                                        return false;
index 072a777e104b0c1406ad9b234bf360047fcc8961..abd3b9925a584b3f7f9cd972545eaf1f2f4f1f20 100644 (file)
@@ -37,8 +37,6 @@ import org.apache.poi.util.Internal;
  * will be used in all subsequent evaluations.<br/>
  *
  * For POI internal use only
- *
- * @author Josh Micich
  */
 @Internal
 final class ForkedEvaluationSheet implements EvaluationSheet {
@@ -128,7 +126,9 @@ final class ForkedEvaluationSheet implements EvaluationSheet {
         }
         @Override
         public boolean equals(Object obj) {
-            assert obj instanceof RowColKey : "these private cache key instances are only compared to themselves";
+            if (!(obj instanceof RowColKey)) {
+                return false;
+            }
             RowColKey other = (RowColKey) obj;
             return _rowIndex == other._rowIndex && _columnIndex == other._columnIndex;
         }
@@ -136,6 +136,7 @@ final class ForkedEvaluationSheet implements EvaluationSheet {
         public int hashCode() {
             return _rowIndex ^ _columnIndex;
         }
+        @Override
         public int compareTo(RowColKey o) {
             int cmp = _rowIndex - o._rowIndex;
             if (cmp != 0) {
index f2a7ebe3ac9c2328e2c2fa45169f765b97f3db9e..04328d28d1f6d8b956fea50ea619f7830ef6664b 100644 (file)
@@ -136,6 +136,7 @@ public final class Countif extends Fixed2ArgFunction {
             throw new RuntimeException("Cannot call boolean evaluate on non-equality operator '"
                     + _representation + "'");
         }
+        @Override
         public String toString() {
             StringBuffer sb = new StringBuffer(64);
             sb.append(getClass().getName());
@@ -187,6 +188,7 @@ public final class Countif extends Fixed2ArgFunction {
             return String.valueOf(_value);
         }
 
+        @Override
         public boolean matches(ValueEval x) {
             double testValue;
             if(x instanceof StringEval) {
@@ -246,22 +248,21 @@ public final class Countif extends Fixed2ArgFunction {
             return value ? 1 : 0;
         }
 
+        @Override
         public boolean matches(ValueEval x) {
             int testValue;
             if(x instanceof StringEval) {
-                if (true) { // change to false to observe more intuitive behaviour
-                    // Note - Unlike with numbers, it seems that COUNTIF never matches
-                    // boolean values when the target(x) is a string
-                    return false;
-                }
-                @SuppressWarnings("unused")
-                StringEval se = (StringEval)x;
-                Boolean val = parseBoolean(se.getStringValue());
-                if(val == null) {
-                    // x is text that is not a boolean
-                    return false;
-                }
-                testValue = boolToInt(val.booleanValue());
+                // Note - Unlike with numbers, it seems that COUNTIF never matches
+                // boolean values when the target(x) is a string
+                return false;
+                // uncomment to observe more intuitive behaviour
+                // StringEval se = (StringEval)x;
+                // Boolean val = parseBoolean(se.getStringValue());
+                // if(val == null) {
+                //     // x is text that is not a boolean
+                //     return false;
+                // }
+                // testValue = boolToInt(val.booleanValue());
             } else if((x instanceof BoolEval)) {
                 BoolEval be = (BoolEval) x;
                 testValue = boolToInt(be.getBooleanValue());
@@ -300,6 +301,7 @@ public final class Countif extends Fixed2ArgFunction {
             return FormulaError.forInt(_value).getString();
         }
 
+        @Override
         public boolean matches(ValueEval x) {
             if(x instanceof ErrorEval) {
                 int testValue = ((ErrorEval)x).getErrorCode();
@@ -339,6 +341,7 @@ public final class Countif extends Fixed2ArgFunction {
             return _pattern.pattern();
         }
 
+        @Override
         public boolean matches(ValueEval x) {
             if (x instanceof BlankEval) {
                 switch(getCode()) {
@@ -433,6 +436,7 @@ public final class Countif extends Fixed2ArgFunction {
         }
     }
 
+    @Override
     public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
 
         I_MatchPredicate mp = createCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex);
@@ -525,13 +529,27 @@ public final class Countif extends Fixed2ArgFunction {
         if (value.length() < 4 || value.charAt(0) != '#') {
             return null;
         }
-        if (value.equals("#NULL!"))  return ErrorEval.NULL_INTERSECTION;
-        if (value.equals("#DIV/0!")) return ErrorEval.DIV_ZERO;
-        if (value.equals("#VALUE!")) return ErrorEval.VALUE_INVALID;
-        if (value.equals("#REF!"))   return ErrorEval.REF_INVALID;
-        if (value.equals("#NAME?"))  return ErrorEval.NAME_INVALID;
-        if (value.equals("#NUM!"))   return ErrorEval.NUM_ERROR;
-        if (value.equals("#N/A"))    return ErrorEval.NA;
+        if (value.equals("#NULL!")) {
+            return ErrorEval.NULL_INTERSECTION;
+        }
+        if (value.equals("#DIV/0!")) {
+            return ErrorEval.DIV_ZERO;
+        }
+        if (value.equals("#VALUE!")) {
+            return ErrorEval.VALUE_INVALID;
+        }
+        if (value.equals("#REF!")) {
+            return ErrorEval.REF_INVALID;
+        }
+        if (value.equals("#NAME?")) {
+            return ErrorEval.NAME_INVALID;
+        }
+        if (value.equals("#NUM!")) {
+            return ErrorEval.NUM_ERROR;
+        }
+        if (value.equals("#N/A")) {
+            return ErrorEval.NA;
+        }
 
         return null;
     }
index bb6fb64fbfadd1d40ac995cb7be987607c70edcf..73885703b7ca724f2503984e834560439e86a3a5 100644 (file)
@@ -35,10 +35,6 @@ import org.apache.poi.util.LittleEndianOutput;
  * parsed formula.  However, in BIFF files <tt>Ptg</tt>s are written/read in
  * <em>Reverse-Polish Notation</em> order. The RPN ordering also simplifies formula
  * evaluation logic, so POI mostly accesses <tt>Ptg</tt>s in the same way.
- *
- * @author  andy
- * @author avik
- * @author Jason Height (jheight at chariot dot net dot au)
  */
 public abstract class Ptg {
        public static final Ptg[] EMPTY_PTG_ARRAY = { };
@@ -201,8 +197,8 @@ public abstract class Ptg {
         * @return number of bytes written
         */
        public static int serializePtgs(Ptg[] ptgs, byte[] array, int offset) {
-               LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(array, offset);
-
+               LittleEndianByteArrayOutputStream out = new LittleEndianByteArrayOutputStream(array, offset); // NOSONAR
+               
                List<Ptg> arrayPtgs = null;
 
                for (Ptg ptg : ptgs) {
index c07ee5bf926a1599a79c8ec56a4384c312755438..f530a37835f308d44bd8c26d383f721dd82b02dc 100644 (file)
@@ -323,6 +323,7 @@ public class CellReference {
     /**
      * @deprecated 3.15 beta 2. Use {@link #isColumnWithinRange}.
      */
+    @Deprecated
     public static boolean isColumnWithnRange(String colStr, SpreadsheetVersion ssVersion) {
         return isColumnWithinRange(colStr, ssVersion);
     }
@@ -352,6 +353,7 @@ public class CellReference {
     /**
      * @deprecated 3.15 beta 2. Use {@link #isRowWithinRange}
      */
+    @Deprecated
     public static boolean isRowWithnRange(String rowStr, SpreadsheetVersion ssVersion) {
         return isRowWithinRange(rowStr, ssVersion);
     }
@@ -388,7 +390,9 @@ public class CellReference {
         final String sheetName = parseSheetName(reference, plingPos);
         String cell = reference.substring(plingPos+1).toUpperCase(Locale.ROOT);
         Matcher matcher = CELL_REF_PATTERN.matcher(cell);
-        if (!matcher.matches()) throw new IllegalArgumentException("Invalid CellReference: " + reference);
+        if (!matcher.matches()) {
+            throw new IllegalArgumentException("Invalid CellReference: " + reference);
+        }
         String col = matcher.group(1);
         String row = matcher.group(2);
 
@@ -430,13 +434,11 @@ public class CellReference {
                 sb.append(ch);
                 continue;
             }
-            if(i < lastQuotePos) {
-                if(reference.charAt(i+1) == SPECIAL_NAME_DELIMITER) {
-                    // two consecutive quotes is the escape sequence for a single one
-                    i++; // skip this and keep parsing the special name
-                    sb.append(ch);
-                    continue;
-                }
+            if(i+1 < lastQuotePos && reference.charAt(i+1) == SPECIAL_NAME_DELIMITER) {
+                // two consecutive quotes is the escape sequence for a single one
+                i++; // skip this and keep parsing the special name
+                sb.append(ch);
+                continue;
             }
             throw new IllegalArgumentException("Bad sheet name quote escaping: (" + reference + ")");
         }
index d25bd7d1b81198350c05707fd967ae598616faae..783b16cfd25aedce42c57de608b30896a58c85b8 100644 (file)
@@ -48,6 +48,7 @@ import java.util.UUID;
 import javax.xml.crypto.MarshalException;\r
 \r
 import org.apache.poi.poifs.crypt.dsig.services.RevocationData;\r
+import org.apache.poi.util.IOUtils;\r
 import org.apache.poi.util.POILogFactory;\r
 import org.apache.poi.util.POILogger;\r
 import org.apache.xml.security.c14n.Canonicalizer;\r
@@ -62,28 +63,7 @@ import org.bouncycastle.asn1.x509.Extension;
 import org.bouncycastle.cert.ocsp.BasicOCSPResp;\r
 import org.bouncycastle.cert.ocsp.OCSPResp;\r
 import org.bouncycastle.cert.ocsp.RespID;\r
-import org.etsi.uri.x01903.v13.CRLIdentifierType;\r
-import org.etsi.uri.x01903.v13.CRLRefType;\r
-import org.etsi.uri.x01903.v13.CRLRefsType;\r
-import org.etsi.uri.x01903.v13.CRLValuesType;\r
-import org.etsi.uri.x01903.v13.CertIDListType;\r
-import org.etsi.uri.x01903.v13.CertIDType;\r
-import org.etsi.uri.x01903.v13.CertificateValuesType;\r
-import org.etsi.uri.x01903.v13.CompleteCertificateRefsType;\r
-import org.etsi.uri.x01903.v13.CompleteRevocationRefsType;\r
-import org.etsi.uri.x01903.v13.DigestAlgAndValueType;\r
-import org.etsi.uri.x01903.v13.EncapsulatedPKIDataType;\r
-import org.etsi.uri.x01903.v13.OCSPIdentifierType;\r
-import org.etsi.uri.x01903.v13.OCSPRefType;\r
-import org.etsi.uri.x01903.v13.OCSPRefsType;\r
-import org.etsi.uri.x01903.v13.OCSPValuesType;\r
-import org.etsi.uri.x01903.v13.QualifyingPropertiesDocument;\r
-import org.etsi.uri.x01903.v13.QualifyingPropertiesType;\r
-import org.etsi.uri.x01903.v13.ResponderIDType;\r
-import org.etsi.uri.x01903.v13.RevocationValuesType;\r
-import org.etsi.uri.x01903.v13.UnsignedPropertiesType;\r
-import org.etsi.uri.x01903.v13.UnsignedSignaturePropertiesType;\r
-import org.etsi.uri.x01903.v13.XAdESTimeStampType;\r
+import org.etsi.uri.x01903.v13.*;\r
 import org.etsi.uri.x01903.v14.ValidationDataType;\r
 import org.w3.x2000.x09.xmldsig.CanonicalizationMethodType;\r
 import org.w3c.dom.Document;\r
@@ -341,8 +321,8 @@ public class XAdESXLSignatureFacet extends SignatureFacet {
                 ASN1Integer integer = (ASN1Integer)asn1IS2.readObject();\r
                 return integer.getPositiveValue();\r
             } finally {\r
-                asn1IS2.close();\r
-                asn1IS1.close();\r
+                IOUtils.closeQuietly(asn1IS2);\r
+                IOUtils.closeQuietly(asn1IS1);\r
             }\r
         } catch (IOException e) {\r
             throw new RuntimeException("I/O error: " + e.getMessage(), e);\r
index 621e71d8de6bdd3efd0b396183c835f603ac172b..83b1e8609bd6128cf18286a48e5ac1ee3287e6f0 100644 (file)
 ==================================================================== */
 package org.apache.poi.ss.usermodel;
 
-import java.io.*;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PushbackInputStream;
 
 import org.apache.poi.EmptyFileException;
 import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
 import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
@@ -28,6 +31,7 @@ import org.apache.poi.openxml4j.opc.OPCPackage;
 import org.apache.poi.openxml4j.opc.PackageAccess;
 import org.apache.poi.poifs.crypt.Decryptor;
 import org.apache.poi.poifs.filesystem.DirectoryNode;
+import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
@@ -252,8 +256,7 @@ public class WorkbookFactory {
                 return create(fs, password);
             } catch (RuntimeException e) {
                 // ensure that the file-handle is closed again
-                fs.close();
-                
+                IOUtils.closeQuietly(fs);
                 throw e;
             }
         } catch(OfficeXmlFileException e) {
@@ -261,20 +264,18 @@ public class WorkbookFactory {
             OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE);
             try {
                 return new XSSFWorkbook(pkg);
-            } catch (IOException ioe) {
-                // ensure that file handles are closed (use revert() to not re-write the file)
-                pkg.revert();
-                //pkg.close();
-
-                // rethrow exception
-                throw ioe;
-            } catch (RuntimeException ioe) {
-                // ensure that file handles are closed (use revert() to not re-write the file)
+            } catch (Exception ioe) {
+                // ensure that file handles are closed - use revert() to not re-write the file
                 pkg.revert();
-                //pkg.close();
+                // do not pkg.close();
 
-                // rethrow exception
-                throw ioe;
+                if (ioe instanceof IOException) {
+                    throw (IOException)ioe;
+                } else if (ioe instanceof RuntimeException) {
+                    throw (RuntimeException)ioe;
+                } else {
+                    throw new IOException(ioe);
+                }
             }
         }
     }