From ba66108653b1cba7b2f09a949979243407a51874 Mon Sep 17 00:00:00 2001 From: Dominik Stadler Date: Thu, 15 Aug 2019 07:54:58 +0000 Subject: [PATCH] Close file-resources in unit-tests, fix IDE warnings git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1865208 13f79535-47bb-0310-9956-ffa450edef68 --- .../poi/xssf/model/TestThemesTable.java | 159 +- .../streaming/TestSXSSFEvaluationSheet.java | 19 +- .../usermodel/TestMissingWorkbookOnXSSF.java | 10 +- .../poi/xssf/usermodel/TestXSSFBugs.java | 1911 ++++++++--------- .../poi/xssf/usermodel/TestXSSFChart.java | 94 +- .../xssf/usermodel/TestXSSFChartSheet.java | 87 +- .../poi/xssf/usermodel/TestXSSFColor.java | 303 ++- .../usermodel/TestXSSFFormulaEvaluation.java | 377 ++-- .../poi/xssf/usermodel/TestXSSFHyperlink.java | 194 +- .../poi/xssf/usermodel/TestXSSFShape.java | 32 +- .../usermodel/TestXSSFSheetRowGrouping.java | 105 +- .../poi/xwpf/usermodel/TestXWPFDocument.java | 403 ++-- .../poi/xwpf/usermodel/TestXWPFRun.java | 26 +- .../poi/ss/formula/TestMissingWorkbook.java | 56 +- .../apache/poi/ss/usermodel/BaseTestCell.java | 15 +- 15 files changed, 1937 insertions(+), 1854 deletions(-) diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java index 2f0ece2420..2642fb0074 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java @@ -18,9 +18,13 @@ package org.apache.poi.xssf.model; 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 java.io.FileOutputStream; +import java.io.IOException; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; @@ -70,7 +74,9 @@ public class TestThemesTable { XSSFWorkbook simpleRS = XSSFTestDataSamples.writeOutAndReadBack(simple); XSSFWorkbook complexRS = XSSFTestDataSamples.writeOutAndReadBack(complex); // Fetch fresh copies to test with + simple.close(); simple = XSSFTestDataSamples.openSampleWorkbook(testFileSimple); + complex.close(); complex = XSSFTestDataSamples.openSampleWorkbook(testFileComplex); // Files and descriptions Map workbooks = new LinkedHashMap<>(); @@ -111,13 +117,13 @@ public class TestThemesTable { XSSFFont font = cell.getCellStyle().getFont(); CTColor ctColor = font.getCTFont().getColorArray(0); assertNotNull(ctColor); - assertEquals(true, ctColor.isSetTheme()); + assertTrue(ctColor.isSetTheme()); assertEquals(themeElem.idx, ctColor.getTheme()); // Get the colour, via the theme XSSFColor color = font.getXSSFColor(); // Theme colours aren't tinted - assertEquals(false, color.hasTint()); + assertFalse(color.hasTint()); // Check the RGB part (no tint) assertEquals( "Wrong theme colour " + themeElem.name + " on " + whatWorkbook, @@ -141,6 +147,11 @@ public class TestThemesTable { fos.close(); } } + + simpleRS.close(); + simple.close(); + complexRS.close(); + complex.close(); } /** @@ -155,80 +166,78 @@ public class TestThemesTable { * Note - Grey Row has an odd way of doing the styling... */ @Test - public void themedAndNonThemedColours() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFileComplex); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFCellStyle style; - XSSFColor color; - XSSFCell cell; - - String[] names = {"White","Black","Grey","Dark Blue","Blue","Red","Green"}; - String[] explicitFHexes = { "FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060", - "FF0070C0", "FFFF0000", "FF00B050" }; - String[] explicitBHexes = { "FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060", - "FF0000FF", "FFFF0000", "FF00FF00" }; - assertEquals(7, names.length); - - // Check the non-CF colours in Columns A, B, C and E - for (int rn=1; rn<8; rn++) { - int idx = rn-1; - XSSFRow row = sheet.getRow(rn); - assertNotNull("Missing row " + rn, row); - - // Theme cells come first - XSSFCell themeCell = row.getCell(0); - ThemeElement themeElem = ThemeElement.byId(idx); - assertCellContents(themeElem.name, themeCell); + public void themedAndNonThemedColours() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFileComplex)) { + XSSFSheet sheet = wb.getSheetAt(0); - // Sanity check names - assertCellContents(names[idx], row.getCell(1)); - assertCellContents(names[idx], row.getCell(2)); - assertCellContents(names[idx], row.getCell(4)); - - - // Check the colours - - // A: Theme Based, Foreground - style = themeCell.getCellStyle(); - color = style.getFont().getXSSFColor(); - assertEquals(true, color.isThemed()); - assertEquals(idx, color.getTheme()); - assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB())); - - // B: Theme Based, Foreground - cell = row.getCell(1); - style = cell.getCellStyle(); - color = style.getFont().getXSSFColor(); - assertEquals(true, color.isThemed()); - if (idx != 2) { + String[] names = {"White", "Black", "Grey", "Dark Blue", "Blue", "Red", "Green"}; + String[] explicitFHexes = {"FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060", + "FF0070C0", "FFFF0000", "FF00B050"}; + String[] explicitBHexes = {"FFFFFFFF", "FF000000", "FFC0C0C0", "FF002060", + "FF0000FF", "FFFF0000", "FF00FF00"}; + assertEquals(7, names.length); + + // Check the non-CF colours in Columns A, B, C and E + for (int rn = 1; rn < 8; rn++) { + int idx = rn - 1; + XSSFRow row = sheet.getRow(rn); + assertNotNull("Missing row " + rn, row); + + // Theme cells come first + XSSFCell themeCell = row.getCell(0); + ThemeElement themeElem = ThemeElement.byId(idx); + assertCellContents(themeElem.name, themeCell); + + // Sanity check names + assertCellContents(names[idx], row.getCell(1)); + assertCellContents(names[idx], row.getCell(2)); + assertCellContents(names[idx], row.getCell(4)); + + + // Check the colours + + // A: Theme Based, Foreground + XSSFCellStyle style = themeCell.getCellStyle(); + XSSFColor color = style.getFont().getXSSFColor(); + assertTrue(color.isThemed()); assertEquals(idx, color.getTheme()); assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB())); - } else { - assertEquals(1, color.getTheme()); - assertEquals(0.50, color.getTint(), 0.001); + + // B: Theme Based, Foreground + XSSFCell cell = row.getCell(1); + style = cell.getCellStyle(); + color = style.getFont().getXSSFColor(); + assertTrue(color.isThemed()); + if (idx != 2) { + assertEquals(idx, color.getTheme()); + assertEquals(rgbExpected[idx], Hex.encodeHexString(color.getRGB())); + } else { + assertEquals(1, color.getTheme()); + assertEquals(0.50, color.getTint(), 0.001); + } + + // C: Explicit, Foreground + cell = row.getCell(2); + style = cell.getCellStyle(); + color = style.getFont().getXSSFColor(); + assertFalse(color.isThemed()); + assertEquals(explicitFHexes[idx], color.getARGBHex()); + + // E: Explicit Background, Foreground all Black + cell = row.getCell(4); + style = cell.getCellStyle(); + + color = style.getFont().getXSSFColor(); + assertTrue(color.isThemed()); + assertEquals("FF000000", color.getARGBHex()); + + color = style.getFillForegroundXSSFColor(); + assertFalse(color.isThemed()); + assertEquals(explicitBHexes[idx], color.getARGBHex()); + color = style.getFillBackgroundColorColor(); + assertFalse(color.isThemed()); + assertNull(color.getARGBHex()); } - - // C: Explicit, Foreground - cell = row.getCell(2); - style = cell.getCellStyle(); - color = style.getFont().getXSSFColor(); - assertEquals(false, color.isThemed()); - assertEquals(explicitFHexes[idx], color.getARGBHex()); - - // E: Explicit Background, Foreground all Black - cell = row.getCell(4); - style = cell.getCellStyle(); - - color = style.getFont().getXSSFColor(); - assertEquals(true, color.isThemed()); - assertEquals("FF000000", color.getARGBHex()); - - color = style.getFillForegroundXSSFColor(); - assertEquals(false, color.isThemed()); - assertEquals(explicitBHexes[idx], color.getARGBHex()); - color = style.getFillBackgroundColorColor(); - assertEquals(false, color.isThemed()); - assertEquals(null, color.getARGBHex()); } // Check the CF colours @@ -242,13 +251,13 @@ public class TestThemesTable { @Test @SuppressWarnings("resource") - public void testAddNew() throws Exception { + public void testAddNew() { XSSFWorkbook wb = new XSSFWorkbook(); wb.createSheet(); - assertEquals(null, wb.getTheme()); + assertNull(wb.getTheme()); StylesTable styles = wb.getStylesSource(); - assertEquals(null, styles.getTheme()); + assertNull(styles.getTheme()); styles.ensureThemesTable(); diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java index 1c20bb815e..4ffa081908 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFEvaluationSheet.java @@ -19,14 +19,31 @@ package org.apache.poi.xssf.streaming; import org.apache.poi.ss.formula.EvaluationSheet; import org.apache.poi.ss.usermodel.BaseTestXEvaluationSheet; import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.junit.After; +import java.io.IOException; import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; import java.util.Map; public class TestSXSSFEvaluationSheet extends BaseTestXEvaluationSheet { + private List workbooksToClose = new ArrayList<>(); + + @After + public void closeWorkbooks() throws IOException { + for (Workbook workbook : workbooksToClose) { + workbook.close(); + } + } + @Override protected Map.Entry getInstance() { - SXSSFSheet sheet = new SXSSFWorkbook().createSheet(); + SXSSFWorkbook workbook = new SXSSFWorkbook(); + workbooksToClose.add(workbook); + + SXSSFSheet sheet = workbook.createSheet(); return new AbstractMap.SimpleEntry<>(sheet, new SXSSFEvaluationSheet(sheet)); } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java index 2427dd1d82..0de5eb5a46 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java @@ -20,6 +20,9 @@ package org.apache.poi.xssf.usermodel; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.formula.TestMissingWorkbook; import org.apache.poi.xssf.XSSFTestDataSamples; +import org.junit.Before; + +import static org.junit.Assert.assertNotNull; /** * XSSF Specific version of the Missing Workbooks test @@ -28,12 +31,13 @@ public final class TestMissingWorkbookOnXSSF extends TestMissingWorkbook { public TestMissingWorkbookOnXSSF() { super("52575_main.xlsx", "source_dummy.xlsx", "52575_source.xls"); } - + @Override - protected void setUp() throws Exception { + @Before + public void setUp() { mainWorkbook = XSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); - + assertNotNull(mainWorkbook); assertNotNull(sourceWorkbook); } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java index e0bf0f415c..da056eb1ea 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java @@ -160,32 +160,31 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug45430() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx"); - assertFalse(wb.isMacroEnabled()); - assertEquals(3, wb.getNumberOfNames()); - - assertEquals(0, wb.getName("SheetAA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetAA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetA!$A$1", wb.getName("SheetAA1").getRefersToFormula()); - assertEquals("SheetA", wb.getName("SheetAA1").getSheetName()); - - assertEquals(0, wb.getName("SheetBA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetBA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetB!$A$1", wb.getName("SheetBA1").getRefersToFormula()); - assertEquals("SheetB", wb.getName("SheetBA1").getSheetName()); - - assertEquals(0, wb.getName("SheetCA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetCA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetC!$A$1", wb.getName("SheetCA1").getRefersToFormula()); - assertEquals("SheetC", wb.getName("SheetCA1").getSheetName()); - - // Save and re-load, still there - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, nwb.getNumberOfNames()); - assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula()); - - nwb.close(); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx")) { + assertFalse(wb.isMacroEnabled()); + assertEquals(3, wb.getNumberOfNames()); + + assertEquals(0, wb.getName("SheetAA1").getCTName().getLocalSheetId()); + assertFalse(wb.getName("SheetAA1").getCTName().isSetLocalSheetId()); + assertEquals("SheetA!$A$1", wb.getName("SheetAA1").getRefersToFormula()); + assertEquals("SheetA", wb.getName("SheetAA1").getSheetName()); + + assertEquals(0, wb.getName("SheetBA1").getCTName().getLocalSheetId()); + assertFalse(wb.getName("SheetBA1").getCTName().isSetLocalSheetId()); + assertEquals("SheetB!$A$1", wb.getName("SheetBA1").getRefersToFormula()); + assertEquals("SheetB", wb.getName("SheetBA1").getSheetName()); + + assertEquals(0, wb.getName("SheetCA1").getCTName().getLocalSheetId()); + assertFalse(wb.getName("SheetCA1").getCTName().isSetLocalSheetId()); + assertEquals("SheetC!$A$1", wb.getName("SheetCA1").getRefersToFormula()); + assertEquals("SheetC", wb.getName("SheetCA1").getSheetName()); + + // Save and re-load, still there + try (XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + assertEquals(3, nwb.getNumberOfNames()); + assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula()); + } + } } /** @@ -276,8 +275,9 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug49020() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx"); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx")) { + assertNotNull(wb); + } } /** @@ -285,10 +285,10 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug49325() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx"); - CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet(); - assertNotNull(sh.getPhoneticPr()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx")) { + CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet(); + assertNotNull(sh.getPhoneticPr()); + } } /** @@ -297,35 +297,34 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug48923() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx"); - assertEquals(4, wb.getNumberOfNames()); - - Name b1 = wb.getName("NameB1"); - Name b2 = wb.getName("NameB2"); - Name sheet2 = wb.getName("NameSheet2"); - Name test = wb.getName("Test"); - - assertNotNull(b1); - assertEquals("NameB1", b1.getNameName()); - assertEquals("Sheet1", b1.getSheetName()); - assertEquals(-1, b1.getSheetIndex()); - - assertNotNull(b2); - assertEquals("NameB2", b2.getNameName()); - assertEquals("Sheet1", b2.getSheetName()); - assertEquals(-1, b2.getSheetIndex()); - - assertNotNull(sheet2); - assertEquals("NameSheet2", sheet2.getNameName()); - assertEquals("Sheet2", sheet2.getSheetName()); - assertEquals(-1, sheet2.getSheetIndex()); - - assertNotNull(test); - assertEquals("Test", test.getNameName()); - assertEquals("Sheet1", test.getSheetName()); - assertEquals(-1, test.getSheetIndex()); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx")) { + assertEquals(4, wb.getNumberOfNames()); + + Name b1 = wb.getName("NameB1"); + Name b2 = wb.getName("NameB2"); + Name sheet2 = wb.getName("NameSheet2"); + Name test = wb.getName("Test"); + + assertNotNull(b1); + assertEquals("NameB1", b1.getNameName()); + assertEquals("Sheet1", b1.getSheetName()); + assertEquals(-1, b1.getSheetIndex()); + + assertNotNull(b2); + assertEquals("NameB2", b2.getNameName()); + assertEquals("Sheet1", b2.getSheetName()); + assertEquals(-1, b2.getSheetIndex()); + + assertNotNull(sheet2); + assertEquals("NameSheet2", sheet2.getNameName()); + assertEquals("Sheet2", sheet2.getSheetName()); + assertEquals(-1, sheet2.getSheetIndex()); + + assertNotNull(test); + assertEquals("Test", test.getNameName()); + assertEquals("Sheet1", test.getSheetName()); + assertEquals(-1, test.getSheetIndex()); + } } /** @@ -375,37 +374,36 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug48779() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx"); - XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); - XSSFCellStyle cs = cell.getCellStyle(); - - assertNotNull(cs); - assertEquals(1, cs.getIndex()); - - // Look at the low level xml elements - assertEquals(2, cs.getCoreXf().getFillId()); - assertEquals(0, cs.getCoreXf().getXfId()); - assertTrue(cs.getCoreXf().getApplyFill()); - - XSSFCellFill fg = wb.getStylesSource().getFillAt(2); - assertNotNull(fg.getFillForegroundColor()); - assertEquals(0, fg.getFillForegroundColor().getIndexed()); - assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0); - assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex()); - assertNotNull(fg.getFillBackgroundColor()); - assertEquals(64, fg.getFillBackgroundColor().getIndexed()); - - // Now look higher up - assertNotNull(cs.getFillForegroundXSSFColor()); - assertEquals(0, cs.getFillForegroundColor()); - assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex()); - assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex()); - - assertEquals(64, cs.getFillBackgroundColor()); - assertNull(cs.getFillBackgroundXSSFColor().getARGBHex()); - assertNull(cs.getFillBackgroundColorColor().getARGBHex()); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { + XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); + XSSFCellStyle cs = cell.getCellStyle(); + + assertNotNull(cs); + assertEquals(1, cs.getIndex()); + + // Look at the low level xml elements + assertEquals(2, cs.getCoreXf().getFillId()); + assertEquals(0, cs.getCoreXf().getXfId()); + assertTrue(cs.getCoreXf().getApplyFill()); + + XSSFCellFill fg = wb.getStylesSource().getFillAt(2); + assertNotNull(fg.getFillForegroundColor()); + assertEquals(0, fg.getFillForegroundColor().getIndexed()); + assertEquals(0.0, fg.getFillForegroundColor().getTint(), 0); + assertEquals("FFFF0000", fg.getFillForegroundColor().getARGBHex()); + assertNotNull(fg.getFillBackgroundColor()); + assertEquals(64, fg.getFillBackgroundColor().getIndexed()); + + // Now look higher up + assertNotNull(cs.getFillForegroundXSSFColor()); + assertEquals(0, cs.getFillForegroundColor()); + assertEquals("FFFF0000", cs.getFillForegroundXSSFColor().getARGBHex()); + assertEquals("FFFF0000", cs.getFillForegroundColorColor().getARGBHex()); + + assertEquals(64, cs.getFillBackgroundColor()); + assertNull(cs.getFillBackgroundXSSFColor().getARGBHex()); + assertNull(cs.getFillBackgroundColorColor().getARGBHex()); + } } /** @@ -414,33 +412,32 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug47490() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx"); - Sheet s = wb.getSheetAt(1); - Row r; - DataFormatter df = new DataFormatter(); - - r = s.getRow(1); - assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0); - assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("1", df.formatCellValue(r.getCell(2))); - assertEquals("1", df.formatRawCellContents(1.0, -1, "@")); - assertEquals("1", df.formatRawCellContents(1.0, -1, "General")); - - r = s.getRow(2); - assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0); - assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("12", df.formatCellValue(r.getCell(2))); - assertEquals("12", df.formatRawCellContents(12.0, -1, "@")); - assertEquals("12", df.formatRawCellContents(12.0, -1, "General")); - - r = s.getRow(3); - assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0); - assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("123", df.formatCellValue(r.getCell(2))); - assertEquals("123", df.formatRawCellContents(123.0, -1, "@")); - assertEquals("123", df.formatRawCellContents(123.0, -1, "General")); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GeneralFormatTests.xlsx")) { + Sheet s = wb.getSheetAt(1); + Row r; + DataFormatter df = new DataFormatter(); + + r = s.getRow(1); + assertEquals(1.0, r.getCell(2).getNumericCellValue(), 0); + assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); + assertEquals("1", df.formatCellValue(r.getCell(2))); + assertEquals("1", df.formatRawCellContents(1.0, -1, "@")); + assertEquals("1", df.formatRawCellContents(1.0, -1, "General")); + + r = s.getRow(2); + assertEquals(12.0, r.getCell(2).getNumericCellValue(), 0); + assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); + assertEquals("12", df.formatCellValue(r.getCell(2))); + assertEquals("12", df.formatRawCellContents(12.0, -1, "@")); + assertEquals("12", df.formatRawCellContents(12.0, -1, "General")); + + r = s.getRow(3); + assertEquals(123.0, r.getCell(2).getNumericCellValue(), 0); + assertEquals("General", r.getCell(2).getCellStyle().getDataFormatString()); + assertEquals("123", df.formatCellValue(r.getCell(2))); + assertEquals("123", df.formatRawCellContents(123.0, -1, "@")); + assertEquals("123", df.formatRawCellContents(123.0, -1, "General")); + } } /** @@ -453,38 +450,37 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug49609() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx"); - assertEquals("FAM", wb.getSheetName(0)); - assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49609.xlsx")) { + assertEquals("FAM", wb.getSheetName(0)); + assertEquals("Cycle", wb.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); + } } @Test public void bug49783() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx"); - Sheet sheet = wb.getSheetAt(0); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell; - - cell = sheet.getRow(0).getCell(0); - assertEquals("#REF!*#REF!", cell.getCellFormula()); - assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType()); - assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); - - Name nm1 = wb.getName("sale_1"); - assertNotNull("name sale_1 should be present", nm1); - assertEquals("Sheet1!#REF!", nm1.getRefersToFormula()); - Name nm2 = wb.getName("sale_2"); - assertNotNull("name sale_2 should be present", nm2); - assertEquals("Sheet1!#REF!", nm2.getRefersToFormula()); - - cell = sheet.getRow(1).getCell(0); - assertEquals("sale_1*sale_2", cell.getCellFormula()); - assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType()); - assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); - - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49783.xlsx")) { + Sheet sheet = wb.getSheetAt(0); + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + Cell cell; + + cell = sheet.getRow(0).getCell(0); + assertEquals("#REF!*#REF!", cell.getCellFormula()); + assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType()); + assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); + + Name nm1 = wb.getName("sale_1"); + assertNotNull("name sale_1 should be present", nm1); + assertEquals("Sheet1!#REF!", nm1.getRefersToFormula()); + Name nm2 = wb.getName("sale_2"); + assertNotNull("name sale_2 should be present", nm2); + assertEquals("Sheet1!#REF!", nm2.getRefersToFormula()); + + cell = sheet.getRow(1).getCell(0); + assertEquals("sale_1*sale_2", cell.getCellFormula()); + assertEquals(CellType.ERROR, evaluator.evaluateInCell(cell).getCellType()); + assertEquals("#REF!", FormulaError.forInt(cell.getErrorCellValue()).getString()); + } } /** @@ -575,28 +571,27 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug49940() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - assertEquals(10, wb.getStylesSource().getNumCellStyles()); - - ByteArrayOutputStream b1 = new ByteArrayOutputStream(); - ByteArrayOutputStream b2 = new ByteArrayOutputStream(); - ByteArrayOutputStream b3 = new ByteArrayOutputStream(); - wb.write(b1); - wb.write(b2); - wb.write(b3); - - for (byte[] data : new byte[][]{ - b1.toByteArray(), b2.toByteArray(), b3.toByteArray() - }) { - ByteArrayInputStream bais = new ByteArrayInputStream(data); - XSSFWorkbook wb2 = new XSSFWorkbook(bais); - assertEquals(3, wb2.getNumberOfSheets()); - assertEquals(10, wb2.getStylesSource().getNumCellStyles()); - wb2.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx")) { + assertEquals(3, wb.getNumberOfSheets()); + assertEquals(10, wb.getStylesSource().getNumCellStyles()); + + ByteArrayOutputStream b1 = new ByteArrayOutputStream(); + ByteArrayOutputStream b2 = new ByteArrayOutputStream(); + ByteArrayOutputStream b3 = new ByteArrayOutputStream(); + wb.write(b1); + wb.write(b2); + wb.write(b3); + + for (byte[] data : new byte[][]{ + b1.toByteArray(), b2.toByteArray(), b3.toByteArray() + }) { + ByteArrayInputStream bais = new ByteArrayInputStream(data); + XSSFWorkbook wb2 = new XSSFWorkbook(bais); + assertEquals(3, wb2.getNumberOfSheets()); + assertEquals(10, wb2.getStylesSource().getNumCellStyles()); + wb2.close(); + } } - - wb.close(); } /** @@ -605,71 +600,71 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug49966() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples - .openSampleWorkbook("shared_formulas.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - // CalcChain has lots of entries - CalculationChain cc = wb1.getCalculationChain(); - assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR()); - assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR()); - assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR()); - assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR()); - assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR()); - assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR()); - assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR()); - assertEquals(40, cc.getCTCalcChain().sizeOfCArray()); - - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - // Try various ways of changing the formulas - // If it stays a formula, chain entry should remain - // Otherwise should go - sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay - sheet.getRow(2).getCell(0).setCellFormula(null); // go - sheet.getRow(3).getCell(0).setCellFormula("14"); // stay - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - sheet.getRow(4).getCell(0).setBlank(); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - validateCells(sheet); - sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go - validateCells(sheet); - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - sheet.getRow(6).getCell(0).setBlank(); // go - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - sheet.getRow(7).getCell(0).setCellValue((String) null); // go - - XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - - // Save and check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(35, cc.getCTCalcChain().sizeOfCArray()); - - cc = wb2.getCalculationChain(); - assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR()); - assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR()); - assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR()); - wb2.close(); + try (XSSFWorkbook wb1 = XSSFTestDataSamples + .openSampleWorkbook("shared_formulas.xlsx")) { + XSSFSheet sheet = wb1.getSheetAt(0); + + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + // CalcChain has lots of entries + CalculationChain cc = wb1.getCalculationChain(); + assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR()); + assertEquals("A3", cc.getCTCalcChain().getCArray(1).getR()); + assertEquals("A4", cc.getCTCalcChain().getCArray(2).getR()); + assertEquals("A5", cc.getCTCalcChain().getCArray(3).getR()); + assertEquals("A6", cc.getCTCalcChain().getCArray(4).getR()); + assertEquals("A7", cc.getCTCalcChain().getCArray(5).getR()); + assertEquals("A8", cc.getCTCalcChain().getCArray(6).getR()); + assertEquals(40, cc.getCTCalcChain().sizeOfCArray()); + + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + // Try various ways of changing the formulas + // If it stays a formula, chain entry should remain + // Otherwise should go + sheet.getRow(1).getCell(0).setCellFormula("A1"); // stay + sheet.getRow(2).getCell(0).setCellFormula(null); // go + sheet.getRow(3).getCell(0).setCellFormula("14"); // stay + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + sheet.getRow(4).getCell(0).setBlank(); // go + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + validateCells(sheet); + sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go + validateCells(sheet); + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + sheet.getRow(6).getCell(0).setBlank(); // go + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + sheet.getRow(7).getCell(0).setCellValue((String) null); // go + + XSSFTestDataSamples.writeOutAndReadBack(wb1).close(); + + // Save and check + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + wb1.close(); + assertEquals(35, cc.getCTCalcChain().sizeOfCArray()); + + cc = wb2.getCalculationChain(); + assertEquals("A2", cc.getCTCalcChain().getCArray(0).getR()); + assertEquals("A4", cc.getCTCalcChain().getCArray(1).getR()); + assertEquals("A9", cc.getCTCalcChain().getCArray(2).getR()); + } + } } @Test public void bug49966Row() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("shared_formulas.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - - validateCells(sheet); - sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go - validateCells(sheet); + try (XSSFWorkbook wb = XSSFTestDataSamples + .openSampleWorkbook("shared_formulas.xlsx")) { + XSSFSheet sheet = wb.getSheetAt(0); - wb.close(); + validateCells(sheet); + sheet.getRow(5).removeCell(sheet.getRow(5).getCell(0)); // go + validateCells(sheet); + } } private void validateCells(XSSFSheet sheet) { @@ -681,18 +676,18 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void bug49156() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx"); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("49156.xlsx")) { + FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sheet = wb.getSheetAt(0); - for (Row row : sheet) { - for (Cell cell : row) { - if (cell.getCellType() == CellType.FORMULA) { - formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells + Sheet sheet = wb.getSheetAt(0); + for (Row row : sheet) { + for (Cell cell : row) { + if (cell.getCellType() == CellType.FORMULA) { + formulaEvaluator.evaluateInCell(cell); // caused NPE on some cells + } } } } - wb.close(); } /** @@ -700,26 +695,25 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug50440And51875() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx"); - Sheet s = wb.getSheetAt(0); - Cell c = s.getRow(0).getCell(0); - - assertEquals("SUM(\n1,2\n)", c.getCellFormula()); - assertEquals(3.0, c.getNumericCellValue(), 0); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("NewlineInFormulas.xlsx")) { + Sheet s = wb.getSheetAt(0); + Cell c = s.getRow(0).getCell(0); - FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - formulaEvaluator.evaluateFormulaCell(c); + assertEquals("SUM(\n1,2\n)", c.getCellFormula()); + assertEquals(3.0, c.getNumericCellValue(), 0); - assertEquals("SUM(\n1,2\n)", c.getCellFormula()); - assertEquals(3.0, c.getNumericCellValue(), 0); + FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); + formulaEvaluator.evaluateFormulaCell(c); - // For 51875 - Cell b3 = s.getRow(2).getCell(1); - formulaEvaluator.evaluateFormulaCell(b3); - assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas - assertEquals(3.0, b3.getNumericCellValue(), 0); + assertEquals("SUM(\n1,2\n)", c.getCellFormula()); + assertEquals(3.0, c.getNumericCellValue(), 0); - wb.close(); + // For 51875 + Cell b3 = s.getRow(2).getCell(1); + formulaEvaluator.evaluateFormulaCell(b3); + assertEquals("B1+B2", b3.getCellFormula()); // The newline is lost for shared formulas + assertEquals(3.0, b3.getNumericCellValue(), 0); + } } /** @@ -789,31 +783,30 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug50299() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx"); - - // Check all the colours - for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) { - Sheet s = wb.getSheetAt(sn); - for (Row r : s) { - for (Cell c : r) { - CellStyle cs = c.getCellStyle(); - if (cs != null) { - cs.getFillForegroundColor(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) { + + // Check all the colours + for (int sn = 0; sn < wb.getNumberOfSheets(); sn++) { + Sheet s = wb.getSheetAt(sn); + for (Row r : s) { + for (Cell c : r) { + CellStyle cs = c.getCellStyle(); + if (cs != null) { + cs.getFillForegroundColor(); + } } } } - } - - // Check one bit in detail - // Check that we get back foreground=0 for the theme colours, - // and background=64 for the auto colouring - Sheet s = wb.getSheetAt(0); - assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor()); - assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor()); - assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor()); - assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor()); - wb.close(); + // Check one bit in detail + // Check that we get back foreground=0 for the theme colours, + // and background=64 for the auto colouring + Sheet s = wb.getSheetAt(0); + assertEquals(0, s.getRow(0).getCell(8).getCellStyle().getFillForegroundColor()); + assertEquals(64, s.getRow(0).getCell(8).getCellStyle().getFillBackgroundColor()); + assertEquals(0, s.getRow(1).getCell(8).getCellStyle().getFillForegroundColor()); + assertEquals(64, s.getRow(1).getCell(8).getCellStyle().getFillBackgroundColor()); + } } /** @@ -821,21 +814,21 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug50786() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx"); - XSSFSheet s = wb.getSheetAt(0); - XSSFRow r = s.getRow(2); - - // Check we have the right cell - XSSFCell c = r.getCell(1); - assertEquals("test\u00a0", c.getRichStringCellValue().getString()); - - // It should be light green - XSSFCellStyle cs = c.getCellStyle(); - assertEquals(42, cs.getFillForegroundColor()); - assertEquals(42, cs.getFillForegroundColorColor().getIndexed()); - assertNotNull(cs.getFillForegroundColorColor().getRGB()); - assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50786-indexed_colours.xlsx")) { + XSSFSheet s = wb.getSheetAt(0); + XSSFRow r = s.getRow(2); + + // Check we have the right cell + XSSFCell c = r.getCell(1); + assertEquals("test\u00a0", c.getRichStringCellValue().getString()); + + // It should be light green + XSSFCellStyle cs = c.getCellStyle(); + assertEquals(42, cs.getFillForegroundColor()); + assertEquals(42, cs.getFillForegroundColorColor().getIndexed()); + assertNotNull(cs.getFillForegroundColorColor().getRGB()); + assertEquals("FFCCFFCC", cs.getFillForegroundColorColor().getARGBHex()); + } } /** @@ -844,27 +837,27 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug50846() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx"); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50846-border_colours.xlsx")) { - XSSFSheet sheet = wb.getSheetAt(0); - XSSFRow row = sheet.getRow(0); + XSSFSheet sheet = wb.getSheetAt(0); + XSSFRow row = sheet.getRow(0); - // Border from a theme, brown - XSSFCell cellT = row.getCell(0); - XSSFCellStyle styleT = cellT.getCellStyle(); - XSSFColor colorT = styleT.getBottomBorderXSSFColor(); + // Border from a theme, brown + XSSFCell cellT = row.getCell(0); + XSSFCellStyle styleT = cellT.getCellStyle(); + XSSFColor colorT = styleT.getBottomBorderXSSFColor(); - assertEquals(5, colorT.getTheme()); - assertEquals("FFC0504D", colorT.getARGBHex()); + assertEquals(5, colorT.getTheme()); + assertEquals("FFC0504D", colorT.getARGBHex()); - // Border from a style direct, red - XSSFCell cellS = row.getCell(1); - XSSFCellStyle styleS = cellS.getCellStyle(); - XSSFColor colorS = styleS.getBottomBorderXSSFColor(); + // Border from a style direct, red + XSSFCell cellS = row.getCell(1); + XSSFCellStyle styleS = cellS.getCellStyle(); + XSSFColor colorS = styleS.getBottomBorderXSSFColor(); - assertEquals(0, colorS.getTheme()); - assertEquals("FFFF0000", colorS.getARGBHex()); - wb.close(); + assertEquals(0, colorS.getTheme()); + assertEquals("FFFF0000", colorS.getARGBHex()); + } } /** @@ -874,29 +867,29 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug50784() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx"); - XSSFSheet s = wb.getSheetAt(0); - XSSFRow r = s.getRow(0); - - // Column 1 has a font with regular colours - XSSFCell cr = r.getCell(1); - XSSFFont fr = wb.getFontAt(cr.getCellStyle().getFontIndexAsInt()); - XSSFColor colr = fr.getXSSFColor(); - // No theme, has colours - assertEquals(0, colr.getTheme()); - assertNotNull(colr.getRGB()); - - // Column 0 has a font with colours from a theme - XSSFCell ct = r.getCell(0); - XSSFFont ft = wb.getFontAt(ct.getCellStyle().getFontIndexAsInt()); - XSSFColor colt = ft.getXSSFColor(); - // Has a theme, which has the colours on it - assertEquals(9, colt.getTheme()); - XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme()); - assertNotNull(themeC.getRGB()); - assertNotNull(colt.getRGB()); - assertEquals(themeC.getARGBHex(), colt.getARGBHex()); // The same colour - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50784-font_theme_colours.xlsx")) { + XSSFSheet s = wb.getSheetAt(0); + XSSFRow r = s.getRow(0); + + // Column 1 has a font with regular colours + XSSFCell cr = r.getCell(1); + XSSFFont fr = wb.getFontAt(cr.getCellStyle().getFontIndexAsInt()); + XSSFColor colr = fr.getXSSFColor(); + // No theme, has colours + assertEquals(0, colr.getTheme()); + assertNotNull(colr.getRGB()); + + // Column 0 has a font with colours from a theme + XSSFCell ct = r.getCell(0); + XSSFFont ft = wb.getFontAt(ct.getCellStyle().getFontIndexAsInt()); + XSSFColor colt = ft.getXSSFColor(); + // Has a theme, which has the colours on it + assertEquals(9, colt.getTheme()); + XSSFColor themeC = wb.getTheme().getThemeColor(colt.getTheme()); + assertNotNull(themeC.getRGB()); + assertNotNull(colt.getRGB()); + assertEquals(themeC.getARGBHex(), colt.getARGBHex()); // The same colour + } } /** @@ -1247,65 +1240,64 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug51222() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx"); - XSSFSheet s = wb.getSheetAt(0); - - XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0); - XSSFCell cA5_1F497D = s.getRow(4).getCell(0); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51222.xlsx")) { + XSSFSheet s = wb.getSheetAt(0); - // Check the text - assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString()); - assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString()); + XSSFCell cA4_EEECE1 = s.getRow(3).getCell(0); + XSSFCell cA5_1F497D = s.getRow(4).getCell(0); - // Check the styles assigned to them - assertEquals(4, cA4_EEECE1.getCTCell().getS()); - assertEquals(5, cA5_1F497D.getCTCell().getS()); + // Check the text + assertEquals("A4", cA4_EEECE1.getRichStringCellValue().getString()); + assertEquals("A5", cA5_1F497D.getRichStringCellValue().getString()); - // Check we look up the correct style - assertEquals(4, cA4_EEECE1.getCellStyle().getIndex()); - assertEquals(5, cA5_1F497D.getCellStyle().getIndex()); + // Check the styles assigned to them + assertEquals(4, cA4_EEECE1.getCTCell().getS()); + assertEquals(5, cA5_1F497D.getCTCell().getS()); - // Check the fills on them at the low level - assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId()); - assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId()); + // Check we look up the correct style + assertEquals(4, cA4_EEECE1.getCellStyle().getIndex()); + assertEquals(5, cA5_1F497D.getCellStyle().getIndex()); - // These should reference themes 2 and 3 - assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme()); - assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme()); + // Check the fills on them at the low level + assertEquals(5, cA4_EEECE1.getCellStyle().getCoreXf().getFillId()); + assertEquals(6, cA5_1F497D.getCellStyle().getCoreXf().getFillId()); - // Ensure we get the right colours for these themes - // TODO fix - // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex()); - // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex()); + // These should reference themes 2 and 3 + assertEquals(2, wb.getStylesSource().getFillAt(5).getCTFill().getPatternFill().getFgColor().getTheme()); + assertEquals(3, wb.getStylesSource().getFillAt(6).getCTFill().getPatternFill().getFgColor().getTheme()); - // Finally check the colours on the styles - // TODO fix - // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex()); - // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex()); + // Ensure we get the right colours for these themes + // TODO fix + // assertEquals("FFEEECE1", wb.getTheme().getThemeColor(2).getARGBHex()); + // assertEquals("FF1F497D", wb.getTheme().getThemeColor(3).getARGBHex()); - wb.close(); + // Finally check the colours on the styles + // TODO fix + // assertEquals("FFEEECE1", cA4_EEECE1.getCellStyle().getFillForegroundXSSFColor().getARGBHex()); + // assertEquals("FF1F497D", cA5_1F497D.getCellStyle().getFillForegroundXSSFColor().getARGBHex()); + } } @Test public void bug51470() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx"); - XSSFSheet sh0 = wb.getSheetAt(0); - XSSFSheet sh1 = wb.cloneSheet(0); - List rels0 = sh0.getRelationParts(); - List rels1 = sh1.getRelationParts(); - assertEquals(1, rels0.size()); - assertEquals(1, rels1.size()); - - PackageRelationship pr0 = rels0.get(0).getRelationship(); - PackageRelationship pr1 = rels1.get(0).getRelationship(); - - assertEquals(pr0.getTargetMode(), pr1.getTargetMode()); - assertEquals(pr0.getTargetURI(), pr1.getTargetURI()); - POIXMLDocumentPart doc0 = rels0.get(0).getDocumentPart(); - POIXMLDocumentPart doc1 = rels1.get(0).getDocumentPart(); - - assertEquals(doc0, doc1); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51470.xlsx")) { + XSSFSheet sh0 = wb.getSheetAt(0); + XSSFSheet sh1 = wb.cloneSheet(0); + List rels0 = sh0.getRelationParts(); + List rels1 = sh1.getRelationParts(); + assertEquals(1, rels0.size()); + assertEquals(1, rels1.size()); + + PackageRelationship pr0 = rels0.get(0).getRelationship(); + PackageRelationship pr1 = rels1.get(0).getRelationship(); + + assertEquals(pr0.getTargetMode(), pr1.getTargetMode()); + assertEquals(pr0.getTargetURI(), pr1.getTargetURI()); + POIXMLDocumentPart doc0 = rels0.get(0).getDocumentPart(); + POIXMLDocumentPart doc1 = rels1.get(0).getDocumentPart(); + + assertEquals(doc0, doc1); + } } /** @@ -1379,19 +1371,19 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug51963() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx"); - Sheet sheet = wb.getSheetAt(0); - assertEquals("Abc,1", sheet.getSheetName()); - - Name name = wb.getName("Intekon.ProdCodes"); - assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula()); - - AreaReference ref = wb.getCreationHelper().createAreaReference(name.getRefersToFormula()); - assertEquals(0, ref.getFirstCell().getRow()); - assertEquals(0, ref.getFirstCell().getCol()); - assertEquals(1, ref.getLastCell().getRow()); - assertEquals(0, ref.getLastCell().getCol()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx")) { + Sheet sheet = wb.getSheetAt(0); + assertEquals("Abc,1", sheet.getSheetName()); + + Name name = wb.getName("Intekon.ProdCodes"); + assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula()); + + AreaReference ref = wb.getCreationHelper().createAreaReference(name.getRefersToFormula()); + assertEquals(0, ref.getFirstCell().getRow()); + assertEquals(0, ref.getFirstCell().getCol()); + assertEquals(1, ref.getLastCell().getRow()); + assertEquals(0, ref.getLastCell().getCol()); + } } /** @@ -1400,29 +1392,29 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug48703() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx")) { + XSSFSheet sheet = wb.getSheetAt(0); - // Contains two forms, one with a range and one a list - XSSFRow r1 = sheet.getRow(0); - XSSFRow r2 = sheet.getRow(1); - XSSFCell c1 = r1.getCell(1); - XSSFCell c2 = r2.getCell(1); + // Contains two forms, one with a range and one a list + XSSFRow r1 = sheet.getRow(0); + XSSFRow r2 = sheet.getRow(1); + XSSFCell c1 = r1.getCell(1); + XSSFCell c2 = r2.getCell(1); - assertEquals(20.0, c1.getNumericCellValue(), 0); - assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula()); + assertEquals(20.0, c1.getNumericCellValue(), 0); + assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula()); - assertEquals(20.0, c2.getNumericCellValue(), 0); - assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula()); + assertEquals(20.0, c2.getNumericCellValue(), 0); + assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula()); - // Try evaluating both - XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - eval.evaluateFormulaCell(c1); - eval.evaluateFormulaCell(c2); + // Try evaluating both + XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); + eval.evaluateFormulaCell(c1); + eval.evaluateFormulaCell(c2); - assertEquals(20.0, c1.getNumericCellValue(), 0); - assertEquals(20.0, c2.getNumericCellValue(), 0); - wb.close(); + assertEquals(20.0, c1.getNumericCellValue(), 0); + assertEquals(20.0, c2.getNumericCellValue(), 0); + } } /** @@ -1430,31 +1422,31 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug51710() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx"); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx")) { - final String[] columns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}; - final int rowMax = 500; // bug triggers on row index 59 + final String[] columns = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}; + final int rowMax = 500; // bug triggers on row index 59 - Sheet sheet = wb.getSheetAt(0); + Sheet sheet = wb.getSheetAt(0); - // go through all formula cells - for (int rInd = 2; rInd <= rowMax; rInd++) { - Row row = sheet.getRow(rInd); + // go through all formula cells + for (int rInd = 2; rInd <= rowMax; rInd++) { + Row row = sheet.getRow(rInd); - for (int cInd = 1; cInd <= 12; cInd++) { - Cell cell = row.getCell(cInd); - String formula = cell.getCellFormula(); - CellReference ref = new CellReference(cell); + for (int cInd = 1; cInd <= 12; cInd++) { + Cell cell = row.getCell(cInd); + String formula = cell.getCellFormula(); + CellReference ref = new CellReference(cell); - //simulate correct answer - String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2"; + //simulate correct answer + String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2"; - assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula); - } + assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula); + } + } } - wb.close(); } /** @@ -1462,35 +1454,35 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug5301() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx"); - FormulaEvaluator evaluator = - wb.getCreationHelper().createFormulaEvaluator(); - // A1: SUM(B1: IZ1) - double a1Value = - evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(0)).getNumberValue(); - - // Assert - assertEquals(259.0, a1Value, 0.0); - - // KY: SUM(B1: IZ1) - /*double ky1Value =*/ - assertEquals(259.0, evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(310)).getNumberValue(), 0.0001); - - // Assert - assertEquals(259.0, a1Value, 0.0); - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx")) { + FormulaEvaluator evaluator = + wb.getCreationHelper().createFormulaEvaluator(); + // A1: SUM(B1: IZ1) + double a1Value = + evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(0)).getNumberValue(); + + // Assert + assertEquals(259.0, a1Value, 0.0); + + // KY: SUM(B1: IZ1) + /*double ky1Value =*/ + assertEquals(259.0, evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(310)).getNumberValue(), 0.0001); + + // Assert + assertEquals(259.0, a1Value, 0.0); + } } @Test public void bug54436() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx"); - if (!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")) { - Function func = (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA; + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx")) { + if (!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")) { + Function func = (args, srcRowIndex, srcColumnIndex) -> ErrorEval.NA; - WorkbookEvaluator.registerFunction("GETPIVOTDATA", func); + WorkbookEvaluator.registerFunction("GETPIVOTDATA", func); + } + wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); } - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - wb.close(); } /** @@ -1510,33 +1502,33 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { public void bug55692_stream() throws IOException { // Directly on a Stream, will go via POIFS and spot it's // actually a .xlsx file encrypted with the default password, and open - Workbook wb = WorkbookFactory.create( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); + try (Workbook wb = WorkbookFactory.create( + POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) { + assertNotNull(wb); + assertEquals(3, wb.getNumberOfSheets()); + } } @Test public void bug55692_poifs2() throws IOException { // Via a POIFSFileSystem, will spot it's actually a .xlsx file // encrypted with the default password, and open - POIFSFileSystem fsNP = new POIFSFileSystem( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - Workbook wb = WorkbookFactory.create(fsNP); - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); - fsNP.close(); + try (POIFSFileSystem fsNP = new POIFSFileSystem( + POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"))) { + Workbook wb = WorkbookFactory.create(fsNP); + assertNotNull(wb); + assertEquals(3, wb.getNumberOfSheets()); + wb.close(); + } } @Test public void bug53282() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx"); - Cell c = wb.getSheetAt(0).getRow(1).getCell(0); - assertEquals("#@_#", c.getStringCellValue()); - assertEquals("http://invalid.uri", c.getHyperlink().getAddress()); - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx")) { + Cell c = wb.getSheetAt(0).getRow(1).getCell(0); + assertEquals("#@_#", c.getStringCellValue()); + assertEquals("http://invalid.uri", c.getHyperlink().getAddress()); + } } /** @@ -1546,24 +1538,24 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug56278() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx"); - assertEquals(0, wb.getSheetIndex("Market Rates")); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx")) { + assertEquals(0, wb.getSheetIndex("Market Rates")); - // Save and re-check - Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(0, nwb.getSheetIndex("Market Rates")); - nwb.close(); - wb.close(); + // Save and re-check + Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); + assertEquals(0, nwb.getSheetIndex("Market Rates")); + nwb.close(); + } } @Test public void bug56315() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx"); - Cell c = wb.getSheetAt(0).getRow(1).getCell(0); - CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c); - double rounded = cv.getNumberValue(); - assertEquals(0.1, rounded, 0.0); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx")) { + Cell c = wb.getSheetAt(0).getRow(1).getCell(0); + CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c); + double rounded = cv.getNumberValue(); + assertEquals(0.1, rounded, 0.0); + } } @Test @@ -1613,17 +1605,16 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { TimeZone tz = LocaleUtil.getUserTimeZone(); LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); try { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx"); - Sheet sheet = wb.getSheet("Sheet1"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(2); - assertTrue(DateUtil.isCellDateFormatted(cell)); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx")) { + Sheet sheet = wb.getSheet("Sheet1"); + Row row = sheet.getRow(1); + Cell cell = row.getCell(2); + assertTrue(DateUtil.isCellDateFormatted(cell)); - DataFormatter fmt = new DataFormatter(); - assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); - assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); - - wb.close(); + DataFormatter fmt = new DataFormatter(); + assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); + assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); + } } finally { LocaleUtil.setUserTimeZone(tz); } @@ -1632,21 +1623,21 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void testBug53798XLSX() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); - bug53798Work(wb, xlsOutput); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { + File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); + bug53798Work(wb, xlsOutput); + } } @Ignore("Shifting rows is not yet implemented in SXSSFSheet") @Test public void testBug53798XLSXStream() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); - SXSSFWorkbook wb2 = new SXSSFWorkbook(wb); - bug53798Work(wb2, xlsOutput); - wb2.close(); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx")) { + File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); + SXSSFWorkbook wb2 = new SXSSFWorkbook(wb); + bug53798Work(wb2, xlsOutput); + wb2.close(); + } } @Test @@ -1662,17 +1653,17 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void testBug56420SumIfNPE() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx"); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx")) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sheet = wb.getSheetAt(0); - Row r = sheet.getRow(2); - Cell c = r.getCell(2); - assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula()); - Cell eval = evaluator.evaluateInCell(c); - assertEquals(0.0, eval.getNumericCellValue(), 0.0001); - wb.close(); + Sheet sheet = wb.getSheetAt(0); + Row r = sheet.getRow(2); + Cell c = r.getCell(2); + assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula()); + Cell eval = evaluator.evaluateInCell(c); + assertEquals(0.0, eval.getNumericCellValue(), 0.0001); + } } private void bug53798Work(Workbook wb, File xlsOutput) throws IOException { @@ -1724,24 +1715,24 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug56702() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx"); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx")) { - Sheet sheet = wb.getSheetAt(0); + Sheet sheet = wb.getSheetAt(0); - // Get wrong cell by row 8 & column 7 - Cell cell = sheet.getRow(8).getCell(7); - assertEquals(CellType.NUMERIC, cell.getCellType()); + // Get wrong cell by row 8 & column 7 + Cell cell = sheet.getRow(8).getCell(7); + assertEquals(CellType.NUMERIC, cell.getCellType()); - // Check the value - will be zero as it is - assertEquals(0.0, cell.getNumericCellValue(), 0.001); + // Check the value - will be zero as it is + assertEquals(0.0, cell.getNumericCellValue(), 0.001); - // Try to format - DataFormatter formatter = new DataFormatter(); - formatter.formatCellValue(cell); + // Try to format + DataFormatter formatter = new DataFormatter(); + formatter.formatCellValue(cell); - // Check the formatting - assertEquals("0", formatter.formatCellValue(cell)); - wb.close(); + // Check the formatting + assertEquals("0", formatter.formatCellValue(cell)); + } } /** @@ -1753,36 +1744,36 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug56737() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx")) { - // Check the named range definitions - Name nSheetScope = wb.getName("NR_To_A1"); - Name nWBScope = wb.getName("NR_Global_B2"); + // Check the named range definitions + Name nSheetScope = wb.getName("NR_To_A1"); + Name nWBScope = wb.getName("NR_Global_B2"); - assertNotNull(nSheetScope); - assertNotNull(nWBScope); + assertNotNull(nSheetScope); + assertNotNull(nWBScope); - assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); - assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); + assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); + assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); - // Check the different kinds of formulas - Sheet s = wb.getSheetAt(0); - Cell cRefSName = s.getRow(1).getCell(3); - Cell cRefWName = s.getRow(2).getCell(3); + // Check the different kinds of formulas + Sheet s = wb.getSheetAt(0); + Cell cRefSName = s.getRow(1).getCell(3); + Cell cRefWName = s.getRow(2).getCell(3); - assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); - // Note the formula, as stored in the file, has the external name index not filename - // TODO Provide a way to get the one with the filename - assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula()); + assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); + // Note the formula, as stored in the file, has the external name index not filename + // TODO Provide a way to get the one with the filename + assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula()); - // Try to evaluate them - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); - assertEquals(142, (int) eval.evaluate(cRefWName).getNumberValue()); + // Try to evaluate them + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); + assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); + assertEquals(142, (int) eval.evaluate(cRefWName).getNumberValue()); - // Try to evaluate everything - eval.evaluateAll(); - wb.close(); + // Try to evaluate everything + eval.evaluateAll(); + } } private void saveAndReloadReport(Workbook wb, File outFile) throws IOException { @@ -1897,23 +1888,23 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug56502() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx"); - Sheet sheet = wb.getSheetAt(0); - - Cell cFunc = sheet.getRow(3).getCell(0); - assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); - Cell cRef = sheet.getRow(3).createCell(1); - cRef.setCellFormula("A3"); - - // Shift it down one row - sheet.shiftRows(1, sheet.getLastRowNum(), 1); - - // Check the new formulas: Function won't change, Reference will - cFunc = sheet.getRow(4).getCell(0); - assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); - cRef = sheet.getRow(4).getCell(1); - assertEquals("A4", cRef.getCellFormula()); - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx")) { + Sheet sheet = wb.getSheetAt(0); + + Cell cFunc = sheet.getRow(3).getCell(0); + assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); + Cell cRef = sheet.getRow(3).createCell(1); + cRef.setCellFormula("A3"); + + // Shift it down one row + sheet.shiftRows(1, sheet.getLastRowNum(), 1); + + // Check the new formulas: Function won't change, Reference will + cFunc = sheet.getRow(4).getCell(0); + assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); + cRef = sheet.getRow(4).getCell(1); + assertEquals("A4", cRef.getCellFormula()); + } } @Test @@ -1945,9 +1936,9 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } // Check we can still parse valid files after all that - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx")) { + assertEquals(3, wb.getNumberOfSheets()); + } } @Test @@ -1985,15 +1976,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug57176() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx"); - CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames(); - List definedNameList = definedNames.getDefinedNameList(); - for (CTDefinedName defName : definedNameList) { - assertNotNull(defName.getName()); - assertNotNull(defName.getStringValue()); - } - assertEquals("TestDefinedName", definedNameList.get(0).getName()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx")) { + CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames(); + List definedNameList = definedNames.getDefinedNameList(); + for (CTDefinedName defName : definedNameList) { + assertNotNull(defName.getName()); + assertNotNull(defName.getStringValue()); + } + assertEquals("TestDefinedName", definedNameList.get(0).getName()); + } } /** @@ -2045,15 +2036,15 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void testBug57196() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx"); - Sheet sheet = wb.getSheet("Feuil1"); - Row mod = sheet.getRow(1); - mod.getCell(1).setCellValue(3); - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx")) { + Sheet sheet = wb.getSheet("Feuil1"); + Row mod = sheet.getRow(1); + mod.getCell(1).setCellValue(3); + HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); // FileOutputStream fileOutput = new FileOutputStream("/tmp/57196.xlsx"); // wb.write(fileOutput); // fileOutput.close(); - wb.close(); + } } @Test @@ -2232,22 +2223,21 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug57535() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - evaluator.clearAllCachedResultValues(); - - Sheet sheet = wb.getSheet("Sheet1"); - Cell cell = sheet.getRow(5).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellType()); - assertEquals("E4+E5", cell.getCellFormula()); - - CellValue value = evaluator.evaluate(cell); - assertEquals(CellType.ERROR, value.getCellType()); - assertEquals(-60, value.getErrorValue()); - assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString()); - assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString()); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx")) { + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + evaluator.clearAllCachedResultValues(); - wb.close(); + Sheet sheet = wb.getSheet("Sheet1"); + Cell cell = sheet.getRow(5).getCell(4); + assertEquals(CellType.FORMULA, cell.getCellType()); + assertEquals("E4+E5", cell.getCellFormula()); + + CellValue value = evaluator.evaluate(cell); + assertEquals(CellType.ERROR, value.getCellType()); + assertEquals(-60, value.getErrorValue()); + assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString()); + assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString()); + } } @@ -2379,18 +2369,17 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test @Ignore("XMLBeans namespace mis-match on ooxml-strict files") public void test57699() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - // TODO Check sheet contents - // TODO Check formula evaluation - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, wbBack.getNumberOfSheets()); - // TODO Re-check sheet contents - // TODO Re-check formula evaluation + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx")) { + assertEquals(3, wb.getNumberOfSheets()); + // TODO Check sheet contents + // TODO Check formula evaluation - wb.close(); - wbBack.close(); + try (XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + assertEquals(3, wbBack.getNumberOfSheets()); + // TODO Re-check sheet contents + // TODO Re-check formula evaluation + } + } } @Test @@ -2548,64 +2537,64 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { } private void runTest56574(boolean createRow) throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx"); - - Sheet sheet = wb.getSheet("Func"); - assertNotNull(sheet); - - Map data; - data = new TreeMap<>(); - data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); - data.put("2", new Object[]{2, "Amit", "Shukla"}); - data.put("3", new Object[]{1, "Lokesh", "Gupta"}); - data.put("4", new Object[]{4, "John", "Adwards"}); - data.put("5", new Object[]{2, "Brian", "Schultz"}); - - int rownum = 1; - for (Map.Entry me : data.entrySet()) { - final Row row; - if (createRow) { - row = sheet.createRow(rownum++); - } else { - row = sheet.getRow(rownum++); - } - assertNotNull(row); - - int cellnum = 0; - for (Object obj : me.getValue()) { - Cell cell = row.getCell(cellnum); - if (cell == null) { - cell = row.createCell(cellnum); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56574.xlsx")) { + + Sheet sheet = wb.getSheet("Func"); + assertNotNull(sheet); + + Map data; + data = new TreeMap<>(); + data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); + data.put("2", new Object[]{2, "Amit", "Shukla"}); + data.put("3", new Object[]{1, "Lokesh", "Gupta"}); + data.put("4", new Object[]{4, "John", "Adwards"}); + data.put("5", new Object[]{2, "Brian", "Schultz"}); + + int rownum = 1; + for (Map.Entry me : data.entrySet()) { + final Row row; + if (createRow) { + row = sheet.createRow(rownum++); } else { - if (cell.getCellType() == CellType.FORMULA) { - cell.setCellFormula(null); - cell.getCellStyle().setDataFormat((short) 0); - } + row = sheet.getRow(rownum++); } - if (obj instanceof String) { - cell.setCellValue((String) obj); - } else if (obj instanceof Integer) { - cell.setCellValue((Integer) obj); + assertNotNull(row); + + int cellnum = 0; + for (Object obj : me.getValue()) { + Cell cell = row.getCell(cellnum); + if (cell == null) { + cell = row.createCell(cellnum); + } else { + if (cell.getCellType() == CellType.FORMULA) { + cell.setCellFormula(null); + cell.getCellStyle().setDataFormat((short) 0); + } + } + if (obj instanceof String) { + cell.setCellValue((String) obj); + } else if (obj instanceof Integer) { + cell.setCellValue((Integer) obj); + } + cellnum++; } - cellnum++; } - } - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); + XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); + wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - CalculationChain chain = wb.getCalculationChain(); - checkCellsAreGone(chain); + CalculationChain chain = wb.getCalculationChain(); + checkCellsAreGone(chain); - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - Sheet sheetBack = wbBack.getSheet("Func"); - assertNotNull(sheetBack); + XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); + Sheet sheetBack = wbBack.getSheet("Func"); + assertNotNull(sheetBack); - chain = wbBack.getCalculationChain(); - checkCellsAreGone(chain); + chain = wbBack.getCalculationChain(); + checkCellsAreGone(chain); - wbBack.close(); - wb.close(); + wbBack.close(); + } } private void checkCellsAreGone(CalculationChain chain) { @@ -2624,61 +2613,61 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { */ @Test public void bug57181() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm"); - assertEquals(9, wb.getNumberOfSheets()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm")) { + assertEquals(9, wb.getNumberOfSheets()); + } } @Test public void bug52111() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx"); - Sheet s = wb.getSheetAt(0); - assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); - assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0"); - assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!11:12", null); - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx")) { + Sheet s = wb.getSheetAt(0); + assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); + assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0"); + assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!11:12", null); + } } @Test public void test48962() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx"); - Sheet sh = wb.getSheetAt(0); - Row row = sh.getRow(1); - Cell cell = row.getCell(0); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx")) { + Sheet sh = wb.getSheetAt(0); + Row row = sh.getRow(1); + Cell cell = row.getCell(0); - CellStyle style = cell.getCellStyle(); - assertNotNull(style); + CellStyle style = cell.getCellStyle(); + assertNotNull(style); - // color index - assertEquals(64, style.getFillBackgroundColor()); - XSSFColor color = ((XSSFCellStyle) style).getFillBackgroundXSSFColor(); - assertNotNull(color); + // color index + assertEquals(64, style.getFillBackgroundColor()); + XSSFColor color = ((XSSFCellStyle) style).getFillBackgroundXSSFColor(); + assertNotNull(color); - // indexed color - assertEquals(64, color.getIndexed()); - assertEquals(64, color.getIndex()); + // indexed color + assertEquals(64, color.getIndexed()); + assertEquals(64, color.getIndex()); - // not an RGB color - assertFalse(color.isRGB()); - assertNull(color.getRGB()); - wb.close(); + // not an RGB color + assertFalse(color.isRGB()); + assertNull(color.getRGB()); + } } @Test public void test50755_workday_formula_example() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx"); - Sheet sheet = wb.getSheet("Sheet1"); - for (Row aRow : sheet) { - Cell cell = aRow.getCell(1); - if (cell.getCellType() == CellType.FORMULA) { - String formula = cell.getCellFormula(); - assertNotNull(formula); - assertTrue(formula.contains("WORKDAY")); - } else { - assertNotNull(cell.toString()); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx")) { + Sheet sheet = wb.getSheet("Sheet1"); + for (Row aRow : sheet) { + Cell cell = aRow.getCell(1); + if (cell.getCellType() == CellType.FORMULA) { + String formula = cell.getCellFormula(); + assertNotNull(formula); + assertTrue(formula.contains("WORKDAY")); + } else { + assertNotNull(cell.toString()); + } } } - wb.close(); } @Test @@ -2726,68 +2715,65 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void test53105() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx"); - assertNotNull(wb); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx")) { + assertNotNull(wb); - // Act - // evaluate SUM('Skye Lookup Input'!A4:XFD4), cells in range each contain "1" - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - double numericValue = evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(0)).getNumberValue(); - - // Assert - assertEquals(16384.0, numericValue, 0.0); + // Act + // evaluate SUM('Skye Lookup Input'!A4:XFD4), cells in range each contain "1" + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + double numericValue = evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(0)).getNumberValue(); - wb.close(); + // Assert + assertEquals(16384.0, numericValue, 0.0); + } } @Test public void test58315() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx"); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - assertNotNull(cell); - StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue()); - XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue(); - - for (int i = richText.length() - 1; i >= 0; i--) { - Font f = richText.getFontAtIndex(i); - if (f != null && f.getStrikeout()) { - tmpCellContent.deleteCharAt(i); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx")) { + Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); + assertNotNull(cell); + StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue()); + XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue(); + + for (int i = richText.length() - 1; i >= 0; i--) { + Font f = richText.getFontAtIndex(i); + if (f != null && f.getStrikeout()) { + tmpCellContent.deleteCharAt(i); + } } + String result = tmpCellContent.toString(); + assertEquals("320 350", result); } - String result = tmpCellContent.toString(); - assertEquals("320 350", result); - - wb.close(); } @Test public void test55406() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx"); - Sheet sheet = wb.getSheetAt(0); - Cell cellA1 = sheet.getRow(0).getCell(0); - Cell cellA2 = sheet.getRow(1).getCell(0); - - assertEquals(0, cellA1.getCellStyle().getFillForegroundColor()); - assertEquals("FFFDFDFD", ((XSSFColor) cellA1.getCellStyle().getFillForegroundColorColor()).getARGBHex()); - assertEquals(0, cellA2.getCellStyle().getFillForegroundColor()); - assertEquals("FFFDFDFD", ((XSSFColor) cellA2.getCellStyle().getFillForegroundColorColor()).getARGBHex()); - - SheetConditionalFormatting cond = sheet.getSheetConditionalFormatting(); - assertEquals(2, cond.getNumConditionalFormattings()); - - assertEquals(1, cond.getConditionalFormattingAt(0).getNumberOfRules()); - assertEquals(64, cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColor()); - assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(0).getRule(0).getFormula1()); - assertNull(((XSSFColor) cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); - - assertEquals(1, cond.getConditionalFormattingAt(1).getNumberOfRules()); - assertEquals(64, cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColor()); - assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(1).getRule(0).getFormula1()); - assertNull(((XSSFColor) cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); - - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx")) { + Sheet sheet = wb.getSheetAt(0); + Cell cellA1 = sheet.getRow(0).getCell(0); + Cell cellA2 = sheet.getRow(1).getCell(0); + + assertEquals(0, cellA1.getCellStyle().getFillForegroundColor()); + assertEquals("FFFDFDFD", ((XSSFColor) cellA1.getCellStyle().getFillForegroundColorColor()).getARGBHex()); + assertEquals(0, cellA2.getCellStyle().getFillForegroundColor()); + assertEquals("FFFDFDFD", ((XSSFColor) cellA2.getCellStyle().getFillForegroundColorColor()).getARGBHex()); + + SheetConditionalFormatting cond = sheet.getSheetConditionalFormatting(); + assertEquals(2, cond.getNumConditionalFormattings()); + + assertEquals(1, cond.getConditionalFormattingAt(0).getNumberOfRules()); + assertEquals(64, cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColor()); + assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(0).getRule(0).getFormula1()); + assertNull(((XSSFColor) cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); + + assertEquals(1, cond.getConditionalFormattingAt(1).getNumberOfRules()); + assertEquals(64, cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColor()); + assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(1).getRule(0).getFormula1()); + assertNull(((XSSFColor) cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); + } } @Test @@ -2821,39 +2807,38 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void test58731() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx"); - Sheet sheet = wb.createSheet("Java Books"); - - Object[][] bookData = { - {"Head First Java", "Kathy Serria", 79}, - {"Effective Java", "Joshua Bloch", 36}, - {"Clean Code", "Robert martin", 42}, - {"Thinking in Java", "Bruce Eckel", 35}, - }; - - int rowCount = 0; - for (Object[] aBook : bookData) { - Row row = sheet.createRow(rowCount++); - - int columnCount = 0; - for (Object field : aBook) { - Cell cell = row.createCell(columnCount++); - if (field instanceof String) { - cell.setCellValue((String) field); - } else if (field instanceof Integer) { - cell.setCellValue((Integer) field); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx")) { + Sheet sheet = wb.createSheet("Java Books"); + + Object[][] bookData = { + {"Head First Java", "Kathy Serria", 79}, + {"Effective Java", "Joshua Bloch", 36}, + {"Clean Code", "Robert martin", 42}, + {"Thinking in Java", "Bruce Eckel", 35}, + }; + + int rowCount = 0; + for (Object[] aBook : bookData) { + Row row = sheet.createRow(rowCount++); + + int columnCount = 0; + for (Object field : aBook) { + Cell cell = row.createCell(columnCount++); + if (field instanceof String) { + cell.setCellValue((String) field); + } else if (field instanceof Integer) { + cell.setCellValue((Integer) field); + } } } - } - - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb2.getSheet("Java Books"); - assertNotNull(sheet.getRow(0)); - assertNotNull(sheet.getRow(0).getCell(0)); - assertEquals(bookData[0][0], sheet.getRow(0).getCell(0).getStringCellValue()); - wb2.close(); - wb.close(); + try (Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + sheet = wb2.getSheet("Java Books"); + assertNotNull(sheet.getRow(0)); + assertNotNull(sheet.getRow(0).getCell(0)); + assertEquals(bookData[0][0], sheet.getRow(0).getCell(0).getStringCellValue()); + } + } } /** @@ -2886,21 +2871,20 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { DataFormatter formatter = new DataFormatter(true); - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx"); - for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { - Sheet sheet = wb.getSheetAt(sheetNum); - for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum(); rowNum++) { - Row row = sheet.getRow(rowNum); - for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) { - Cell cell = row.getCell(cellNum); - String fmtCellValue = formatter.formatCellValue(cell); - assertNotNull(fmtCellValue); - assertNotEquals("0", fmtCellValue); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx")) { + for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) { + Sheet sheet = wb.getSheetAt(sheetNum); + for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum(); rowNum++) { + Row row = sheet.getRow(rowNum); + for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) { + Cell cell = row.getCell(cellNum); + String fmtCellValue = formatter.formatCellValue(cell); + assertNotNull(fmtCellValue); + assertNotEquals("0", fmtCellValue); + } } } } - - wb.close(); } /** @@ -3032,35 +3016,37 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Ignore("currently fails on POI 3.15 beta 2") @Test - public void test55273() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx"); - Sheet sheet = wb.getSheet("ExcelTable"); + public void test55273() throws IOException { + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx")) { + Sheet sheet = wb.getSheet("ExcelTable"); - Name name = wb.getName("TableAsRangeName"); - assertEquals("TableName[#All]", name.getRefersToFormula()); - // POI 3.15-beta 2 (2016-06-15): getSheetName throws IllegalArgumentException: Invalid CellReference: TableName[#All] - assertEquals("TableName", name.getSheetName()); + Name name = wb.getName("TableAsRangeName"); + assertEquals("TableName[#All]", name.getRefersToFormula()); + // POI 3.15-beta 2 (2016-06-15): getSheetName throws IllegalArgumentException: Invalid CellReference: TableName[#All] + assertEquals("TableName", name.getSheetName()); - XSSFSheet xsheet = (XSSFSheet) sheet; - List tables = xsheet.getTables(); - assertEquals(2, tables.size()); //FIXME: how many tables are there in this spreadsheet? - assertEquals("Table1", tables.get(0).getName()); //FIXME: what is the table name? - assertEquals("Table2", tables.get(1).getName()); //FIXME: what is the table name? + XSSFSheet xsheet = (XSSFSheet) sheet; + List tables = xsheet.getTables(); + assertEquals(2, tables.size()); //FIXME: how many tables are there in this spreadsheet? + assertEquals("Table1", tables.get(0).getName()); //FIXME: what is the table name? + assertEquals("Table2", tables.get(1).getName()); //FIXME: what is the table name? + } } @Test - public void test57523() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx"); - Sheet sheet = wb.getSheet("Attribute Master"); - Row row = sheet.getRow(15); + public void test57523() throws IOException { + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx")) { + Sheet sheet = wb.getSheet("Attribute Master"); + Row row = sheet.getRow(15); - int N = CellReference.convertColStringToIndex("N"); - Cell N16 = row.getCell(N); - assertEquals(500.0, N16.getNumericCellValue(), 0.00001); + int N = CellReference.convertColStringToIndex("N"); + Cell N16 = row.getCell(N); + assertEquals(500.0, N16.getNumericCellValue(), 0.00001); - int P = CellReference.convertColStringToIndex("P"); - Cell P16 = row.getCell(P); - assertEquals(10.0, P16.getNumericCellValue(), 0.00001); + int P = CellReference.convertColStringToIndex("P"); + Cell P16 = row.getCell(P); + assertEquals(10.0, P16.getNumericCellValue(), 0.00001); + } } /** @@ -3068,29 +3054,31 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { * to include the row number on the row tags */ @Test - public void noRowNumbers59746() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx"); - Sheet sheet = wb.getSheetAt(0); - assertTrue("Last row num: " + sheet.getLastRowNum(), sheet.getLastRowNum() > 20); - assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Checked", sheet.getRow(9).getCell(2).getStringCellValue()); - assertFalse(sheet.getRow(70).getCell(8).getBooleanCellValue()); - assertEquals(71, sheet.getPhysicalNumberOfRows()); - assertEquals(70, sheet.getLastRowNum()); - assertEquals(70, sheet.getRow(sheet.getLastRowNum()).getRowNum()); + public void noRowNumbers59746() throws IOException { + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx")) { + Sheet sheet = wb.getSheetAt(0); + assertTrue("Last row num: " + sheet.getLastRowNum(), sheet.getLastRowNum() > 20); + assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue()); + assertEquals("Checked", sheet.getRow(9).getCell(2).getStringCellValue()); + assertFalse(sheet.getRow(70).getCell(8).getBooleanCellValue()); + assertEquals(71, sheet.getPhysicalNumberOfRows()); + assertEquals(70, sheet.getLastRowNum()); + assertEquals(70, sheet.getRow(sheet.getLastRowNum()).getRowNum()); + } } @Test - public void testWorkdayFunction() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx"); - XSSFSheet sheet = workbook.getSheet("Test"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - DataFormatter form = new DataFormatter(); - FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - String result = form.formatCellValue(cell, evaluator); + public void testWorkdayFunction() throws IOException { + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx")) { + XSSFSheet sheet = workbook.getSheet("Test"); + Row row = sheet.getRow(1); + Cell cell = row.getCell(0); + DataFormatter form = new DataFormatter(); + FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); + String result = form.formatCellValue(cell, evaluator); - assertEquals("09 Mar 2016", result); + assertEquals("09 Mar 2016", result); + } } // This bug is currently open. When this bug is fixed, it should not throw an AssertionError @@ -3136,41 +3124,42 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { * part with a part number) */ @Test - public void drawingNumbersAlreadyTaken_60255() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx"); - assertEquals(4, wb.getNumberOfSheets()); - - // Sheet 3 starts with a drawing - Sheet sheet = wb.getSheetAt(0); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(1); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(2); - assertNotNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(3); - assertNull(sheet.getDrawingPatriarch()); - - // Add another sheet, and give it a drawing - sheet = wb.createSheet(); - assertNull(sheet.getDrawingPatriarch()); - sheet.createDrawingPatriarch(); - assertNotNull(sheet.getDrawingPatriarch()); - - // Save and check - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(5, wb.getNumberOfSheets()); - - // Sheets 3 and 5 now - sheet = wb.getSheetAt(0); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(1); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(2); - assertNotNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(3); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(4); - assertNotNull(sheet.getDrawingPatriarch()); + public void drawingNumbersAlreadyTaken_60255() throws IOException { + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx")) { + assertEquals(4, wb.getNumberOfSheets()); + + // Sheet 3 starts with a drawing + Sheet sheet = wb.getSheetAt(0); + assertNull(sheet.getDrawingPatriarch()); + sheet = wb.getSheetAt(1); + assertNull(sheet.getDrawingPatriarch()); + sheet = wb.getSheetAt(2); + assertNotNull(sheet.getDrawingPatriarch()); + sheet = wb.getSheetAt(3); + assertNull(sheet.getDrawingPatriarch()); + + // Add another sheet, and give it a drawing + sheet = wb.createSheet(); + assertNull(sheet.getDrawingPatriarch()); + sheet.createDrawingPatriarch(); + assertNotNull(sheet.getDrawingPatriarch()); + + // Save and check + Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); + assertEquals(5, wbBack.getNumberOfSheets()); + + // Sheets 3 and 5 now + sheet = wbBack.getSheetAt(0); + assertNull(sheet.getDrawingPatriarch()); + sheet = wbBack.getSheetAt(1); + assertNull(sheet.getDrawingPatriarch()); + sheet = wbBack.getSheetAt(2); + assertNotNull(sheet.getDrawingPatriarch()); + sheet = wbBack.getSheetAt(3); + assertNull(sheet.getDrawingPatriarch()); + sheet = wbBack.getSheetAt(4); + assertNotNull(sheet.getDrawingPatriarch()); + } } @Test @@ -3220,24 +3209,23 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void bug61063() throws Exception { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61063.xlsx"); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s = wb.getSheetAt(0); - - Row r = s.getRow(3); - Cell c = r.getCell(0); - assertEquals(CellType.FORMULA, c.getCellType()); - eval.setDebugEvaluationOutputForNextEval(true); - CellValue cv = eval.evaluate(c); - assertNotNull(cv); - assertEquals("Had: " + cv, 2.0, cv.getNumberValue(), 0.00001); - - wb.close(); + try (Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61063.xlsx")) { + + FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); + Sheet s = wb.getSheetAt(0); + + Row r = s.getRow(3); + Cell c = r.getCell(0); + assertEquals(CellType.FORMULA, c.getCellType()); + eval.setDebugEvaluationOutputForNextEval(true); + CellValue cv = eval.evaluate(c); + assertNotNull(cv); + assertEquals("Had: " + cv, 2.0, cv.getNumberValue(), 0.00001); + } } @Test - public void bug61516(){ + public void bug61516() throws IOException { final String initialFormula = "A1"; final String expectedFormula = "#REF!"; // from ms excel @@ -3287,6 +3275,8 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { CellValue cellValue = evaluator.evaluate(c2); assertEquals(1, cellValue.getNumberValue(), 0.0001); } + + wb.close(); } @Test @@ -3310,23 +3300,21 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { @Test public void test61543() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - XSSFSheet sheet = wb.createSheet(); - XSSFTable table1 = sheet.createTable(null); - XSSFTable table2 = sheet.createTable(null); - XSSFTable table3 = sheet.createTable(null); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFTable table1 = sheet.createTable(null); + XSSFTable table2 = sheet.createTable(null); + XSSFTable table3 = sheet.createTable(null); - sheet.removeTable(table1); + sheet.removeTable(table1); - sheet.createTable(null); + sheet.createTable(null); - sheet.removeTable(table2); - sheet.removeTable(table3); + sheet.removeTable(table2); + sheet.removeTable(table3); - sheet.createTable(null); - - wb.close(); + sheet.createTable(null); + } } /** @@ -3334,54 +3322,57 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { * errors like ArrayIndexOutOfBoundsException: -32765 */ @Test - public void test62108() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(0); + public void test62108() throws IOException { + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + XSSFRow row = sheet.createRow(0); - // Create lots of fonts - XSSFDataFormat formats = wb.createDataFormat(); - XSSFFont[] fonts = new XSSFFont[50000]; - for (int i=0; i ranges = sheet.getMergedRegions(); - final int numMergedRegions = sheet.getNumMergedRegions(); - final CTWorksheet ctSheet = sheet.getCTWorksheet(); - final CTMergeCells ctMergeCells = ctSheet.getMergeCells(); - final List ctMergeCellList = ctMergeCells.getMergeCellList(); - final long ctMergeCellCount = ctMergeCells.getCount(); - final int ctMergeCellListSize = ctMergeCellList.size(); + final List ranges = sheet.getMergedRegions(); + final int numMergedRegions = sheet.getNumMergedRegions(); + final CTWorksheet ctSheet = sheet.getCTWorksheet(); + final CTMergeCells ctMergeCells = ctSheet.getMergeCells(); + final List ctMergeCellList = ctMergeCells.getMergeCellList(); + final long ctMergeCellCount = ctMergeCells.getCount(); + final int ctMergeCellListSize = ctMergeCellList.size(); /*System.out.println(String.format("\ntestMergeRegions(%s)", "After adding first region")); System.out.println(String.format("ranges.size=%d", ranges.size())); @@ -3458,35 +3449,35 @@ public final class TestXSSFBugs extends BaseTestBugzillaIssues { System.out.println(String.format("ctMergeCellCount=%d", ctMergeCellCount)); System.out.println(String.format("ctMergeCellListSize=%d", ctMergeCellListSize));*/ - assertEquals(1, ranges.size()); - assertEquals(1, numMergedRegions); - assertEquals(1, ctMergeCellCount); - assertEquals(1, ctMergeCellListSize); + assertEquals(1, ranges.size()); + assertEquals(1, numMergedRegions); + assertEquals(1, ctMergeCellCount); + assertEquals(1, ctMergeCellListSize); + } } @Test public void testBug63509() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - - XSSFSheet sheet = workbook.createSheet("sheet1"); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { - Row row = sheet.createRow(0); + XSSFSheet sheet = workbook.createSheet("sheet1"); - Cell cell = row.createCell(0); - cell.setCellValue("1000"); + Row row = sheet.createRow(0); - // This causes the error - sheet.addIgnoredErrors(new CellReference(cell), IgnoredErrorType.NUMBER_STORED_AS_TEXT); + Cell cell = row.createCell(0); + cell.setCellValue("1000"); - // Workaround - // sheet.addIgnoredErrors(new CellReference(cell.getRowIndex(), cell.getColumnIndex(), false, false), - // IgnoredErrorType.NUMBER_STORED_AS_TEXT); + // This causes the error + sheet.addIgnoredErrors(new CellReference(cell), IgnoredErrorType.NUMBER_STORED_AS_TEXT); - /*File file = new File("/tmp/63509.xlsx"); - try(FileOutputStream outputStream = new FileOutputStream(file)) { - workbook.write(outputStream); - }*/ + // Workaround + // sheet.addIgnoredErrors(new CellReference(cell.getRowIndex(), cell.getColumnIndex(), false, false), + // IgnoredErrorType.NUMBER_STORED_AS_TEXT); - workbook.close(); + /*File file = new File("/tmp/63509.xlsx"); + try(FileOutputStream outputStream = new FileOutputStream(file)) { + workbook.write(outputStream); + }*/ + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java index bdaacb8993..a81472527f 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java @@ -21,62 +21,70 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import junit.framework.TestCase; +import java.io.IOException; + public final class TestXSSFChart extends TestCase { - public void testGetAccessors() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx"); - XSSFSheet s1 = wb.getSheetAt(0); - XSSFSheet s2 = wb.getSheetAt(1); - XSSFSheet s3 = wb.getSheetAt(2); + public void testGetAccessors() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) { + XSSFSheet s1 = wb.getSheetAt(0); + XSSFSheet s2 = wb.getSheetAt(1); + XSSFSheet s3 = wb.getSheetAt(2); - assertEquals(0, s1.getRelations().size()); - assertEquals(1, s2.getRelations().size()); - assertEquals(1, s3.getRelations().size()); + assertEquals(0, s1.getRelations().size()); + assertEquals(1, s2.getRelations().size()); + assertEquals(1, s3.getRelations().size()); - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); + assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); + } } public void testGetCharts() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx"); - - XSSFSheet s1 = wb.getSheetAt(0); - XSSFSheet s2 = wb.getSheetAt(1); - XSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, s1.createDrawingPatriarch().getCharts().size()); - assertEquals(2, s2.createDrawingPatriarch().getCharts().size()); - assertEquals(1, s3.createDrawingPatriarch().getCharts().size()); - - // Check the titles - XSSFChart chart = s2.createDrawingPatriarch().getCharts().get(0); - assertEquals(null, chart.getTitleText()); - - chart = s2.createDrawingPatriarch().getCharts().get(1); - assertEquals("Pie Chart Title Thingy", chart.getTitleText().getString()); - - chart = s3.createDrawingPatriarch().getCharts().get(0); - assertEquals("Sheet 3 Chart with Title", chart.getTitleText().getString()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx")) { + XSSFSheet s1 = wb.getSheetAt(0); + XSSFSheet s2 = wb.getSheetAt(1); + XSSFSheet s3 = wb.getSheetAt(2); + + assertEquals(0, s1.createDrawingPatriarch().getCharts().size()); + assertEquals(2, s2.createDrawingPatriarch().getCharts().size()); + assertEquals(1, s3.createDrawingPatriarch().getCharts().size()); + + // Check the titles + XSSFChart chart = s2.createDrawingPatriarch().getCharts().get(0); + assertNull(chart.getTitleText()); + + chart = s2.createDrawingPatriarch().getCharts().get(1); + XSSFRichTextString title = chart.getTitleText(); + assertNotNull(title); + assertEquals("Pie Chart Title Thingy", title.getString()); + + chart = s3.createDrawingPatriarch().getCharts().get(0); + title = chart.getTitleText(); + assertNotNull(title); + assertEquals("Sheet 3 Chart with Title", title.getString()); + + assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); + } } public void testAddChartsToNewWorkbook() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s1 = wb.createSheet(); - XSSFDrawing d1 = s1.createDrawingPatriarch(); - XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart c1 = d1.createChart(a1); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet s1 = wb.createSheet(); + XSSFDrawing d1 = s1.createDrawingPatriarch(); + XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); + XSSFChart c1 = d1.createChart(a1); - assertEquals(1, d1.getCharts().size()); + assertEquals(1, d1.getCharts().size()); - assertNotNull(c1.getGraphicFrame()); - assertNotNull(c1.getOrAddLegend()); + assertNotNull(c1.getGraphicFrame()); + assertNotNull(c1.getOrAddLegend()); - XSSFClientAnchor a2 = new XSSFClientAnchor(0, 0, 0, 0, 1, 11, 10, 60); - XSSFChart c2 = d1.createChart(a2); - assertNotNull(c2); - assertEquals(2, d1.getCharts().size()); + XSSFClientAnchor a2 = new XSSFClientAnchor(0, 0, 0, 0, 1, 11, 10, 60); + XSSFChart c2 = d1.createChart(a2); + assertNotNull(c2); + assertEquals(2, d1.getCharts().size()); - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); + assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java index 90aa40e42c..ebb098ee93 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java @@ -22,60 +22,65 @@ import org.apache.poi.xssf.XSSFTestDataSamples; import org.junit.Test; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTChartsheet; +import java.io.IOException; + import static org.junit.Assert.*; public final class TestXSSFChartSheet { @Test - public void testXSSFFactory() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx"); - assertEquals(4, wb.getNumberOfSheets()); + public void testXSSFFactory() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { + assertEquals(4, wb.getNumberOfSheets()); - //the third sheet is of type 'chartsheet' - assertEquals("Chart1", wb.getSheetName(2)); - assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet); - assertEquals("Chart1", wb.getSheetAt(2).getSheetName()); + //the third sheet is of type 'chartsheet' + assertEquals("Chart1", wb.getSheetName(2)); + assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet); + assertEquals("Chart1", wb.getSheetAt(2).getSheetName()); - final CTChartsheet ctChartsheet = ((XSSFChartSheet) wb.getSheetAt(2)).getCTChartsheet(); - assertNotNull(ctChartsheet); + final CTChartsheet ctChartsheet = ((XSSFChartSheet) wb.getSheetAt(2)).getCTChartsheet(); + assertNotNull(ctChartsheet); + } } @Test - public void testGetAccessors() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx"); - XSSFChartSheet sheet = (XSSFChartSheet)wb.getSheetAt(2); - - assertFalse("Row iterator for charts sheets should return zero rows", - sheet.iterator().hasNext()); - - //access to a arbitrary row - assertNull(sheet.getRow(1)); - - //some basic get* accessors - assertEquals(0, sheet.getNumberOfComments()); - assertEquals(0, sheet.getNumHyperlinks()); - assertEquals(0, sheet.getNumMergedRegions()); - assertNull(sheet.getActiveCell()); - assertTrue(sheet.getAutobreaks()); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - assertEquals(0, sheet.getColumnBreaks().length); - assertTrue(sheet.getRowSumsBelow()); - assertNotNull(sheet.createDrawingPatriarch()); - assertNotNull(sheet.getDrawingPatriarch()); - assertNotNull(sheet.getCTChartsheet()); + public void testGetAccessors() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { + XSSFChartSheet sheet = (XSSFChartSheet) wb.getSheetAt(2); + + assertFalse("Row iterator for charts sheets should return zero rows", + sheet.iterator().hasNext()); + + //access to a arbitrary row + assertNull(sheet.getRow(1)); + + //some basic get* accessors + assertEquals(0, sheet.getNumberOfComments()); + assertEquals(0, sheet.getNumHyperlinks()); + assertEquals(0, sheet.getNumMergedRegions()); + assertNull(sheet.getActiveCell()); + assertTrue(sheet.getAutobreaks()); + assertNull(sheet.getCellComment(new CellAddress(0, 0))); + assertEquals(0, sheet.getColumnBreaks().length); + assertTrue(sheet.getRowSumsBelow()); + assertNotNull(sheet.createDrawingPatriarch()); + assertNotNull(sheet.getDrawingPatriarch()); + assertNotNull(sheet.getCTChartsheet()); + } } @Test public void testGetCharts() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx"); - - XSSFSheet ns = wb.getSheetAt(0); - XSSFChartSheet cs = (XSSFChartSheet)wb.getSheetAt(2); - - assertEquals(0, ns.createDrawingPatriarch().getCharts().size()); - assertEquals(1, cs.createDrawingPatriarch().getCharts().size()); - - XSSFChart chart = cs.createDrawingPatriarch().getCharts().get(0); - assertNull(chart.getTitleText()); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx")) { + + XSSFSheet ns = wb.getSheetAt(0); + XSSFChartSheet cs = (XSSFChartSheet) wb.getSheetAt(2); + + assertEquals(0, ns.createDrawingPatriarch().getCharts().size()); + assertEquals(1, cs.createDrawingPatriarch().getCharts().size()); + + XSSFChart chart = cs.createDrawingPatriarch().getCharts().get(0); + assertNull(chart.getTitleText()); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java index b9339ba019..2a2eece2f5 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java @@ -19,6 +19,7 @@ package org.apache.poi.xssf.usermodel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; @@ -32,173 +33,169 @@ public final class TestXSSFColor { @Test public void testIndexedColour() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx"); - - // Check the CTColor is as expected - XSSFColor indexed = wb.getCellStyleAt(1).getFillBackgroundXSSFColor(); - assertEquals(true, indexed.getCTColor().isSetIndexed()); - assertEquals(64, indexed.getCTColor().getIndexed()); - assertEquals(false, indexed.getCTColor().isSetRgb()); - assertEquals(null, indexed.getCTColor().getRgb()); - - // Now check the XSSFColor - // Note - 64 is a special "auto" one with no rgb equiv - assertEquals(64, indexed.getIndexed()); - assertEquals(null, indexed.getRGB()); - assertEquals(null, indexed.getRGBWithTint()); - assertEquals(null, indexed.getARGBHex()); - assertFalse(indexed.hasAlpha()); - assertFalse(indexed.hasTint()); - - // Now move to one with indexed rgb values - indexed.setIndexed(59); - assertEquals(true, indexed.getCTColor().isSetIndexed()); - assertEquals(59, indexed.getCTColor().getIndexed()); - assertEquals(false, indexed.getCTColor().isSetRgb()); - assertEquals(null, indexed.getCTColor().getRgb()); - - assertEquals(59, indexed.getIndexed()); - assertEquals("FF333300", indexed.getARGBHex()); - - assertEquals(3, indexed.getRGB().length); - assertEquals(0x33, indexed.getRGB()[0]); - assertEquals(0x33, indexed.getRGB()[1]); - assertEquals(0x00, indexed.getRGB()[2]); - - assertEquals(4, indexed.getARGB().length); - assertEquals(-1, indexed.getARGB()[0]); - assertEquals(0x33, indexed.getARGB()[1]); - assertEquals(0x33, indexed.getARGB()[2]); - assertEquals(0x00, indexed.getARGB()[3]); - - // You don't get tinted indexed colours, sorry... - assertEquals(null, indexed.getRGBWithTint()); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { + // Check the CTColor is as expected + XSSFColor indexed = wb.getCellStyleAt(1).getFillBackgroundXSSFColor(); + assertTrue(indexed.getCTColor().isSetIndexed()); + assertEquals(64, indexed.getCTColor().getIndexed()); + assertFalse(indexed.getCTColor().isSetRgb()); + assertNull(indexed.getCTColor().getRgb()); + + // Now check the XSSFColor + // Note - 64 is a special "auto" one with no rgb equiv + assertEquals(64, indexed.getIndexed()); + assertNull(indexed.getRGB()); + assertNull(indexed.getRGBWithTint()); + assertNull(indexed.getARGBHex()); + assertFalse(indexed.hasAlpha()); + assertFalse(indexed.hasTint()); + + // Now move to one with indexed rgb values + indexed.setIndexed(59); + assertTrue(indexed.getCTColor().isSetIndexed()); + assertEquals(59, indexed.getCTColor().getIndexed()); + assertFalse(indexed.getCTColor().isSetRgb()); + assertNull(indexed.getCTColor().getRgb()); + + assertEquals(59, indexed.getIndexed()); + assertEquals("FF333300", indexed.getARGBHex()); + + assertEquals(3, indexed.getRGB().length); + assertEquals(0x33, indexed.getRGB()[0]); + assertEquals(0x33, indexed.getRGB()[1]); + assertEquals(0x00, indexed.getRGB()[2]); + + assertEquals(4, indexed.getARGB().length); + assertEquals(-1, indexed.getARGB()[0]); + assertEquals(0x33, indexed.getARGB()[1]); + assertEquals(0x33, indexed.getARGB()[2]); + assertEquals(0x00, indexed.getARGB()[3]); + + // You don't get tinted indexed colours, sorry... + assertNull(indexed.getRGBWithTint()); + } } @Test public void testRGBColour() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx"); - - // Check the CTColor is as expected - XSSFColor rgb3 = wb.getCellStyleAt((short)25).getFillForegroundXSSFColor(); - assertEquals(false, rgb3.getCTColor().isSetIndexed()); - assertEquals(0, rgb3.getCTColor().getIndexed()); - assertEquals(true, rgb3.getCTColor().isSetTint()); - assertEquals(-0.34999, rgb3.getCTColor().getTint(), 0.00001); - assertEquals(true, rgb3.getCTColor().isSetRgb()); - assertEquals(3, rgb3.getCTColor().getRgb().length); - - // Now check the XSSFColor - assertEquals(0, rgb3.getIndexed()); - assertEquals(-0.34999, rgb3.getTint(), 0.00001); - assertFalse(rgb3.hasAlpha()); - assertTrue(rgb3.hasTint()); - - assertEquals("FFFFFFFF", rgb3.getARGBHex()); - assertEquals(3, rgb3.getRGB().length); - assertEquals(-1, rgb3.getRGB()[0]); - assertEquals(-1, rgb3.getRGB()[1]); - assertEquals(-1, rgb3.getRGB()[2]); - - assertEquals(4, rgb3.getARGB().length); - assertEquals(-1, rgb3.getARGB()[0]); - assertEquals(-1, rgb3.getARGB()[1]); - assertEquals(-1, rgb3.getARGB()[2]); - assertEquals(-1, rgb3.getARGB()[3]); - - // Tint doesn't have the alpha - // tint = -0.34999 - // 255 * (1 + tint) = 165 truncated - // or (byte) -91 (which is 165 - 256) - assertEquals(3, rgb3.getRGBWithTint().length); - assertEquals(-91, rgb3.getRGBWithTint()[0]); - assertEquals(-91, rgb3.getRGBWithTint()[1]); - assertEquals(-91, rgb3.getRGBWithTint()[2]); - - // Set the color to black (no theme). - rgb3.setRGB(new byte[] {0, 0, 0}); - assertEquals("FF000000", rgb3.getARGBHex()); - assertEquals(0, rgb3.getCTColor().getRgb()[0]); - assertEquals(0, rgb3.getCTColor().getRgb()[1]); - assertEquals(0, rgb3.getCTColor().getRgb()[2]); - - // Set another, is fine - rgb3.setRGB(new byte[] {16,17,18}); - assertFalse(rgb3.hasAlpha()); - assertEquals("FF101112", rgb3.getARGBHex()); - assertEquals(0x10, rgb3.getCTColor().getRgb()[0]); - assertEquals(0x11, rgb3.getCTColor().getRgb()[1]); - assertEquals(0x12, rgb3.getCTColor().getRgb()[2]); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx")) { + + // Check the CTColor is as expected + XSSFColor rgb3 = wb.getCellStyleAt((short) 25).getFillForegroundXSSFColor(); + assertFalse(rgb3.getCTColor().isSetIndexed()); + assertEquals(0, rgb3.getCTColor().getIndexed()); + assertTrue(rgb3.getCTColor().isSetTint()); + assertEquals(-0.34999, rgb3.getCTColor().getTint(), 0.00001); + assertTrue(rgb3.getCTColor().isSetRgb()); + assertEquals(3, rgb3.getCTColor().getRgb().length); + + // Now check the XSSFColor + assertEquals(0, rgb3.getIndexed()); + assertEquals(-0.34999, rgb3.getTint(), 0.00001); + assertFalse(rgb3.hasAlpha()); + assertTrue(rgb3.hasTint()); + + assertEquals("FFFFFFFF", rgb3.getARGBHex()); + assertEquals(3, rgb3.getRGB().length); + assertEquals(-1, rgb3.getRGB()[0]); + assertEquals(-1, rgb3.getRGB()[1]); + assertEquals(-1, rgb3.getRGB()[2]); + + assertEquals(4, rgb3.getARGB().length); + assertEquals(-1, rgb3.getARGB()[0]); + assertEquals(-1, rgb3.getARGB()[1]); + assertEquals(-1, rgb3.getARGB()[2]); + assertEquals(-1, rgb3.getARGB()[3]); + + // Tint doesn't have the alpha + // tint = -0.34999 + // 255 * (1 + tint) = 165 truncated + // or (byte) -91 (which is 165 - 256) + assertEquals(3, rgb3.getRGBWithTint().length); + assertEquals(-91, rgb3.getRGBWithTint()[0]); + assertEquals(-91, rgb3.getRGBWithTint()[1]); + assertEquals(-91, rgb3.getRGBWithTint()[2]); + + // Set the color to black (no theme). + rgb3.setRGB(new byte[]{0, 0, 0}); + assertEquals("FF000000", rgb3.getARGBHex()); + assertEquals(0, rgb3.getCTColor().getRgb()[0]); + assertEquals(0, rgb3.getCTColor().getRgb()[1]); + assertEquals(0, rgb3.getCTColor().getRgb()[2]); + + // Set another, is fine + rgb3.setRGB(new byte[]{16, 17, 18}); + assertFalse(rgb3.hasAlpha()); + assertEquals("FF101112", rgb3.getARGBHex()); + assertEquals(0x10, rgb3.getCTColor().getRgb()[0]); + assertEquals(0x11, rgb3.getCTColor().getRgb()[1]); + assertEquals(0x12, rgb3.getCTColor().getRgb()[2]); + } } @Test public void testARGBColour() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx"); - - // Check the CTColor is as expected - XSSFColor rgb4 = wb.getCellStyleAt((short)1).getFillForegroundXSSFColor(); - assertEquals(false, rgb4.getCTColor().isSetIndexed()); - assertEquals(0, rgb4.getCTColor().getIndexed()); - assertEquals(true, rgb4.getCTColor().isSetRgb()); - assertEquals(4, rgb4.getCTColor().getRgb().length); - - // Now check the XSSFColor - assertEquals(0, rgb4.getIndexed()); - assertEquals(0.0, rgb4.getTint(), 0); - assertFalse(rgb4.hasTint()); - assertTrue(rgb4.hasAlpha()); - - assertEquals("FFFF0000", rgb4.getARGBHex()); - assertEquals(3, rgb4.getRGB().length); - assertEquals(-1, rgb4.getRGB()[0]); - assertEquals(0, rgb4.getRGB()[1]); - assertEquals(0, rgb4.getRGB()[2]); - - assertEquals(4, rgb4.getARGB().length); - assertEquals(-1, rgb4.getARGB()[0]); - assertEquals(-1, rgb4.getARGB()[1]); - assertEquals(0, rgb4.getARGB()[2]); - assertEquals(0, rgb4.getARGB()[3]); - - // Tint doesn't have the alpha - assertEquals(3, rgb4.getRGBWithTint().length); - assertEquals(-1, rgb4.getRGBWithTint()[0]); - assertEquals(0, rgb4.getRGBWithTint()[1]); - assertEquals(0, rgb4.getRGBWithTint()[2]); - - - // Turn on tinting, and check it behaves - // TODO These values are suspected to be wrong... - rgb4.setTint(0.4); - assertTrue(rgb4.hasTint()); - assertEquals(0.4, rgb4.getTint(), 0); - - assertEquals(3, rgb4.getRGBWithTint().length); - assertEquals(-1, rgb4.getRGBWithTint()[0]); - assertEquals(102, rgb4.getRGBWithTint()[1]); - assertEquals(102, rgb4.getRGBWithTint()[2]); - - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx")) { + + // Check the CTColor is as expected + XSSFColor rgb4 = wb.getCellStyleAt((short) 1).getFillForegroundXSSFColor(); + assertFalse(rgb4.getCTColor().isSetIndexed()); + assertEquals(0, rgb4.getCTColor().getIndexed()); + assertTrue(rgb4.getCTColor().isSetRgb()); + assertEquals(4, rgb4.getCTColor().getRgb().length); + + // Now check the XSSFColor + assertEquals(0, rgb4.getIndexed()); + assertEquals(0.0, rgb4.getTint(), 0); + assertFalse(rgb4.hasTint()); + assertTrue(rgb4.hasAlpha()); + + assertEquals("FFFF0000", rgb4.getARGBHex()); + assertEquals(3, rgb4.getRGB().length); + assertEquals(-1, rgb4.getRGB()[0]); + assertEquals(0, rgb4.getRGB()[1]); + assertEquals(0, rgb4.getRGB()[2]); + + assertEquals(4, rgb4.getARGB().length); + assertEquals(-1, rgb4.getARGB()[0]); + assertEquals(-1, rgb4.getARGB()[1]); + assertEquals(0, rgb4.getARGB()[2]); + assertEquals(0, rgb4.getARGB()[3]); + + // Tint doesn't have the alpha + assertEquals(3, rgb4.getRGBWithTint().length); + assertEquals(-1, rgb4.getRGBWithTint()[0]); + assertEquals(0, rgb4.getRGBWithTint()[1]); + assertEquals(0, rgb4.getRGBWithTint()[2]); + + + // Turn on tinting, and check it behaves + // TODO These values are suspected to be wrong... + rgb4.setTint(0.4); + assertTrue(rgb4.hasTint()); + assertEquals(0.4, rgb4.getTint(), 0); + + assertEquals(3, rgb4.getRGBWithTint().length); + assertEquals(-1, rgb4.getRGBWithTint()[0]); + assertEquals(102, rgb4.getRGBWithTint()[1]); + assertEquals(102, rgb4.getRGBWithTint()[2]); + } } @Test public void testCustomIndexedColour() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("customIndexedColors.xlsx"); - XSSFCell cell = wb.getSheetAt(1).getRow(0).getCell(0); - XSSFColor color = cell.getCellStyle().getFillForegroundColorColor(); - CTColors ctColors = wb.getStylesSource().getCTStylesheet().getColors(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("customIndexedColors.xlsx")) { + XSSFCell cell = wb.getSheetAt(1).getRow(0).getCell(0); + XSSFColor color = cell.getCellStyle().getFillForegroundColorColor(); + CTColors ctColors = wb.getStylesSource().getCTStylesheet().getColors(); - CTRgbColor ctRgbColor = ctColors.getIndexedColors() - .getRgbColorList() - .get(color.getIndex()); + CTRgbColor ctRgbColor = ctColors.getIndexedColors() + .getRgbColorList() + .get(color.getIndex()); - String hexRgb = ctRgbColor.getDomNode().getAttributes().getNamedItem("rgb").getNodeValue(); + String hexRgb = ctRgbColor.getDomNode().getAttributes().getNamedItem("rgb").getNodeValue(); - assertEquals(hexRgb, color.getARGBHex()); - + assertEquals(hexRgb, color.getARGBHex()); + } } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java index 9f4479240c..b5aa83026a 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java @@ -53,30 +53,29 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { @Test public void testSharedFormulas_evaluateInCell() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFSheet sheet = wb.getSheetAt(0); + try (XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx")) { + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + XSSFSheet sheet = wb.getSheetAt(0); - double result = 3.0; + double result = 3.0; - // B3 is a master shared formula, C3 and D3 don't have the formula written in their f element. - // Instead, the attribute si for a particular cell is used to figure what the formula expression - // should be based on the cell's relative location to the master formula, e.g. - // B3: B1+B2 - // C3 and D3: + // B3 is a master shared formula, C3 and D3 don't have the formula written in their f element. + // Instead, the attribute si for a particular cell is used to figure what the formula expression + // should be based on the cell's relative location to the master formula, e.g. + // B3: B1+B2 + // C3 and D3: - // get B3 and evaluate it in the cell - XSSFCell b3 = sheet.getRow(2).getCell(1); - assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0); + // get B3 and evaluate it in the cell + XSSFCell b3 = sheet.getRow(2).getCell(1); + assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0); - //at this point the master formula is gone, but we are still able to evaluate dependent cells - XSSFCell c3 = sheet.getRow(2).getCell(2); - assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0); + //at this point the master formula is gone, but we are still able to evaluate dependent cells + XSSFCell c3 = sheet.getRow(2).getCell(2); + assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0); - XSSFCell d3 = sheet.getRow(2).getCell(3); - assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0); - - wb.close(); + XSSFCell d3 = sheet.getRow(2).getCell(3); + assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0); + } } /** @@ -84,32 +83,31 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { */ @Test public void testEvaluateColumnGreaterThan255() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx"); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - /* - * The first row simply contains the numbers 1 - 300. - * The second row simply refers to the cell value above in the first row by a simple formula. - */ - for (int i = 245; i < 265; i++) { - XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i); - XSSFCell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i); - - CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); - CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); - String fmla = cell_formula.getCellFormula(); - // assure that the formula refers to the cell above. - // the check below is 'deep' and involves conversion of the shared formula: - // in the sample file a shared formula in GN1 is spanned in the range GN2:IY2, - assertEquals(ref_noformula.formatAsString(), fmla); - - CellValue cv_noformula = evaluator.evaluate(cell_noformula); - CellValue cv_formula = evaluator.evaluate(cell_formula); - assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(), - cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0); + try (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx")) { + XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + + /* + * The first row simply contains the numbers 1 - 300. + * The second row simply refers to the cell value above in the first row by a simple formula. + */ + for (int i = 245; i < 265; i++) { + XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i); + XSSFCell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i); + + CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); + CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); + String fmla = cell_formula.getCellFormula(); + // assure that the formula refers to the cell above. + // the check below is 'deep' and involves conversion of the shared formula: + // in the sample file a shared formula in GN1 is spanned in the range GN2:IY2, + assertEquals(ref_noformula.formatAsString(), fmla); + + CellValue cv_noformula = evaluator.evaluate(cell_noformula); + CellValue cv_formula = evaluator.evaluate(cell_formula); + assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(), + cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0); + } } - - wb.close(); } /** @@ -119,105 +117,110 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { */ @Test public void testReferencesToOtherWorkbooks() throws Exception { - XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx"); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFSheet s = wb.getSheetAt(0); - - // References to a .xlsx file - Row rXSLX = s.getRow(2); - Cell cXSLX_cell = rXSLX.getCell(4); - Cell cXSLX_sNR = rXSLX.getCell(6); - Cell cXSLX_gNR = rXSLX.getCell(8); - assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula()); - assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula()); - assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula()); - - assertEquals("Hello!", cXSLX_cell.getStringCellValue()); - assertEquals("Test A1", cXSLX_sNR.getStringCellValue()); - assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0); - - // References to a .xls file - Row rXSL = s.getRow(4); - Cell cXSL_cell = rXSL.getCell(4); - Cell cXSL_sNR = rXSL.getCell(6); - Cell cXSL_gNR = rXSL.getCell(8); - assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula()); - assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula()); - assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula()); - - assertEquals("Hello!", cXSL_cell.getStringCellValue()); - assertEquals("Test A1", cXSL_sNR.getStringCellValue()); - assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0); - - // Try to evaluate without references, won't work - // (At least, not unit we fix bug #56752 that is) - try { - evaluator.evaluate(cXSL_cell); - fail("Without a fix for #56752, shouldn't be able to evaluate a " + - "reference to a non-provided linked workbook"); - } catch(Exception e) { - // expected here - } - - // Setup the environment - Map evaluators = new HashMap<>(); - evaluators.put("ref2-56737.xlsx", evaluator); - evaluators.put("56737.xlsx", - _testDataProvider.openSampleWorkbook("56737.xlsx").getCreationHelper().createFormulaEvaluator()); - evaluators.put("56737.xls", - HSSFTestDataSamples.openSampleWorkbook("56737.xls").getCreationHelper().createFormulaEvaluator()); - evaluator.setupReferencedWorkbooks(evaluators); - - // Try evaluating all of them, ensure we don't blow up - for(Row r : s) { - for (Cell c : r) { - evaluator.evaluate(c); + try (XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx")) { + XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + XSSFSheet s = wb.getSheetAt(0); + + // References to a .xlsx file + Row rXSLX = s.getRow(2); + Cell cXSLX_cell = rXSLX.getCell(4); + Cell cXSLX_sNR = rXSLX.getCell(6); + Cell cXSLX_gNR = rXSLX.getCell(8); + assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula()); + assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula()); + assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula()); + + assertEquals("Hello!", cXSLX_cell.getStringCellValue()); + assertEquals("Test A1", cXSLX_sNR.getStringCellValue()); + assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0); + + // References to a .xls file + Row rXSL = s.getRow(4); + Cell cXSL_cell = rXSL.getCell(4); + Cell cXSL_sNR = rXSL.getCell(6); + Cell cXSL_gNR = rXSL.getCell(8); + assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula()); + assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula()); + assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula()); + + assertEquals("Hello!", cXSL_cell.getStringCellValue()); + assertEquals("Test A1", cXSL_sNR.getStringCellValue()); + assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0); + + // Try to evaluate without references, won't work + // (At least, not unit we fix bug #56752 that is) + try { + evaluator.evaluate(cXSL_cell); + fail("Without a fix for #56752, shouldn't be able to evaluate a " + + "reference to a non-provided linked workbook"); + } catch (Exception e) { + // expected here } - } - // And evaluate the other way too - evaluator.evaluateAll(); - - // Static evaluator won't work, as no references passed in - try { - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - fail("Static method lacks references, shouldn't work"); - } catch(Exception e) { - // expected here - } - - - // Evaluate specific cells and check results - assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString()); - - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString()); - - - // Add another formula referencing these workbooks - Cell cXSL_cell2 = rXSL.createCell(40); - cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1"); - // TODO Shouldn't it become [2] like the others? - assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula()); - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString()); - - - // Now add a formula that refers to yet another (different) workbook - // Won't work without the workbook being linked - Cell cXSLX_nw_cell = rXSLX.createCell(42); - try { - cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"); - fail("New workbook not linked, shouldn't be able to add"); - } catch (Exception e) { - // expected here - } - - // Link and re-try - try (Workbook alt = new XSSFWorkbook()) { - alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); - // TODO Implement the rest of this, see bug #57184 + + // Setup the environment + Map evaluators = new HashMap<>(); + evaluators.put("ref2-56737.xlsx", evaluator); + Workbook wbEval1 = _testDataProvider.openSampleWorkbook("56737.xlsx"); + evaluators.put("56737.xlsx", + wbEval1.getCreationHelper().createFormulaEvaluator()); + Workbook wbEval2 = HSSFTestDataSamples.openSampleWorkbook("56737.xls"); + evaluators.put("56737.xls", + wbEval2.getCreationHelper().createFormulaEvaluator()); + evaluator.setupReferencedWorkbooks(evaluators); + + // Try evaluating all of them, ensure we don't blow up + for (Row r : s) { + for (Cell c : r) { + evaluator.evaluate(c); + } + } + // And evaluate the other way too + evaluator.evaluateAll(); + + // Static evaluator won't work, as no references passed in + try { + XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); + fail("Static method lacks references, shouldn't work"); + } catch (Exception e) { + // expected here + } + + + // Evaluate specific cells and check results + assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString()); + assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString()); + assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString()); + + assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString()); + assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString()); + assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString()); + + + // Add another formula referencing these workbooks + Cell cXSL_cell2 = rXSL.createCell(40); + cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1"); + // TODO Shouldn't it become [2] like the others? + assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula()); + assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString()); + + + // Now add a formula that refers to yet another (different) workbook + // Won't work without the workbook being linked + Cell cXSLX_nw_cell = rXSLX.createCell(42); + try { + cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"); + fail("New workbook not linked, shouldn't be able to add"); + } catch (Exception e) { + // expected here + } + + wbEval1.close(); + wbEval2.close(); + + // Link and re-try + try (Workbook alt = new XSSFWorkbook()) { + alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); + // TODO Implement the rest of this, see bug #57184 /* wb.linkExternalWorkbook("alt.xlsx", alt); @@ -238,9 +241,8 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { evaluator.evaluate(cXSLX_nw_cell); assertEquals("In another workbook", cXSLX_nw_cell.getStringCellValue()); */ + } } - - wb.close(); } /** @@ -389,63 +391,66 @@ public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { // FIXME: use junit4 parametrization private static void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook) throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook); - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook)) { + XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); + } } @Test - public void test59736() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - assertEquals(1, cell.getNumericCellValue(), 0.001); - - cell = wb.getSheetAt(0).getRow(1).getCell(0); - CellValue value = evaluator.evaluate(cell); - assertEquals(1, value.getNumberValue(), 0.001); - - cell = wb.getSheetAt(0).getRow(2).getCell(0); - value = evaluator.evaluate(cell); - assertEquals(1, value.getNumberValue(), 0.001); + public void test59736() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx")) { + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); + assertEquals(1, cell.getNumericCellValue(), 0.001); + + cell = wb.getSheetAt(0).getRow(1).getCell(0); + CellValue value = evaluator.evaluate(cell); + assertEquals(1, value.getNumberValue(), 0.001); + + cell = wb.getSheetAt(0).getRow(2).getCell(0); + value = evaluator.evaluate(cell); + assertEquals(1, value.getNumberValue(), 0.001); + } } @Test public void evaluateInCellReturnsSameDataType() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet().createRow(0).createCell(0); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); - XSSFCell same = evaluator.evaluateInCell(cell); - assertSame(cell, same); - wb.close(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + wb.createSheet().createRow(0).createCell(0); + XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); + XSSFCell same = evaluator.evaluateInCell(cell); + assertSame(cell, same); + } } @Test - public void testBug61468() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(8).getCell(4); - assertEquals(3750, cell.getNumericCellValue(), 0.001); - - CellValue value = evaluator.evaluate(cell); - assertEquals(3750, value.getNumberValue(), 0.001); + public void testBug61468() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("simple-monthly-budget.xlsx")) { + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + Cell cell = wb.getSheetAt(0).getRow(8).getCell(4); + assertEquals(3750, cell.getNumericCellValue(), 0.001); + + CellValue value = evaluator.evaluate(cell); + assertEquals(3750, value.getNumberValue(), 0.001); + } } @Test @Ignore // this is from an open bug/discussion over handling localization for number formats - public void testBug61495() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(1); + public void testBug61495() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("61495-test.xlsm")) { + FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); + Cell cell = wb.getSheetAt(0).getRow(0).getCell(1); // assertEquals("D 67.10", cell.getStringCellValue()); - - CellValue value = evaluator.evaluate(cell); - assertEquals("D 67.10", - value.getStringValue()); - - assertEquals("D 0,068", - evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(1)).getStringValue()); + + CellValue value = evaluator.evaluate(cell); + assertEquals("D 67.10", + value.getStringValue()); + + assertEquals("D 0,068", + evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(1)).getStringValue()); + } } diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java index 3cbbfc517c..0a7cf4a2f5 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java @@ -39,15 +39,16 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink { } @Test - public void testLoadExisting() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - assertEquals(3, workbook.getNumberOfSheets()); + public void testLoadExisting() throws IOException { + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) { + assertEquals(3, workbook.getNumberOfSheets()); - XSSFSheet sheet = workbook.getSheetAt(0); + XSSFSheet sheet = workbook.getSheetAt(0); - // Check the hyperlinks - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); + // Check the hyperlinks + assertEquals(4, sheet.getNumHyperlinks()); + doTestHyperlinkContents(sheet); + } } @Test @@ -117,73 +118,74 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink { } @Test - public void testLoadSave() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - CreationHelper createHelper = workbook.getCreationHelper(); - assertEquals(3, workbook.getNumberOfSheets()); - XSSFSheet sheet = workbook.getSheetAt(0); + public void testLoadSave() throws IOException { + try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) { + CreationHelper createHelper = workbook.getCreationHelper(); + assertEquals(3, workbook.getNumberOfSheets()); + XSSFSheet sheet = workbook.getSheetAt(0); - // Check hyperlinks - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); + // Check hyperlinks + assertEquals(4, sheet.getNumHyperlinks()); + doTestHyperlinkContents(sheet); - // Write out, and check + // Write out, and check - // Load up again, check all links still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); + // Load up again, check all links still there + XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); + assertEquals(3, wb2.getNumberOfSheets()); + assertNotNull(wb2.getSheetAt(0)); + assertNotNull(wb2.getSheetAt(1)); + assertNotNull(wb2.getSheetAt(2)); - sheet = wb2.getSheetAt(0); + sheet = wb2.getSheetAt(0); - // Check hyperlinks again - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); + // Check hyperlinks again + assertEquals(4, sheet.getNumHyperlinks()); + doTestHyperlinkContents(sheet); - // Add one more, and re-check - Row r17 = sheet.createRow(17); - Cell r17c = r17.createCell(2); + // Add one more, and re-check + Row r17 = sheet.createRow(17); + Cell r17c = r17.createCell(2); - Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("http://poi.apache.org/spreadsheet/"); - hyperlink.setLabel("POI SS Link"); - r17c.setHyperlink(hyperlink); + Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL); + hyperlink.setAddress("http://poi.apache.org/spreadsheet/"); + hyperlink.setLabel("POI SS Link"); + r17c.setHyperlink(hyperlink); - assertEquals(5, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); + assertEquals(5, sheet.getNumHyperlinks()); + doTestHyperlinkContents(sheet); - assertEquals(HyperlinkType.URL, - sheet.getRow(17).getCell(2).getHyperlink().getType()); - assertEquals("POI SS Link", - sheet.getRow(17).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/spreadsheet/", - sheet.getRow(17).getCell(2).getHyperlink().getAddress()); + assertEquals(HyperlinkType.URL, + sheet.getRow(17).getCell(2).getHyperlink().getType()); + assertEquals("POI SS Link", + sheet.getRow(17).getCell(2).getHyperlink().getLabel()); + assertEquals("http://poi.apache.org/spreadsheet/", + sheet.getRow(17).getCell(2).getHyperlink().getAddress()); - // Save and re-load once more + // Save and re-load once more - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertEquals(3, wb3.getNumberOfSheets()); - assertNotNull(wb3.getSheetAt(0)); - assertNotNull(wb3.getSheetAt(1)); - assertNotNull(wb3.getSheetAt(2)); + XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); + assertEquals(3, wb3.getNumberOfSheets()); + assertNotNull(wb3.getSheetAt(0)); + assertNotNull(wb3.getSheetAt(1)); + assertNotNull(wb3.getSheetAt(2)); - sheet = wb3.getSheetAt(0); + sheet = wb3.getSheetAt(0); - assertEquals(5, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); + assertEquals(5, sheet.getNumHyperlinks()); + doTestHyperlinkContents(sheet); - assertEquals(HyperlinkType.URL, - sheet.getRow(17).getCell(2).getHyperlink().getType()); - assertEquals("POI SS Link", - sheet.getRow(17).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/spreadsheet/", - sheet.getRow(17).getCell(2).getHyperlink().getAddress()); + assertEquals(HyperlinkType.URL, + sheet.getRow(17).getCell(2).getHyperlink().getType()); + assertEquals("POI SS Link", + sheet.getRow(17).getCell(2).getHyperlink().getLabel()); + assertEquals("http://poi.apache.org/spreadsheet/", + sheet.getRow(17).getCell(2).getHyperlink().getAddress()); + } } /** @@ -198,8 +200,7 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink { // First is a link to poi assertEquals(HyperlinkType.URL, sheet.getRow(3).getCell(2).getHyperlink().getType()); - assertEquals(null, - sheet.getRow(3).getCell(2).getHyperlink().getLabel()); + assertNull(sheet.getRow(3).getCell(2).getHyperlink().getLabel()); assertEquals("http://poi.apache.org/", sheet.getRow(3).getCell(2).getHyperlink().getAddress()); @@ -214,60 +215,63 @@ public final class TestXSSFHyperlink extends BaseTestHyperlink { // Next is a file assertEquals(HyperlinkType.FILE, sheet.getRow(15).getCell(2).getHyperlink().getType()); - assertEquals(null, - sheet.getRow(15).getCell(2).getHyperlink().getLabel()); + assertNull(sheet.getRow(15).getCell(2).getHyperlink().getLabel()); assertEquals("WithVariousData.xlsx", sheet.getRow(15).getCell(2).getHyperlink().getAddress()); // Last is a mailto assertEquals(HyperlinkType.EMAIL, sheet.getRow(16).getCell(2).getHyperlink().getType()); - assertEquals(null, - sheet.getRow(16).getCell(2).getHyperlink().getLabel()); + assertNull(sheet.getRow(16).getCell(2).getHyperlink().getLabel()); assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", sheet.getRow(16).getCell(2).getHyperlink().getAddress()); } @Test - public void test52716() { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("52716.xlsx"); - XSSFSheet sh1 = wb1.getSheetAt(0); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - XSSFSheet sh2 = wb2.getSheetAt(0); - - assertEquals(sh1.getNumberOfComments(), sh2.getNumberOfComments()); - XSSFHyperlink l1 = sh1.getHyperlink(0, 1); - assertEquals(HyperlinkType.DOCUMENT, l1.getType()); - assertEquals("B1", l1.getCellRef()); - assertEquals("Sort on Titel", l1.getTooltip()); - - XSSFHyperlink l2 = sh2.getHyperlink(0, 1); - assertEquals(l1.getTooltip(), l2.getTooltip()); - assertEquals(HyperlinkType.DOCUMENT, l2.getType()); - assertEquals("B1", l2.getCellRef()); + public void test52716() throws IOException { + try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("52716.xlsx")) { + XSSFSheet sh1 = wb1.getSheetAt(0); + + XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); + XSSFSheet sh2 = wb2.getSheetAt(0); + + assertEquals(sh1.getNumberOfComments(), sh2.getNumberOfComments()); + XSSFHyperlink l1 = sh1.getHyperlink(0, 1); + assertEquals(HyperlinkType.DOCUMENT, l1.getType()); + assertEquals("B1", l1.getCellRef()); + assertEquals("Sort on Titel", l1.getTooltip()); + + XSSFHyperlink l2 = sh2.getHyperlink(0, 1); + assertEquals(l1.getTooltip(), l2.getTooltip()); + assertEquals(HyperlinkType.DOCUMENT, l2.getType()); + assertEquals("B1", l2.getCellRef()); + } } @Test - public void test53734() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53734.xlsx"); - XSSFHyperlink link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); - assertEquals("javascript:///", link.getAddress()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); - assertEquals("javascript:///", link.getAddress()); + public void test53734() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53734.xlsx")) { + Hyperlink link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); + assertEquals("javascript:///", link.getAddress()); + + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + link = wb2.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); + assertEquals("javascript:///", link.getAddress()); + } + } } @Test - public void test53282() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53282.xlsx"); - XSSFHyperlink link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); + public void test53282() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53282.xlsx")) { + Hyperlink link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); + assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); + + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + link = wb2.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); + assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); + } + } } @Override diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java index 1f5599c426..3955219e20 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFShape.java @@ -20,7 +20,7 @@ package org.apache.poi.xssf.usermodel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.util.Iterator; +import java.io.IOException; import java.util.List; import org.apache.poi.xssf.XSSFTestDataSamples; @@ -32,13 +32,17 @@ import org.junit.Test; public final class TestXSSFShape { @Test - public void test58325_one() { - check58325(XSSFTestDataSamples.openSampleWorkbook("58325_lt.xlsx"), 1); + public void test58325_one() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58325_lt.xlsx")) { + check58325(wb, 1); + } } @Test - public void test58325_three() { - check58325(XSSFTestDataSamples.openSampleWorkbook("58325_db.xlsx"), 3); + public void test58325_three() throws IOException { + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("58325_db.xlsx")) { + check58325(wb, 3); + } } private void check58325(XSSFWorkbook wb, int expectedShapes) { @@ -46,21 +50,19 @@ public final class TestXSSFShape { assertNotNull(sheet); StringBuilder str = new StringBuilder(); - str.append("sheet " + sheet.getSheetName() + " - "); + str.append("sheet ").append(sheet.getSheetName()).append(" - "); XSSFDrawing drawing = sheet.getDrawingPatriarch(); //drawing = ((XSSFSheet)sheet).createDrawingPatriarch(); List shapes = drawing.getShapes(); - str.append("drawing.getShapes().size() = " + shapes.size()); - Iterator it = shapes.iterator(); - while(it.hasNext()) { - XSSFShape shape = it.next(); - str.append(", " + shape); - str.append(", Col1:"+((XSSFClientAnchor)shape.getAnchor()).getCol1()); - str.append(", Col2:"+((XSSFClientAnchor)shape.getAnchor()).getCol2()); - str.append(", Row1:"+((XSSFClientAnchor)shape.getAnchor()).getRow1()); - str.append(", Row2:"+((XSSFClientAnchor)shape.getAnchor()).getRow2()); + str.append("drawing.getShapes().size() = ").append(shapes.size()); + for (XSSFShape shape : shapes) { + str.append(", ").append(shape); + str.append(", Col1:").append(((XSSFClientAnchor) shape.getAnchor()).getCol1()); + str.append(", Col2:").append(((XSSFClientAnchor) shape.getAnchor()).getCol2()); + str.append(", Row1:").append(((XSSFClientAnchor) shape.getAnchor()).getRow1()); + str.append(", Row2:").append(((XSSFClientAnchor) shape.getAnchor()).getRow2()); } assertEquals("Having shapes: " + str, diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java index cb8fc60c0e..c2eb54ebe5 100644 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java +++ b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java @@ -34,7 +34,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { //private int o_groupsNumber = 0; - public void test55640() throws IOException { + public void test55640() { //long startTime = System.currentTimeMillis(); Workbook wb = new XSSFWorkbook(); fillData(wb); @@ -78,7 +78,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { return Math.random() > 0.5d; } - private void writeToFile(Workbook p_wb) throws IOException { + private void writeToFile(Workbook p_wb) { // FileOutputStream fileOut = new FileOutputStream("/tmp/55640.xlsx"); // try { // p_wb.write(fileOut); @@ -88,7 +88,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(p_wb)); } - public void test55640reduce1() throws IOException { + public void test55640reduce1() { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("sheet123"); sheet.setRowSumsBelow(false); @@ -117,7 +117,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { } - public void test55640_VerifyCases() throws IOException { + public void test55640_VerifyCases() { // NOTE: This is currently based on current behavior of POI, somehow // what POI returns in the calls to collapsed/hidden is not fully matching // the examples in the spec or I did not fully understand how POI stores the data internally... @@ -210,7 +210,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { private void verifyGroupCollapsed(boolean level1, boolean level2, boolean level3, - Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException { + Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("sheet123"); @@ -282,7 +282,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { } private void verifyGroupCollapsedSpec(boolean level1, boolean level2, boolean level3, - Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException { + Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("sheet123"); @@ -301,7 +301,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel); } - private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException { + private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) { printWorkbook(wb); Sheet sheet = wb.getSheetAt(0); @@ -327,7 +327,7 @@ public final class TestXSSFSheetRowGrouping extends TestCase { } - public void test55640working() throws IOException { + public void test55640working() { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("sheet123"); @@ -366,50 +366,51 @@ public final class TestXSSFSheetRowGrouping extends TestCase { } public void testGroupingTest() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx"); - - assertEquals(31, wb.getSheetAt(0).getLastRowNum()); - - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - checkWorkbookGrouping(wb, - new Boolean [] { - // 0-4 - false, false, false, false, false, null, null, - // 7-11 - false, false, true, true, true, null, null, - // 14-18 - false, false, true, false, false, null, - // 20-24 - false, false, true, true, false, null, null, - // 27-31 - false, false, false, true, false }, - new boolean[] { - // 0-4 - false, false, false, false, false, false, false, - // 7-11 - true, true, true, true, false, false, false, - // 14-18 - true, true, false, false, false, false, - // 20-24 - true, true, true, false, false, false, false, - // 27-31 - true, true, true, true, false }, - // outlineLevel - new int[] { - // 0-4 - 3, 3, 2, 1, 0, 0, 0, - // 7-11 - 3, 3, 2, 1, 0, 0, 0, - // 14-18 - 3, 3, 2, 1, 0, 0, - // 20-24 - 3, 3, 2, 1, 0, 0, 0, - // 27-31 - 3, 3, 2, 1, 0, - } - ); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx")) { + + assertEquals(31, wb.getSheetAt(0).getLastRowNum()); + + // NOTE: This is currently based on current behavior of POI, somehow + // what POI returns in the calls to collapsed/hidden is not fully matching + // the examples in the spec or I did not fully understand how POI stores the data internally... + checkWorkbookGrouping(wb, + new Boolean[]{ + // 0-4 + false, false, false, false, false, null, null, + // 7-11 + false, false, true, true, true, null, null, + // 14-18 + false, false, true, false, false, null, + // 20-24 + false, false, true, true, false, null, null, + // 27-31 + false, false, false, true, false}, + new boolean[]{ + // 0-4 + false, false, false, false, false, false, false, + // 7-11 + true, true, true, true, false, false, false, + // 14-18 + true, true, false, false, false, false, + // 20-24 + true, true, true, false, false, false, false, + // 27-31 + true, true, true, true, false}, + // outlineLevel + new int[]{ + // 0-4 + 3, 3, 2, 1, 0, 0, 0, + // 7-11 + 3, 3, 2, 1, 0, 0, 0, + // 14-18 + 3, 3, 2, 1, 0, 0, + // 20-24 + 3, 3, 2, 1, 0, 0, 0, + // 27-31 + 3, 3, 2, 1, 0, + } + ); + } /* Row: 0: Level: 3 Collapsed: false Hidden: false Row: 1: Level: 3 Collapsed: false Hidden: false diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java index f68dd50a13..cb9b102bd9 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java @@ -20,6 +20,7 @@ package org.apache.poi.xwpf.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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -28,6 +29,7 @@ import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.List; +import java.util.Optional; import org.apache.poi.POIDataSamples; import org.apache.poi.ooxml.POIXMLDocumentPart; @@ -96,7 +98,7 @@ public final class TestXWPFDocument { assertEquals(1315, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); assertEquals(10, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - assertEquals(null, xml.getProperties().getCoreProperties().getTitle()); + assertNull(xml.getProperties().getCoreProperties().getTitle()); assertFalse(xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().isPresent()); } } @@ -112,7 +114,9 @@ public final class TestXWPFDocument { assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); assertEquals(" ", xml.getProperties().getCoreProperties().getTitle()); - assertEquals(" ", xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().get()); + Optional subjectProperty = xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty(); + assertTrue(subjectProperty.isPresent()); + assertEquals(" ", subjectProperty.get()); xml.close(); } @@ -153,7 +157,9 @@ public final class TestXWPFDocument { byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg"); String relationId = doc.addPictureData(jpeg, Document.PICTURE_TYPE_JPEG); - byte[] newJpeg = ((XWPFPictureData) doc.getRelationById(relationId)).getData(); + XWPFPictureData relationById = (XWPFPictureData) doc.getRelationById(relationId); + assertNotNull(relationById); + byte[] newJpeg = relationById.getData(); assertEquals(newJpeg.length, jpeg.length); for (int i = 0; i < jpeg.length; i++) { assertEquals(newJpeg[i], jpeg[i]); @@ -187,225 +193,225 @@ public final class TestXWPFDocument { @Test public void testAddHyperlink() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - XWPFParagraph p = doc.createParagraph(); - XWPFHyperlinkRun h = p.createHyperlinkRun("http://poi.apache.org/"); - h.setText("Apache POI"); - - assertEquals("http://poi.apache.org/", h.getHyperlink(doc).getURL()); - assertEquals(p.getRuns().size(), 1); - assertEquals(p.getRuns().get(0), h); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx")) { + XWPFParagraph p = doc.createParagraph(); + XWPFHyperlinkRun h = p.createHyperlinkRun("http://poi.apache.org/"); + h.setText("Apache POI"); + + assertEquals("http://poi.apache.org/", h.getHyperlink(doc).getURL()); + assertEquals(p.getRuns().size(), 1); + assertEquals(p.getRuns().get(0), h); + } } @Test public void testRemoveBodyElement() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - assertEquals(3, doc.getParagraphs().size()); - assertEquals(3, doc.getBodyElements().size()); - - XWPFParagraph p1 = doc.getParagraphs().get(0); - XWPFParagraph p2 = doc.getParagraphs().get(1); - XWPFParagraph p3 = doc.getParagraphs().get(2); - - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p2, doc.getBodyElements().get(1)); - assertEquals(p2, doc.getParagraphs().get(1)); - assertEquals(p3, doc.getBodyElements().get(2)); - assertEquals(p3, doc.getParagraphs().get(2)); - - // Add another - XWPFParagraph p4 = doc.createParagraph(); - - assertEquals(4, doc.getParagraphs().size()); - assertEquals(4, doc.getBodyElements().size()); - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p2, doc.getBodyElements().get(1)); - assertEquals(p2, doc.getParagraphs().get(1)); - assertEquals(p3, doc.getBodyElements().get(2)); - assertEquals(p3, doc.getParagraphs().get(2)); - assertEquals(p4, doc.getBodyElements().get(3)); - assertEquals(p4, doc.getParagraphs().get(3)); - - // Remove the 2nd - assertEquals(true, doc.removeBodyElement(1)); - assertEquals(3, doc.getParagraphs().size()); - assertEquals(3, doc.getBodyElements().size()); - - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p3, doc.getBodyElements().get(1)); - assertEquals(p3, doc.getParagraphs().get(1)); - assertEquals(p4, doc.getBodyElements().get(2)); - assertEquals(p4, doc.getParagraphs().get(2)); - - // Remove the 1st - assertEquals(true, doc.removeBodyElement(0)); - assertEquals(2, doc.getParagraphs().size()); - assertEquals(2, doc.getBodyElements().size()); - - assertEquals(p3, doc.getBodyElements().get(0)); - assertEquals(p3, doc.getParagraphs().get(0)); - assertEquals(p4, doc.getBodyElements().get(1)); - assertEquals(p4, doc.getParagraphs().get(1)); - - // Remove the last - assertEquals(true, doc.removeBodyElement(1)); - assertEquals(1, doc.getParagraphs().size()); - assertEquals(1, doc.getBodyElements().size()); - - assertEquals(p3, doc.getBodyElements().get(0)); - assertEquals(p3, doc.getParagraphs().get(0)); - doc.close(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { + assertEquals(3, doc.getParagraphs().size()); + assertEquals(3, doc.getBodyElements().size()); + + XWPFParagraph p1 = doc.getParagraphs().get(0); + XWPFParagraph p2 = doc.getParagraphs().get(1); + XWPFParagraph p3 = doc.getParagraphs().get(2); + + assertEquals(p1, doc.getBodyElements().get(0)); + assertEquals(p1, doc.getParagraphs().get(0)); + assertEquals(p2, doc.getBodyElements().get(1)); + assertEquals(p2, doc.getParagraphs().get(1)); + assertEquals(p3, doc.getBodyElements().get(2)); + assertEquals(p3, doc.getParagraphs().get(2)); + + // Add another + XWPFParagraph p4 = doc.createParagraph(); + + assertEquals(4, doc.getParagraphs().size()); + assertEquals(4, doc.getBodyElements().size()); + assertEquals(p1, doc.getBodyElements().get(0)); + assertEquals(p1, doc.getParagraphs().get(0)); + assertEquals(p2, doc.getBodyElements().get(1)); + assertEquals(p2, doc.getParagraphs().get(1)); + assertEquals(p3, doc.getBodyElements().get(2)); + assertEquals(p3, doc.getParagraphs().get(2)); + assertEquals(p4, doc.getBodyElements().get(3)); + assertEquals(p4, doc.getParagraphs().get(3)); + + // Remove the 2nd + assertTrue(doc.removeBodyElement(1)); + assertEquals(3, doc.getParagraphs().size()); + assertEquals(3, doc.getBodyElements().size()); + + assertEquals(p1, doc.getBodyElements().get(0)); + assertEquals(p1, doc.getParagraphs().get(0)); + assertEquals(p3, doc.getBodyElements().get(1)); + assertEquals(p3, doc.getParagraphs().get(1)); + assertEquals(p4, doc.getBodyElements().get(2)); + assertEquals(p4, doc.getParagraphs().get(2)); + + // Remove the 1st + assertTrue(doc.removeBodyElement(0)); + assertEquals(2, doc.getParagraphs().size()); + assertEquals(2, doc.getBodyElements().size()); + + assertEquals(p3, doc.getBodyElements().get(0)); + assertEquals(p3, doc.getParagraphs().get(0)); + assertEquals(p4, doc.getBodyElements().get(1)); + assertEquals(p4, doc.getParagraphs().get(1)); + + // Remove the last + assertTrue(doc.removeBodyElement(1)); + assertEquals(1, doc.getParagraphs().size()); + assertEquals(1, doc.getBodyElements().size()); + + assertEquals(p3, doc.getBodyElements().get(0)); + assertEquals(p3, doc.getParagraphs().get(0)); + } } @Test public void testRegisterPackagePictureData() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - - /* manually assemble a new image package part*/ - OPCPackage opcPckg = doc.getPackage(); - XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG; - PackagePartName partName = PackagingURIHelper.createPartName(jpgRelation.getDefaultFileName().replace('#', '2')); - PackagePart newImagePart = opcPckg.createPart(partName, jpgRelation.getContentType()); - byte[] nature1 = XWPFTestDataSamples.getImage("abstract4.jpg"); - OutputStream os = newImagePart.getOutputStream(); - os.write(nature1); - os.close(); - XWPFHeader xwpfHeader = doc.getHeaderArray(0); - XWPFPictureData newPicData = new XWPFPictureData(newImagePart); - /* new part is now ready to rumble */ - - assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPackagePictures().contains(newPicData)); - - doc.registerPackagePictureData(newPicData); - - assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPictures().contains(newPicData)); - assertTrue(doc.getAllPackagePictures().contains(newPicData)); - - doc.getPackage().revert(); - opcPckg.close(); - doc.close(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) { + /* manually assemble a new image package part*/ + OPCPackage opcPkg = doc.getPackage(); + XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG; + PackagePartName partName = PackagingURIHelper.createPartName(jpgRelation.getDefaultFileName().replace('#', '2')); + PackagePart newImagePart = opcPkg.createPart(partName, jpgRelation.getContentType()); + byte[] nature1 = XWPFTestDataSamples.getImage("abstract4.jpg"); + OutputStream os = newImagePart.getOutputStream(); + os.write(nature1); + os.close(); + XWPFHeader xwpfHeader = doc.getHeaderArray(0); + XWPFPictureData newPicData = new XWPFPictureData(newImagePart); + /* new part is now ready to rumble */ + + assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); + assertFalse(doc.getAllPictures().contains(newPicData)); + assertFalse(doc.getAllPackagePictures().contains(newPicData)); + + doc.registerPackagePictureData(newPicData); + + assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); + assertFalse(doc.getAllPictures().contains(newPicData)); + assertTrue(doc.getAllPackagePictures().contains(newPicData)); + + doc.getPackage().revert(); + opcPkg.close(); + } } @Test public void testFindPackagePictureData() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - byte[] nature1 = XWPFTestDataSamples.getImage("nature1.gif"); - XWPFPictureData part = doc.findPackagePictureData(nature1, Document.PICTURE_TYPE_GIF); - assertNotNull(part); - assertTrue(doc.getAllPictures().contains(part)); - assertTrue(doc.getAllPackagePictures().contains(part)); - doc.getPackage().revert(); - doc.close(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) { + byte[] nature1 = XWPFTestDataSamples.getImage("nature1.gif"); + XWPFPictureData part = doc.findPackagePictureData(nature1, Document.PICTURE_TYPE_GIF); + assertNotNull(part); + assertTrue(doc.getAllPictures().contains(part)); + assertTrue(doc.getAllPackagePictures().contains(part)); + doc.getPackage().revert(); + } } @Test public void testGetAllPictures() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); - List allPictures = doc.getAllPictures(); - List allPackagePictures = doc.getAllPackagePictures(); - - assertNotNull(allPictures); - assertEquals(3, allPictures.size()); - for (XWPFPictureData xwpfPictureData : allPictures) { - assertTrue(allPackagePictures.contains(xwpfPictureData)); - } + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) { + List allPictures = doc.getAllPictures(); + List allPackagePictures = doc.getAllPackagePictures(); + + assertNotNull(allPictures); + assertEquals(3, allPictures.size()); + for (XWPFPictureData xwpfPictureData : allPictures) { + assertTrue(allPackagePictures.contains(xwpfPictureData)); + } - try { - allPictures.add(allPictures.get(0)); - fail("This list must be unmodifiable!"); - } catch (UnsupportedOperationException e) { - // all ok - } + try { + allPictures.add(allPictures.get(0)); + fail("This list must be unmodifiable!"); + } catch (UnsupportedOperationException e) { + // all ok + } - doc.getPackage().revert(); - doc.close(); + doc.getPackage().revert(); + } } @Test public void testGetAllPackagePictures() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); - List allPackagePictures = doc.getAllPackagePictures(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) { + List allPackagePictures = doc.getAllPackagePictures(); - assertNotNull(allPackagePictures); - assertEquals(5, allPackagePictures.size()); + assertNotNull(allPackagePictures); + assertEquals(5, allPackagePictures.size()); - try { - allPackagePictures.add(allPackagePictures.get(0)); - fail("This list must be unmodifiable!"); - } catch (UnsupportedOperationException e) { - // all ok - } + try { + allPackagePictures.add(allPackagePictures.get(0)); + fail("This list must be unmodifiable!"); + } catch (UnsupportedOperationException e) { + // all ok + } - doc.getPackage().revert(); - doc.close(); + doc.getPackage().revert(); + } } @Test public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - assertEquals(1, doc.getAllPackagePictures().size()); - byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg"); - String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG); - assertEquals(2, doc.getAllPackagePictures().size()); - /* copy data, to avoid instance-equality */ - byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length); - String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG); - assertEquals(id1, id2); - doc.getPackage().revert(); - doc.close(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx")) { + assertEquals(1, doc.getAllPackagePictures().size()); + byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg"); + String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG); + assertEquals(2, doc.getAllPackagePictures().size()); + /* copy data, to avoid instance-equality */ + byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length); + String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG); + assertEquals(id1, id2); + doc.getPackage().revert(); + } } @Test public void testPictureHandlingHeaderDocumentImages() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx"); - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, doc.getAllPackagePictures().size()); - assertEquals(1, doc.getHeaderArray(0).getAllPictures().size()); - doc.getPackage().revert(); - doc.close(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx")) { + assertEquals(1, doc.getAllPictures().size()); + assertEquals(1, doc.getAllPackagePictures().size()); + assertEquals(1, doc.getHeaderArray(0).getAllPictures().size()); + doc.getPackage().revert(); + } } @Test public void testPictureHandlingComplex() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); - XWPFHeader xwpfHeader = doc.getHeaderArray(0); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx")) { + XWPFHeader xwpfHeader = doc.getHeaderArray(0); - assertEquals(3, doc.getAllPictures().size()); - assertEquals(3, xwpfHeader.getAllPictures().size()); - assertEquals(5, doc.getAllPackagePictures().size()); + assertEquals(3, doc.getAllPictures().size()); + assertEquals(3, xwpfHeader.getAllPictures().size()); + assertEquals(5, doc.getAllPackagePictures().size()); - byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg"); - String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG); - POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1"); - XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id); - assertSame(part1, part2); + byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg"); + String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG); + POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1"); + XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id); + assertSame(part1, part2); - doc.getPackage().revert(); - doc.close(); + doc.getPackage().revert(); + } } @Test public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx"); - POIXMLProperties properties = doc.getProperties(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx")) { + POIXMLProperties properties = doc.getProperties(); - assertNotNull(properties.getCoreProperties()); + assertNotNull(properties.getCoreProperties()); - XWPFHeader headerArray = doc.getHeaderArray(0); - assertEquals(1, headerArray.getAllPictures().size()); - assertEquals("image1.png", headerArray.pictures.get(0).getFileName()); - assertEquals("", headerArray.getText()); + XWPFHeader headerArray = doc.getHeaderArray(0); + assertEquals(1, headerArray.getAllPictures().size()); + assertEquals("image1.png", headerArray.pictures.get(0).getFileName()); + assertEquals("", headerArray.getText()); - POIXMLProperties.ExtendedProperties extendedProperties = properties.getExtendedProperties(); - assertNotNull(extendedProperties); - assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters()); - doc.close(); + POIXMLProperties.ExtendedProperties extendedProperties = properties.getExtendedProperties(); + assertNotNull(extendedProperties); + assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters()); + } } @Test @@ -414,14 +420,14 @@ public final class TestXWPFDocument { assertEquals(100, settings.getZoomPercent()); settings.setZoomPercent(50); assertEquals(50, settings.getZoomPercent()); - - assertEquals(false, settings.getEvenAndOddHeadings()); + + assertFalse(settings.getEvenAndOddHeadings()); settings.setEvenAndOddHeadings(true); - assertEquals(true, settings.getEvenAndOddHeadings()); + assertTrue(settings.getEvenAndOddHeadings()); - assertEquals(false, settings.getMirrorMargins()); + assertFalse(settings.getMirrorMargins()); settings.setMirrorMargins(true); - assertEquals(true, settings.getMirrorMargins()); + assertTrue(settings.getMirrorMargins()); XWPFDocument doc = new XWPFDocument(); assertEquals(100, doc.getZoomPercent()); @@ -432,13 +438,13 @@ public final class TestXWPFDocument { doc.setZoomPercent(200); assertEquals(200, doc.getZoomPercent()); - assertEquals(false, doc.getEvenAndOddHeadings()); + assertFalse(doc.getEvenAndOddHeadings()); doc.setEvenAndOddHeadings(true); - assertEquals(true, doc.getEvenAndOddHeadings()); + assertTrue(doc.getEvenAndOddHeadings()); - assertEquals(false, doc.getMirrorMargins()); + assertFalse(doc.getMirrorMargins()); doc.setMirrorMargins(true); - assertEquals(true, doc.getMirrorMargins()); + assertTrue(doc.getMirrorMargins()); XWPFDocument back = XWPFTestDataSamples.writeOutAndReadBack(doc); assertEquals(200, back.getZoomPercent()); @@ -453,10 +459,10 @@ public final class TestXWPFDocument { @Test public void testEnforcedWith() throws IOException { - XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx"); - assertTrue(docx.isEnforcedProtection()); - docx.close(); - } + try (XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx")) { + assertTrue(docx.isEnforcedProtection()); + } + } @Test @Ignore("XWPF should be able to write to a new Stream when opened Read-Only") @@ -466,14 +472,15 @@ public final class TestXWPFDocument { PackageAccess.READ ); XWPFDocument doc = new XWPFDocument(opc); - XWPFWordExtractor ext = new XWPFWordExtractor(doc); - String origText = ext.getText(); - - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - ext.close(); - ext = new XWPFWordExtractor(doc); - - assertEquals(origText, ext.getText()); - ext.close(); - } + + final String origText; + try (XWPFWordExtractor ext = new XWPFWordExtractor(doc)) { + origText = ext.getText(); + + doc = XWPFTestDataSamples.writeOutAndReadBack(doc); + } + try (XWPFWordExtractor ext = new XWPFWordExtractor(doc)) { + assertEquals(origText, ext.getText()); + } + } } diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java index 27df95095e..e6b864fdbe 100644 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java @@ -790,23 +790,23 @@ public class TestXWPFRun { @Test public void testGetDepthWidth() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFParagraph p = hdr.createParagraph(); - XWPFRun r = p.createRun(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx")) { + XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); + XWPFParagraph p = hdr.createParagraph(); + XWPFRun r = p.createRun(); - assertEquals(0, hdr.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); + assertEquals(0, hdr.getAllPictures().size()); + assertEquals(0, r.getEmbeddedPictures().size()); - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); + r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - assertEquals(1, hdr.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); + assertEquals(1, hdr.getAllPictures().size()); + assertEquals(1, r.getEmbeddedPictures().size()); - XWPFPicture pic = r.getEmbeddedPictures().get(0); + XWPFPicture pic = r.getEmbeddedPictures().get(0); - assertEquals(pic.getWidth(), Units.toPoints(21), 0.0); - assertEquals(pic.getDepth(), Units.toPoints(32), 0.0); + assertEquals(pic.getWidth(), Units.toPoints(21), 0.0); + assertEquals(pic.getDepth(), Units.toPoints(32), 0.0); + } } - } diff --git a/src/testcases/org/apache/poi/ss/formula/TestMissingWorkbook.java b/src/testcases/org/apache/poi/ss/formula/TestMissingWorkbook.java index d1a5f02101..1093e541a9 100644 --- a/src/testcases/org/apache/poi/ss/formula/TestMissingWorkbook.java +++ b/src/testcases/org/apache/poi/ss/formula/TestMissingWorkbook.java @@ -19,12 +19,6 @@ package org.apache.poi.ss.formula; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; @@ -32,8 +26,20 @@ import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; -public class TestMissingWorkbook extends TestCase { +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class TestMissingWorkbook { protected Workbook mainWorkbook; protected Workbook sourceWorkbook; @@ -44,6 +50,7 @@ public class TestMissingWorkbook extends TestCase { public TestMissingWorkbook() { this("52575_main.xls", "source_dummy.xls", "52575_source.xls"); } + protected TestMissingWorkbook(String MAIN_WORKBOOK_FILENAME, String SOURCE_DUMMY_WORKBOOK_FILENAME, String SOURCE_WORKBOOK_FILENAME) { this.MAIN_WORKBOOK_FILENAME = MAIN_WORKBOOK_FILENAME; @@ -51,8 +58,8 @@ public class TestMissingWorkbook extends TestCase { this.SOURCE_WORKBOOK_FILENAME = SOURCE_WORKBOOK_FILENAME; } - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); @@ -60,7 +67,19 @@ public class TestMissingWorkbook extends TestCase { assertNotNull(sourceWorkbook); } - public void testMissingWorkbookMissing() throws IOException { + @After + public void tearDown() throws Exception { + if(mainWorkbook != null) { + mainWorkbook.close(); + } + + if(sourceWorkbook != null) { + sourceWorkbook.close(); + } + } + + @Test + public void testMissingWorkbookMissing() { FormulaEvaluator evaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator(); Sheet lSheet = mainWorkbook.getSheetAt(0); @@ -71,12 +90,13 @@ public class TestMissingWorkbook extends TestCase { try { evaluator.evaluateFormulaCell(lA1Cell); fail("Missing external workbook reference exception expected!"); - }catch(RuntimeException re) { + } catch(RuntimeException re) { assertTrue("Unexpected exception: " + re, re.getMessage().contains(SOURCE_DUMMY_WORKBOOK_FILENAME)); } } - - public void testMissingWorkbookMissingOverride() throws IOException { + + @Test + public void testMissingWorkbookMissingOverride() { Sheet lSheet = mainWorkbook.getSheetAt(0); Cell lA1Cell = lSheet.getRow(0).getCell(0); Cell lB1Cell = lSheet.getRow(1).getCell(0); @@ -89,7 +109,7 @@ public class TestMissingWorkbook extends TestCase { // Check cached values assertEquals(10.0d, lA1Cell.getNumericCellValue(), 0.00001d); assertEquals("POI rocks!", lB1Cell.getStringCellValue()); - assertEquals(true, lC1Cell.getBooleanCellValue()); + assertTrue(lC1Cell.getBooleanCellValue()); // Evaluate FormulaEvaluator evaluator = mainWorkbook.getCreationHelper().createFormulaEvaluator(); @@ -101,11 +121,11 @@ public class TestMissingWorkbook extends TestCase { assertEquals(10.0d, lA1Cell.getNumericCellValue(), 0.00001d); assertEquals("POI rocks!", lB1Cell.getStringCellValue()); - assertEquals(true, lC1Cell.getBooleanCellValue()); + assertTrue(lC1Cell.getBooleanCellValue()); } - - public void testExistingWorkbook() throws IOException { + @Test + public void testExistingWorkbook() { Sheet lSheet = mainWorkbook.getSheetAt(0); Cell lA1Cell = lSheet.getRow(0).getCell(0); Cell lB1Cell = lSheet.getRow(1).getCell(0); @@ -128,6 +148,6 @@ public class TestMissingWorkbook extends TestCase { assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d); assertEquals("Apache rocks!", lB1Cell.getStringCellValue()); - assertEquals(false, lC1Cell.getBooleanCellValue()); + assertFalse(lC1Cell.getBooleanCellValue()); } } diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java index ce16b01a44..e2c195fa41 100644 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java +++ b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java @@ -30,9 +30,11 @@ import static org.mockito.Mockito.verify; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; +import java.util.List; import java.util.Locale; import java.util.TimeZone; @@ -42,6 +44,7 @@ import org.apache.poi.ss.ITestDataProvider; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.util.LocaleUtil; +import org.junit.After; import org.junit.Test; /** @@ -1423,7 +1426,17 @@ public abstract class BaseTestCell { verify(cell).setBlank(); } + private List workbooksToClose = new ArrayList<>(); + + @After + public void closeWorkbooks() throws IOException { + for (Workbook workbook : workbooksToClose) { + workbook.close(); + } + } private Cell getInstance() { - return _testDataProvider.createWorkbook().createSheet().createRow(0).createCell(0); + Workbook workbookToClose = _testDataProvider.createWorkbook(); + workbooksToClose.add(workbookToClose); + return workbookToClose.createSheet().createRow(0).createCell(0); } } -- 2.39.5