Eclipse warnings, code formatting, simplify ExcelAntWorkbookUtilFactory, always close resources, ...

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1703028 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Dominik Stadler 2015-09-14 18:40:23 +00:00
parent 909882c980
commit 37c4510343
8 changed files with 190 additions and 168 deletions

View File

@ -21,8 +21,8 @@ package org.apache.poi.ss.excelant.util;
* A simple class that encapsulates information about a cell evaluation
* from POI.
*
* @author Jon Svede ( jon [at] loquatic [dot] com )
* @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
* @author Jon Svede (jon [at] loquatic [dot] com)
* @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
*
*/
public class ExcelAntEvaluationResult {
@ -62,12 +62,12 @@ public class ExcelAntEvaluationResult {
public ExcelAntEvaluationResult( boolean completedWithError,
public ExcelAntEvaluationResult(boolean completedWithError,
boolean passed,
double retValue,
String errMessage,
double delta,
String cellId ) {
String cellId) {
evaluationCompletedWithError = completedWithError;
didPass = passed;

View File

@ -17,13 +17,28 @@
package org.apache.poi.ss.excelant.util;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.FreeRefFunction;
import org.apache.poi.ss.formula.udf.AggregatingUDFFinder;
import org.apache.poi.ss.formula.udf.DefaultUDFFinder;
import org.apache.poi.ss.formula.udf.UDFFinder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaError;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -31,19 +46,12 @@ import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Typedef;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
/**
* A general utility class that abstracts the POI details of loading the
* workbook, accessing and updating cells.
*
* @author Jon Svede ( jon [at] loquatic [dot] com )
* @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
* @author Jon Svede (jon [at] loquatic [dot] com)
* @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
*
*/
public class ExcelAntWorkbookUtil extends Typedef {
@ -52,7 +60,7 @@ public class ExcelAntWorkbookUtil extends Typedef {
private Workbook workbook;
private final HashMap<String, FreeRefFunction> xlsMacroList = new HashMap<String, FreeRefFunction>();
private final Map<String, FreeRefFunction> xlsMacroList = new HashMap<String, FreeRefFunction>();
/**
* Constructs an instance using a String that contains the fully qualified
@ -95,7 +103,7 @@ public class ExcelAntWorkbookUtil extends Typedef {
+ ". Make sure the path and file permissions are correct.", e);
}
return workbook ;
return workbook;
}
/**
@ -106,11 +114,11 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @throws InstantiationException
* @throws IllegalAccessException
*/
public void addFunction( String name, String clazzName ) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clazzInst = Class.forName( clazzName ) ;
Object newInst = clazzInst.newInstance() ;
if( newInst instanceof FreeRefFunction ) {
addFunction( name, (FreeRefFunction)newInst ) ;
public void addFunction(String name, String clazzName) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class<?> clazzInst = Class.forName(clazzName);
Object newInst = clazzInst.newInstance();
if(newInst instanceof FreeRefFunction) {
addFunction(name, (FreeRefFunction)newInst);
}
}
@ -136,13 +144,10 @@ public class ExcelAntWorkbookUtil extends Typedef {
String[] names = new String[xlsMacroList.size()];
FreeRefFunction[] functions = new FreeRefFunction[xlsMacroList.size()];
Iterator<String> keysIt = xlsMacroList.keySet().iterator();
int x = 0;
while (keysIt.hasNext()) {
String name = keysIt.next();
FreeRefFunction function = xlsMacroList.get(name);
names[x] = name;
functions[x] = function;
for(Map.Entry<String, FreeRefFunction> entry : xlsMacroList.entrySet()) {
names[x] = entry.getKey();
functions[x] = entry.getValue();
}
UDFFinder udff1 = new DefaultUDFFinder(names, functions);
@ -159,26 +164,26 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @param fileName
* @return
*/
protected FormulaEvaluator getEvaluator( String fileName ) {
FormulaEvaluator evaluator ;
protected FormulaEvaluator getEvaluator(String fileName) {
FormulaEvaluator evaluator;
if (fileName.endsWith(".xlsx")) {
if( xlsMacroList.size() > 0 ) {
evaluator = XSSFFormulaEvaluator.create( (XSSFWorkbook) workbook,
if(xlsMacroList.size() > 0) {
evaluator = XSSFFormulaEvaluator.create((XSSFWorkbook) workbook,
null,
getFunctions() ) ;
getFunctions());
}
evaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
} else {
if( xlsMacroList.size() > 0 ) {
evaluator = HSSFFormulaEvaluator.create( (HSSFWorkbook)workbook,
if(xlsMacroList.size() > 0) {
evaluator = HSSFFormulaEvaluator.create((HSSFWorkbook)workbook,
null,
getFunctions() ) ;
getFunctions());
}
evaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook);
}
return evaluator ;
return evaluator;
}
@ -206,16 +211,16 @@ public class ExcelAntWorkbookUtil extends Typedef {
*
* @return
*/
public ArrayList<String> getSheets() {
ArrayList<String> sheets = new ArrayList<String>() ;
public List<String> getSheets() {
ArrayList<String> sheets = new ArrayList<String>();
int sheetCount = workbook.getNumberOfSheets() ;
int sheetCount = workbook.getNumberOfSheets();
for( int x=0; x<sheetCount; x++ ) {
sheets.add( workbook.getSheetName( x ) ) ;
for(int x=0; x<sheetCount; x++) {
sheets.add(workbook.getSheetName(x));
}
return sheets ;
return sheets;
}
/**
@ -241,7 +246,7 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @param cellName
* @param value
*/
public void setStringValue( String cellName, String value ) {
public void setStringValue(String cellName, String value) {
Cell cell = getCell(cellName);
cell.setCellValue(value);
}
@ -252,9 +257,9 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @param cellName
* @param formula
*/
public void setFormulaValue( String cellName, String formula ) {
public void setFormulaValue(String cellName, String formula) {
Cell cell = getCell(cellName);
cell.setCellFormula( formula );
cell.setCellFormula(formula);
}
/**
@ -262,9 +267,9 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @param cellName
* @param date
*/
public void setDateValue( String cellName, Date date ) {
public void setDateValue(String cellName, Date date) {
Cell cell = getCell(cellName);
cell.setCellValue( date ) ;
cell.setCellValue(date);
}
/**
* Uses a String in standard Excel format (SheetName!CellId) to locate a
@ -281,7 +286,7 @@ public class ExcelAntWorkbookUtil extends Typedef {
Cell cell = getCell(cellName);
FormulaEvaluator evaluator = getEvaluator( excelFileName );
FormulaEvaluator evaluator = getEvaluator(excelFileName);
CellValue resultOfEval = evaluator.evaluate(cell);
@ -294,20 +299,19 @@ public class ExcelAntWorkbookUtil extends Typedef {
evalResults = new ExcelAntEvaluationResult(false, false,
resultOfEval.getNumberValue(),
"Results was out of range based on precision " + " of "
+ precision + ". Delta was actually " + delta, delta, cellName );
+ precision + ". Delta was actually " + delta, delta, cellName);
} else {
evalResults = new ExcelAntEvaluationResult(false, true,
resultOfEval.getNumberValue(),
"Evaluation passed without error within in range.", delta, cellName );
"Evaluation passed without error within in range.", delta, cellName);
}
} else {
String errorMeaning = null ;
String errorMeaning = null;
try {
errorMeaning = ErrorConstants.getText( resultOfEval
.getErrorValue() ) ;
} catch( IllegalArgumentException iae ) {
errorMeaning = FormulaError.forInt(resultOfEval.getErrorValue()).getString();
} catch(IllegalArgumentException iae) {
errorMeaning = "unknown error code: " +
Byte.toString( resultOfEval.getErrorValue() ) ;
Byte.toString(resultOfEval.getErrorValue());
}
evalResults = new ExcelAntEvaluationResult(true, false,
@ -315,7 +319,7 @@ public class ExcelAntWorkbookUtil extends Typedef {
"Evaluation failed due to an evaluation error of "
+ resultOfEval.getErrorValue()
+ " which is "
+ errorMeaning, 0, cellName );
+ errorMeaning, 0, cellName);
}
return evalResults;
@ -327,9 +331,9 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @param cellName
* @return
*/
public String getCellAsString( String cellName ) {
Cell cell = getCell( cellName ) ;
return cell.getStringCellValue() ;
public String getCellAsString(String cellName) {
Cell cell = getCell(cellName);
return cell.getStringCellValue();
}
@ -339,9 +343,9 @@ public class ExcelAntWorkbookUtil extends Typedef {
* @param cellName
* @return
*/
public double getCellAsDouble( String cellName ) {
Cell cell = getCell( cellName ) ;
return cell.getNumericCellValue() ;
public double getCellAsDouble(String cellName) {
Cell cell = getCell(cellName);
return cell.getNumericCellValue();
}
/**
* Returns a cell reference based on a String in standard Excel format
@ -363,14 +367,14 @@ public class ExcelAntWorkbookUtil extends Typedef {
int colIdx = cellRef.getCol();
Row row = sheet.getRow(rowIdx);
if( row == null ) {
row = sheet.createRow( rowIdx ) ;
if(row == null) {
row = sheet.createRow(rowIdx);
}
Cell cell = row.getCell(colIdx);
if( cell == null ) {
cell = row.createCell( colIdx ) ;
if(cell == null) {
cell = row.createCell(colIdx);
}
return cell;

View File

@ -18,24 +18,22 @@
package org.apache.poi.ss.excelant.util;
import java.util.HashMap;
import java.util.Map;
/**
* This is a factory class maps file names to WorkbookUtil instances. This
* helps ExcelAnt be more efficient when being run many times in an Ant build.
*
* @author Jon Svede ( jon [at] loquatic [dot] com )
* @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
* @author Jon Svede (jon [at] loquatic [dot] com)
* @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
*
*/
public class ExcelAntWorkbookUtilFactory {
public final class ExcelAntWorkbookUtilFactory {
private static HashMap<String, ExcelAntWorkbookUtil> workbookUtilMap ;
private static ExcelAntWorkbookUtilFactory factory ;
private static Map<String, ExcelAntWorkbookUtil> workbookUtilMap;
private ExcelAntWorkbookUtilFactory() {
workbookUtilMap = new HashMap<String, ExcelAntWorkbookUtil>() ;
}
/**
@ -45,19 +43,17 @@ public class ExcelAntWorkbookUtilFactory {
* @param fileName
* @return
*/
public static ExcelAntWorkbookUtil getInstance( String fileName ) {
if( factory == null ) {
factory = new ExcelAntWorkbookUtilFactory() ;
public static ExcelAntWorkbookUtil getInstance(String fileName) {
if(workbookUtilMap == null) {
workbookUtilMap = new HashMap<String, ExcelAntWorkbookUtil>();
}
if( workbookUtilMap != null &&
workbookUtilMap.containsKey( fileName ) ) {
return workbookUtilMap.get( fileName ) ;
if(workbookUtilMap != null &&
workbookUtilMap.containsKey(fileName)) {
return workbookUtilMap.get(fileName);
}
ExcelAntWorkbookUtil wbu = new ExcelAntWorkbookUtil( fileName ) ;
workbookUtilMap.put( fileName, wbu ) ;
return wbu ;
ExcelAntWorkbookUtil wbu = new ExcelAntWorkbookUtil(fileName);
workbookUtilMap.put(fileName, wbu);
return wbu;
}
}

View File

@ -16,52 +16,61 @@
==================================================================== */
package org.apache.poi.ss.excelant.util;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class TestExcelAntEvaluationResult extends TestCase {
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestExcelAntEvaluationResult {
private ExcelAntEvaluationResult fixture;
private ExcelAntEvaluationResult fixture ;
private boolean completedWithError = false ;
private boolean passed = false ;
private double retValue = 1.1 ;
private String errMessage = "error message" ;
private double delta = 2.2 ;
private String cellId = "testCell!$F$1" ;
private boolean completedWithError = false;
private boolean passed = false;
private double retValue = 1.1;
private String errMessage = "error message";
private double delta = 2.2;
private String cellId = "testCell!$F$1";
@Before
public void setUp() {
fixture = new ExcelAntEvaluationResult( completedWithError,
fixture = new ExcelAntEvaluationResult(completedWithError,
passed,
retValue,
errMessage,
delta,
cellId ) ;
cellId);
}
@After
public void tearDown() {
fixture = null ;
fixture = null;
}
@Test
public void testCompletedWithErrorMessage() {
String errMsg = fixture.getErrorMessage() ;
assertNotNull( errMsg ) ;
assertEquals( errMsg, errMessage ) ;
String errMsg = fixture.getErrorMessage();
assertNotNull(errMsg);
assertEquals(errMsg, errMessage);
}
@Test
public void testPassed() {
boolean passedValue = fixture.didTestPass() ;
assertEquals( passedValue, passed ) ;
boolean passedValue = fixture.didTestPass();
assertEquals(passedValue, passed);
}
@Test
public void testDelta() {
double deltaValue = fixture.getDelta() ;
assertEquals(deltaValue, delta, 0.0 ) ;
double deltaValue = fixture.getDelta();
assertEquals(deltaValue, delta, 0.0);
}
@Test
public void testCellId() {
String cellIdValue = fixture.getCellName() ;
assertNotNull( cellIdValue ) ;
assertEquals( cellIdValue, cellId ) ;
String cellIdValue = fixture.getCellName();
assertNotNull(cellIdValue);
assertEquals(cellIdValue, cellId);
}
}

View File

@ -19,10 +19,8 @@ package org.apache.poi.ss.excelant.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import junit.framework.TestCase;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.examples.formula.CalculateMortgageFunction;
@ -34,6 +32,8 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.tools.ant.BuildException;
import junit.framework.TestCase;
public class TestExcelAntWorkbookUtil extends TestCase {
private static final String mortgageCalculatorFileName =
@ -198,9 +198,10 @@ public class TestExcelAntWorkbookUtil extends TestCase {
precision);
//System.out.println(result);
assertTrue(result.toString().contains("evaluationCompletedWithError=false"));
assertTrue(result.toString().contains("returnValue=790.79"));
assertTrue(result.toString().contains("cellName='MortgageCalculator'!B4"));
assertTrue("Had:" + result.toString(), result.toString().contains("evaluationCompletedWithError=false"));
assertTrue("Had:" + result.toString(), result.toString().contains("returnValue=790.79"));
assertTrue("Had:" + result.toString(), result.toString().contains("cellName='MortgageCalculator'!B4"));
assertFalse(result.toString().contains("#N/A"));
assertFalse(result.evaluationCompleteWithError());
assertTrue(result.didTestPass());
@ -219,9 +220,10 @@ public class TestExcelAntWorkbookUtil extends TestCase {
precision);
//System.out.println(result);
assertTrue(result.toString().contains("evaluationCompletedWithError=false"));
assertTrue(result.toString().contains("returnValue=790.79"));
assertTrue(result.toString().contains("cellName='MortgageCalculator'!B4"));
assertTrue("Had:" + result.toString(), result.toString().contains("evaluationCompletedWithError=false"));
assertTrue("Had:" + result.toString(), result.toString().contains("returnValue=790.79"));
assertTrue("Had:" + result.toString(), result.toString().contains("cellName='MortgageCalculator'!B4"));
assertFalse("Should not see an error, but had:" + result.toString(), result.toString().contains("#"));
assertFalse(result.evaluationCompleteWithError());
assertFalse(result.didTestPass());
@ -240,9 +242,10 @@ public class TestExcelAntWorkbookUtil extends TestCase {
precision);
System.out.println(result);
assertTrue(result.toString().contains("evaluationCompletedWithError=true"));
assertTrue(result.toString().contains("returnValue=0.0"));
assertTrue(result.toString().contains("cellName='ErrorCell'!A1"));
assertTrue("Had:" + result.toString(), result.toString().contains("evaluationCompletedWithError=true"));
assertTrue("Had:" + result.toString(), result.toString().contains("returnValue=0.0"));
assertTrue("Had:" + result.toString(), result.toString().contains("cellName='ErrorCell'!A1"));
assertTrue("Had:" + result.toString(), result.toString().contains("#N/A"));
assertTrue(result.evaluationCompleteWithError());
assertFalse(result.didTestPass());
@ -252,7 +255,7 @@ public class TestExcelAntWorkbookUtil extends TestCase {
fixture = new ExcelAntWorkbookUtilTestHelper(
mortgageCalculatorFileName);
ArrayList<String> sheets = fixture.getSheets();
List<String> sheets = fixture.getSheets();
assertNotNull(sheets);
assertEquals(sheets.size(), 3);

View File

@ -16,19 +16,21 @@
==================================================================== */
package org.apache.poi.ss.excelant.util;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.poi.ss.excelant.BuildFileTest;
import org.junit.Test;
/**
* Tests for the ExcelAntWorbookUtilFactory.
*
* @author Jon Svede ( jon [at] loquatic [dot] com )
* @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov )
* @author Jon Svede (jon [at] loquatic [dot] com)
* @author Brian Bush (brian [dot] bush [at] nrel [dot] gov)
*
*/
public class TestExcelAntWorkbookUtilFactory extends TestCase{
public class TestExcelAntWorkbookUtilFactory {
private static final String mortgageCalculatorWorkbookFile =
BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
@ -38,13 +40,12 @@ public class TestExcelAntWorkbookUtilFactory extends TestCase{
* Simple test to determine if the factory properly returns an non-null
* instance of the ExcelAntWorkbookUtil class.
*/
@Test
public void testGetNewWorkbookUtilInstance() {
ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance(
mortgageCalculatorWorkbookFile ) ;
assertNotNull( util ) ;
mortgageCalculatorWorkbookFile) ;
assertNotNull(util) ;
}
@ -53,19 +54,19 @@ public class TestExcelAntWorkbookUtilFactory extends TestCase{
* to an ExcelAnt WorkbookUtil when two different Strings, that point to
* the same resource, are passed in.
*/
@Test
public void testVerifyEquivalence() {
String sameFileName = BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ;
ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance(
mortgageCalculatorWorkbookFile ) ;
mortgageCalculatorWorkbookFile) ;
ExcelAntWorkbookUtil util2 = ExcelAntWorkbookUtilFactory.getInstance(
sameFileName ) ;
sameFileName) ;
assertNotNull( util ) ;
assertNotNull( util2 ) ;
assertNotNull(util) ;
assertNotNull(util2) ;
assertEquals( util, util2 ) ;
assertEquals(util, util2) ;
}
}

View File

@ -53,40 +53,48 @@ final class FunctionMetadataReader {
private static final Set<String> DIGIT_ENDING_FUNCTION_NAMES_SET = new HashSet<String>(Arrays.asList(DIGIT_ENDING_FUNCTION_NAMES));
public static FunctionMetadataRegistry createRegistry() {
InputStream is = FunctionMetadataReader.class.getResourceAsStream(METADATA_FILE_NAME);
if (is == null) {
throw new RuntimeException("resource '" + METADATA_FILE_NAME + "' not found");
}
try {
InputStream is = FunctionMetadataReader.class.getResourceAsStream(METADATA_FILE_NAME);
if (is == null) {
throw new RuntimeException("resource '" + METADATA_FILE_NAME + "' not found");
}
try {
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
try {
FunctionDataBuilder fdb = new FunctionDataBuilder(400);
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
if (line.length() < 1 || line.charAt(0) == '#') {
continue;
}
String trimLine = line.trim();
if (trimLine.length() < 1) {
continue;
}
processLine(fdb, line);
}
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
FunctionDataBuilder fdb = new FunctionDataBuilder(400);
try {
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
if (line.length() < 1 || line.charAt(0) == '#') {
continue;
}
String trimLine = line.trim();
if (trimLine.length() < 1) {
continue;
}
processLine(fdb, line);
}
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fdb.build();
return fdb.build();
} finally {
br.close();
}
} finally {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void processLine(FunctionDataBuilder fdb, String line) {

View File

@ -31,6 +31,7 @@ import org.junit.Test;
* @author Evgeniy Berlog
* @date 25.06.12
*/
@SuppressWarnings("deprecation")
public class TestText {
@Test