\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
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
FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx");\r
wb.write(out);\r
out.close();\r
-\r
+ \r
+ wb.close();\r
}\r
\r
}\r
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
*/\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
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;
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
* 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
{
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();
* @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
+ }
+}
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
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
}\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
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
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
}\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
} 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
==================================================================== */\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
\r
return createXSLFSlideShow(stream);\r
} finally {\r
- if (stream != null) stream.close();\r
+ IOUtils.closeQuietly(stream);\r
}\r
}\r
\r
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
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 {
_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;
}
_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);
import java.util.HashMap;
import java.util.Map;
-/**
- *
- * @author Josh Micich
- */
final class PlainCellCache {
public static final class Loc {
_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;
}
* 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;
* @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;
* will be used in all subsequent evaluations.<br/>
*
* For POI internal use only
- *
- * @author Josh Micich
*/
@Internal
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;
}
public int hashCode() {
return _rowIndex ^ _columnIndex;
}
+ @Override
public int compareTo(RowColKey o) {
int cmp = _rowIndex - o._rowIndex;
if (cmp != 0) {
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());
return String.valueOf(_value);
}
+ @Override
public boolean matches(ValueEval x) {
double testValue;
if(x instanceof StringEval) {
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());
return FormulaError.forInt(_value).getString();
}
+ @Override
public boolean matches(ValueEval x) {
if(x instanceof ErrorEval) {
int testValue = ((ErrorEval)x).getErrorCode();
return _pattern.pattern();
}
+ @Override
public boolean matches(ValueEval x) {
if (x instanceof BlankEval) {
switch(getCode()) {
}
}
+ @Override
public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) {
I_MatchPredicate mp = createCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex);
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;
}
* 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 = { };
* @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) {
/**
* @deprecated 3.15 beta 2. Use {@link #isColumnWithinRange}.
*/
+ @Deprecated
public static boolean isColumnWithnRange(String colStr, SpreadsheetVersion ssVersion) {
return isColumnWithinRange(colStr, ssVersion);
}
/**
* @deprecated 3.15 beta 2. Use {@link #isRowWithinRange}
*/
+ @Deprecated
public static boolean isRowWithnRange(String rowStr, SpreadsheetVersion ssVersion) {
return isRowWithinRange(rowStr, ssVersion);
}
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);
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 + ")");
}
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
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
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
==================================================================== */
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;
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;
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) {
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);
+ }
}
}
}