You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@poi.apache.org by fa...@apache.org on 2021/05/22 20:56:49 UTC
svn commit: r1890120 [39/43] - in /poi/trunk/poi/src:
main/java/org/apache/poi/ main/java/org/apache/poi/ddf/
main/java/org/apache/poi/extractor/ main/java/org/apache/poi/hpsf/
main/java/org/apache/poi/hssf/ main/java/org/apache/poi/hssf/dev/
main/java...
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java Sat May 22 20:56:44 2021
@@ -62,562 +62,562 @@ import org.xml.sax.helpers.DefaultHandle
*/
public final class ExcelFileFormatDocFunctionExtractor {
- private static final String SOURCE_DOC_FILE_NAME = "excelfileformat.odt";
+ private static final String SOURCE_DOC_FILE_NAME = "excelfileformat.odt";
- /**
- * For simplicity, the output file is strictly simple ASCII.
- * This method detects any unexpected characters.
- */
- /* package */ static boolean isSimpleAscii(char c) {
-
- if (c>=0x21 && c<=0x7E) {
- // everything from '!' to '~' (includes letters, digits, punctuation
- return true;
- }
- // some specific whitespace chars below 0x21:
- switch(c) {
- case ' ':
- case '\t':
- case '\r':
- case '\n':
- return true;
- }
- return false;
- }
-
-
- private static final class FunctionData {
- // special characters from the ooo document
- private static final int CHAR_ELLIPSIS_8230 = 8230;
- private static final int CHAR_NDASH_8211 = 8211;
-
- private final int _index;
- private final boolean _hasFootnote;
- private final String _name;
- private final int _minParams;
- private final int _maxParams;
- private final String _returnClass;
- private final String _paramClasses;
- private final boolean _isVolatile;
-
- public FunctionData(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams,
- String returnClass, String paramClasses, boolean isVolatile) {
- _index = funcIx;
- _hasFootnote = hasFootnote;
- _name = funcName;
- _minParams = minParams;
- _maxParams = maxParams;
- _returnClass = convertSpecialChars(returnClass);
- _paramClasses = convertSpecialChars(paramClasses);
- _isVolatile = isVolatile;
- }
- private static String convertSpecialChars(String ss) {
- StringBuilder sb = new StringBuilder(ss.length() + 4);
- for(int i=0; i<ss.length(); i++) {
- char c = ss.charAt(i);
- if (isSimpleAscii(c)) {
- sb.append(c);
- continue;
- }
- switch (c) {
- case CHAR_NDASH_8211:
- sb.append('-');
- continue;
- case CHAR_ELLIPSIS_8230:
- sb.append("...");
- continue;
- }
- throw new RuntimeException("bad char (" + ((int)c) + ") in string '" + ss + "'");
- }
- return sb.toString();
- }
- public int getIndex() {
- return _index;
- }
- public String getName() {
- return _name;
- }
- public boolean hasFootnote() {
- return _hasFootnote;
- }
- public String formatAsDataLine() {
- return _index + "\t" + _name + "\t" + _minParams + "\t"
- + _maxParams + "\t" + _returnClass + "\t" + _paramClasses
- + "\t" + checkMark(_isVolatile) + "\t" + checkMark(_hasFootnote);
- }
- private static String checkMark(boolean b) {
- return b ? "x" : "";
- }
- }
-
- private static final class FunctionDataCollector {
-
- private final Map<Integer, FunctionData> _allFunctionsByIndex;
- private final Map<String, FunctionData> _allFunctionsByName;
- private final Set<Integer> _groupFunctionIndexes;
- private final Set<String> _groupFunctionNames;
- private final PrintStream _ps;
-
- public FunctionDataCollector(PrintStream ps) {
- _ps = ps;
- _allFunctionsByIndex = new HashMap<>();
- _allFunctionsByName = new HashMap<>();
- _groupFunctionIndexes = new HashSet<>();
- _groupFunctionNames = new HashSet<>();
- }
-
- public void addFuntion(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams,
- String returnClass, String paramClasses, String volatileFlagStr) {
- boolean isVolatile = volatileFlagStr.length() > 0;
-
- Integer funcIxKey = Integer.valueOf(funcIx);
- if(!_groupFunctionIndexes.add(funcIxKey)) {
- throw new RuntimeException("Duplicate function index (" + funcIx + ")");
- }
- if(!_groupFunctionNames.add(funcName)) {
- throw new RuntimeException("Duplicate function name '" + funcName + "'");
- }
-
- checkRedefinedFunction(hasFootnote, funcName, funcIxKey);
- FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName,
- minParams, maxParams, returnClass, paramClasses, isVolatile);
-
- _allFunctionsByIndex.put(funcIxKey, fd);
- _allFunctionsByName.put(funcName, fd);
- }
-
- /**
- * Some extra validation here.
- * Any function which changes definition will have a footnote in the source document
- */
- private void checkRedefinedFunction(boolean hasNote, String funcName, Integer funcIxKey) {
- FunctionData fdPrev;
- // check by index
- fdPrev = _allFunctionsByIndex.get(funcIxKey);
- if(fdPrev != null) {
- if(!fdPrev.hasFootnote() || !hasNote) {
- throw new RuntimeException("changing function ["
- + funcIxKey + "] definition without foot-note");
- }
- _allFunctionsByName.remove(fdPrev.getName());
- }
- // check by name
- fdPrev = _allFunctionsByName.get(funcName);
- if(fdPrev != null) {
- if(!fdPrev.hasFootnote() || !hasNote) {
- throw new RuntimeException("changing function '"
- + funcName + "' definition without foot-note");
- }
- _allFunctionsByIndex.remove(Integer.valueOf(fdPrev.getIndex()));
- }
- }
-
- public void endTableGroup(String headingText) {
- Integer[] keys = new Integer[_groupFunctionIndexes.size()];
- _groupFunctionIndexes.toArray(keys);
- _groupFunctionIndexes.clear();
- _groupFunctionNames.clear();
- Arrays.sort(keys);
-
- _ps.println("# " + headingText);
- for (Integer key : keys) {
- FunctionData fd = _allFunctionsByIndex.get(key);
- _ps.println(fd.formatAsDataLine());
- }
- }
- }
-
- /**
- * To avoid drag-in - parse XML using only JDK.
- */
- private static class EFFDocHandler extends DefaultHandler {
- private static final String[] HEADING_PATH_NAMES = {
- "office:document-content", "office:body", "office:text", "text:h",
- };
- private static final String[] TABLE_BASE_PATH_NAMES = {
- "office:document-content", "office:body", "office:text", "table:table",
- };
- private static final String[] TABLE_ROW_RELPATH_NAMES = {
- "table:table-row",
- };
- private static final String[] TABLE_CELL_RELPATH_NAMES = {
- "table:table-row", "table:table-cell", "text:p",
- };
- // after May 2008 there was one more style applied to the footnotes
- private static final String[] NOTE_REF_RELPATH_NAMES_OLD = {
- "table:table-row", "table:table-cell", "text:p", "text:span", "text:note-ref",
- };
- private static final String[] NOTE_REF_RELPATH_NAMES = {
- "table:table-row", "table:table-cell", "text:p", "text:span", "text:span", "text:note-ref",
- };
-
-
- private final Stack<String> _elemNameStack;
- /** <code>true</code> only when parsing the target tables */
- private boolean _isInsideTable;
-
- private final List<String> _rowData;
- private final StringBuilder _textNodeBuffer;
- private final List<Boolean> _rowNoteFlags;
- private boolean _cellHasNote;
-
- private final FunctionDataCollector _fdc;
- private String _lastHeadingText;
-
- public EFFDocHandler(FunctionDataCollector fdc) {
- _fdc = fdc;
- _elemNameStack = new Stack<>();
- _isInsideTable = false;
- _rowData = new ArrayList<>();
- _textNodeBuffer = new StringBuilder();
- _rowNoteFlags = new ArrayList<>();
- }
-
- private boolean matchesTargetPath() {
- return matchesPath(0, TABLE_BASE_PATH_NAMES);
- }
-
- private boolean matchesRelPath(String[] pathNames) {
- return matchesPath(TABLE_BASE_PATH_NAMES.length, pathNames);
- }
-
- private boolean matchesPath(int baseStackIndex, String[] pathNames) {
- if(_elemNameStack.size() != baseStackIndex + pathNames.length) {
- return false;
- }
- for (int i = 0; i < pathNames.length; i++) {
- if(!_elemNameStack.get(baseStackIndex + i).equals(pathNames[i])) {
- return false;
- }
- }
- return true;
- }
+ /**
+ * For simplicity, the output file is strictly simple ASCII.
+ * This method detects any unexpected characters.
+ */
+ /* package */ static boolean isSimpleAscii(char c) {
+
+ if (c>=0x21 && c<=0x7E) {
+ // everything from '!' to '~' (includes letters, digits, punctuation
+ return true;
+ }
+ // some specific whitespace chars below 0x21:
+ switch(c) {
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ return true;
+ }
+ return false;
+ }
+
+
+ private static final class FunctionData {
+ // special characters from the ooo document
+ private static final int CHAR_ELLIPSIS_8230 = 8230;
+ private static final int CHAR_NDASH_8211 = 8211;
+
+ private final int _index;
+ private final boolean _hasFootnote;
+ private final String _name;
+ private final int _minParams;
+ private final int _maxParams;
+ private final String _returnClass;
+ private final String _paramClasses;
+ private final boolean _isVolatile;
+
+ public FunctionData(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams,
+ String returnClass, String paramClasses, boolean isVolatile) {
+ _index = funcIx;
+ _hasFootnote = hasFootnote;
+ _name = funcName;
+ _minParams = minParams;
+ _maxParams = maxParams;
+ _returnClass = convertSpecialChars(returnClass);
+ _paramClasses = convertSpecialChars(paramClasses);
+ _isVolatile = isVolatile;
+ }
+ private static String convertSpecialChars(String ss) {
+ StringBuilder sb = new StringBuilder(ss.length() + 4);
+ for(int i=0; i<ss.length(); i++) {
+ char c = ss.charAt(i);
+ if (isSimpleAscii(c)) {
+ sb.append(c);
+ continue;
+ }
+ switch (c) {
+ case CHAR_NDASH_8211:
+ sb.append('-');
+ continue;
+ case CHAR_ELLIPSIS_8230:
+ sb.append("...");
+ continue;
+ }
+ throw new RuntimeException("bad char (" + ((int)c) + ") in string '" + ss + "'");
+ }
+ return sb.toString();
+ }
+ public int getIndex() {
+ return _index;
+ }
+ public String getName() {
+ return _name;
+ }
+ public boolean hasFootnote() {
+ return _hasFootnote;
+ }
+ public String formatAsDataLine() {
+ return _index + "\t" + _name + "\t" + _minParams + "\t"
+ + _maxParams + "\t" + _returnClass + "\t" + _paramClasses
+ + "\t" + checkMark(_isVolatile) + "\t" + checkMark(_hasFootnote);
+ }
+ private static String checkMark(boolean b) {
+ return b ? "x" : "";
+ }
+ }
+
+ private static final class FunctionDataCollector {
+
+ private final Map<Integer, FunctionData> _allFunctionsByIndex;
+ private final Map<String, FunctionData> _allFunctionsByName;
+ private final Set<Integer> _groupFunctionIndexes;
+ private final Set<String> _groupFunctionNames;
+ private final PrintStream _ps;
+
+ public FunctionDataCollector(PrintStream ps) {
+ _ps = ps;
+ _allFunctionsByIndex = new HashMap<>();
+ _allFunctionsByName = new HashMap<>();
+ _groupFunctionIndexes = new HashSet<>();
+ _groupFunctionNames = new HashSet<>();
+ }
+
+ public void addFuntion(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams,
+ String returnClass, String paramClasses, String volatileFlagStr) {
+ boolean isVolatile = volatileFlagStr.length() > 0;
+
+ Integer funcIxKey = Integer.valueOf(funcIx);
+ if(!_groupFunctionIndexes.add(funcIxKey)) {
+ throw new RuntimeException("Duplicate function index (" + funcIx + ")");
+ }
+ if(!_groupFunctionNames.add(funcName)) {
+ throw new RuntimeException("Duplicate function name '" + funcName + "'");
+ }
+
+ checkRedefinedFunction(hasFootnote, funcName, funcIxKey);
+ FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName,
+ minParams, maxParams, returnClass, paramClasses, isVolatile);
+
+ _allFunctionsByIndex.put(funcIxKey, fd);
+ _allFunctionsByName.put(funcName, fd);
+ }
+
+ /**
+ * Some extra validation here.
+ * Any function which changes definition will have a footnote in the source document
+ */
+ private void checkRedefinedFunction(boolean hasNote, String funcName, Integer funcIxKey) {
+ FunctionData fdPrev;
+ // check by index
+ fdPrev = _allFunctionsByIndex.get(funcIxKey);
+ if(fdPrev != null) {
+ if(!fdPrev.hasFootnote() || !hasNote) {
+ throw new RuntimeException("changing function ["
+ + funcIxKey + "] definition without foot-note");
+ }
+ _allFunctionsByName.remove(fdPrev.getName());
+ }
+ // check by name
+ fdPrev = _allFunctionsByName.get(funcName);
+ if(fdPrev != null) {
+ if(!fdPrev.hasFootnote() || !hasNote) {
+ throw new RuntimeException("changing function '"
+ + funcName + "' definition without foot-note");
+ }
+ _allFunctionsByIndex.remove(Integer.valueOf(fdPrev.getIndex()));
+ }
+ }
+
+ public void endTableGroup(String headingText) {
+ Integer[] keys = new Integer[_groupFunctionIndexes.size()];
+ _groupFunctionIndexes.toArray(keys);
+ _groupFunctionIndexes.clear();
+ _groupFunctionNames.clear();
+ Arrays.sort(keys);
+
+ _ps.println("# " + headingText);
+ for (Integer key : keys) {
+ FunctionData fd = _allFunctionsByIndex.get(key);
+ _ps.println(fd.formatAsDataLine());
+ }
+ }
+ }
+
+ /**
+ * To avoid drag-in - parse XML using only JDK.
+ */
+ private static class EFFDocHandler extends DefaultHandler {
+ private static final String[] HEADING_PATH_NAMES = {
+ "office:document-content", "office:body", "office:text", "text:h",
+ };
+ private static final String[] TABLE_BASE_PATH_NAMES = {
+ "office:document-content", "office:body", "office:text", "table:table",
+ };
+ private static final String[] TABLE_ROW_RELPATH_NAMES = {
+ "table:table-row",
+ };
+ private static final String[] TABLE_CELL_RELPATH_NAMES = {
+ "table:table-row", "table:table-cell", "text:p",
+ };
+ // after May 2008 there was one more style applied to the footnotes
+ private static final String[] NOTE_REF_RELPATH_NAMES_OLD = {
+ "table:table-row", "table:table-cell", "text:p", "text:span", "text:note-ref",
+ };
+ private static final String[] NOTE_REF_RELPATH_NAMES = {
+ "table:table-row", "table:table-cell", "text:p", "text:span", "text:span", "text:note-ref",
+ };
+
+
+ private final Stack<String> _elemNameStack;
+ /** <code>true</code> only when parsing the target tables */
+ private boolean _isInsideTable;
+
+ private final List<String> _rowData;
+ private final StringBuilder _textNodeBuffer;
+ private final List<Boolean> _rowNoteFlags;
+ private boolean _cellHasNote;
+
+ private final FunctionDataCollector _fdc;
+ private String _lastHeadingText;
+
+ public EFFDocHandler(FunctionDataCollector fdc) {
+ _fdc = fdc;
+ _elemNameStack = new Stack<>();
+ _isInsideTable = false;
+ _rowData = new ArrayList<>();
+ _textNodeBuffer = new StringBuilder();
+ _rowNoteFlags = new ArrayList<>();
+ }
+
+ private boolean matchesTargetPath() {
+ return matchesPath(0, TABLE_BASE_PATH_NAMES);
+ }
+
+ private boolean matchesRelPath(String[] pathNames) {
+ return matchesPath(TABLE_BASE_PATH_NAMES.length, pathNames);
+ }
+
+ private boolean matchesPath(int baseStackIndex, String[] pathNames) {
+ if(_elemNameStack.size() != baseStackIndex + pathNames.length) {
+ return false;
+ }
+ for (int i = 0; i < pathNames.length; i++) {
+ if(!_elemNameStack.get(baseStackIndex + i).equals(pathNames[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
- @Override
+ @Override
public void characters(char[] ch, int start, int length) {
- // only 2 text nodes where text is collected:
- if(matchesRelPath(TABLE_CELL_RELPATH_NAMES) || matchesPath(0, HEADING_PATH_NAMES)) {
- _textNodeBuffer.append(ch, start, length);
- }
- }
+ // only 2 text nodes where text is collected:
+ if(matchesRelPath(TABLE_CELL_RELPATH_NAMES) || matchesPath(0, HEADING_PATH_NAMES)) {
+ _textNodeBuffer.append(ch, start, length);
+ }
+ }
- @Override
+ @Override
public void endElement(String namespaceURI, String localName, String name) {
- String expectedName = _elemNameStack.peek();
- if(expectedName != name) {
- throw new RuntimeException("close tag mismatch");
- }
- if(matchesPath(0, HEADING_PATH_NAMES)) {
- _lastHeadingText = _textNodeBuffer.toString().trim();
- _textNodeBuffer.setLength(0);
- }
- if(_isInsideTable) {
- if(matchesTargetPath()) {
- _fdc.endTableGroup(_lastHeadingText);
- _isInsideTable = false;
- } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) {
- String[] cellData = new String[_rowData.size()];
- _rowData.toArray(cellData);
- _rowData.clear();
- Boolean[] noteFlags = new Boolean[_rowNoteFlags.size()];
- _rowNoteFlags.toArray(noteFlags);
- _rowNoteFlags.clear();
- processTableRow(cellData, noteFlags);
- } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) {
- _rowData.add(_textNodeBuffer.toString().trim());
- _rowNoteFlags.add(Boolean.valueOf(_cellHasNote));
- _textNodeBuffer.setLength(0);
- }
- }
- _elemNameStack.pop();
- }
-
- private void processTableRow(String[] cellData, Boolean[] noteFlags) {
- // each table row of the document contains data for two functions
- if(cellData.length != 15) {
- throw new RuntimeException("Bad table row size");
- }
- processFunction(cellData, noteFlags, 0);
- processFunction(cellData, noteFlags, 8);
- }
-
- public void processFunction(String[] cellData, Boolean[] noteFlags, int i) {
- String funcIxStr = cellData[i + 0];
- if (funcIxStr.length() < 1) {
- // empty (happens on the right hand side when there is an odd number of functions)
- return;
- }
- int funcIx = parseInt(funcIxStr);
-
- boolean hasFootnote = noteFlags[i + 1].booleanValue();
- String funcName = cellData[i + 1];
- int minParams = parseInt(cellData[i + 2]);
- int maxParams = parseInt(cellData[i + 3]);
-
- String returnClass = cellData[i + 4];
- String paramClasses = cellData[i + 5];
- String volatileFlagStr = cellData[i + 6];
-
- _fdc.addFuntion(funcIx, hasFootnote, funcName, minParams, maxParams, returnClass, paramClasses, volatileFlagStr);
- }
-
- private static int parseInt(String valStr) {
- try {
- return Integer.parseInt(valStr);
- } catch (NumberFormatException e) {
- throw new RuntimeException("Value '" + valStr + "' could not be parsed as an integer");
- }
- }
+ String expectedName = _elemNameStack.peek();
+ if(expectedName != name) {
+ throw new RuntimeException("close tag mismatch");
+ }
+ if(matchesPath(0, HEADING_PATH_NAMES)) {
+ _lastHeadingText = _textNodeBuffer.toString().trim();
+ _textNodeBuffer.setLength(0);
+ }
+ if(_isInsideTable) {
+ if(matchesTargetPath()) {
+ _fdc.endTableGroup(_lastHeadingText);
+ _isInsideTable = false;
+ } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) {
+ String[] cellData = new String[_rowData.size()];
+ _rowData.toArray(cellData);
+ _rowData.clear();
+ Boolean[] noteFlags = new Boolean[_rowNoteFlags.size()];
+ _rowNoteFlags.toArray(noteFlags);
+ _rowNoteFlags.clear();
+ processTableRow(cellData, noteFlags);
+ } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) {
+ _rowData.add(_textNodeBuffer.toString().trim());
+ _rowNoteFlags.add(Boolean.valueOf(_cellHasNote));
+ _textNodeBuffer.setLength(0);
+ }
+ }
+ _elemNameStack.pop();
+ }
+
+ private void processTableRow(String[] cellData, Boolean[] noteFlags) {
+ // each table row of the document contains data for two functions
+ if(cellData.length != 15) {
+ throw new RuntimeException("Bad table row size");
+ }
+ processFunction(cellData, noteFlags, 0);
+ processFunction(cellData, noteFlags, 8);
+ }
+
+ public void processFunction(String[] cellData, Boolean[] noteFlags, int i) {
+ String funcIxStr = cellData[i + 0];
+ if (funcIxStr.length() < 1) {
+ // empty (happens on the right hand side when there is an odd number of functions)
+ return;
+ }
+ int funcIx = parseInt(funcIxStr);
+
+ boolean hasFootnote = noteFlags[i + 1].booleanValue();
+ String funcName = cellData[i + 1];
+ int minParams = parseInt(cellData[i + 2]);
+ int maxParams = parseInt(cellData[i + 3]);
+
+ String returnClass = cellData[i + 4];
+ String paramClasses = cellData[i + 5];
+ String volatileFlagStr = cellData[i + 6];
+
+ _fdc.addFuntion(funcIx, hasFootnote, funcName, minParams, maxParams, returnClass, paramClasses, volatileFlagStr);
+ }
+
+ private static int parseInt(String valStr) {
+ try {
+ return Integer.parseInt(valStr);
+ } catch (NumberFormatException e) {
+ throw new RuntimeException("Value '" + valStr + "' could not be parsed as an integer");
+ }
+ }
- @Override
+ @Override
public void startElement(String namespaceURI, String localName, String name, Attributes atts) {
- _elemNameStack.add(name);
- if(matchesTargetPath()) {
- String tableName = atts.getValue("table:name");
- if(tableName.startsWith("tab_fml_func") && !tableName.equals("tab_fml_func0")) {
- _isInsideTable = true;
- }
- return;
- }
- if(matchesPath(0, HEADING_PATH_NAMES)) {
- _textNodeBuffer.setLength(0);
- } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) {
- _rowData.clear();
- _rowNoteFlags.clear();
- } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) {
- _textNodeBuffer.setLength(0);
- _cellHasNote = false;
- } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES_OLD)) {
- _cellHasNote = true;
- } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES)) {
- _cellHasNote = true;
- }
- }
+ _elemNameStack.add(name);
+ if(matchesTargetPath()) {
+ String tableName = atts.getValue("table:name");
+ if(tableName.startsWith("tab_fml_func") && !tableName.equals("tab_fml_func0")) {
+ _isInsideTable = true;
+ }
+ return;
+ }
+ if(matchesPath(0, HEADING_PATH_NAMES)) {
+ _textNodeBuffer.setLength(0);
+ } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) {
+ _rowData.clear();
+ _rowNoteFlags.clear();
+ } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) {
+ _textNodeBuffer.setLength(0);
+ _cellHasNote = false;
+ } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES_OLD)) {
+ _cellHasNote = true;
+ } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES)) {
+ _cellHasNote = true;
+ }
+ }
- @Override
+ @Override
public void endDocument() {
- // do nothing
- }
- @Override
+ // do nothing
+ }
+ @Override
public void endPrefixMapping(String prefix) {
- // do nothing
- }
+ // do nothing
+ }
+ @Override
+ public void ignorableWhitespace(char[] ch, int start, int length) {
+ // do nothing
+ }
@Override
- public void ignorableWhitespace(char[] ch, int start, int length) {
- // do nothing
- }
- @Override
- public void processingInstruction(String target, String data) {
- // do nothing
- }
- @Override
- public void setDocumentLocator(Locator locator) {
- // do nothing
- }
- @Override
- public void skippedEntity(String name) {
- // do nothing
- }
- @Override
- public void startDocument() {
- // do nothing
- }
- @Override
- public void startPrefixMapping(String prefix, String uri) {
- // do nothing
- }
- }
-
- private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) {
- SAXParserFactory sf = XMLHelper.getSaxParserFactory();
- SAXParser xr;
-
- try {
- // First up, try the default one
- xr = sf.newSAXParser();
- } catch (SAXException | ParserConfigurationException e) {
- throw new RuntimeException(e);
- }
-
- try (InputStream is2 = is) {
- xr.parse(is2, new EFFDocHandler(fdc));
- } catch (IOException | SAXException e) {
- throw new RuntimeException(e);
- }
- }
- /**
- * To be sure that no tricky unicode chars make it through to the output file.
- */
- private static final class SimpleAsciiOutputStream extends OutputStream {
-
- private final OutputStream _os;
-
- public SimpleAsciiOutputStream(OutputStream os) {
- _os = os;
- }
+ public void processingInstruction(String target, String data) {
+ // do nothing
+ }
+ @Override
+ public void setDocumentLocator(Locator locator) {
+ // do nothing
+ }
+ @Override
+ public void skippedEntity(String name) {
+ // do nothing
+ }
+ @Override
+ public void startDocument() {
+ // do nothing
+ }
+ @Override
+ public void startPrefixMapping(String prefix, String uri) {
+ // do nothing
+ }
+ }
+
+ private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) {
+ SAXParserFactory sf = XMLHelper.getSaxParserFactory();
+ SAXParser xr;
+
+ try {
+ // First up, try the default one
+ xr = sf.newSAXParser();
+ } catch (SAXException | ParserConfigurationException e) {
+ throw new RuntimeException(e);
+ }
+
+ try (InputStream is2 = is) {
+ xr.parse(is2, new EFFDocHandler(fdc));
+ } catch (IOException | SAXException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ /**
+ * To be sure that no tricky unicode chars make it through to the output file.
+ */
+ private static final class SimpleAsciiOutputStream extends OutputStream {
+
+ private final OutputStream _os;
+
+ public SimpleAsciiOutputStream(OutputStream os) {
+ _os = os;
+ }
- @Override
+ @Override
public void write(int b) throws IOException {
- checkByte(b);
- _os.write(b);
- }
-
- private static void checkByte(int b) {
- if (!isSimpleAscii((char)b)) {
- throw new RuntimeException("Encountered char (" + b + ") which was not simple ascii as expected");
- }
- }
+ checkByte(b);
+ _os.write(b);
+ }
+
+ private static void checkByte(int b) {
+ if (!isSimpleAscii((char)b)) {
+ throw new RuntimeException("Encountered char (" + b + ") which was not simple ascii as expected");
+ }
+ }
- @Override
+ @Override
public void write(byte[] b, int off, int len) throws IOException {
- for (int i = 0; i < len; i++) {
- checkByte(b[i + off]);
+ for (int i = 0; i < len; i++) {
+ checkByte(b[i + off]);
- }
- _os.write(b, off, len);
- }
- }
-
- private static void processFile(File effDocFile, File outFile) {
- if(!effDocFile.exists()) {
- throw new RuntimeException("file '" + effDocFile.getAbsolutePath() + "' does not exist");
- }
- OutputStream os;
- try {
- os = new FileOutputStream(outFile);
- } catch (FileNotFoundException e) {
- throw new RuntimeException(e);
- }
- os = new SimpleAsciiOutputStream(os);
- PrintStream ps;
- try {
- ps = new PrintStream(os, true, "UTF-8");
- } catch(UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
-
- outputLicenseHeader(ps);
- Class<?> genClass = ExcelFileFormatDocFunctionExtractor.class;
- ps.println("# Created by (" + genClass.getName() + ")");
- // identify the source file
- ps.print("# from source file '" + SOURCE_DOC_FILE_NAME + "'");
- ps.println(" (size=" + effDocFile.length() + ", md5=" + getFileMD5(effDocFile) + ")");
- ps.println("#");
- ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )");
- ps.println();
- try {
- // can't use ZipHelper here, because its in a different module
- ZipFile zf = new ZipFile(effDocFile);
- InputStream is = zf.getInputStream(zf.getEntry("content.xml"));
- extractFunctionData(new FunctionDataCollector(ps), is);
- zf.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- ps.close();
-
- String canonicalOutputFileName;
- try {
- canonicalOutputFileName = outFile.getCanonicalPath();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- System.out.println("Successfully output to '" + canonicalOutputFileName + "'");
- }
-
- private static void outputLicenseHeader(PrintStream ps) {
- String[] lines= {
- "Licensed to the Apache Software Foundation (ASF) under one or more",
- "contributor license agreements. See the NOTICE file distributed with",
- "this work for additional information regarding copyright ownership.",
- "The ASF licenses this file to You under the Apache License, Version 2.0",
- "(the \"License\"); you may not use this file except in compliance with",
- "the License. You may obtain a copy of the License at",
- "",
- " http://www.apache.org/licenses/LICENSE-2.0",
- "",
- "Unless required by applicable law or agreed to in writing, software",
- "distributed under the License is distributed on an \"AS IS\" BASIS,",
- "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
- "See the License for the specific language governing permissions and",
- "limitations under the License.",
- };
- for (String line : lines) {
- ps.print("# ");
- ps.println(line);
- }
- ps.println();
- }
-
- /**
- * Helps identify the source file
- */
- private static String getFileMD5(File f) {
- MessageDigest m = CryptoFunctions.getMessageDigest(HashAlgorithm.md5);
-
- byte[]buf = new byte[2048];
- try {
- InputStream is = new FileInputStream(f);
- while(true) {
- int bytesRead = is.read(buf);
- if(bytesRead<1) {
- break;
- }
- m.update(buf, 0, bytesRead);
- }
- is.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- return "0x" + new BigInteger(1, m.digest()).toString(16);
- }
-
- private static File downloadSourceFile() {
- URL url;
- try {
- url = new URL("http://sc.openoffice.org/" + SOURCE_DOC_FILE_NAME);
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
-
- File result;
- byte[]buf = new byte[2048];
- try {
- URLConnection conn = url.openConnection();
- InputStream is = conn.getInputStream();
- System.out.println("downloading " + url.toExternalForm());
- result = TempFile.createTempFile("excelfileformat", ".odt");
- OutputStream os = new FileOutputStream(result);
- while(true) {
- int bytesRead = is.read(buf);
- if(bytesRead<1) {
- break;
- }
- os.write(buf, 0, bytesRead);
- }
- is.close();
- os.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- System.out.println("file downloaded ok");
- return result;
- }
-
- public static void main(String[] args) {
-
- File outFile = new File("functionMetadata-asGenerated.txt");
-
-// if (false) { // set true to use local file
-// File dir = new File("c:/temp");
-// File effDocFile = new File(dir, SOURCE_DOC_FILE_NAME);
-// processFile(effDocFile, outFile);
-// return;
-// }
-
- File tempEFFDocFile = downloadSourceFile();
- processFile(tempEFFDocFile, outFile);
- tempEFFDocFile.delete();
- }
+ }
+ _os.write(b, off, len);
+ }
+ }
+
+ private static void processFile(File effDocFile, File outFile) {
+ if(!effDocFile.exists()) {
+ throw new RuntimeException("file '" + effDocFile.getAbsolutePath() + "' does not exist");
+ }
+ OutputStream os;
+ try {
+ os = new FileOutputStream(outFile);
+ } catch (FileNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+ os = new SimpleAsciiOutputStream(os);
+ PrintStream ps;
+ try {
+ ps = new PrintStream(os, true, "UTF-8");
+ } catch(UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+
+ outputLicenseHeader(ps);
+ Class<?> genClass = ExcelFileFormatDocFunctionExtractor.class;
+ ps.println("# Created by (" + genClass.getName() + ")");
+ // identify the source file
+ ps.print("# from source file '" + SOURCE_DOC_FILE_NAME + "'");
+ ps.println(" (size=" + effDocFile.length() + ", md5=" + getFileMD5(effDocFile) + ")");
+ ps.println("#");
+ ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )");
+ ps.println();
+ try {
+ // can't use ZipHelper here, because its in a different module
+ ZipFile zf = new ZipFile(effDocFile);
+ InputStream is = zf.getInputStream(zf.getEntry("content.xml"));
+ extractFunctionData(new FunctionDataCollector(ps), is);
+ zf.close();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ ps.close();
+
+ String canonicalOutputFileName;
+ try {
+ canonicalOutputFileName = outFile.getCanonicalPath();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ System.out.println("Successfully output to '" + canonicalOutputFileName + "'");
+ }
+
+ private static void outputLicenseHeader(PrintStream ps) {
+ String[] lines= {
+ "Licensed to the Apache Software Foundation (ASF) under one or more",
+ "contributor license agreements. See the NOTICE file distributed with",
+ "this work for additional information regarding copyright ownership.",
+ "The ASF licenses this file to You under the Apache License, Version 2.0",
+ "(the \"License\"); you may not use this file except in compliance with",
+ "the License. You may obtain a copy of the License at",
+ "",
+ " http://www.apache.org/licenses/LICENSE-2.0",
+ "",
+ "Unless required by applicable law or agreed to in writing, software",
+ "distributed under the License is distributed on an \"AS IS\" BASIS,",
+ "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
+ "See the License for the specific language governing permissions and",
+ "limitations under the License.",
+ };
+ for (String line : lines) {
+ ps.print("# ");
+ ps.println(line);
+ }
+ ps.println();
+ }
+
+ /**
+ * Helps identify the source file
+ */
+ private static String getFileMD5(File f) {
+ MessageDigest m = CryptoFunctions.getMessageDigest(HashAlgorithm.md5);
+
+ byte[]buf = new byte[2048];
+ try {
+ InputStream is = new FileInputStream(f);
+ while(true) {
+ int bytesRead = is.read(buf);
+ if(bytesRead<1) {
+ break;
+ }
+ m.update(buf, 0, bytesRead);
+ }
+ is.close();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ return "0x" + new BigInteger(1, m.digest()).toString(16);
+ }
+
+ private static File downloadSourceFile() {
+ URL url;
+ try {
+ url = new URL("http://sc.openoffice.org/" + SOURCE_DOC_FILE_NAME);
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+
+ File result;
+ byte[]buf = new byte[2048];
+ try {
+ URLConnection conn = url.openConnection();
+ InputStream is = conn.getInputStream();
+ System.out.println("downloading " + url.toExternalForm());
+ result = TempFile.createTempFile("excelfileformat", ".odt");
+ OutputStream os = new FileOutputStream(result);
+ while(true) {
+ int bytesRead = is.read(buf);
+ if(bytesRead<1) {
+ break;
+ }
+ os.write(buf, 0, bytesRead);
+ }
+ is.close();
+ os.close();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ System.out.println("file downloaded ok");
+ return result;
+ }
+
+ public static void main(String[] args) {
+
+ File outFile = new File("functionMetadata-asGenerated.txt");
+
+// if (false) { // set true to use local file
+// File dir = new File("c:/temp");
+// File effDocFile = new File(dir, SOURCE_DOC_FILE_NAME);
+// processFile(effDocFile, outFile);
+// return;
+// }
+
+ File tempEFFDocFile = downloadSourceFile();
+ processFile(tempEFFDocFile, outFile);
+ tempEFFDocFile.delete();
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java Sat May 22 20:56:44 2021
@@ -23,21 +23,21 @@ import static org.junit.jupiter.api.Asse
import org.junit.jupiter.api.Test;
final class TestFunctionMetadataRegistry {
- @Test
- void testWellKnownFunctions() {
- confirmFunction(0, "COUNT");
- confirmFunction(1, "IF");
+ @Test
+ void testWellKnownFunctions() {
+ confirmFunction(0, "COUNT");
+ confirmFunction(1, "IF");
- }
+ }
- private static void confirmFunction(int index, String funcName) {
- FunctionMetadata fm;
- fm = FunctionMetadataRegistry.getFunctionByIndex(index);
- assertNotNull(fm);
- assertEquals(funcName, fm.getName());
+ private static void confirmFunction(int index, String funcName) {
+ FunctionMetadata fm;
+ fm = FunctionMetadataRegistry.getFunctionByIndex(index);
+ assertNotNull(fm);
+ assertEquals(funcName, fm.getName());
- fm = FunctionMetadataRegistry.getFunctionByName(funcName);
- assertNotNull(fm);
- assertEquals(index, fm.getIndex());
- }
+ fm = FunctionMetadataRegistry.getFunctionByName(funcName);
+ assertNotNull(fm);
+ assertEquals(index, fm.getIndex());
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java Sat May 22 20:56:44 2021
@@ -36,69 +36,69 @@ import org.junit.jupiter.api.Test;
*/
final class TestParseMissingBuiltInFuncs {
- private static Ptg[] parse(String formula) throws IOException {
- HSSFWorkbook book = new HSSFWorkbook();
- Ptg[] ptgs = HSSFFormulaParser.parse(formula, book);
- book.close();
- return ptgs;
- }
-
- private static void confirmFunc(String formula, int expPtgArraySize, boolean isVarArgFunc, int funcIx)
- throws IOException {
- Ptg[] ptgs = parse(formula);
- Ptg ptgF = ptgs[ptgs.length-1]; // func is last RPN token in all these formulas
-
- // Check critical things in the Ptg array encoding.
- if(!(ptgF instanceof AbstractFunctionPtg)) {
- throw new RuntimeException("function token missing");
- }
- AbstractFunctionPtg func = (AbstractFunctionPtg) ptgF;
- assertNotEquals(255, func.getFunctionIndex(), "Failed to recognise built-in function in formula");
- assertEquals(expPtgArraySize, ptgs.length);
- assertEquals(funcIx, func.getFunctionIndex());
- Class<? extends AbstractFunctionPtg> expCls = isVarArgFunc ? FuncVarPtg.class : FuncPtg.class;
- assertEquals(expCls, ptgF.getClass());
-
- // check that parsed Ptg array converts back to formula text OK
- HSSFWorkbook book = new HSSFWorkbook();
- String reRenderedFormula = HSSFFormulaParser.toFormulaString(book, ptgs);
- assertEquals(formula, reRenderedFormula);
- book.close();
- }
-
- @Test
- void testDatedif() throws IOException {
- int expSize = 4; // NB would be 5 if POI added tAttrVolatile properly
- confirmFunc("DATEDIF(NOW(),NOW(),\"d\")", expSize, false, 351);
- }
-
- @Test
- void testDdb() throws IOException {
- confirmFunc("DDB(1,1,1,1,1)", 6, true, 144);
- }
-
- @Test
- void testAtan() throws IOException {
- confirmFunc("ATAN(1)", 2, false, 18);
- }
-
- @Test
- void testUsdollar() throws IOException {
- confirmFunc("USDOLLAR(1)", 2, true, 204);
- }
-
- @Test
- void testDBCS() throws IOException {
- confirmFunc("DBCS(\"abc\")", 2, false, 215);
- }
-
- @Test
- void testIsnontext() throws IOException {
- confirmFunc("ISNONTEXT(\"abc\")", 2, false, 190);
- }
-
- @Test
- void testDproduct() throws IOException {
- confirmFunc("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", 4, false, 189);
- }
+ private static Ptg[] parse(String formula) throws IOException {
+ HSSFWorkbook book = new HSSFWorkbook();
+ Ptg[] ptgs = HSSFFormulaParser.parse(formula, book);
+ book.close();
+ return ptgs;
+ }
+
+ private static void confirmFunc(String formula, int expPtgArraySize, boolean isVarArgFunc, int funcIx)
+ throws IOException {
+ Ptg[] ptgs = parse(formula);
+ Ptg ptgF = ptgs[ptgs.length-1]; // func is last RPN token in all these formulas
+
+ // Check critical things in the Ptg array encoding.
+ if(!(ptgF instanceof AbstractFunctionPtg)) {
+ throw new RuntimeException("function token missing");
+ }
+ AbstractFunctionPtg func = (AbstractFunctionPtg) ptgF;
+ assertNotEquals(255, func.getFunctionIndex(), "Failed to recognise built-in function in formula");
+ assertEquals(expPtgArraySize, ptgs.length);
+ assertEquals(funcIx, func.getFunctionIndex());
+ Class<? extends AbstractFunctionPtg> expCls = isVarArgFunc ? FuncVarPtg.class : FuncPtg.class;
+ assertEquals(expCls, ptgF.getClass());
+
+ // check that parsed Ptg array converts back to formula text OK
+ HSSFWorkbook book = new HSSFWorkbook();
+ String reRenderedFormula = HSSFFormulaParser.toFormulaString(book, ptgs);
+ assertEquals(formula, reRenderedFormula);
+ book.close();
+ }
+
+ @Test
+ void testDatedif() throws IOException {
+ int expSize = 4; // NB would be 5 if POI added tAttrVolatile properly
+ confirmFunc("DATEDIF(NOW(),NOW(),\"d\")", expSize, false, 351);
+ }
+
+ @Test
+ void testDdb() throws IOException {
+ confirmFunc("DDB(1,1,1,1,1)", 6, true, 144);
+ }
+
+ @Test
+ void testAtan() throws IOException {
+ confirmFunc("ATAN(1)", 2, false, 18);
+ }
+
+ @Test
+ void testUsdollar() throws IOException {
+ confirmFunc("USDOLLAR(1)", 2, true, 204);
+ }
+
+ @Test
+ void testDBCS() throws IOException {
+ confirmFunc("DBCS(\"abc\")", 2, false, 215);
+ }
+
+ @Test
+ void testIsnontext() throws IOException {
+ confirmFunc("ISNONTEXT(\"abc\")", 2, false, 190);
+ }
+
+ @Test
+ void testDproduct() throws IOException {
+ confirmFunc("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", 4, false, 189);
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java Sat May 22 20:56:44 2021
@@ -38,118 +38,118 @@ import org.junit.jupiter.api.Test;
*/
final class TestReadMissingBuiltInFuncs {
- /**
- * This spreadsheet has examples of calls to the interesting built-in functions in cells A1:A7
- */
- private static final String SAMPLE_SPREADSHEET_FILE_NAME = "missingFuncs44675.xls";
+ /**
+ * This spreadsheet has examples of calls to the interesting built-in functions in cells A1:A7
+ */
+ private static final String SAMPLE_SPREADSHEET_FILE_NAME = "missingFuncs44675.xls";
- private static HSSFWorkbook wb;
- private static HSSFSheet _sheet;
+ private static HSSFWorkbook wb;
+ private static HSSFSheet _sheet;
- @BeforeAll
- public static void initSheet() {
+ @BeforeAll
+ public static void initSheet() {
wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME);
try {
_sheet = wb.getSheetAt(0);
- } catch (RecordFormatException e) {
+ } catch (RecordFormatException e) {
if(e.getCause() instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException) e.getCause();
if(ite.getTargetException() instanceof RuntimeException) {
RuntimeException re = (RuntimeException) ite.getTargetException();
- assertNotEquals("Invalid built-in function index (189)", re.getMessage(),
- "DPRODUCT() registered with wrong index");
+ assertNotEquals("Invalid built-in function index (189)", re.getMessage(),
+ "DPRODUCT() registered with wrong index");
}
}
// some other unexpected error
throw e;
}
- }
+ }
- @AfterAll
- public static void closeResources() throws Exception {
- wb.close();
- }
-
- @Test
- void testDatedif() {
- String formula;
- try {
- formula = getCellFormula(0);
- } catch (IllegalStateException e) {
- if(e.getMessage().startsWith("Too few arguments")) {
- assertFalse(e.getMessage().contains("AttrPtg"),
- "tAttrVolatile not supported in FormulaParser.toFormulaString");
- fail("NOW() registered with 1 arg instead of 0");
- }
- if(e.getMessage().startsWith("too much stuff")) {
- fail("DATEDIF() not registered");
- }
- // some other unexpected error
- throw e;
- }
- assertEquals("DATEDIF(NOW(),NOW(),\"d\")", formula);
- }
-
- @Test
- void testDdb() {
- String formula = getCellFormula(1);
- assertNotEquals("externalflag(1,1,1,1,1)", formula, "DDB() not registered");
- assertEquals("DDB(1,1,1,1,1)", formula);
- }
-
- @Test
- void testAtan() {
- String formula = getCellFormula(2);
- assertNotEquals("ARCTAN(1)", formula, "func ix 18 registered as ARCTAN() instead of ATAN()");
- assertEquals("ATAN(1)", formula);
- }
-
- @Test
- void testUsdollar() {
- String formula = getCellFormula(3);
- assertNotEquals("YEN(1)", formula, "func ix 204 registered as YEN() instead of USDOLLAR()");
- assertEquals("USDOLLAR(1)", formula);
- }
-
- @Test
- void testDBCS() {
- String formula = "";
- try {
- formula = getCellFormula(4);
- } catch (IllegalStateException e) {
- assertFalse(e.getMessage().startsWith("too much stuff"), "DBCS() not registered");
- // some other unexpected error
- throw e;
- } catch (NegativeArraySizeException e) {
- fail("found err- DBCS() registered with -1 args");
- }
- assertNotEquals("JIS(\"abc\")", formula, "func ix 215 registered as JIS() instead of DBCS()");
- assertEquals("DBCS(\"abc\")", formula);
- }
-
- @Test
- void testIsnontext() {
- String formula;
- try {
- formula = getCellFormula(5);
- } catch (IllegalStateException e) {
- assertFalse(e.getMessage().startsWith("too much stuff"), "ISNONTEXT() registered with wrong index");
- // some other unexpected error
- throw e;
- }
- assertEquals("ISNONTEXT(\"abc\")", formula);
- }
-
- @Test
- void testDproduct() {
- String formula = getCellFormula(6);
- assertEquals("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", formula);
- }
-
- private String getCellFormula(int rowIx) {
- // if (false) {
-// System.err.println(result);
-// }
- return _sheet.getRow(rowIx).getCell(0).getCellFormula();
- }
+ @AfterAll
+ public static void closeResources() throws Exception {
+ wb.close();
+ }
+
+ @Test
+ void testDatedif() {
+ String formula;
+ try {
+ formula = getCellFormula(0);
+ } catch (IllegalStateException e) {
+ if(e.getMessage().startsWith("Too few arguments")) {
+ assertFalse(e.getMessage().contains("AttrPtg"),
+ "tAttrVolatile not supported in FormulaParser.toFormulaString");
+ fail("NOW() registered with 1 arg instead of 0");
+ }
+ if(e.getMessage().startsWith("too much stuff")) {
+ fail("DATEDIF() not registered");
+ }
+ // some other unexpected error
+ throw e;
+ }
+ assertEquals("DATEDIF(NOW(),NOW(),\"d\")", formula);
+ }
+
+ @Test
+ void testDdb() {
+ String formula = getCellFormula(1);
+ assertNotEquals("externalflag(1,1,1,1,1)", formula, "DDB() not registered");
+ assertEquals("DDB(1,1,1,1,1)", formula);
+ }
+
+ @Test
+ void testAtan() {
+ String formula = getCellFormula(2);
+ assertNotEquals("ARCTAN(1)", formula, "func ix 18 registered as ARCTAN() instead of ATAN()");
+ assertEquals("ATAN(1)", formula);
+ }
+
+ @Test
+ void testUsdollar() {
+ String formula = getCellFormula(3);
+ assertNotEquals("YEN(1)", formula, "func ix 204 registered as YEN() instead of USDOLLAR()");
+ assertEquals("USDOLLAR(1)", formula);
+ }
+
+ @Test
+ void testDBCS() {
+ String formula = "";
+ try {
+ formula = getCellFormula(4);
+ } catch (IllegalStateException e) {
+ assertFalse(e.getMessage().startsWith("too much stuff"), "DBCS() not registered");
+ // some other unexpected error
+ throw e;
+ } catch (NegativeArraySizeException e) {
+ fail("found err- DBCS() registered with -1 args");
+ }
+ assertNotEquals("JIS(\"abc\")", formula, "func ix 215 registered as JIS() instead of DBCS()");
+ assertEquals("DBCS(\"abc\")", formula);
+ }
+
+ @Test
+ void testIsnontext() {
+ String formula;
+ try {
+ formula = getCellFormula(5);
+ } catch (IllegalStateException e) {
+ assertFalse(e.getMessage().startsWith("too much stuff"), "ISNONTEXT() registered with wrong index");
+ // some other unexpected error
+ throw e;
+ }
+ assertEquals("ISNONTEXT(\"abc\")", formula);
+ }
+
+ @Test
+ void testDproduct() {
+ String formula = getCellFormula(6);
+ assertEquals("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", formula);
+ }
+
+ private String getCellFormula(int rowIx) {
+ // if (false) {
+// System.err.println(result);
+// }
+ return _sheet.getRow(rowIx).getCell(0).getCellFormula();
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/EvalFactory.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/EvalFactory.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/EvalFactory.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/EvalFactory.java Sat May 22 20:56:44 2021
@@ -36,149 +36,149 @@ import org.apache.poi.ss.util.AreaRefere
*/
public final class EvalFactory {
- private EvalFactory() {
- // no instances of this class
- }
-
- /**
- * Creates a dummy AreaEval
- * @param values empty (<code>null</code>) entries in this array will be converted to NumberEval.ZERO
- */
- public static AreaEval createAreaEval(String areaRefStr, ValueEval[] values) {
- AreaPtg areaPtg = new AreaPtg(new AreaReference(areaRefStr, SpreadsheetVersion.EXCEL2007));
- return createAreaEval(areaPtg, values);
- }
-
- /**
- * Creates a dummy AreaEval
- * @param values empty (<code>null</code>) entries in this array will be converted to NumberEval.ZERO
- */
- public static AreaEval createAreaEval(AreaPtg areaPtg, ValueEval[] values) {
- int nCols = areaPtg.getLastColumn() - areaPtg.getFirstColumn() + 1;
- int nRows = areaPtg.getLastRow() - areaPtg.getFirstRow() + 1;
- int nExpected = nRows * nCols;
- if (values.length != nExpected) {
- throw new RuntimeException("Expected " + nExpected + " values but got " + values.length);
- }
- for (int i = 0; i < nExpected; i++) {
- if (values[i] == null) {
- values[i] = NumberEval.ZERO;
- }
- }
- return new MockAreaEval(areaPtg, values);
- }
-
- /**
- * Creates a single RefEval (with value zero)
- */
- public static RefEval createRefEval(String refStr) {
- return createRefEval(refStr, NumberEval.ZERO);
- }
- public static RefEval createRefEval(String refStr, ValueEval value) {
- return new MockRefEval(new RefPtg(refStr), value);
- }
-
- private static final class MockAreaEval extends AreaEvalBase {
- private final ValueEval[] _values;
- public MockAreaEval(AreaI areaPtg, ValueEval[] values) {
- super(areaPtg);
- _values = values;
- }
- private MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn, ValueEval[] values) {
- super(firstRow, firstColumn, lastRow, lastColumn);
- _values = values;
- }
- @Override
+ private EvalFactory() {
+ // no instances of this class
+ }
+
+ /**
+ * Creates a dummy AreaEval
+ * @param values empty (<code>null</code>) entries in this array will be converted to NumberEval.ZERO
+ */
+ public static AreaEval createAreaEval(String areaRefStr, ValueEval[] values) {
+ AreaPtg areaPtg = new AreaPtg(new AreaReference(areaRefStr, SpreadsheetVersion.EXCEL2007));
+ return createAreaEval(areaPtg, values);
+ }
+
+ /**
+ * Creates a dummy AreaEval
+ * @param values empty (<code>null</code>) entries in this array will be converted to NumberEval.ZERO
+ */
+ public static AreaEval createAreaEval(AreaPtg areaPtg, ValueEval[] values) {
+ int nCols = areaPtg.getLastColumn() - areaPtg.getFirstColumn() + 1;
+ int nRows = areaPtg.getLastRow() - areaPtg.getFirstRow() + 1;
+ int nExpected = nRows * nCols;
+ if (values.length != nExpected) {
+ throw new RuntimeException("Expected " + nExpected + " values but got " + values.length);
+ }
+ for (int i = 0; i < nExpected; i++) {
+ if (values[i] == null) {
+ values[i] = NumberEval.ZERO;
+ }
+ }
+ return new MockAreaEval(areaPtg, values);
+ }
+
+ /**
+ * Creates a single RefEval (with value zero)
+ */
+ public static RefEval createRefEval(String refStr) {
+ return createRefEval(refStr, NumberEval.ZERO);
+ }
+ public static RefEval createRefEval(String refStr, ValueEval value) {
+ return new MockRefEval(new RefPtg(refStr), value);
+ }
+
+ private static final class MockAreaEval extends AreaEvalBase {
+ private final ValueEval[] _values;
+ public MockAreaEval(AreaI areaPtg, ValueEval[] values) {
+ super(areaPtg);
+ _values = values;
+ }
+ private MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn, ValueEval[] values) {
+ super(firstRow, firstColumn, lastRow, lastColumn);
+ _values = values;
+ }
+ @Override
public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) {
- return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex);
- }
+ return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex);
+ }
@Override
public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) {
- if (relativeRowIndex < 0 || relativeRowIndex >=getHeight()) {
- throw new IllegalArgumentException("row index out of range");
- }
- int width = getWidth();
- if (relativeColumnIndex < 0 || relativeColumnIndex >=width) {
- throw new IllegalArgumentException("column index out of range");
- }
- int oneDimensionalIndex = relativeRowIndex * width + relativeColumnIndex;
- return _values[oneDimensionalIndex];
- }
- @Override
+ if (relativeRowIndex < 0 || relativeRowIndex >=getHeight()) {
+ throw new IllegalArgumentException("row index out of range");
+ }
+ int width = getWidth();
+ if (relativeColumnIndex < 0 || relativeColumnIndex >=width) {
+ throw new IllegalArgumentException("column index out of range");
+ }
+ int oneDimensionalIndex = relativeRowIndex * width + relativeColumnIndex;
+ return _values[oneDimensionalIndex];
+ }
+ @Override
public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) {
- if (relFirstRowIx < 0 || relFirstColIx < 0
- || relLastRowIx >= getHeight() || relLastColIx >= getWidth()) {
- throw new RuntimeException("Operation not implemented on this mock object");
- }
-
- if (relFirstRowIx == 0 && relFirstColIx == 0
- && relLastRowIx == getHeight()-1 && relLastColIx == getWidth()-1) {
- return this;
- }
- ValueEval[] values = transpose(_values, getWidth(), relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
- return new MockAreaEval(getFirstRow() + relFirstRowIx, getFirstColumn() + relFirstColIx,
- getFirstRow() + relLastRowIx, getFirstColumn() + relLastColIx, values);
- }
- private static ValueEval[] transpose(ValueEval[] srcValues, int srcWidth,
- int relFirstRowIx, int relLastRowIx,
- int relFirstColIx, int relLastColIx) {
- int height = relLastRowIx - relFirstRowIx + 1;
- int width = relLastColIx - relFirstColIx + 1;
- ValueEval[] result = new ValueEval[height * width];
- for (int r=0; r<height; r++) {
- int srcRowIx = r + relFirstRowIx;
- for (int c=0; c<width; c++) {
- int srcColIx = c + relFirstColIx;
- int destIx = r * width + c;
- int srcIx = srcRowIx * srcWidth + srcColIx;
- result[destIx] = srcValues[srcIx];
- }
- }
- return result;
- }
- @Override
+ if (relFirstRowIx < 0 || relFirstColIx < 0
+ || relLastRowIx >= getHeight() || relLastColIx >= getWidth()) {
+ throw new RuntimeException("Operation not implemented on this mock object");
+ }
+
+ if (relFirstRowIx == 0 && relFirstColIx == 0
+ && relLastRowIx == getHeight()-1 && relLastColIx == getWidth()-1) {
+ return this;
+ }
+ ValueEval[] values = transpose(_values, getWidth(), relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
+ return new MockAreaEval(getFirstRow() + relFirstRowIx, getFirstColumn() + relFirstColIx,
+ getFirstRow() + relLastRowIx, getFirstColumn() + relLastColIx, values);
+ }
+ private static ValueEval[] transpose(ValueEval[] srcValues, int srcWidth,
+ int relFirstRowIx, int relLastRowIx,
+ int relFirstColIx, int relLastColIx) {
+ int height = relLastRowIx - relFirstRowIx + 1;
+ int width = relLastColIx - relFirstColIx + 1;
+ ValueEval[] result = new ValueEval[height * width];
+ for (int r=0; r<height; r++) {
+ int srcRowIx = r + relFirstRowIx;
+ for (int c=0; c<width; c++) {
+ int srcColIx = c + relFirstColIx;
+ int destIx = r * width + c;
+ int srcIx = srcRowIx * srcWidth + srcColIx;
+ result[destIx] = srcValues[srcIx];
+ }
+ }
+ return result;
+ }
+ @Override
public TwoDEval getRow(int rowIndex) {
- if (rowIndex >= getHeight()) {
- throw new IllegalArgumentException("Invalid rowIndex " + rowIndex
- + ". Allowable range is (0.." + getHeight() + ").");
- }
- ValueEval[] values = new ValueEval[getWidth()];
- for (int i = 0; i < values.length; i++) {
- values[i] = getRelativeValue(rowIndex, i);
- }
- return new MockAreaEval(rowIndex, getFirstColumn(), rowIndex, getLastColumn(), values);
- }
- @Override
+ if (rowIndex >= getHeight()) {
+ throw new IllegalArgumentException("Invalid rowIndex " + rowIndex
+ + ". Allowable range is (0.." + getHeight() + ").");
+ }
+ ValueEval[] values = new ValueEval[getWidth()];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = getRelativeValue(rowIndex, i);
+ }
+ return new MockAreaEval(rowIndex, getFirstColumn(), rowIndex, getLastColumn(), values);
+ }
+ @Override
public TwoDEval getColumn(int columnIndex) {
- if (columnIndex >= getWidth()) {
- throw new IllegalArgumentException("Invalid columnIndex " + columnIndex
- + ". Allowable range is (0.." + getWidth() + ").");
- }
- ValueEval[] values = new ValueEval[getHeight()];
- for (int i = 0; i < values.length; i++) {
- values[i] = getRelativeValue(i, columnIndex);
- }
- return new MockAreaEval(getFirstRow(), columnIndex, getLastRow(), columnIndex, values);
- }
- }
-
- private static final class MockRefEval extends RefEvalBase {
- private final ValueEval _value;
- public MockRefEval(RefPtg ptg, ValueEval value) {
- super(-1, -1, ptg.getRow(), ptg.getColumn());
- _value = value;
- }
- public MockRefEval(Ref3DPtg ptg, ValueEval value) {
- super(-1, -1, ptg.getRow(), ptg.getColumn());
- _value = value;
- }
- @Override
+ if (columnIndex >= getWidth()) {
+ throw new IllegalArgumentException("Invalid columnIndex " + columnIndex
+ + ". Allowable range is (0.." + getWidth() + ").");
+ }
+ ValueEval[] values = new ValueEval[getHeight()];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = getRelativeValue(i, columnIndex);
+ }
+ return new MockAreaEval(getFirstRow(), columnIndex, getLastRow(), columnIndex, values);
+ }
+ }
+
+ private static final class MockRefEval extends RefEvalBase {
+ private final ValueEval _value;
+ public MockRefEval(RefPtg ptg, ValueEval value) {
+ super(-1, -1, ptg.getRow(), ptg.getColumn());
+ _value = value;
+ }
+ public MockRefEval(Ref3DPtg ptg, ValueEval value) {
+ super(-1, -1, ptg.getRow(), ptg.getColumn());
+ _value = value;
+ }
+ @Override
public ValueEval getInnerValueEval(int sheetIndex) {
- return _value;
- }
- @Override
+ return _value;
+ }
+ @Override
public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) {
- throw new RuntimeException("Operation not implemented on this mock object");
- }
- }
+ throw new RuntimeException("Operation not implemented on this mock object");
+ }
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java Sat May 22 20:56:44 2021
@@ -29,74 +29,74 @@ import org.apache.poi.ss.formula.eval.Va
*/
public final class NumericFunctionInvoker {
- private NumericFunctionInvoker() {
- // no instances of this class
- }
-
- private static final class NumericEvalEx extends Exception {
- public NumericEvalEx(String msg) {
- super(msg);
- }
- }
-
- /**
- * Invokes the specified function with the arguments.
- * <p>
- * Assumes that the cell coordinate parameters of
- * <code>Function.evaluate(args, srcCellRow, srcCellCol)</code>
- * are not required.
- * <p>
- * This method cannot be used for confirming error return codes. Any non-numeric evaluation
- * result causes the current junit test to fail.
- */
- public static double invoke(Function f, ValueEval[] args) {
- return invoke(f, args, -1, -1);
- }
- /**
- * Invokes the specified operator with the arguments.
- * <p>
- * This method cannot be used for confirming error return codes. Any non-numeric evaluation
- * result causes the current junit test to fail.
- */
- public static double invoke(Function f, ValueEval[] args, int srcCellRow, int srcCellCol) {
- try {
- return invokeInternal(f, args, srcCellRow, srcCellCol);
- } catch (NumericEvalEx e) {
- fail("Evaluation of function (" + f.getClass().getName() + ") failed: " + e.getMessage());
- return -1;
- }
- }
- /**
- * Formats nicer error messages for the junit output
- */
- private static double invokeInternal(Function target, ValueEval[] args, int srcCellRow, int srcCellCol)
- throws NumericEvalEx {
- ValueEval evalResult;
- try {
- evalResult = target.evaluate(args, srcCellRow, (short)srcCellCol);
- } catch (NotImplementedException e) {
- throw new NumericEvalEx("Not implemented:" + e.getMessage());
- }
-
- if(evalResult == null) {
- throw new NumericEvalEx("Result object was null");
- }
- if(evalResult instanceof ErrorEval) {
- ErrorEval ee = (ErrorEval) evalResult;
- throw new NumericEvalEx(formatErrorMessage(ee));
- }
- if(!(evalResult instanceof NumericValueEval)) {
- throw new NumericEvalEx("Result object type (" + evalResult.getClass().getName()
- + ") is invalid. Expected implementor of ("
- + NumericValueEval.class.getName() + ")");
- }
-
- NumericValueEval result = (NumericValueEval) evalResult;
- return result.getNumberValue();
- }
-
- private static String formatErrorMessage(ErrorEval ee) {
- boolean b = (ee == ErrorEval.VALUE_INVALID || ee.getErrorCode() == ErrorEval.VALUE_INVALID.getErrorCode());
- return b ? "Error code: #VALUE! (invalid value)" : "Error code=" + ee.getErrorCode();
- }
+ private NumericFunctionInvoker() {
+ // no instances of this class
+ }
+
+ private static final class NumericEvalEx extends Exception {
+ public NumericEvalEx(String msg) {
+ super(msg);
+ }
+ }
+
+ /**
+ * Invokes the specified function with the arguments.
+ * <p>
+ * Assumes that the cell coordinate parameters of
+ * <code>Function.evaluate(args, srcCellRow, srcCellCol)</code>
+ * are not required.
+ * <p>
+ * This method cannot be used for confirming error return codes. Any non-numeric evaluation
+ * result causes the current junit test to fail.
+ */
+ public static double invoke(Function f, ValueEval[] args) {
+ return invoke(f, args, -1, -1);
+ }
+ /**
+ * Invokes the specified operator with the arguments.
+ * <p>
+ * This method cannot be used for confirming error return codes. Any non-numeric evaluation
+ * result causes the current junit test to fail.
+ */
+ public static double invoke(Function f, ValueEval[] args, int srcCellRow, int srcCellCol) {
+ try {
+ return invokeInternal(f, args, srcCellRow, srcCellCol);
+ } catch (NumericEvalEx e) {
+ fail("Evaluation of function (" + f.getClass().getName() + ") failed: " + e.getMessage());
+ return -1;
+ }
+ }
+ /**
+ * Formats nicer error messages for the junit output
+ */
+ private static double invokeInternal(Function target, ValueEval[] args, int srcCellRow, int srcCellCol)
+ throws NumericEvalEx {
+ ValueEval evalResult;
+ try {
+ evalResult = target.evaluate(args, srcCellRow, (short)srcCellCol);
+ } catch (NotImplementedException e) {
+ throw new NumericEvalEx("Not implemented:" + e.getMessage());
+ }
+
+ if(evalResult == null) {
+ throw new NumericEvalEx("Result object was null");
+ }
+ if(evalResult instanceof ErrorEval) {
+ ErrorEval ee = (ErrorEval) evalResult;
+ throw new NumericEvalEx(formatErrorMessage(ee));
+ }
+ if(!(evalResult instanceof NumericValueEval)) {
+ throw new NumericEvalEx("Result object type (" + evalResult.getClass().getName()
+ + ") is invalid. Expected implementor of ("
+ + NumericValueEval.class.getName() + ")");
+ }
+
+ NumericValueEval result = (NumericValueEval) evalResult;
+ return result.getNumberValue();
+ }
+
+ private static String formatErrorMessage(ErrorEval ee) {
+ boolean b = (ee == ErrorEval.VALUE_INVALID || ee.getErrorCode() == ErrorEval.VALUE_INVALID.getErrorCode());
+ return b ? "Error code: #VALUE! (invalid value)" : "Error code=" + ee.getErrorCode();
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAddress.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAddress.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAddress.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAddress.java Sat May 22 20:56:44 2021
@@ -36,7 +36,7 @@ final class TestAddress {
String formulaText = "ADDRESS(1,2)";
confirmResult(fe, cell, formulaText, "$B$1");
- formulaText = "ADDRESS(1,2,)"; // with explicitly empty third parameter
+ formulaText = "ADDRESS(1,2,)"; // with explicitly empty third parameter
confirmResult(fe, cell, formulaText, "$B$1");
formulaText = "ADDRESS(22,44)";
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAverage.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAverage.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAverage.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestAverage.java Sat May 22 20:56:44 2021
@@ -31,71 +31,71 @@ import org.junit.jupiter.api.Test;
*/
final class TestAverage {
- private static ValueEval invokeAverage(ValueEval[] args) {
- return AggregateFunction.AVERAGE.evaluate(args, -1, (short)-1);
- }
-
- private void confirmAverage(ValueEval[] args, double expected) {
- ValueEval result = invokeAverage(args);
- assertEquals(NumberEval.class, result.getClass());
- assertEquals(expected, ((NumberEval)result).getNumberValue(), 0);
- }
-
- private void confirmAverage(ValueEval[] args, ErrorEval expectedError) {
- ValueEval result = invokeAverage(args);
- assertEquals(ErrorEval.class, result.getClass());
- assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode());
- }
-
- @Test
- void testBasic() {
-
- ValueEval[] values = {
- new NumberEval(1),
- new NumberEval(2),
- new NumberEval(3),
- new NumberEval(4),
- };
-
- confirmAverage(values, 2.5);
-
- values = new ValueEval[] {
- new NumberEval(1),
- new NumberEval(2),
- BlankEval.instance,
- new NumberEval(3),
- BlankEval.instance,
- new NumberEval(4),
- BlankEval.instance,
- };
-
- confirmAverage(values, 2.5);
- }
-
- /**
- * Valid cases where values are not pure numbers
- */
- @Test
- void testUnusualArgs() {
- ValueEval[] values = {
- new NumberEval(1),
- new NumberEval(2),
- BoolEval.TRUE,
- BoolEval.FALSE,
- };
-
- confirmAverage(values, 1.0);
-
- }
-
- @Test
- void testErrors() {
- ValueEval[] values = {
- new NumberEval(1),
- ErrorEval.NAME_INVALID,
- new NumberEval(3),
- ErrorEval.DIV_ZERO,
- };
- confirmAverage(values, ErrorEval.NAME_INVALID);
- }
+ private static ValueEval invokeAverage(ValueEval[] args) {
+ return AggregateFunction.AVERAGE.evaluate(args, -1, (short)-1);
+ }
+
+ private void confirmAverage(ValueEval[] args, double expected) {
+ ValueEval result = invokeAverage(args);
+ assertEquals(NumberEval.class, result.getClass());
+ assertEquals(expected, ((NumberEval)result).getNumberValue(), 0);
+ }
+
+ private void confirmAverage(ValueEval[] args, ErrorEval expectedError) {
+ ValueEval result = invokeAverage(args);
+ assertEquals(ErrorEval.class, result.getClass());
+ assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode());
+ }
+
+ @Test
+ void testBasic() {
+
+ ValueEval[] values = {
+ new NumberEval(1),
+ new NumberEval(2),
+ new NumberEval(3),
+ new NumberEval(4),
+ };
+
+ confirmAverage(values, 2.5);
+
+ values = new ValueEval[] {
+ new NumberEval(1),
+ new NumberEval(2),
+ BlankEval.instance,
+ new NumberEval(3),
+ BlankEval.instance,
+ new NumberEval(4),
+ BlankEval.instance,
+ };
+
+ confirmAverage(values, 2.5);
+ }
+
+ /**
+ * Valid cases where values are not pure numbers
+ */
+ @Test
+ void testUnusualArgs() {
+ ValueEval[] values = {
+ new NumberEval(1),
+ new NumberEval(2),
+ BoolEval.TRUE,
+ BoolEval.FALSE,
+ };
+
+ confirmAverage(values, 1.0);
+
+ }
+
+ @Test
+ void testErrors() {
+ ValueEval[] values = {
+ new NumberEval(1),
+ ErrorEval.NAME_INVALID,
+ new NumberEval(3),
+ ErrorEval.DIV_ZERO,
+ };
+ confirmAverage(values, ErrorEval.NAME_INVALID);
+ }
}
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestBin2Dec.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestBin2Dec.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestBin2Dec.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestBin2Dec.java Sat May 22 20:56:44 2021
@@ -35,15 +35,15 @@ import org.junit.jupiter.api.Test;
final class TestBin2Dec {
private static ValueEval invokeValue(String number1) {
- ValueEval[] args = new ValueEval[] { new StringEval(number1) };
- return new Bin2Dec().evaluate(args, -1, -1);
- }
+ ValueEval[] args = new ValueEval[] { new StringEval(number1) };
+ return new Bin2Dec().evaluate(args, -1, -1);
+ }
private static void confirmValue(String msg, String number1, String expected) {
- ValueEval result = invokeValue(number1);
- assertEquals(NumberEval.class, result.getClass(), "Had: " + result);
- assertEquals(expected, ((NumberEval) result).getStringValue(), msg);
- }
+ ValueEval result = invokeValue(number1);
+ assertEquals(NumberEval.class, result.getClass(), "Had: " + result);
+ assertEquals(expected, ((NumberEval) result).getStringValue(), msg);
+ }
private static void confirmValueError(String msg, String number1, ErrorEval numError) {
ValueEval result = invokeValue(number1);
@@ -52,12 +52,12 @@ final class TestBin2Dec {
}
@Test
- void testBasic() {
- confirmValue("Converts binary '00101' to decimal (5)", "00101", "5");
- confirmValue("Converts binary '1111111111' to decimal (-1)", "1111111111", "-1");
- confirmValue("Converts binary '1111111110' to decimal (-2)", "1111111110", "-2");
+ void testBasic() {
+ confirmValue("Converts binary '00101' to decimal (5)", "00101", "5");
+ confirmValue("Converts binary '1111111111' to decimal (-1)", "1111111111", "-1");
+ confirmValue("Converts binary '1111111110' to decimal (-2)", "1111111110", "-2");
confirmValue("Converts binary '0111111111' to decimal (511)", "0111111111", "511");
- }
+ }
@Test
void testErrors() {
Modified: poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java
URL: http://svn.apache.org/viewvc/poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java?rev=1890120&r1=1890119&r2=1890120&view=diff
==============================================================================
--- poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java (original)
+++ poi/trunk/poi/src/test/java/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java Sat May 22 20:56:44 2021
@@ -63,9 +63,9 @@ final class TestCalendarFieldFunction {
@Test
void testRounding() {
- // 41484.999994200 = 23:59:59,499
- // 41484.9999942129 = 23:59:59,500 (but sub-milliseconds are below 0.5 (0.49999453965575), XLS-second results in 59)
- // 41484.9999942130 = 23:59:59,500 (sub-milliseconds are 0.50000334065408, XLS-second results in 00)
+ // 41484.999994200 = 23:59:59,499
+ // 41484.9999942129 = 23:59:59,500 (but sub-milliseconds are below 0.5 (0.49999453965575), XLS-second results in 59)
+ // 41484.9999942130 = 23:59:59,500 (sub-milliseconds are 0.50000334065408, XLS-second results in 00)
confirm("DAY(41484.999994200)", 29);
confirm("SECOND(41484.999994200)", 59);
@@ -79,16 +79,16 @@ final class TestCalendarFieldFunction {
confirm("HOUR(41484.9999942130)", 0);
confirm("MINUTE(41484.9999942130)", 0);
confirm("SECOND(41484.9999942130)", 0);
- }
+ }
@Test
void testDaylightSaving() {
- confirm("HOUR(41364.08263888890000)", 1); // 31.03.2013 01:59:00,000
- confirm("HOUR(41364.08333333330000)", 2); // 31.03.2013 02:00:00,000 (this time does not exist in TZ CET, but EXCEL does not care)
- confirm("HOUR(41364.08402777780000)", 2); // 31.03.2013 02:01:00,000
- confirm("HOUR(41364.12430555560000)", 2); // 31.03.2013 02:59:00,000
- confirm("HOUR(41364.12500000000000)", 3); // 31.03.2013 03:00:00,000
- }
+ confirm("HOUR(41364.08263888890000)", 1); // 31.03.2013 01:59:00,000
+ confirm("HOUR(41364.08333333330000)", 2); // 31.03.2013 02:00:00,000 (this time does not exist in TZ CET, but EXCEL does not care)
+ confirm("HOUR(41364.08402777780000)", 2); // 31.03.2013 02:01:00,000
+ confirm("HOUR(41364.12430555560000)", 2); // 31.03.2013 02:59:00,000
+ confirm("HOUR(41364.12500000000000)", 3); // 31.03.2013 03:00:00,000
+ }
@Test
void testBugDate() {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org