From: Andreas Beeker Date: Sun, 1 Nov 2015 03:23:16 +0000 (+0000) Subject: findbugs fixes X-Git-Tag: REL_3_14_BETA1~191 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=5fd534c44bb95d55c3b6b84a2e11df35221f48b4;p=poi.git findbugs fixes close resources in tests git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1711712 13f79535-47bb-0310-9956-ffa450edef68 --- diff --git a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java b/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java index e3b899373e..375982b876 100644 --- a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java +++ b/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java @@ -157,11 +157,13 @@ public class ZipSecureFile extends ZipFile { * @throws IOException if an I/O error has occurred * @throws IllegalStateException if the zip file has been closed */ + @SuppressWarnings("resource") public InputStream getInputStream(ZipEntry entry) throws IOException { InputStream zipIS = super.getInputStream(entry); return addThreshold(zipIS); } + @SuppressWarnings("resource") public static ThresholdInputStream addThreshold(InputStream zipIS) throws IOException { ThresholdInputStream newInner; if (zipIS instanceof InflaterInputStream) { @@ -246,7 +248,7 @@ public class ZipSecureFile extends ZipFile { throw new IOException("Zip bomb detected! The file would exceed the max. ratio of compressed file size to the size of the expanded data. " + "This may indicate that the file is used to inflate memory usage and thus could pose a security risk. " + "You can adjust this limit via ZipSecureFile.setMinInflateRatio() if you need to work with files which exceed this limit. " - + "Counter: " + counter + ", cis.counter: " + (cis == null ? 0 : cis.counter) + ", ratio: " + (cis == null ? 0 : ((double)cis.counter)/counter) + + "Counter: " + counter + ", cis.counter: " + cis.counter + ", ratio: " + (((double)cis.counter)/counter) + "Limits: MIN_INFLATE_RATIO: " + MIN_INFLATE_RATIO); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java index 9533215a71..3ebedd6fae 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java @@ -19,9 +19,13 @@ package org.apache.poi.xssf.streaming; +import java.io.IOException; + import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.BaseTestRow; import org.apache.poi.xssf.SXSSFITestDataProvider; +import org.junit.After; +import org.junit.Test; /** * Tests for XSSFRow @@ -33,16 +37,18 @@ public final class TestSXSSFRow extends BaseTestRow { } - @Override - public void tearDown(){ + @After + public void tearDown() { SXSSFITestDataProvider.instance.cleanup(); } - public void testRowBounds() { + @Test + public void testRowBounds() throws IOException { baseTestRowBounds(SpreadsheetVersion.EXCEL2007.getLastRowIndex()); } - public void testCellBounds() { + @Test + public void testCellBounds() throws IOException { baseTestCellBounds(SpreadsheetVersion.EXCEL2007.getLastColumnIndex()); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java index 6540e049d5..230db006ea 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java @@ -62,7 +62,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { */ @Override @Test - public void cloneSheet() { + public void cloneSheet() throws IOException { try { super.cloneSheet(); fail("expected exception"); @@ -83,27 +83,27 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { @Test public void existingWorkbook() throws IOException { - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); - xssfWorkbook.createSheet("S1"); - SXSSFWorkbook wb = new SXSSFWorkbook(xssfWorkbook); - try { - xssfWorkbook = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - assertTrue(wb.dispose()); - - wb = new SXSSFWorkbook(xssfWorkbook); - assertEquals(1, wb.getNumberOfSheets()); - Sheet sheet = wb.getSheetAt(0); - assertNotNull(sheet); - assertEquals("S1", sheet.getSheetName()); - } finally { - assertTrue(wb.dispose()); - wb.close(); - } - + XSSFWorkbook xssfWb1 = new XSSFWorkbook(); + xssfWb1.createSheet("S1"); + @SuppressWarnings("resource") + SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); + XSSFWorkbook xssfWb2 = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); + assertTrue(wb1.dispose()); + + @SuppressWarnings("resource") + SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); + assertEquals(1, wb2.getNumberOfSheets()); + Sheet sheet = wb2.getSheetAt(0); + assertNotNull(sheet); + assertEquals("S1", sheet.getSheetName()); + assertTrue(wb2.dispose()); + xssfWb2.close(); + xssfWb1.close(); } @Test public void useSharedStringsTable() throws Exception { + @SuppressWarnings("resource") SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true); Field f = SXSSFWorkbook.class.getDeclaredField("_sharedStringSource"); @@ -137,44 +137,49 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { cell = row.getCell(2); assertNotNull(cell); assertEquals("A", cell.getStringCellValue()); + + xssfWorkbook.close(); } @Test - public void addToExistingWorkbook() { - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); - xssfWorkbook.createSheet("S1"); - Sheet sheet = xssfWorkbook.createSheet("S2"); + public void addToExistingWorkbook() throws IOException { + XSSFWorkbook xssfWb1 = new XSSFWorkbook(); + xssfWb1.createSheet("S1"); + Sheet sheet = xssfWb1.createSheet("S2"); Row row = sheet.createRow(1); Cell cell = row.createCell(1); cell.setCellValue("value 2_1_1"); - SXSSFWorkbook wb = new SXSSFWorkbook(xssfWorkbook); - xssfWorkbook = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - assertTrue(wb.dispose()); - - wb = new SXSSFWorkbook(xssfWorkbook); + @SuppressWarnings("resource") + SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); + XSSFWorkbook xssfWb2 = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); + assertTrue(wb1.dispose()); + xssfWb1.close(); + SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); // Add a row to the existing empty sheet - Sheet sheet1 = wb.getSheetAt(0); + Sheet sheet1 = wb2.getSheetAt(0); Row row1_1 = sheet1.createRow(1); Cell cell1_1_1 = row1_1.createCell(1); cell1_1_1.setCellValue("value 1_1_1"); // Add a row to the existing non-empty sheet - Sheet sheet2 = wb.getSheetAt(1); + Sheet sheet2 = wb2.getSheetAt(1); Row row2_2 = sheet2.createRow(2); Cell cell2_2_1 = row2_2.createCell(1); cell2_2_1.setCellValue("value 2_2_1"); // Add a sheet with one row - Sheet sheet3 = wb.createSheet("S3"); + Sheet sheet3 = wb2.createSheet("S3"); Row row3_1 = sheet3.createRow(1); Cell cell3_1_1 = row3_1.createCell(1); cell3_1_1.setCellValue("value 3_1_1"); - xssfWorkbook = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - assertEquals(3, xssfWorkbook.getNumberOfSheets()); + XSSFWorkbook xssfWb3 = (XSSFWorkbook) SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2); + wb2.close(); + + assertEquals(3, xssfWb3.getNumberOfSheets()); // Verify sheet 1 - sheet1 = xssfWorkbook.getSheetAt(0); + sheet1 = xssfWb3.getSheetAt(0); assertEquals("S1", sheet1.getSheetName()); assertEquals(1, sheet1.getPhysicalNumberOfRows()); row1_1 = sheet1.getRow(1); @@ -183,7 +188,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { assertNotNull(cell1_1_1); assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); // Verify sheet 2 - sheet2 = xssfWorkbook.getSheetAt(1); + sheet2 = xssfWb3.getSheetAt(1); assertEquals("S2", sheet2.getSheetName()); assertEquals(2, sheet2.getPhysicalNumberOfRows()); Row row2_1 = sheet2.getRow(1); @@ -197,7 +202,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { assertNotNull(cell2_2_1); assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); // Verify sheet 3 - sheet3 = xssfWorkbook.getSheetAt(2); + sheet3 = xssfWb3.getSheetAt(2); assertEquals("S3", sheet3.getSheetName()); assertEquals(1, sheet3.getPhysicalNumberOfRows()); row3_1 = sheet3.getRow(1); @@ -205,6 +210,9 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { cell3_1_1 = row3_1.getCell(1); assertNotNull(cell3_1_1); assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); + + xssfWb2.close(); + xssfWb3.close(); } @Test @@ -239,11 +247,12 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { assertTrue(wb.dispose()); wb.close(); - + xssfWorkbook.close(); } @Test - public void gzipSheetdataWriter(){ + public void gzipSheetdataWriter() throws IOException { + @SuppressWarnings("resource") SXSSFWorkbook wb = new SXSSFWorkbook(); wb.setCompressTempFiles(true); int rowNum = 1000; @@ -282,7 +291,7 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { } assertTrue(wb.dispose()); - + xwb.close(); } static void assertWorkbookDispose(SXSSFWorkbook wb) @@ -315,33 +324,37 @@ public final class TestSXSSFWorkbook extends BaseTestWorkbook { } } + @SuppressWarnings("resource") @Test public void workbookDispose() { - SXSSFWorkbook wb = new SXSSFWorkbook(); + SXSSFWorkbook wb1 = new SXSSFWorkbook(); // the underlying writer is SheetDataWriter - assertWorkbookDispose(wb); + assertWorkbookDispose(wb1); - wb = new SXSSFWorkbook(); - wb.setCompressTempFiles(true); + SXSSFWorkbook wb2 = new SXSSFWorkbook(); + wb2.setCompressTempFiles(true); // the underlying writer is GZIPSheetDataWriter - assertWorkbookDispose(wb); + assertWorkbookDispose(wb2); } // currently writing the same sheet multiple times is not supported... @Ignore public void bug53515() throws Exception { - Workbook wb = new SXSSFWorkbook(10); - populateWorkbook(wb); - saveTwice(wb); - wb = new XSSFWorkbook(); - populateWorkbook(wb); - saveTwice(wb); + Workbook wb1 = new SXSSFWorkbook(10); + populateWorkbook(wb1); + saveTwice(wb1); + Workbook wb2 = new XSSFWorkbook(); + populateWorkbook(wb2); + saveTwice(wb2); + wb2.close(); + wb1.close(); } // Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files // See http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html + @SuppressWarnings("resource") @Ignore public void bug53515a() throws Exception { File out = new File("Test.xlsx"); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java index 81f9ce8119..79a820b688 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java @@ -17,9 +17,12 @@ package org.apache.poi.xssf.usermodel; +import java.io.IOException; + import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.BaseTestRow; import org.apache.poi.xssf.XSSFITestDataProvider; +import org.junit.Test; /** * Tests for XSSFRow @@ -30,11 +33,13 @@ public final class TestXSSFRow extends BaseTestRow { super(XSSFITestDataProvider.instance); } - public void testRowBounds() { + @Test + public void testRowBounds() throws IOException { baseTestRowBounds(SpreadsheetVersion.EXCEL2007.getLastRowIndex()); } - public void testCellBounds() { + @Test + public void testCellBounds() throws IOException { baseTestCellBounds(SpreadsheetVersion.EXCEL2007.getLastColumnIndex()); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java index d1d948d33a..159e256b6a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java @@ -17,6 +17,8 @@ package org.apache.poi.xssf.usermodel; +import static org.junit.Assert.*; + import java.io.IOException; import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows; @@ -33,6 +35,7 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellUtil; import org.apache.poi.xssf.XSSFITestDataProvider; import org.apache.poi.xssf.XSSFTestDataSamples; +import org.junit.Test; /** * @author Yegor Kozlov @@ -44,23 +47,27 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { } @Override + @Test public void testShiftRowBreaks() { // disabled test from superclass // TODO - support shifting of page breaks } + @Test public void testBug54524() throws IOException { XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54524.xlsx"); XSSFSheet sheet = workbook.getSheetAt(0); sheet.shiftRows(3, 5, -1); Cell cell = CellUtil.getCell(sheet.getRow(1), 0); - assertEquals(1.0, cell.getNumericCellValue()); + assertEquals(1.0, cell.getNumericCellValue(), 0); cell = CellUtil.getCell(sheet.getRow(2), 0); assertEquals("SUM(A2:A2)", cell.getCellFormula()); cell = CellUtil.getCell(sheet.getRow(3), 0); assertEquals("X", cell.getStringCellValue()); + workbook.close(); } + @Test public void testBug53798() throws IOException { // NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); @@ -88,6 +95,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { //saveReport(wb, new File("/tmp/53798.xlsx")); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); + wb.close(); assertNotNull(read); Sheet readSheet = read.getSheetAt(0); @@ -100,6 +108,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { verifyCellContent(readSheet, 6, null); verifyCellContent(readSheet, 7, "6.0"); verifyCellContent(readSheet, 8, "7.0"); + read.close(); } private void verifyCellContent(Sheet readSheet, int row, String expect) { @@ -116,6 +125,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { } } + @Test public void testBug53798a() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); @@ -128,6 +138,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { //saveReport(wb, new File("/tmp/53798.xlsx")); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); + wb.close(); assertNotNull(read); Sheet readSheet = read.getSheetAt(0); @@ -140,8 +151,10 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { verifyCellContent(readSheet, 6, null); verifyCellContent(readSheet, 7, "6.0"); verifyCellContent(readSheet, 8, "8.0"); + read.close(); } + @Test public void testBug56017() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56017.xlsx"); @@ -172,6 +185,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { // } Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); + wb.close(); assertNotNull(wbBack); Sheet sheetBack = wbBack.getSheetAt(0); @@ -185,23 +199,28 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { assertNotNull(comment); assertEquals("Amdocs", comment.getAuthor()); assertEquals("Amdocs:\ntest\n", comment.getString().getString()); + wbBack.close(); } - public void test57171() throws Exception { + @Test + public void test57171() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); assertEquals(5, wb.getActiveSheetIndex()); removeAllSheetsBut(5, wb); // 5 is the active / selected sheet assertEquals(0, wb.getActiveSheetIndex()); Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb); + wb.close(); assertEquals(0, wbRead.getActiveSheetIndex()); wbRead.removeSheetAt(0); assertEquals(0, wbRead.getActiveSheetIndex()); //wb.write(new FileOutputStream("/tmp/57171.xls")); + wbRead.close(); } + @Test public void test57163() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); assertEquals(5, wb.getActiveSheetIndex()); @@ -209,9 +228,11 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { assertEquals(4, wb.getActiveSheetIndex()); //wb.write(new FileOutputStream("/tmp/57163.xls")); + wb.close(); } - public void testSetSheetOrderAndAdjustActiveSheet() throws Exception { + @Test + public void testSetSheetOrderAndAdjustActiveSheet() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); assertEquals(5, wb.getActiveSheetIndex()); @@ -256,9 +277,12 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { wb.setSheetOrder(wb.getSheetName(0), 5); assertEquals(5, wb.getActiveSheetIndex()); + + wb.close(); } - public void testRemoveSheetAndAdjustActiveSheet() throws Exception { + @Test + public void testRemoveSheetAndAdjustActiveSheet() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); assertEquals(5, wb.getActiveSheetIndex()); @@ -297,10 +321,13 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { wb.removeSheetAt(0); assertEquals(0, wb.getActiveSheetIndex()); + + wb.close(); } // TODO: enable when bug 57165 is fixed - public void disabled_test57165() throws IOException { + @Test + public void test57165() throws IOException { Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); assertEquals(5, wb.getActiveSheetIndex()); removeAllSheetsBut(3, wb); @@ -312,6 +339,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { assertEquals(0, wb.getActiveSheetIndex()); //wb.write(new FileOutputStream("/tmp/57165.xls")); + wb.close(); } // public void test57165b() throws IOException { @@ -324,8 +352,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { // } // } - private static void removeAllSheetsBut(int sheetIndex, Workbook wb) - { + private static void removeAllSheetsBut(int sheetIndex, Workbook wb) { int sheetNb = wb.getNumberOfSheets(); // Move this sheet at the first position wb.setSheetOrder(wb.getSheetName(sheetIndex), 0); @@ -338,6 +365,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { } } + @Test public void testBug57828_OnlyOneCommentShiftedInRow() throws IOException { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx"); XSSFSheet sheet = wb.getSheetAt(0); @@ -372,6 +400,7 @@ public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { wb.close(); } + @Test public void testBug46742_shiftHyperlinks() throws IOException { XSSFWorkbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("test"); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java index 1378cd4fa5..cc37c81532 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java @@ -38,6 +38,7 @@ import java.util.zip.CRC32; import org.apache.poi.POIXMLProperties; import org.apache.poi.hssf.HSSFTestDataSamples; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.ContentTypes; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -83,36 +84,35 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { * Tests that we can save, and then re-load a new document */ @Test - public void saveLoadNew() throws Exception { - @SuppressWarnings("resource") - XSSFWorkbook workbook = new XSSFWorkbook(); + public void saveLoadNew() throws IOException, InvalidFormatException { + XSSFWorkbook wb1 = new XSSFWorkbook(); //check that the default date system is set to 1900 - CTWorkbookPr pr = workbook.getCTWorkbook().getWorkbookPr(); + CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr(); assertNotNull(pr); assertTrue(pr.isSetDate1904()); assertFalse("XSSF must use the 1900 date system", pr.getDate1904()); - Sheet sheet1 = workbook.createSheet("sheet1"); - Sheet sheet2 = workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); + Sheet sheet1 = wb1.createSheet("sheet1"); + Sheet sheet2 = wb1.createSheet("sheet2"); + wb1.createSheet("sheet3"); - RichTextString rts = workbook.getCreationHelper().createRichTextString("hello world"); + RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world"); sheet1.createRow(0).createCell((short)0).setCellValue(1.2); sheet1.createRow(1).createCell((short)0).setCellValue(rts); sheet2.createRow(0); - assertEquals(0, workbook.getSheetAt(0).getFirstRowNum()); - assertEquals(1, workbook.getSheetAt(0).getLastRowNum()); - assertEquals(0, workbook.getSheetAt(1).getFirstRowNum()); - assertEquals(0, workbook.getSheetAt(1).getLastRowNum()); - assertEquals(0, workbook.getSheetAt(2).getFirstRowNum()); - assertEquals(0, workbook.getSheetAt(2).getLastRowNum()); + assertEquals(0, wb1.getSheetAt(0).getFirstRowNum()); + assertEquals(1, wb1.getSheetAt(0).getLastRowNum()); + assertEquals(0, wb1.getSheetAt(1).getFirstRowNum()); + assertEquals(0, wb1.getSheetAt(1).getLastRowNum()); + assertEquals(0, wb1.getSheetAt(2).getFirstRowNum()); + assertEquals(0, wb1.getSheetAt(2).getLastRowNum()); File file = TempFile.createTempFile("poi-", ".xlsx"); OutputStream out = new FileOutputStream(file); - workbook.write(out); + wb1.write(out); out.close(); // Check the package contains what we'd expect it to @@ -128,26 +128,27 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { // Links to the three sheets, shared strings and styles assertTrue(wbPart.hasRelationships()); assertEquals(5, wbPart.getRelationships().size()); - workbook.close(); - + wb1.close(); + // Load back the XSSFWorkbook - workbook = new XSSFWorkbook(pkg); - assertEquals(3, workbook.getNumberOfSheets()); - assertNotNull(workbook.getSheetAt(0)); - assertNotNull(workbook.getSheetAt(1)); - assertNotNull(workbook.getSheetAt(2)); + @SuppressWarnings("resource") + XSSFWorkbook wb2 = new XSSFWorkbook(pkg); + assertEquals(3, wb2.getNumberOfSheets()); + assertNotNull(wb2.getSheetAt(0)); + assertNotNull(wb2.getSheetAt(1)); + assertNotNull(wb2.getSheetAt(2)); - assertNotNull(workbook.getSharedStringSource()); - assertNotNull(workbook.getStylesSource()); + assertNotNull(wb2.getSharedStringSource()); + assertNotNull(wb2.getStylesSource()); - assertEquals(0, workbook.getSheetAt(0).getFirstRowNum()); - assertEquals(1, workbook.getSheetAt(0).getLastRowNum()); - assertEquals(0, workbook.getSheetAt(1).getFirstRowNum()); - assertEquals(0, workbook.getSheetAt(1).getLastRowNum()); - assertEquals(0, workbook.getSheetAt(2).getFirstRowNum()); - assertEquals(0, workbook.getSheetAt(2).getLastRowNum()); + assertEquals(0, wb2.getSheetAt(0).getFirstRowNum()); + assertEquals(1, wb2.getSheetAt(0).getLastRowNum()); + assertEquals(0, wb2.getSheetAt(1).getFirstRowNum()); + assertEquals(0, wb2.getSheetAt(1).getLastRowNum()); + assertEquals(0, wb2.getSheetAt(2).getFirstRowNum()); + assertEquals(0, wb2.getSheetAt(2).getLastRowNum()); - sheet1 = workbook.getSheetAt(0); + sheet1 = wb2.getSheetAt(0); assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001); assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString()); @@ -171,6 +172,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertEquals(6, wbPart.getRelationships().size()); pkg.close(); + workbook.close(); } @Test @@ -181,7 +183,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { //get default style CellStyle cellStyleAt = workbook.getCellStyleAt(i); assertNotNull(cellStyleAt); - + //get custom style StylesTable styleSource = workbook.getStylesSource(); XSSFCellStyle customStyle = new XSSFCellStyle(styleSource); @@ -205,7 +207,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { //get default font Font fontAt = workbook.getFontAt(i); assertNotNull(fontAt); - + //get customized font XSSFFont customFont = new XSSFFont(); customFont.setItalic(true); @@ -230,7 +232,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { } @Test - public void loadSave() { + public void loadSave() throws IOException { XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); assertEquals(3, workbook.getNumberOfSheets()); assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); @@ -251,13 +253,16 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertEquals("yy/mm/dd", wb2.getSheetAt(0).getRow(4).getCell(0).getRichStringCellValue().getString()); assertNotNull(wb2.getSharedStringSource()); assertNotNull(wb2.getStylesSource()); + + workbook.close(); + wb2.close(); } @Test - public void styles() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); + public void styles() throws IOException { + XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - StylesTable ss = workbook.getStylesSource(); + StylesTable ss = wb1.getStylesSource(); assertNotNull(ss); StylesTable st = ss; @@ -281,15 +286,17 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { // Save, load back in again, and check - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); + XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); + wb1.close(); - ss = workbook.getStylesSource(); + ss = wb2.getStylesSource(); assertNotNull(ss); assertEquals(10, st._getNumberFormatSize()); assertEquals(2, st.getFonts().size()); assertEquals(2, st.getFills().size()); assertEquals(1, st.getBorders().size()); + wb2.close(); } @Test @@ -300,7 +307,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertEquals(1, sheetId); sheetId = (int)wb.createSheet().sheet.getSheetId(); assertEquals(2, sheetId); - + //test file with gaps in the sheetId sequence XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm"); try { @@ -317,7 +324,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { /** * Test setting of core properties such as Title and Author - * @throws IOException + * @throws IOException */ @Test public void workbookProperties() throws IOException { @@ -327,19 +334,20 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertNotNull(props); //the Application property must be set for new workbooks, see Bugzilla #47559 assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); - + PackagePropertiesPart opcProps = props.getCoreProperties().getUnderlyingProperties(); assertNotNull(opcProps); - + opcProps.setTitleProperty("Testing Bugzilla #47460"); assertEquals("Apache POI", opcProps.getCreatorProperty().getValue()); opcProps.setCreatorProperty("poi-dev@poi.apache.org"); - + XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties(); assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue()); assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue()); + wbBack.close(); } finally { workbook.close(); } @@ -380,13 +388,14 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { crc1.update(data1); assertEquals(crc0.getValue(), crc1.getValue()); + workbook.close(); } /** * When deleting a sheet make sure that we adjust sheet indices of named ranges */ @Test - public void bug47737() { + public void bug47737() throws IOException { XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx"); assertEquals(2, wb.getNumberOfNames()); assertNotNull(wb.getCalculationChain()); @@ -406,6 +415,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertEquals(0, nm2.getCTName().getLocalSheetId()); //calculation chain is removed as well assertNull(wb.getCalculationChain()); + wb.close(); } @@ -413,27 +423,29 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { * Problems with XSSFWorkbook.removeSheetAt when workbook contains charts */ @Test - public void bug47813() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - assertNotNull(wb.getCalculationChain()); + public void bug47813() throws IOException { + XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx"); + assertEquals(3, wb1.getNumberOfSheets()); + assertNotNull(wb1.getCalculationChain()); - assertEquals("Numbers", wb.getSheetName(0)); + assertEquals("Numbers", wb1.getSheetName(0)); //the second sheet is of type 'chartsheet' - assertEquals("Chart", wb.getSheetName(1)); - assertTrue(wb.getSheetAt(1) instanceof XSSFChartSheet); - assertEquals("SomeJunk", wb.getSheetName(2)); - - wb.removeSheetAt(2); - assertEquals(2, wb.getNumberOfSheets()); - assertNull(wb.getCalculationChain()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(2, wb.getNumberOfSheets()); - assertNull(wb.getCalculationChain()); - - assertEquals("Numbers", wb.getSheetName(0)); - assertEquals("Chart", wb.getSheetName(1)); + assertEquals("Chart", wb1.getSheetName(1)); + assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet); + assertEquals("SomeJunk", wb1.getSheetName(2)); + + wb1.removeSheetAt(2); + assertEquals(2, wb1.getNumberOfSheets()); + assertNull(wb1.getCalculationChain()); + + XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); + assertEquals(2, wb2.getNumberOfSheets()); + assertNull(wb2.getCalculationChain()); + + assertEquals("Numbers", wb2.getSheetName(0)); + assertEquals("Chart", wb2.getSheetName(1)); + wb2.close(); + wb1.close(); } /** @@ -441,33 +453,33 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { * coming out wrong */ @Test - public void bug49702() throws Exception { + public void bug49702() throws IOException { // First try with a new file - XSSFWorkbook wb = new XSSFWorkbook(); + XSSFWorkbook wb1 = new XSSFWorkbook(); // Should have one style - assertEquals(1, wb.getNumCellStyles()); - wb.getCellStyleAt((short)0); + assertEquals(1, wb1.getNumCellStyles()); + wb1.getCellStyleAt((short)0); try { - wb.getCellStyleAt((short)1); + wb1.getCellStyleAt((short)1); fail("Shouldn't be able to get style at 1 that doesn't exist"); } catch(IndexOutOfBoundsException e) {} // Add another one - CellStyle cs = wb.createCellStyle(); + CellStyle cs = wb1.createCellStyle(); cs.setDataFormat((short)11); // Re-check - assertEquals(2, wb.getNumCellStyles()); - wb.getCellStyleAt((short)0); - wb.getCellStyleAt((short)1); + assertEquals(2, wb1.getNumCellStyles()); + wb1.getCellStyleAt((short)0); + wb1.getCellStyleAt((short)1); try { - wb.getCellStyleAt((short)2); + wb1.getCellStyleAt((short)2); fail("Shouldn't be able to get style at 2 that doesn't exist"); } catch(IndexOutOfBoundsException e) {} // Save and reload - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); + XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1); assertEquals(2, nwb.getNumCellStyles()); nwb.getCellStyleAt((short)0); nwb.getCellStyleAt((short)1); @@ -477,15 +489,19 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { } catch(IndexOutOfBoundsException e) {} // Now with an existing file - wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - assertEquals(3, wb.getNumCellStyles()); - wb.getCellStyleAt((short)0); - wb.getCellStyleAt((short)1); - wb.getCellStyleAt((short)2); + XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); + assertEquals(3, wb2.getNumCellStyles()); + wb2.getCellStyleAt((short)0); + wb2.getCellStyleAt((short)1); + wb2.getCellStyleAt((short)2); try { - wb.getCellStyleAt((short)3); + wb2.getCellStyleAt((short)3); fail("Shouldn't be able to get style at 3 that doesn't exist"); } catch(IndexOutOfBoundsException e) {} + + wb2.close(); + wb1.close(); + nwb.close(); } @Test @@ -495,20 +511,20 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertFalse(wb.getForceFormulaRecalculation()); CTWorkbook ctWorkbook = wb.getCTWorkbook(); assertFalse(ctWorkbook.isSetCalcPr()); - + wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero - + CTCalcPr calcPr = ctWorkbook.getCalcPr(); assertNotNull(calcPr); assertEquals(0, (int) calcPr.getCalcId()); - + calcPr.setCalcId(100); assertTrue(wb.getForceFormulaRecalculation()); - + wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero assertEquals(0, (int) calcPr.getCalcId()); assertFalse(wb.getForceFormulaRecalculation()); - + // calcMode="manual" is unset when forceFormulaRecalculation=true calcPr.setCalcMode(STCalcMode.MANUAL); wb.setForceFormulaRecalculation(true); @@ -519,7 +535,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { } @Test - public void changeSheetNameWithSharedFormulas() { + public void changeSheetNameWithSharedFormulas() throws IOException { changeSheetNameWithSharedFormulas("shared_formulas.xlsx"); } @@ -549,7 +565,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { sheet = workbook.createSheet(); sheet.setColumnWidth(4, 5000); sheet.setColumnWidth(5, 5000); - + sheet.groupColumn((short) 4, (short) 5); accessWorkbook(workbook); @@ -562,6 +578,7 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { } accessWorkbook(workbook); + workbook.close(); } private void accessWorkbook(XSSFWorkbook workbook) { @@ -573,39 +590,36 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { } @Test - public void bug48495() { - try { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx"); - - assertSheetOrder(wb, "Sheet1"); - - Sheet sheet = wb.getSheetAt(0); - sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false); - Row newRow = sheet.getRow(2); - if (newRow == null) newRow = sheet.createRow(2); - newRow.createCell(0).setCellValue(" Another Header"); - wb.cloneSheet(0); - - assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); - - // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx"); + public void bug48495() throws IOException { + Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx"); + + assertSheetOrder(wb, "Sheet1"); + + Sheet sheet = wb.getSheetAt(0); + sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false); + Row newRow = sheet.getRow(2); + if (newRow == null) newRow = sheet.createRow(2); + newRow.createCell(0).setCellValue(" Another Header"); + wb.cloneSheet(0); + + assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); + + // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx"); // try { // wb.write(fileOut); // } finally { // fileOut.close(); // } - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(read); - assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("Done"); + + Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); + assertNotNull(read); + assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); + read.close(); + wb.close(); } - + @Test - public void bug47090a() { + public void bug47090a() throws IOException { Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.removeSheetAt(0); @@ -614,10 +628,12 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertSheetOrder(workbook, "Sheet2", "Sheet1"); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertSheetOrder(read, "Sheet2", "Sheet1"); + read.close(); + workbook.close(); } - + @Test - public void bug47090b() { + public void bug47090b() throws IOException { Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.removeSheetAt(1); @@ -626,39 +642,45 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertSheetOrder(read, "Sheet1", "Sheet0"); + read.close(); + workbook.close(); } @Test - public void bug47090c() { + public void bug47090c() throws IOException { Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.removeSheetAt(0); assertSheetOrder(workbook, "Sheet2"); - workbook.cloneSheet(0); + workbook.cloneSheet(0); assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); + read.close(); + workbook.close(); } - + @Test - public void bug47090d() { + public void bug47090d() throws IOException { Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); assertSheetOrder(workbook, "Sheet1", "Sheet2"); workbook.createSheet(); assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); workbook.removeSheetAt(0); assertSheetOrder(workbook, "Sheet2", "Sheet0"); - workbook.createSheet(); + workbook.createSheet(); assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); + read.close(); + workbook.close(); } - + @Test public void bug51158() throws IOException { // create a workbook - final XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Test Sheet"); + final XSSFWorkbook wb1 = new XSSFWorkbook(); + XSSFSheet sheet = wb1.createSheet("Test Sheet"); XSSFRow row = sheet.createRow(2); XSSFCell cell = row.createCell(3); cell.setCellValue("test1"); @@ -675,52 +697,59 @@ public final class TestXSSFWorkbook extends BaseTestWorkbook { // row.createCell(0).setCellStyle(cs); // write the first excel file - XSSFWorkbook readBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(readBack); - assertEquals("test1", readBack.getSheetAt(0).getRow(2).getCell(3).getStringCellValue()); - assertNull(readBack.getSheetAt(0).getRow(2).getCell(4)); + XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); + assertNotNull(wb2); + sheet = wb2.getSheetAt(0); + row = sheet.getRow(2); + assertEquals("test1", row.getCell(3).getStringCellValue()); + assertNull(row.getCell(4)); // add a new cell to the sheet cell = row.createCell(4); cell.setCellValue("test2"); // write the second excel file - readBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(readBack); - assertEquals("test1", readBack.getSheetAt(0).getRow(2).getCell(3).getStringCellValue()); - assertEquals("test2", readBack.getSheetAt(0).getRow(2).getCell(4).getStringCellValue()); + XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); + assertNotNull(wb3); + sheet = wb3.getSheetAt(0); + row = sheet.getRow(2); + + assertEquals("test1", row.getCell(3).getStringCellValue()); + assertEquals("test2", row.getCell(4).getStringCellValue()); + wb3.close(); + wb2.close(); + wb1.close(); } - + @Test public void bug51158a() throws IOException { // create a workbook final XSSFWorkbook workbook = new XSSFWorkbook(); try { workbook.createSheet("Test Sheet"); - + XSSFSheet sheetBack = workbook.getSheetAt(0); - + // committing twice did add the XML twice without clearing the part in between sheetBack.commit(); - + // ensure that a memory based package part does not have lingering data from previous commit() calls if(sheetBack.getPackagePart() instanceof MemoryPackagePart) { ((MemoryPackagePart)sheetBack.getPackagePart()).clear(); } - + sheetBack.commit(); - + String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream())); - System.out.println(str); - + assertEquals(1, countMatches(str, " XSSFWorkbook.iterator was committed in r700472 on 2008-09-30 * and has been replaced with Iterator XSSFWorkbook.iterator - * + * * In order to make code for looping over sheets in workbooks standard, regardless * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously * available Iterator iterator and Iterator sheetIterator * have been replaced with Iterator {@link #iterator} and * Iterator {@link #sheetIterator}. This makes iterating over sheets in a workbook * similar to iterating over rows in a sheet and cells in a row. - * + * * Note: this breaks backwards compatibility! Existing codebases will need to * upgrade their code with either of the following options presented in this test case. - * + * */ - public void bug58245_XSSFSheetIterator() { + public void bug58245_XSSFSheetIterator() throws IOException { final XSSFWorkbook wb = new XSSFWorkbook(); - try { - wb.createSheet(); - - // ===================================================================== - // Case 1: Existing code uses XSSFSheet for-each loop - // ===================================================================== - // Original code (no longer valid) - /* - for (XSSFSheet sh : wb) { - sh.createRow(0); - } - */ - - // Option A: - for (XSSFSheet sh : (Iterable) (Iterable) wb) { - sh.createRow(0); - } - - // Option B (preferred for new code): - for (Sheet sh : wb) { - sh.createRow(0); - } - - // ===================================================================== - // Case 2: Existing code creates an iterator variable - // ===================================================================== - // Original code (no longer valid) - /* - Iterator it = wb.iterator(); + wb.createSheet(); + + // ===================================================================== + // Case 1: Existing code uses XSSFSheet for-each loop + // ===================================================================== + // Original code (no longer valid) + /* + for (XSSFSheet sh : wb) { + sh.createRow(0); + } + */ + + // Option A: + for (XSSFSheet sh : (Iterable) (Iterable) wb) { + sh.createRow(0); + } + + // Option B (preferred for new code): + for (Sheet sh : wb) { + sh.createRow(0); + } + + // ===================================================================== + // Case 2: Existing code creates an iterator variable + // ===================================================================== + // Original code (no longer valid) + /* + Iterator it = wb.iterator(); + XSSFSheet sh = it.next(); + sh.createRow(0); + */ + + // Option A: + { + Iterator it = (Iterator) (Iterator) wb.iterator(); XSSFSheet sh = it.next(); sh.createRow(0); - */ - - // Option A: - { - Iterator it = (Iterator) (Iterator) wb.iterator(); - XSSFSheet sh = it.next(); - sh.createRow(0); - } - - // Option B: - { - @SuppressWarnings("deprecation") - Iterator it = wb.xssfSheetIterator(); - XSSFSheet sh = it.next(); - sh.createRow(0); - } - - // Option C (preferred for new code): - { - Iterator it = wb.iterator(); - Sheet sh = it.next(); - sh.createRow(0); - } } - finally { - IOUtils.closeQuietly(wb); + + // Option B: + { + @SuppressWarnings("deprecation") + Iterator it = wb.xssfSheetIterator(); + XSSFSheet sh = it.next(); + sh.createRow(0); } - } + + // Option C (preferred for new code): + { + Iterator it = wb.iterator(); + Sheet sh = it.next(); + sh.createRow(0); + } + wb.close(); + } @Test public void testBug56957CloseWorkbook() throws Exception { File file = TempFile.createTempFile("TestBug56957_", ".xlsx"); - + final String dateExp = "Sun Nov 09 00:00:00 CET 2014"; + try { // as the file is written to, we make a copy before actually working on it FileHelper.copyFile(HSSFTestDataSamples.getSampleFile("56957.xlsx"), file); - + assertTrue(file.exists()); - + // read-only mode works! Workbook workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ)); - System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); + String str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString(); + assertEquals(dateExp, str); workbook.close(); workbook = null; - + workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ)); - System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); + str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString(); + assertEquals(dateExp, str); workbook.close(); workbook = null; - + // now check read/write mode workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE)); - System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); + str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString(); + assertEquals(dateExp, str); workbook.close(); workbook = null; - + workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE)); - System.out.println(workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString()); + str = workbook.getSheetAt(0).getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK).getDateCellValue().toString(); + assertEquals(dateExp, str); workbook.close(); workbook = null; } finally { diff --git a/src/scratchpad/src/org/apache/poi/hwpf/converter/NumberFormatter.java b/src/scratchpad/src/org/apache/poi/hwpf/converter/NumberFormatter.java index 9e4031751d..ec7ed1ca9d 100644 --- a/src/scratchpad/src/org/apache/poi/hwpf/converter/NumberFormatter.java +++ b/src/scratchpad/src/org/apache/poi/hwpf/converter/NumberFormatter.java @@ -29,13 +29,7 @@ import org.apache.poi.util.Beta; * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) */ @Beta -public final class NumberFormatter -{ - - private static final String[] ENGLISH_LETTERS = new String[] { "a", "b", - "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", - "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; - +public final class NumberFormatter { private static final String[] ROMAN_LETTERS = { "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i" }; @@ -67,55 +61,26 @@ public final class NumberFormatter return String.valueOf( num ); } } - - private static String toLetters( int number ) - { - final int base = 26; - - if ( number <= 0 ) + + private static String toLetters(int number) { + if ( number <= 0 ) { throw new IllegalArgumentException( "Unsupported number: " + number ); + } - if ( number < base + 1 ) - return ENGLISH_LETTERS[number - 1]; - - long toProcess = number; + int num = number; + final int radix = 26; - StringBuilder stringBuilder = new StringBuilder(); - int maxPower = 0; - { - int boundary = 0; - while ( toProcess > boundary ) - { - maxPower++; - boundary = boundary * base + base; + char buf[] = new char[33]; + int charPos = buf.length; - if ( boundary > Integer.MAX_VALUE ) - throw new IllegalArgumentException( "Unsupported number: " - + toProcess ); - } + while (num > 0) { + num--; // 1 => a, not 0 => a + int remainder = num % radix; + buf[--charPos] = (char)('a'+remainder); + num = (num - remainder) / radix; } - maxPower--; - for ( int p = maxPower; p > 0; p-- ) - { - long boundary = 0; - long shift = 1; - for ( int i = 0; i < p; i++ ) - { - shift *= base; - boundary = boundary * base + base; - } - - int count = 0; - while ( toProcess > boundary ) - { - count++; - toProcess -= shift; - } - stringBuilder.append( ENGLISH_LETTERS[count - 1] ); - } - stringBuilder.append( ENGLISH_LETTERS[(int) toProcess - 1] ); - return stringBuilder.toString(); + return new String(buf, charPos, (buf.length - charPos)); } private static String toRoman( int number ) diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java index dafb481d3b..ecfe4cf971 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java @@ -17,15 +17,19 @@ package org.apache.poi.hssf.usermodel; -import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; -import junit.framework.AssertionFailedError; +import java.io.IOException; import org.apache.poi.hssf.HSSFITestDataProvider; import org.apache.poi.hssf.record.BlankRecord; import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.ss.usermodel.BaseTestRow; import org.apache.poi.ss.SpreadsheetVersion; +import org.apache.poi.ss.usermodel.BaseTestRow; +import org.junit.Test; /** * Test HSSFRow is okay. @@ -38,15 +42,16 @@ public final class TestHSSFRow extends BaseTestRow { super(HSSFITestDataProvider.instance); } - public void testRowBounds() { + public void testRowBounds() throws IOException { baseTestRowBounds(SpreadsheetVersion.EXCEL97.getLastRowIndex()); } - public void testCellBounds() { + public void testCellBounds() throws IOException { baseTestCellBounds(SpreadsheetVersion.EXCEL97.getLastColumnIndex()); } - public void testLastAndFirstColumns_bug46654() { + @Test + public void testLastAndFirstColumns_bug46654() throws IOException { int ROW_IX = 10; int COL_IX = 3; HSSFWorkbook workbook = new HSSFWorkbook(); @@ -64,15 +69,18 @@ public final class TestHSSFRow extends BaseTestRow { HSSFCell cell = row.createCellFromRecord(br); if (row.getFirstCellNum() == 2 && row.getLastCellNum() == 5) { - throw new AssertionFailedError("Identified bug 46654a"); + fail("Identified bug 46654a"); } assertEquals(COL_IX, row.getFirstCellNum()); assertEquals(COL_IX + 1, row.getLastCellNum()); row.removeCell(cell); assertEquals(-1, row.getFirstCellNum()); assertEquals(-1, row.getLastCellNum()); + + workbook.close(); } + @Test public void testMoveCell() throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); @@ -121,6 +129,7 @@ public final class TestHSSFRow extends BaseTestRow { workbook.close(); } + @Test public void testRowHeight() throws IOException{ HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java index 4b92b30bc2..a8915fe6fe 100644 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java +++ b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java @@ -136,68 +136,73 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } @Test - public void readWriteWithCharts() { - HSSFWorkbook b; + public void readWriteWithCharts() throws IOException { HSSFSheet s; // Single chart, two sheets - b = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); - assertEquals(2, b.getNumberOfSheets()); - assertEquals("Graph2", b.getSheetName(1)); - s = b.getSheetAt(1); + HSSFWorkbook b1 = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); + assertEquals(2, b1.getNumberOfSheets()); + assertEquals("Graph2", b1.getSheetName(1)); + s = b1.getSheetAt(1); assertEquals(0, s.getFirstRowNum()); assertEquals(8, s.getLastRowNum()); // Has chart on 1st sheet?? // FIXME - assertNotNull(b.getSheetAt(0).getDrawingPatriarch()); - assertNull(b.getSheetAt(1).getDrawingPatriarch()); - assertFalse(b.getSheetAt(0).getDrawingPatriarch().containsChart()); + assertNotNull(b1.getSheetAt(0).getDrawingPatriarch()); + assertNull(b1.getSheetAt(1).getDrawingPatriarch()); + assertFalse(b1.getSheetAt(0).getDrawingPatriarch().containsChart()); + b1.close(); // We've now called getDrawingPatriarch() so // everything will be all screwy // So, start again - b = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); + HSSFWorkbook b2 = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); - b = HSSFTestDataSamples.writeOutAndReadBack(b); - assertEquals(2, b.getNumberOfSheets()); - s = b.getSheetAt(1); + HSSFWorkbook b3 = HSSFTestDataSamples.writeOutAndReadBack(b2); + b2.close(); + + assertEquals(2, b3.getNumberOfSheets()); + s = b3.getSheetAt(1); assertEquals(0, s.getFirstRowNum()); assertEquals(8, s.getLastRowNum()); - + b3.close(); // Two charts, three sheets - b = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); - assertEquals(3, b.getNumberOfSheets()); + HSSFWorkbook b4 = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); + assertEquals(3, b4.getNumberOfSheets()); - s = b.getSheetAt(1); + s = b4.getSheetAt(1); assertEquals(0, s.getFirstRowNum()); assertEquals(8, s.getLastRowNum()); - s = b.getSheetAt(2); + s = b4.getSheetAt(2); assertEquals(0, s.getFirstRowNum()); assertEquals(8, s.getLastRowNum()); // Has chart on 1st sheet?? // FIXME - assertNotNull(b.getSheetAt(0).getDrawingPatriarch()); - assertNull(b.getSheetAt(1).getDrawingPatriarch()); - assertNull(b.getSheetAt(2).getDrawingPatriarch()); - assertFalse(b.getSheetAt(0).getDrawingPatriarch().containsChart()); + assertNotNull(b4.getSheetAt(0).getDrawingPatriarch()); + assertNull(b4.getSheetAt(1).getDrawingPatriarch()); + assertNull(b4.getSheetAt(2).getDrawingPatriarch()); + assertFalse(b4.getSheetAt(0).getDrawingPatriarch().containsChart()); + b4.close(); // We've now called getDrawingPatriarch() so // everything will be all screwy // So, start again - b = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); + HSSFWorkbook b5 = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); - b = HSSFTestDataSamples.writeOutAndReadBack(b); - assertEquals(3, b.getNumberOfSheets()); + HSSFWorkbook b6 = HSSFTestDataSamples.writeOutAndReadBack(b5); + b5.close(); + assertEquals(3, b6.getNumberOfSheets()); - s = b.getSheetAt(1); + s = b6.getSheetAt(1); assertEquals(0, s.getFirstRowNum()); assertEquals(8, s.getLastRowNum()); - s = b.getSheetAt(2); + s = b6.getSheetAt(2); assertEquals(0, s.getFirstRowNum()); assertEquals(8, s.getLastRowNum()); + b6.close(); } @SuppressWarnings("deprecation") @@ -399,7 +404,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { * that point to deleted sheets */ @Test - public void namesToDeleteSheets() { + public void namesToDeleteSheets() throws IOException { HSSFWorkbook b = HSSFTestDataSamples.openSampleWorkbook("30978-deleted.xls"); assertEquals(3, b.getNumberOfNames()); @@ -478,6 +483,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { assertEquals("OnSheet3", n.getNameName()); assertEquals("Sheet3", n.getSheetName()); assertEquals("Sheet3!$A$1:$A$2", n.getRefersToFormula()); + + b.close(); } /** @@ -520,30 +527,33 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { * 1-based sheet tab index (not a 1-based extern sheet index) */ @Test - public void findBuiltInNameRecord() { + public void findBuiltInNameRecord() throws IOException { // testRRaC has multiple (3) built-in name records // The second print titles name record has getSheetNumber()==4 - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testRRaC.xls"); + HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("testRRaC.xls"); NameRecord nr; - assertEquals(3, wb.getWorkbook().getNumNames()); - nr = wb.getWorkbook().getNameRecord(2); + assertEquals(3, wb1.getWorkbook().getNumNames()); + nr = wb1.getWorkbook().getNameRecord(2); // TODO - render full row and full column refs properly - assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition())); // 1:1 + assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb1, nr.getNameDefinition())); // 1:1 try { - wb.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12")); - wb.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F")); + wb1.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12")); + wb1.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F")); } catch (RuntimeException e) { if (e.getMessage().equals("Builtin (7) already exists for sheet (4)")) { // there was a problem in the code which locates the existing print titles name record - throw new RuntimeException("Identified bug 45720b"); + fail("Identified bug 45720b"); } + wb1.close(); throw e; } - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, wb.getWorkbook().getNumNames()); - nr = wb.getWorkbook().getNameRecord(2); - assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition())); // E:F,9:12 + HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); + wb1.close(); + assertEquals(3, wb2.getWorkbook().getNumNames()); + nr = wb2.getWorkbook().getNameRecord(2); + assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb2, nr.getNameDefinition())); // E:F,9:12 + wb2.close(); } /** @@ -565,6 +575,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { fs2.close(); wb.close(); + fs1.close(); } /** @@ -827,20 +838,23 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { EscherBSERecord bse = iwb.getBSERecord(pictureIndex); assertEquals(3, bse.getRef()); } + + wb.close(); } @Test - public void changeSheetNameWithSharedFormulas() { + public void changeSheetNameWithSharedFormulas() throws IOException { changeSheetNameWithSharedFormulas("shared_formulas.xls"); } - @Test + // Should throw exception about invalid POIFSFileSystem + @Test(expected=IllegalArgumentException.class) public void emptyDirectoryNode() throws IOException { + POIFSFileSystem fs = new POIFSFileSystem(); try { - assertNotNull(new HSSFWorkbook(new POIFSFileSystem())); - fail("Should catch exception about invalid POIFSFileSystem"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("does not contain a BIFF8")); + new HSSFWorkbook(fs).close(); + } finally { + fs.close(); } } @@ -1060,6 +1074,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); + read.close(); + wb.close(); } @Test @@ -1101,6 +1117,8 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest"); + read.close(); + wb.close(); } @Test @@ -1140,13 +1158,13 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); assertEquals("ASheet!A1", wb.getName(nameName).getRefersToFormula()); - expectName( - new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray())), - nameName, "ASheet!A1"); - expectName( - new HSSFWorkbook( - new ByteArrayInputStream(stream2.toByteArray())), - nameName, "ASheet!A1"); + HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray())); + expectName(wb2, nameName, "ASheet!A1"); + HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray())); + expectName(wb3, nameName, "ASheet!A1"); + wb3.close(); + wb2.close(); + wb.close(); } private void expectName(HSSFWorkbook wb, String name, String expect) { @@ -1183,10 +1201,11 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } assertTrue("Should find some images via Client or Child anchors, but did not find any at all", found); + workbook.close(); } @Test - public void testRewriteFileBug58480() throws Exception { + public void testRewriteFileBug58480() throws IOException { final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); try { @@ -1221,7 +1240,7 @@ public final class TestHSSFWorkbook extends BaseTestWorkbook { } private void writeAndCloseWorkbook(Workbook workbook, File file) - throws IOException, InterruptedException { + throws IOException { final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); workbook.write(bytesOut); workbook.close(); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java index 2ae096aa1a..6801695399 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java @@ -17,18 +17,24 @@ package org.apache.poi.ss.usermodel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.IOException; import java.util.Iterator; -import junit.framework.TestCase; - import org.apache.poi.ss.ITestDataProvider; +import org.junit.Test; /** * A base class for testing implementations of * {@link org.apache.poi.ss.usermodel.Row} */ -public abstract class BaseTestRow extends TestCase { +public abstract class BaseTestRow { private final ITestDataProvider _testDataProvider; @@ -36,7 +42,8 @@ public abstract class BaseTestRow extends TestCase { _testDataProvider = testDataProvider; } - public void testLastAndFirstColumns() { + @Test + public void testLastAndFirstColumns() throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); Sheet sheet = workbook.createSheet(); Row row = sheet.createRow(0); @@ -58,13 +65,14 @@ public abstract class BaseTestRow extends TestCase { row.createCell(3); assertEquals(1, row.getFirstCellNum()); assertEquals(4, row.getLastCellNum()); + workbook.close(); } /** * Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum * This test was added in response to bug report 44987. */ - public void testBoundsInMultipleRows() { + public void testBoundsInMultipleRows() throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); Sheet sheet = workbook.createSheet(); Row rowA = sheet.createRow(0); @@ -86,12 +94,13 @@ public abstract class BaseTestRow extends TestCase { assertEquals(51, rowA.getLastCellNum()); assertEquals(31, rowB.getLastCellNum()); + workbook.close(); } - public void testRemoveCell() { - Workbook workbook = _testDataProvider.createWorkbook(); + public void testRemoveCell() throws IOException { + Workbook wb1 = _testDataProvider.createWorkbook(); { - Sheet sheet = workbook.createSheet(); + Sheet sheet = wb1.createSheet(); Row row = sheet.createRow(0); assertEquals(0, row.getPhysicalNumberOfCells()); @@ -116,18 +125,21 @@ public abstract class BaseTestRow extends TestCase { assertEquals(0, row.getPhysicalNumberOfCells()); } - workbook = _testDataProvider.writeOutAndReadBack(workbook); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); { - Sheet sheet = workbook.getSheetAt(0); + Sheet sheet = wb2.getSheetAt(0); Row row = sheet.getRow(0); assertEquals(-1, row.getLastCellNum()); assertEquals(-1, row.getFirstCellNum()); assertEquals(0, row.getPhysicalNumberOfCells()); } + + wb2.close(); } - public void baseTestRowBounds(int maxRowNum) { + public void baseTestRowBounds(int maxRowNum) throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); Sheet sheet = workbook.createSheet(); //Test low row bound @@ -152,11 +164,13 @@ public abstract class BaseTestRow extends TestCase { // expected during successful test assertEquals("Invalid row number ("+(maxRowNum + 1)+") outside allowable range (0.."+maxRowNum+")", e.getMessage()); } + + workbook.close(); } - public void baseTestCellBounds(int maxCellNum) { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); + public void baseTestCellBounds(int maxCellNum) throws IOException { + Workbook wb1 = _testDataProvider.createWorkbook(); + Sheet sheet = wb1.createSheet(); Row row = sheet.createRow(0); //Test low cell bound @@ -180,22 +194,24 @@ public abstract class BaseTestRow extends TestCase { row.createCell(i); } assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); - workbook = _testDataProvider.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); + + sheet = wb2.getSheetAt(0); row = sheet.getRow(0); assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); for(int i=0; i < maxCellNum; i++){ Cell cell = row.getCell(i); assertEquals(i, cell.getColumnIndex()); } - + wb2.close(); } /** * Prior to patch 43901, POI was producing files with the wrong last-column * number on the row */ - public void testLastCellNumIsCorrectAfterAddCell_bug43901(){ + public void testLastCellNumIsCorrectAfterAddCell_bug43901() throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); Sheet sheet = workbook.createSheet("test"); Row row = sheet.createRow(0); @@ -212,12 +228,13 @@ public abstract class BaseTestRow extends TestCase { assertEquals(1, row.getLastCellNum()); row.createCell(255); assertEquals(256, row.getLastCellNum()); + workbook.close(); } /** * Tests for the missing/blank cell policy stuff */ - public void testGetCellPolicy() { + public void testGetCellPolicy() throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); Sheet sheet = workbook.createSheet("test"); Row row = sheet.createRow(0); @@ -284,11 +301,13 @@ public abstract class BaseTestRow extends TestCase { assertEquals(null, row.getCell(3)); assertEquals(null, row.getCell(4)); assertEquals(Cell.CELL_TYPE_NUMERIC, row.getCell(5).getCellType()); + + workbook.close(); } public void testRowHeight() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); + Workbook wb1 = _testDataProvider.createWorkbook(); + Sheet sheet = wb1.createSheet(); Row row1 = sheet.createRow(0); assertEquals(sheet.getDefaultRowHeight(), row1.getHeight()); @@ -314,8 +333,9 @@ public abstract class BaseTestRow extends TestCase { row4.setZeroHeight(true); assertTrue(row4.getZeroHeight()); - workbook = _testDataProvider.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); + sheet = wb2.getSheetAt(0); row1 = sheet.getRow(0); row2 = sheet.getRow(1); @@ -334,12 +354,13 @@ public abstract class BaseTestRow extends TestCase { assertFalse(row2.getZeroHeight()); assertFalse(row3.getZeroHeight()); assertTrue(row4.getZeroHeight()); + wb2.close(); } /** * Test adding cells to a row in various places and see if we can find them again. */ - public void testCellIterator() { + public void testCellIterator() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); Row row = sheet.createRow(0); @@ -393,11 +414,12 @@ public abstract class BaseTestRow extends TestCase { assertTrue(it.hasNext()); assertTrue(cell2 == it.next()); assertEquals(Cell.CELL_TYPE_STRING, cell5.getCellType()); + wb.close(); } - public void testRowStyle() { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("test"); + public void testRowStyle() throws IOException { + Workbook wb1 = _testDataProvider.createWorkbook(); + Sheet sheet = wb1.createSheet("test"); Row row1 = sheet.createRow(0); Row row2 = sheet.createRow(1); @@ -408,7 +430,7 @@ public abstract class BaseTestRow extends TestCase { assertEquals(null, row2.getRowStyle()); // Style one - CellStyle style = workbook.createCellStyle(); + CellStyle style = wb1.createCellStyle(); style.setDataFormat((short)4); row2.setRowStyle(style); @@ -419,17 +441,21 @@ public abstract class BaseTestRow extends TestCase { assertEquals(style, row2.getRowStyle()); // Save, load and re-check - workbook = _testDataProvider.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); + + sheet = wb2.getSheetAt(0); row1 = sheet.getRow(0); row2 = sheet.getRow(1); - style = workbook.getCellStyleAt(style.getIndex()); + style = wb2.getCellStyleAt(style.getIndex()); assertEquals(false, row1.isFormatted()); assertEquals(true, row2.isFormatted()); assertEquals(null, row1.getRowStyle()); assertEquals(style, row2.getRowStyle()); assertEquals(4, style.getDataFormat()); + + wb2.close(); } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java index 512b4a7e6e..34ef12b7cb 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java @@ -17,14 +17,18 @@ package org.apache.poi.ss.usermodel; -import java.io.IOException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; -import junit.framework.TestCase; +import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; +import org.junit.Test; /** * Tests row shifting capabilities. @@ -32,7 +36,7 @@ import org.apache.poi.ss.util.CellReference; * @author Shawn Laubach (slaubach at apache dot com) * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) */ -public abstract class BaseTestSheetShiftRows extends TestCase { +public abstract class BaseTestSheetShiftRows { private final ITestDataProvider _testDataProvider; @@ -46,20 +50,22 @@ public abstract class BaseTestSheetShiftRows extends TestCase { * check. This ensures that if some changes code that breaks * writing or what not, they realize it. */ - public final void testShiftRows(){ + @Test + public final void testShiftRows() throws IOException { // Read initial file in String sampleName = "SimpleMultiCell." + _testDataProvider.getStandardFileNameExtension(); - Workbook wb = _testDataProvider.openSampleWorkbook(sampleName); - Sheet s = wb.getSheetAt( 0 ); + Workbook wb1 = _testDataProvider.openSampleWorkbook(sampleName); + Sheet s = wb1.getSheetAt( 0 ); // Shift the second row down 1 and write to temp file s.shiftRows( 1, 1, 1 ); - wb = _testDataProvider.writeOutAndReadBack(wb); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); // Read from temp file and check the number of cells in each // row (in original file each row was unique) - s = wb.getSheetAt( 0 ); + s = wb2.getSheetAt( 0 ); assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1); confirmEmptyRow(s, 1); @@ -70,10 +76,11 @@ public abstract class BaseTestSheetShiftRows extends TestCase { // Shift rows 1-3 down 3 in the current one. This tests when // 1 row is blank. Write to a another temp file s.shiftRows( 0, 2, 3 ); - wb = _testDataProvider.writeOutAndReadBack(wb); + Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); + wb2.close(); // Read and ensure things are where they should be - s = wb.getSheetAt(0); + s = wb3.getSheetAt(0); confirmEmptyRow(s, 0); confirmEmptyRow(s, 1); confirmEmptyRow(s, 2); @@ -81,19 +88,23 @@ public abstract class BaseTestSheetShiftRows extends TestCase { confirmEmptyRow(s, 4); assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2); + wb3.close(); + // Read the first file again - wb = _testDataProvider.openSampleWorkbook(sampleName); - s = wb.getSheetAt( 0 ); + Workbook wb4 = _testDataProvider.openSampleWorkbook(sampleName); + s = wb4.getSheetAt( 0 ); // Shift rows 3 and 4 up and write to temp file s.shiftRows( 2, 3, -2 ); - wb = _testDataProvider.writeOutAndReadBack(wb); - s = wb.getSheetAt( 0 ); + Workbook wb5 = _testDataProvider.writeOutAndReadBack(wb4); + wb4.close(); + s = wb5.getSheetAt( 0 ); assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3); assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4); confirmEmptyRow(s, 2); confirmEmptyRow(s, 3); assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); + wb5.close(); } private static void confirmEmptyRow(Sheet s, int rowIx) { Row row = s.getRow(rowIx); @@ -103,44 +114,51 @@ public abstract class BaseTestSheetShiftRows extends TestCase { /** * Tests when rows are null. */ - public final void testShiftRow() { - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet(); + @Test + public final void testShiftRow() throws IOException { + Workbook wb = _testDataProvider.createWorkbook(); + Sheet s = wb.createSheet(); s.createRow(0).createCell(0).setCellValue("TEST1"); s.createRow(3).createCell(0).setCellValue("TEST2"); s.shiftRows(0,4,1); + wb.close(); } /** * Tests when shifting the first row. */ - public final void testActiveCell() { - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet(); + @Test + public final void testActiveCell() throws IOException { + Workbook wb = _testDataProvider.createWorkbook(); + Sheet s = wb.createSheet(); s.createRow(0).createCell(0).setCellValue("TEST1"); s.createRow(3).createCell(0).setCellValue("TEST2"); s.shiftRows(0,4,1); + wb.close(); } /** * When shifting rows, the page breaks should go with it */ - public void testShiftRowBreaks() { // TODO - enable XSSF test - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet(); + @Test + public void testShiftRowBreaks() throws IOException { // TODO - enable XSSF test + Workbook wb = _testDataProvider.createWorkbook(); + Sheet s = wb.createSheet(); Row row = s.createRow(4); row.createCell(0).setCellValue("test"); s.setRowBreak(4); s.shiftRows(4, 4, 2); assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6)); + wb.close(); } - public void testShiftWithComments() { - Workbook wb = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension()); + @Test + public void testShiftWithComments() throws IOException { + Workbook wb1 = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension()); - Sheet sheet = wb.getSheet("Sheet1"); + Sheet sheet = wb1.getSheet("Sheet1"); assertEquals(3, sheet.getLastRowNum()); // Verify comments are in the position expected @@ -178,8 +196,10 @@ public abstract class BaseTestSheetShiftRows extends TestCase { // Write out and read back in again // Ensure that the changes were persisted - wb = _testDataProvider.writeOutAndReadBack(wb); - sheet = wb.getSheet("Sheet1"); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); + + sheet = wb2.getSheet("Sheet1"); assertEquals(4, sheet.getLastRowNum()); // Verify comments are in the position expected after the shift @@ -201,7 +221,7 @@ public abstract class BaseTestSheetShiftRows extends TestCase { // TODO: it seems HSSFSheet does not correctly remove comments from rows that are overwritten // by shifting rows... - if(!(wb instanceof HSSFWorkbook)) { + if(!(wb2 instanceof HSSFWorkbook)) { assertEquals(2, sheet.getLastRowNum()); // Verify comments are in the position expected @@ -215,9 +235,12 @@ public abstract class BaseTestSheetShiftRows extends TestCase { assertEquals(comment1,"comment top row3 (index2)\n"); String comment2 = sheet.getCellComment(2,0).getString().getString(); assertEquals(comment2,"comment top row4 (index3)\n"); + + wb2.close(); } - public final void testShiftWithNames() { + @Test + public final void testShiftWithNames() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet1 = wb.createSheet("Sheet1"); wb.createSheet("Sheet2"); @@ -257,9 +280,12 @@ public abstract class BaseTestSheetShiftRows extends TestCase { name4 = wb.getNameAt(3); assertEquals("A1", name4.getRefersToFormula()); + + wb.close(); } - public final void testShiftWithMergedRegions() { + @Test + public final void testShiftWithMergedRegions() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); Row row = sheet.createRow(0); @@ -273,12 +299,14 @@ public abstract class BaseTestSheetShiftRows extends TestCase { sheet.shiftRows(0, 1, 2); region = sheet.getMergedRegion(0); assertEquals("A3:C3", region.formatAsString()); + wb.close(); } /** * See bug #34023 */ - public final void testShiftWithFormulas() { + @Test + public final void testShiftWithFormulas() throws IOException { Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension()); Sheet sheet = wb.getSheet("Sheet1"); @@ -332,6 +360,7 @@ public abstract class BaseTestSheetShiftRows extends TestCase { // Note - named ranges formulas have not been updated + wb.close(); } private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC, @@ -348,7 +377,8 @@ public abstract class BaseTestSheetShiftRows extends TestCase { assertEquals(expectedFormula, cell.getCellFormula()); } - public final void testShiftSharedFormulasBug54206() { + @Test + public final void testShiftSharedFormulasBug54206() throws IOException { Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension()); Sheet sheet = wb.getSheetAt(0); @@ -402,21 +432,21 @@ public abstract class BaseTestSheetShiftRows extends TestCase { assertEquals("SUM(G29:I29)", sheet.getRow(28).getCell(9).getCellFormula()); assertEquals("SUM(G30:I30)", sheet.getRow(29).getCell(9).getCellFormula()); + wb.close(); } + @Test public void testBug55280() throws IOException { Workbook w = _testDataProvider.createWorkbook(); - try { - Sheet s = w.createSheet(); - for (int row = 0; row < 5000; ++row) - s.addMergedRegion(new CellRangeAddress(row, row, 0, 3)); - - s.shiftRows(0, 4999, 1); // takes a long time... - } finally { - w.close(); - } + Sheet s = w.createSheet(); + for (int row = 0; row < 5000; ++row) + s.addMergedRegion(new CellRangeAddress(row, row, 0, 3)); + + s.shiftRows(0, 4999, 1); // takes a long time... + w.close(); } + @Test public void test47169() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet = wb.createSheet(); diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java index 9c3ca693ad..ab14550048 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java @@ -34,8 +34,6 @@ import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.util.CellRangeAddress; import org.junit.Test; -import junit.framework.AssertionFailedError; - /** * @author Yegor Kozlov */ @@ -48,7 +46,7 @@ public abstract class BaseTestWorkbook { } @Test - public void sheetIterator_forEach() { + public void sheetIterator_forEach() throws IOException { final Workbook wb = _testDataProvider.createWorkbook(); wb.createSheet("Sheet0"); wb.createSheet("Sheet1"); @@ -58,10 +56,16 @@ public abstract class BaseTestWorkbook { assertEquals("Sheet"+i, sh.getSheetName()); i++; } + wb.close(); } - @Test - public void sheetIterator_sheetsReordered() { + /** + * Expected ConcurrentModificationException: + * should not be able to advance an iterator when the + * underlying data has been reordered + */ + @Test(expected=ConcurrentModificationException.class) + public void sheetIterator_sheetsReordered() throws IOException { final Workbook wb = _testDataProvider.createWorkbook(); wb.createSheet("Sheet0"); wb.createSheet("Sheet1"); @@ -74,16 +78,18 @@ public abstract class BaseTestWorkbook { // Iterator order should be fixed when iterator is created try { assertEquals("Sheet1", it.next().getSheetName()); - fail("Expected ConcurrentModificationException: "+ - "should not be able to advance an iterator when the "+ - "underlying data has been reordered"); - } catch (final ConcurrentModificationException e) { - // expected + } finally { + wb.close(); } } - @Test - public void sheetIterator_sheetRemoved() { + /** + * Expected ConcurrentModificationException: + * should not be able to advance an iterator when the + * underlying data has been reordered + */ + @Test(expected=ConcurrentModificationException.class) + public void sheetIterator_sheetRemoved() throws IOException { final Workbook wb = _testDataProvider.createWorkbook(); wb.createSheet("Sheet0"); wb.createSheet("Sheet1"); @@ -95,16 +101,17 @@ public abstract class BaseTestWorkbook { // Iterator order should be fixed when iterator is created try { it.next(); - fail("Expected ConcurrentModificationException: "+ - "should not be able to advance an iterator when the "+ - "underlying data has been reordered"); - } catch (final ConcurrentModificationException e) { - // expected + } finally { + wb.close(); } } - @Test - public void sheetIterator_remove() { + /** + * Expected UnsupportedOperationException: + * should not be able to remove sheets from the sheet iterator + */ + @Test(expected=UnsupportedOperationException.class) + public void sheetIterator_remove() throws IOException { final Workbook wb = _testDataProvider.createWorkbook(); wb.createSheet("Sheet0"); @@ -112,16 +119,14 @@ public abstract class BaseTestWorkbook { it.next(); //Sheet0 try { it.remove(); - fail("Expected UnsupportedOperationException: "+ - "should not be able to remove sheets from the sheet iterator"); - } catch (final UnsupportedOperationException e) { - // expected + } finally { + wb.close(); } } @Test - public void createSheet() { + public void createSheet() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); assertEquals(0, wb.getNumberOfSheets()); @@ -146,7 +151,7 @@ public abstract class BaseTestWorkbook { Sheet originalSheet = wb.createSheet("Sheet3"); Sheet fetchedSheet = wb.getSheet("sheet3"); if (fetchedSheet == null) { - throw new AssertionFailedError("Identified bug 44892"); + fail("Identified bug 44892"); } assertEquals("Sheet3", fetchedSheet.getSheetName()); assertEquals(3, wb.getNumberOfSheets()); @@ -212,11 +217,13 @@ public abstract class BaseTestWorkbook { assertNull(wb.getSheet("unknown")); //serialize and read again - wb = _testDataProvider.writeOutAndReadBack(wb); - assertEquals(3, wb.getNumberOfSheets()); - assertEquals(0, wb.getSheetIndex("sheet0")); - assertEquals(1, wb.getSheetIndex("sheet1")); - assertEquals(2, wb.getSheetIndex("I changed!")); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb); + wb.close(); + assertEquals(3, wb2.getNumberOfSheets()); + assertEquals(0, wb2.getSheetIndex("sheet0")); + assertEquals(1, wb2.getSheetIndex("sheet1")); + assertEquals(2, wb2.getSheetIndex("I changed!")); + wb2.close(); } /** @@ -228,23 +235,23 @@ public abstract class BaseTestWorkbook { * but for the purpose of uniqueness long sheet names are silently truncated to 31 chars. */ @Test - public void createSheetWithLongNames() { - Workbook wb = _testDataProvider.createWorkbook(); + public void createSheetWithLongNames() throws IOException { + Workbook wb1 = _testDataProvider.createWorkbook(); String sheetName1 = "My very long sheet name which is longer than 31 chars"; String truncatedSheetName1 = sheetName1.substring(0, 31); - Sheet sh1 = wb.createSheet(sheetName1); + Sheet sh1 = wb1.createSheet(sheetName1); assertEquals(truncatedSheetName1, sh1.getSheetName()); - assertSame(sh1, wb.getSheet(truncatedSheetName1)); + assertSame(sh1, wb1.getSheet(truncatedSheetName1)); // now via wb.setSheetName - wb.setSheetName(0, sheetName1); + wb1.setSheetName(0, sheetName1); assertEquals(truncatedSheetName1, sh1.getSheetName()); - assertSame(sh1, wb.getSheet(truncatedSheetName1)); + assertSame(sh1, wb1.getSheet(truncatedSheetName1)); String sheetName2 = "My very long sheet name which is longer than 31 chars " + "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)"; try { - /*Sheet sh2 =*/ wb.createSheet(sheetName2); + /*Sheet sh2 =*/ wb1.createSheet(sheetName2); fail("expected exception"); } catch (IllegalArgumentException e) { // expected during successful test @@ -253,15 +260,17 @@ public abstract class BaseTestWorkbook { String sheetName3 = "POI allows creating sheets with names longer than 31 characters"; String truncatedSheetName3 = sheetName3.substring(0, 31); - Sheet sh3 = wb.createSheet(sheetName3); + Sheet sh3 = wb1.createSheet(sheetName3); assertEquals(truncatedSheetName3, sh3.getSheetName()); - assertSame(sh3, wb.getSheet(truncatedSheetName3)); + assertSame(sh3, wb1.getSheet(truncatedSheetName3)); //serialize and read again - wb = _testDataProvider.writeOutAndReadBack(wb); - assertEquals(2, wb.getNumberOfSheets()); - assertEquals(0, wb.getSheetIndex(truncatedSheetName1)); - assertEquals(1, wb.getSheetIndex(truncatedSheetName3)); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); + assertEquals(2, wb2.getNumberOfSheets()); + assertEquals(0, wb2.getSheetIndex(truncatedSheetName1)); + assertEquals(1, wb2.getSheetIndex(truncatedSheetName3)); + wb2.close(); } @Test @@ -317,16 +326,17 @@ public abstract class BaseTestWorkbook { } @Test - public void defaultValues() { + public void defaultValues() throws IOException { Workbook b = _testDataProvider.createWorkbook(); assertEquals(0, b.getActiveSheetIndex()); assertEquals(0, b.getFirstVisibleTab()); assertEquals(0, b.getNumberOfNames()); assertEquals(0, b.getNumberOfSheets()); + b.close(); } @Test - public void sheetSelection() { + public void sheetSelection() throws IOException { Workbook b = _testDataProvider.createWorkbook(); b.createSheet("Sheet One"); b.createSheet("Sheet Two"); @@ -335,10 +345,11 @@ public abstract class BaseTestWorkbook { b.setFirstVisibleTab(1); assertEquals(1, b.getActiveSheetIndex()); assertEquals(1, b.getFirstVisibleTab()); + b.close(); } @Test - public void printArea() { + public void printArea() throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); Sheet sheet1 = workbook.createSheet("Test Print Area"); String sheetName1 = sheet1.getSheetName(); @@ -355,10 +366,11 @@ public abstract class BaseTestWorkbook { workbook.removePrintArea(0); assertNull(workbook.getPrintArea(0)); + workbook.close(); } @Test - public void getSetActiveSheet(){ + public void getSetActiveSheet() throws IOException { Workbook workbook = _testDataProvider.createWorkbook(); assertEquals(0, workbook.getActiveSheetIndex()); @@ -373,10 +385,11 @@ public abstract class BaseTestWorkbook { workbook.setActiveSheet(0); // test if second sheet is set up assertEquals(0, workbook.getActiveSheetIndex()); + workbook.close(); } @Test - public void setSheetOrder() { + public void setSheetOrder() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); for (int i=0; i < 10; i++) { @@ -420,6 +433,7 @@ public abstract class BaseTestWorkbook { assertEquals(9, wb.getSheetIndex("Sheet 1")); Workbook wbr = _testDataProvider.writeOutAndReadBack(wb); + wb.close(); assertEquals(0, wbr.getSheetIndex("Sheet 6")); assertEquals(1, wbr.getSheetIndex("Sheet 0")); @@ -439,10 +453,12 @@ public abstract class BaseTestWorkbook { Sheet s = wbr.getSheetAt(i); assertEquals(i, wbr.getSheetIndex(s)); } + + wbr.close(); } @Test - public void cloneSheet() { + public void cloneSheet() throws IOException { Workbook book = _testDataProvider.createWorkbook(); Sheet sheet = book.createSheet("TEST"); sheet.createRow(0).createCell(0).setCellValue("Test"); @@ -467,14 +483,14 @@ public abstract class BaseTestWorkbook { clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2)); assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); assertEquals(3, clonedSheet.getNumMergedRegions()); - + book.close(); } @Test - public void parentReferences(){ - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - assertSame(workbook, sheet.getWorkbook()); + public void parentReferences() throws IOException { + Workbook wb1 = _testDataProvider.createWorkbook(); + Sheet sheet = wb1.createSheet(); + assertSame(wb1, sheet.getWorkbook()); Row row = sheet.createRow(0); assertSame(sheet, row.getSheet()); @@ -483,9 +499,10 @@ public abstract class BaseTestWorkbook { assertSame(sheet, cell.getSheet()); assertSame(row, cell.getRow()); - workbook = _testDataProvider.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); - assertSame(workbook, sheet.getWorkbook()); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); + sheet = wb2.getSheetAt(0); + assertSame(wb2, sheet.getWorkbook()); row = sheet.getRow(0); assertSame(sheet, row.getSheet()); @@ -493,6 +510,7 @@ public abstract class BaseTestWorkbook { cell = row.getCell(1); assertSame(sheet, cell.getSheet()); assertSame(row, cell.getRow()); + wb2.close(); } @@ -505,7 +523,7 @@ public abstract class BaseTestWorkbook { */ @Deprecated @Test - public void setRepeatingRowsAnsColumns(){ + public void setRepeatingRowsAnsColumns() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sheet1 = wb.createSheet(); wb.setRepeatingRowsAndColumns(wb.getSheetIndex(sheet1), 0, 0, 0, 3); @@ -517,22 +535,23 @@ public abstract class BaseTestWorkbook { wb.setRepeatingRowsAndColumns(wb.getSheetIndex(sheet2), 0, 0, 0, 3); assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); assertEquals("A:A", sheet1.getRepeatingColumns().formatAsString()); + wb.close(); } /** * Tests that all of the unicode capable string fields can be set, written and then read back */ @Test - public void unicodeInAll() { - Workbook wb = _testDataProvider.createWorkbook(); - CreationHelper factory = wb.getCreationHelper(); + public void unicodeInAll() throws IOException { + Workbook wb1 = _testDataProvider.createWorkbook(); + CreationHelper factory = wb1.getCreationHelper(); //Create a unicode dataformat (contains euro symbol) - DataFormat df = wb.createDataFormat(); + DataFormat df = wb1.createDataFormat(); final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)"; short fmt = df.getFormat(formatStr); //Create a unicode sheet name (euro symbol) - Sheet s = wb.createSheet("\u20ac"); + Sheet s = wb1.createSheet("\u20ac"); //Set a unicode header (you guessed it the euro symbol) Header h = s.getHeader(); @@ -558,10 +577,11 @@ public abstract class BaseTestWorkbook { String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; c3.setCellFormula(formulaString); - wb = _testDataProvider.writeOutAndReadBack(wb); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); //Test the sheetname - s = wb.getSheet("\u20ac"); + s = wb2.getSheet("\u20ac"); assertNotNull(s); //Test the header @@ -579,7 +599,7 @@ public abstract class BaseTestWorkbook { //Test the dataformat r = s.getRow(0); c = r.getCell(1); - df = wb.createDataFormat(); + df = wb2.createDataFormat(); assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat())); //Test the cell string value @@ -589,9 +609,10 @@ public abstract class BaseTestWorkbook { //Test the cell formula c3 = r.getCell(3); assertEquals(c3.getCellFormula(), formulaString); + wb2.close(); } - private Workbook newSetSheetNameTestingWorkbook() throws Exception { + private Workbook newSetSheetNameTestingWorkbook() throws IOException { Workbook wb = _testDataProvider.createWorkbook(); Sheet sh1 = wb.createSheet("Worksheet"); Sheet sh2 = wb.createSheet("Testing 47100"); @@ -638,15 +659,15 @@ public abstract class BaseTestWorkbook { * @see Bugzilla 47100 */ @Test - public void setSheetName() throws Exception { + public void setSheetName() throws IOException { - Workbook wb = newSetSheetNameTestingWorkbook(); + Workbook wb1 = newSetSheetNameTestingWorkbook(); - Sheet sh1 = wb.getSheetAt(0); + Sheet sh1 = wb1.getSheetAt(0); - Name sale_2 = wb.getNameAt(1); - Name sale_3 = wb.getNameAt(2); - Name sale_4 = wb.getNameAt(3); + Name sale_2 = wb1.getNameAt(1); + Name sale_3 = wb1.getNameAt(2); + Name sale_4 = wb1.getNameAt(3); assertEquals("sale_2", sale_2.getNameName()); assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula()); @@ -655,7 +676,7 @@ public abstract class BaseTestWorkbook { assertEquals("sale_4", sale_4.getNameName()); assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula()); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + FormulaEvaluator evaluator = wb1.getCreationHelper().createFormulaEvaluator(); Cell cell0 = sh1.getRow(0).getCell(0); Cell cell1 = sh1.getRow(1).getCell(0); @@ -669,8 +690,8 @@ public abstract class BaseTestWorkbook { assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - wb.setSheetName(1, "47100 - First"); - wb.setSheetName(2, "47100 - Second"); + wb1.setSheetName(1, "47100 - First"); + wb1.setSheetName(2, "47100 - Second"); assertEquals("sale_2", sale_2.getNameName()); assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula()); @@ -688,13 +709,14 @@ public abstract class BaseTestWorkbook { assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - wb = _testDataProvider.writeOutAndReadBack(wb); + Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); + wb1.close(); - sh1 = wb.getSheetAt(0); + sh1 = wb2.getSheetAt(0); - sale_2 = wb.getNameAt(1); - sale_3 = wb.getNameAt(2); - sale_4 = wb.getNameAt(3); + sale_2 = wb2.getNameAt(1); + sale_3 = wb2.getNameAt(2); + sale_4 = wb2.getNameAt(3); cell0 = sh1.getRow(0).getCell(0); cell1 = sh1.getRow(1).getCell(0); @@ -711,13 +733,14 @@ public abstract class BaseTestWorkbook { assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula()); assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula()); - evaluator = wb.getCreationHelper().createFormulaEvaluator(); + evaluator = wb2.getCreationHelper().createFormulaEvaluator(); assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); + wb2.close(); } - public void changeSheetNameWithSharedFormulas(String sampleFile){ + public void changeSheetNameWithSharedFormulas(String sampleFile) throws IOException { Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); @@ -740,6 +763,7 @@ public abstract class BaseTestWorkbook { assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); } + wb.close(); } protected void assertSheetOrder(Workbook wb, String... sheets) {