diff options
author | Andreas Beeker <kiwiwings@apache.org> | 2021-10-18 22:35:17 +0000 |
---|---|---|
committer | Andreas Beeker <kiwiwings@apache.org> | 2021-10-18 22:35:17 +0000 |
commit | 3c3154ea8c330833fc38bd2144018f09a7d56b09 (patch) | |
tree | 89fd43d1280fa4865fe7f0fd4b821b5ad148178c | |
parent | 646fb8c69080d191256468168ce63e1d3cb81c2d (diff) | |
download | poi-3c3154ea8c330833fc38bd2144018f09a7d56b09.tar.gz poi-3c3154ea8c330833fc38bd2144018f09a7d56b09.zip |
sonar fixes
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1894365 13f79535-47bb-0310-9956-ffa450edef68
30 files changed, 1151 insertions, 1244 deletions
diff --git a/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java b/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java index d0bd16f782..56a7f5a397 100644 --- a/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java +++ b/poi-examples/src/test/java/org/apache/poi/integration/TestXLSX2CSV.java @@ -106,7 +106,7 @@ public class TestXLSX2CSV { } String errorOutput = errorBytes.toString(StandardCharsets.UTF_8); - assertEquals(errorOutput.length(), 0); + assertEquals(0, errorOutput.length()); String output = outputBytes.toString(StandardCharsets.UTF_8); assertTrue(output.contains("\"Lorem\",111,,,"), "Had: " + output); diff --git a/poi-excelant/src/test/java/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java b/poi-excelant/src/test/java/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java index 3bfe15e47a..545801c722 100644 --- a/poi-excelant/src/test/java/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java +++ b/poi-excelant/src/test/java/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java @@ -274,7 +274,7 @@ class TestExcelAntWorkbookUtil { List<String> sheets = fixture.getSheets(); assertNotNull(sheets); - assertEquals(sheets.size(), 3); + assertEquals(3, sheets.size()); } @Test diff --git a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java index 1fe70833c9..7c3121ae2c 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java +++ b/poi-ooxml/src/test/java/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java @@ -23,11 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.IOException; import java.util.Arrays; import java.util.List; -import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -40,7 +38,6 @@ import org.apache.poi.openxml4j.opc.PackagingURIHelper; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFPicture; @@ -88,10 +85,10 @@ public final class TestContentTypeManager { ctm.addContentType(name3, "text/xml+rel"); ctm.addContentType(name4, "text/xml+rel"); - assertEquals(ctm.getContentType(name1), "foo-type1"); - assertEquals(ctm.getContentType(name2), "foo-type2"); - assertEquals(ctm.getContentType(name3), "text/xml+rel"); - assertEquals(ctm.getContentType(name3), "text/xml+rel"); + assertEquals("foo-type1", ctm.getContentType(name1)); + assertEquals("foo-type2", ctm.getContentType(name2)); + assertEquals("text/xml+rel", ctm.getContentType(name3)); + assertEquals("text/xml+rel", ctm.getContentType(name3)); } /** @@ -114,8 +111,8 @@ public final class TestContentTypeManager { ctm.removeContentType(name2); ctm.removeContentType(name3); - assertEquals(ctm.getContentType(name1), "foo-type1"); - assertEquals(ctm.getContentType(name2), "foo-type1"); + assertEquals("foo-type1", ctm.getContentType(name1)); + assertEquals("foo-type1", ctm.getContentType(name2)); assertNull(ctm.getContentType(name3)); ctm.removeContentType(name1); @@ -131,15 +128,6 @@ public final class TestContentTypeManager { // TODO } - protected byte[] toByteArray(Workbook wb) { - try (UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream()) { - wb.write(os); - return os.toByteArray(); - } catch (IOException e) { - throw new RuntimeException("failed to write excel file."); - } - } - @Test void bug62629CombinePictures() throws Exception { // this file has incorrect default content-types which caused problems in Apache POI diff --git a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java index 9d240ef4be..0bb196af50 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java +++ b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java @@ -608,14 +608,14 @@ class TestSignatureInfo { String certDigestXQuery = declareNS + "$this//xades:SigningCertificate/xades:Cert/xades:CertDigest"; XmlObject[] xoList = sigDoc.selectPath(certDigestXQuery); - assertEquals(xoList.length, 1); + assertEquals(1, xoList.length); DigestAlgAndValueType certDigest = (DigestAlgAndValueType) xoList[0]; assertNotNull(certDigest.getDigestValue()); String qualPropXQuery = declareNS + "$this/ds:Signature/ds:Object/xades:QualifyingProperties"; xoList = sigDoc.selectPath(qualPropXQuery); - assertEquals(xoList.length, 1); + assertEquals(1, xoList.length); QualifyingPropertiesType qualProp = (QualifyingPropertiesType) xoList[0]; boolean qualPropXsdOk = qualProp.validate(); assertTrue(qualPropXsdOk); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java index 9ca059b99c..c6d92c4c59 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xslf/TestXSLFBugs.java @@ -50,7 +50,8 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.apache.commons.io.output.NullOutputStream; +import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.POIDataSamples; import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.extractor.ExtractorFactory; @@ -79,11 +80,9 @@ import org.apache.poi.sl.usermodel.TextParagraph; import org.apache.poi.sl.usermodel.TextRun; import org.apache.poi.sl.usermodel.TextShape; import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.commons.io.output.NullPrintStream; import org.apache.poi.xslf.usermodel.*; import org.apache.poi.xslf.util.DummyGraphics2d; import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -114,11 +113,11 @@ class TestXSLFBugs { XSLFSlide slide = ss1.getSlides().get(0); - assertEquals(slide.getShapes().size(), 1); + assertEquals(1,slide.getShapes().size()); XSLFPictureShape picture = (XSLFPictureShape) slide.getShapes().get(0); - assertEquals(picture.getShapeId(), 662); + assertEquals(662, picture.getShapeId()); assertFalse(picture.isExternalLinkedPicture()); assertNull(picture.getPictureData()); assertNull(picture.getPictureLink()); @@ -133,12 +132,12 @@ class TestXSLFBugs { XSLFSlide slide0 = ss1.getSlides().get(0); - assertEquals(slide0.getShapes().size(), 4); + assertEquals(4, slide0.getShapes().size()); assertRelation(slide0, "/ppt/slides/slide1.xml", null); assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); assertRelation(slide0, "/ppt/media/image1.png", "rId2"); - assertEquals(slide0.getRelations().size(), 2); + assertEquals(2, slide0.getRelations().size()); List<XSLFPictureShape> pictures = new ArrayList<>(); for (XSLFShape shape : slide0.getShapes()) { @@ -147,21 +146,21 @@ class TestXSLFBugs { } } - assertEquals(pictures.size(), 2); - assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); - assertEquals(pictures.get(1).getPictureData().getFileName(), "image1.png"); + assertEquals(2, pictures.size()); + assertEquals("image1.png", pictures.get(0).getPictureData().getFileName()); + assertEquals("image1.png", pictures.get(1).getPictureData().getFileName()); // blipId is rId2 of both pictures // remove just the first picture slide0.removeShape(pictures.get(0)); - assertEquals(slide0.getShapes().size(), 3); + assertEquals(3, slide0.getShapes().size()); assertRelation(slide0, "/ppt/slides/slide1.xml", null); assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); // the bug is that the following relation is gone assertRelation(slide0, "/ppt/media/image1.png", "rId2"); - assertEquals(slide0.getRelations().size(), 2); + assertEquals(2, slide0.getRelations().size()); // Save and re-load try (XMLSlideShow ss2 = writeOutAndReadBack(ss1)) { @@ -172,7 +171,7 @@ class TestXSLFBugs { assertRelation(slide0, "/ppt/slides/slide1.xml", null); assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); assertRelation(slide0, "/ppt/media/image1.png", "rId2"); - assertEquals(slide0.getRelations().size(), 2); + assertEquals(2, slide0.getRelations().size()); pictures.clear(); for (XSLFShape shape : slide0.getShapes()) { @@ -181,17 +180,17 @@ class TestXSLFBugs { } } - assertEquals(pictures.size(), 1); - assertEquals(pictures.get(0).getPictureData().getFileName(), "image1.png"); + assertEquals(1, pictures.size()); + assertEquals("image1.png", pictures.get(0).getPictureData().getFileName()); slide0.removeShape(pictures.get(0)); - assertEquals(slide0.getShapes().size(), 2); + assertEquals(2, slide0.getShapes().size()); assertRelation(slide0, "/ppt/slides/slide1.xml", null); assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); assertNull(slide0.getRelationById("rId2")); - assertEquals(slide0.getRelations().size(), 1); + assertEquals(1, slide0.getRelations().size()); // Save and re-load try (XMLSlideShow ss3 = writeOutAndReadBack(ss2)) { @@ -201,7 +200,7 @@ class TestXSLFBugs { assertRelation(slide0, "/ppt/slides/slide1.xml", null); assertRelation(slide0, "/ppt/slideLayouts/slideLayout1.xml", "rId1"); - assertEquals(slide0.getShapes().size(), 2); + assertEquals(2, slide0.getShapes().size()); } } } @@ -919,9 +918,9 @@ class TestXSLFBugs { XSLFSlide slide = ss1.getSlides().get(0); - assertEquals(slide.getShapes().size(), 1); + assertEquals(1, slide.getShapes().size()); XSLFGroupShape group = (XSLFGroupShape) slide.getShapes().get(0); - assertEquals(group.getShapes().size(), 2); + assertEquals(2, group.getShapes().size()); XSLFAutoShape oval = (XSLFAutoShape) group.getShapes().get(0); XSLFAutoShape arrow = (XSLFAutoShape) group.getShapes().get(1); assertNull(oval.getFillColor()); @@ -1067,7 +1066,7 @@ class TestXSLFBugs { XSLFSlide targetSlide = targetPresentation.getSlides().get(0); assertEquals(2, targetPresentation.getPictureData().size()); - targetPresentation.write(new UnsynchronizedByteArrayOutputStream()); + targetPresentation.write(NullOutputStream.NULL_OUTPUT_STREAM); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java index 377918ec1f..eaea83d972 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/eventusermodel/TestXSSFSheetXMLHandler.java @@ -60,7 +60,7 @@ public class TestXSSFSheetXMLHandler { public void cell(final String cellReference, final String formattedValue, final XSSFComment comment) { assertEquals("\uD83D\uDE1Cmore text", formattedValue); - assertEquals(cellCount++, 0); + assertEquals(0, cellCount++); } }, false)); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java index dfc129a47f..d989dca870 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java @@ -19,7 +19,9 @@ package org.apache.poi.xssf.usermodel; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -66,19 +68,16 @@ public abstract class BaseTestXSSFPivotTable { */ @Test void testAddRowLabelToPivotTable() { - int columnIndex = 0; - assertEquals(0, pivotTable.getRowLabelColumns().size()); - pivotTable.addRowLabel(columnIndex); + pivotTable.addRowLabel(0); CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - assertEquals(defintion.getRowFields().getFieldArray(0).getX(), columnIndex); - assertEquals(defintion.getRowFields().getCount(), 1); + assertEquals(0, defintion.getRowFields().getFieldArray(0).getX()); + assertEquals(1, defintion.getRowFields().getCount()); assertEquals(1, pivotTable.getRowLabelColumns().size()); - columnIndex = 1; - pivotTable.addRowLabel(columnIndex); + pivotTable.addRowLabel(1); assertEquals(2, pivotTable.getRowLabelColumns().size()); assertEquals(0, (int)pivotTable.getRowLabelColumns().get(0)); @@ -120,7 +119,7 @@ public abstract class BaseTestXSSFPivotTable { pivotTable.addColumnLabel(DataConsolidateFunction.MIN, columnThree); CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - assertEquals(defintion.getDataFields().getDataFieldList().size(), 3); + assertEquals(3, defintion.getDataFields().getDataFieldList().size()); } @@ -138,7 +137,7 @@ public abstract class BaseTestXSSFPivotTable { pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnThree); CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - assertEquals(defintion.getDataFields().getDataFieldList().size(), 3); + assertEquals(3, defintion.getDataFields().getDataFieldList().size()); } /** @@ -161,15 +160,13 @@ public abstract class BaseTestXSSFPivotTable { */ @Test void testColumnLabelCreatesDataField() { - int columnIndex = 0; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex); + pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 0); CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getSubtotal(), - STDataConsolidateFunction.Enum.forInt(DataConsolidateFunction.SUM.getValue())); + assertEquals(0, defintion.getDataFields().getDataFieldArray(0).getFld()); + assertSame(STDataConsolidateFunction.Enum.forInt(DataConsolidateFunction.SUM.getValue()), + defintion.getDataFields().getDataFieldArray(0).getSubtotal()); } /** @@ -220,12 +217,9 @@ public abstract class BaseTestXSSFPivotTable { */ @Test void testAddDataColumn() { - int columnIndex = 0; - boolean isDataField = true; - - pivotTable.addDataColumn(columnIndex, isDataField); + pivotTable.addDataColumn(0, true); CTPivotFields pivotFields = pivotTable.getCTPivotTableDefinition().getPivotFields(); - assertEquals(pivotFields.getPivotFieldArray(columnIndex).getDataField(), isDataField); + assertTrue(pivotFields.getPivotFieldArray(0).getDataField()); } /** @@ -247,8 +241,8 @@ public abstract class BaseTestXSSFPivotTable { CTPageFields fields = pivotTable.getCTPivotTableDefinition().getPageFields(); CTPageField field = fields.getPageFieldArray(0); assertEquals(field.getFld(), columnIndex); - assertEquals(field.getHier(), -1); - assertEquals(fields.getCount(), 1); + assertEquals(-1, field.getHier()); + assertEquals(1, fields.getCount()); } /** @@ -295,19 +289,16 @@ public abstract class BaseTestXSSFPivotTable { */ @Test void testAddColLabelToPivotTable() { - int columnIndex = 0; - assertEquals(0, pivotTable.getColLabelColumns().size()); - pivotTable.addColLabel(columnIndex); + pivotTable.addColLabel(0); CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - assertEquals(defintion.getColFields().getFieldArray(0).getX(), columnIndex); - assertEquals(defintion.getColFields().getCount(), 1); + assertEquals(0, defintion.getColFields().getFieldArray(0).getX()); + assertEquals(1, defintion.getColFields().getCount()); assertEquals(1, pivotTable.getColLabelColumns().size()); - columnIndex = 1; - pivotTable.addColLabel(columnIndex); + pivotTable.addColLabel(1); assertEquals(2, pivotTable.getColLabelColumns().size()); assertEquals(0, (int)pivotTable.getColLabelColumns().get(0)); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java index 727f399ea8..b21ff6ec4a 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java @@ -121,7 +121,7 @@ class TestXSSFCellStyle { assertTrue(borderId > 0); //check changes in the underlying xml bean CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getBottom().getStyle()); + assertSame(STBorderStyle.MEDIUM, ctBorder.getBottom().getStyle()); num = stylesTable.getBorders().size(); //setting the same border multiple times should not change borderId @@ -141,7 +141,7 @@ class TestXSSFCellStyle { //none is not the same as "not set", therefore the following doesn't work any more //assertFalse(ctBorder.isSetBottom()); //replacement: - assertEquals(ctBorder.getBottom().getStyle(), STBorderStyle.NONE); + assertSame(STBorderStyle.NONE, ctBorder.getBottom().getStyle()); } @Test @@ -159,7 +159,7 @@ class TestXSSFCellStyle { assertTrue(borderId > 0); //check changes in the underlying xml bean CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getRight().getStyle()); + assertSame(STBorderStyle.MEDIUM, ctBorder.getRight().getStyle()); num = stylesTable.getBorders().size(); //setting the same border multiple times should not change borderId @@ -179,7 +179,7 @@ class TestXSSFCellStyle { //none is not the same as "not set", therefore the following doesn't work any more //assertFalse(ctBorder.isSetRight()); //replacement: - assertEquals(ctBorder.getRight().getStyle(), STBorderStyle.NONE); + assertSame(STBorderStyle.NONE, ctBorder.getRight().getStyle()); } @Test @@ -197,7 +197,7 @@ class TestXSSFCellStyle { assertTrue(borderId > 0); //check changes in the underlying xml bean CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getLeft().getStyle()); + assertSame(STBorderStyle.MEDIUM, ctBorder.getLeft().getStyle()); num = stylesTable.getBorders().size(); //setting the same border multiple times should not change borderId @@ -217,7 +217,7 @@ class TestXSSFCellStyle { //none is not the same as "not set", therefore the following doesn't work any more //assertFalse(ctBorder.isSetLeft()); //replacement: - assertEquals(ctBorder.getLeft().getStyle(), STBorderStyle.NONE); + assertSame(STBorderStyle.NONE, ctBorder.getLeft().getStyle()); } @Test @@ -235,7 +235,7 @@ class TestXSSFCellStyle { assertTrue(borderId > 0); //check changes in the underlying xml bean CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getTop().getStyle()); + assertSame(STBorderStyle.MEDIUM, ctBorder.getTop().getStyle()); num = stylesTable.getBorders().size(); //setting the same border multiple times should not change borderId @@ -255,7 +255,7 @@ class TestXSSFCellStyle { //none is not the same as "not set", therefore the following doesn't work any more //assertFalse(ctBorder.isSetTop()); //replacement: - assertEquals(ctBorder.getTop().getStyle(), STBorderStyle.NONE); + assertSame(STBorderStyle.NONE, ctBorder.getTop().getStyle()); } private void testGetSetBorderXMLBean(BorderStyle border, STBorderStyle.Enum expected) { @@ -265,7 +265,7 @@ class TestXSSFCellStyle { assertTrue(borderId > 0); //check changes in the underlying xml bean CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(expected, ctBorder.getTop().getStyle()); + assertSame(expected, ctBorder.getTop().getStyle()); } @@ -641,7 +641,7 @@ class TestXSSFCellStyle { assertTrue(fillId > 0); //check changes in the underlying xml bean CTFill ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertEquals(STPatternType.SOLID, ctFill2.getPatternFill().getPatternType()); + assertSame(STPatternType.SOLID, ctFill2.getPatternFill().getPatternType()); //setting the same fill multiple time does not update the styles table for (int i = 0; i < 3; i++) { @@ -695,15 +695,15 @@ class TestXSSFCellStyle { cellStyle.setAlignment(HorizontalAlignment.LEFT); assertEquals(HorizontalAlignment.LEFT, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.LEFT, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + assertSame(STHorizontalAlignment.LEFT, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); cellStyle.setAlignment(HorizontalAlignment.JUSTIFY); assertEquals(HorizontalAlignment.JUSTIFY, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + assertSame(STHorizontalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); cellStyle.setAlignment(HorizontalAlignment.CENTER); assertEquals(HorizontalAlignment.CENTER, cellStyle.getAlignment()); - assertEquals(STHorizontalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); + assertSame(STHorizontalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); } @Test @@ -728,15 +728,15 @@ class TestXSSFCellStyle { void testGetSetVerticalAlignment() { assertEquals(VerticalAlignment.BOTTOM, cellStyle.getVerticalAlignment()); assertFalse(cellStyle.getCellAlignment().getCTCellAlignment().isSetVertical()); - assertEquals(STVerticalAlignment.BOTTOM, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); + assertSame(STVerticalAlignment.BOTTOM, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); assertEquals(VerticalAlignment.CENTER, cellStyle.getVerticalAlignment()); - assertEquals(STVerticalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); + assertSame(STVerticalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); cellStyle.setVerticalAlignment(VerticalAlignment.JUSTIFY); assertEquals(VerticalAlignment.JUSTIFY, cellStyle.getVerticalAlignment()); - assertEquals(STVerticalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); + assertSame(STVerticalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); } @Test @@ -848,8 +848,8 @@ class TestXSSFCellStyle { assertEquals("TestingFont", clone.getFont().getFontName()); assertEquals(fmtClone.getFormat("Test##"), clone.getDataFormat()); assertNotEquals(fmtClone.getFormat("Test##"), fmt.getFormat("Test##")); - assertEquals(clone.getFillPattern(), FillPatternType.SOLID_FOREGROUND); - assertEquals(clone.getFillForegroundColor(), IndexedColors.BRIGHT_GREEN.getIndex()); + assertEquals(FillPatternType.SOLID_FOREGROUND, clone.getFillPattern()); + assertEquals(IndexedColors.BRIGHT_GREEN.getIndex(), clone.getFillForegroundColor()); // Save it and re-check XSSFWorkbook wbReload = XSSFTestDataSamples.writeOutAndReadBack(wbClone); @@ -862,8 +862,8 @@ class TestXSSFCellStyle { assertEquals("TestingFont", reload.getFont().getFontName()); assertEquals(fmtClone.getFormat("Test##"), reload.getDataFormat()); assertNotEquals(fmtClone.getFormat("Test##"), fmt.getFormat("Test##")); - assertEquals(clone.getFillPattern(), FillPatternType.SOLID_FOREGROUND); - assertEquals(clone.getFillForegroundColor(), IndexedColors.BRIGHT_GREEN.getIndex()); + assertEquals(FillPatternType.SOLID_FOREGROUND, clone.getFillPattern()); + assertEquals(IndexedColors.BRIGHT_GREEN.getIndex(), clone.getFillForegroundColor()); XSSFWorkbook wbOrig2 = XSSFTestDataSamples.writeOutAndReadBack(wbOrig); assertNotNull(wbOrig2); @@ -1006,8 +1006,6 @@ class TestXSSFCellStyle { final CellStyle targetStyle = target.createCellStyle(); targetStyle.cloneStyleFrom(referenceStyle); } - /*System.out.println("Reference : "+reference.getNumCellStyles()); - System.out.println("Target : "+target.getNumCellStyles());*/ } @Test @@ -1025,9 +1023,6 @@ class TestXSSFCellStyle { cell.setCellValue("Coucou"+i); cell.setCellStyle(target.getCellStyleAt(i)); } - /*OutputStream out = new FileOutputStream("C:\\temp\\58084.xlsx"); - target.write(out); - out.close();*/ Workbook copy = XSSFTestDataSamples.writeOutAndReadBack(target); diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java index a3878dcc31..de6ec4324a 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFFont.java @@ -17,6 +17,7 @@ package org.apache.poi.xssf.usermodel; +import static org.apache.poi.ss.usermodel.FontCharset.*; import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; @@ -79,7 +80,7 @@ public final class TestXSSFFont extends BaseTestFont{ xssfFont.setBold(true); - assertEquals(ctFont.sizeOfBArray(),1); + assertEquals(1,ctFont.sizeOfBArray()); assertTrue(ctFont.getBArray(0).getVal()); } @@ -88,27 +89,27 @@ public final class TestXSSFFont extends BaseTestFont{ void testCharSetWithDeprecatedFontCharset() throws IOException { CTFont ctFont=CTFont.Factory.newInstance(); CTIntProperty prop=ctFont.addNewCharset(); - prop.setVal(org.apache.poi.ss.usermodel.FontCharset.ANSI.getValue()); + prop.setVal(ANSI.getValue()); ctFont.setCharsetArray(0,prop); XSSFFont xssfFont=new XSSFFont(ctFont); assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); - xssfFont.setCharSet(org.apache.poi.ss.usermodel.FontCharset.DEFAULT); - assertEquals(org.apache.poi.ss.usermodel.FontCharset.DEFAULT.getValue(),ctFont.getCharsetArray(0).getVal()); + xssfFont.setCharSet(DEFAULT); + assertEquals(DEFAULT.getValue(),ctFont.getCharsetArray(0).getVal()); // Try with a few less usual ones: // Set with the Charset itself - xssfFont.setCharSet(org.apache.poi.ss.usermodel.FontCharset.RUSSIAN); - assertEquals(org.apache.poi.ss.usermodel.FontCharset.RUSSIAN.getValue(), xssfFont.getCharSet()); + xssfFont.setCharSet(RUSSIAN); + assertEquals(RUSSIAN.getValue(), xssfFont.getCharSet()); // And set with the Charset index - xssfFont.setCharSet(org.apache.poi.ss.usermodel.FontCharset.ARABIC.getValue()); - assertEquals(org.apache.poi.ss.usermodel.FontCharset.ARABIC.getValue(), xssfFont.getCharSet()); - xssfFont.setCharSet((byte)(org.apache.poi.ss.usermodel.FontCharset.ARABIC.getValue())); - assertEquals(org.apache.poi.ss.usermodel.FontCharset.ARABIC.getValue(), xssfFont.getCharSet()); + xssfFont.setCharSet(ARABIC.getValue()); + assertEquals(ARABIC.getValue(), xssfFont.getCharSet()); + xssfFont.setCharSet((byte)(ARABIC.getValue())); + assertEquals(ARABIC.getValue(), xssfFont.getCharSet()); // This one isn't allowed - assertNull(org.apache.poi.ss.usermodel.FontCharset.valueOf(9999)); + assertNull(valueOf(9999)); assertThrows(POIXMLException.class, () -> xssfFont.setCharSet(9999), "Shouldn't be able to set an invalid charset"); @@ -198,7 +199,7 @@ public final class TestXSSFFont extends BaseTestFont{ assertFalse(xssfFont.getItalic()); xssfFont.setItalic(true); - assertEquals(ctFont.sizeOfIArray(),1); + assertEquals(1,ctFont.sizeOfIArray()); assertTrue(ctFont.getIArray(0).getVal()); assertTrue(ctFont.getIArray(0).getVal()); } @@ -214,7 +215,7 @@ public final class TestXSSFFont extends BaseTestFont{ assertFalse(xssfFont.getStrikeout()); xssfFont.setStrikeout(true); - assertEquals(ctFont.sizeOfStrikeArray(),1); + assertEquals(1,ctFont.sizeOfStrikeArray()); assertTrue(ctFont.getStrikeArray(0).getVal()); assertTrue(ctFont.getStrikeArray(0).getVal()); } @@ -258,11 +259,11 @@ public final class TestXSSFFont extends BaseTestFont{ assertEquals(Font.U_SINGLE, xssfFont.getUnderline()); xssfFont.setUnderline(Font.U_DOUBLE); - assertEquals(ctFont.sizeOfUArray(),1); + assertEquals(1, ctFont.sizeOfUArray()); assertSame(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal()); xssfFont.setUnderline(FontUnderline.DOUBLE_ACCOUNTING); - assertEquals(ctFont.sizeOfUArray(),1); + assertEquals(1, ctFont.sizeOfUArray()); assertSame(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal()); } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFSheet.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFSheet.java index d73ed34dfb..2b341c3520 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFSheet.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFSheet.java @@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; +import java.io.InputStream; import java.util.Arrays; import java.util.Calendar; import java.util.Date; @@ -37,6 +38,12 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; import org.apache.poi.hssf.HSSFTestDataSamples; import org.apache.poi.ooxml.POIXMLException; @@ -57,6 +64,7 @@ import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; @@ -72,6 +80,8 @@ import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.helpers.ColumnHelper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; @@ -250,198 +260,195 @@ public final class TestXSSFSheet extends BaseTestXSheet { @Test void setCellComment() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); - XSSFDrawing dg = sheet.createDrawingPatriarch(); - XSSFComment comment = dg.createCellComment(new XSSFClientAnchor()); + XSSFDrawing dg = sheet.createDrawingPatriarch(); + XSSFComment comment = dg.createCellComment(new XSSFClientAnchor()); - Cell cell = sheet.createRow(0).createCell(0); - CommentsTable comments = sheet.getCommentsTable(false); - CTComments ctComments = comments.getCTComments(); + Cell cell = sheet.createRow(0).createCell(0); + CommentsTable comments = sheet.getCommentsTable(false); + CTComments ctComments = comments.getCTComments(); - cell.setCellComment(comment); - assertEquals("A1", ctComments.getCommentList().getCommentArray(0).getRef()); - comment.setAuthor("test A1 author"); - assertEquals("test A1 author", comments.getAuthor((int) ctComments.getCommentList().getCommentArray(0).getAuthorId())); - workbook.close(); + cell.setCellComment(comment); + assertEquals("A1", ctComments.getCommentList().getCommentArray(0).getRef()); + comment.setAuthor("test A1 author"); + assertEquals("test A1 author", comments.getAuthor((int) ctComments.getCommentList().getCommentArray(0).getAuthorId())); + } } @Test void getActiveCell() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellAddress R5 = new CellAddress("R5"); - sheet.setActiveCell(R5); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CellAddress R5 = new CellAddress("R5"); + sheet.setActiveCell(R5); - assertEquals(R5, sheet.getActiveCell()); - workbook.close(); + assertEquals(R5, sheet.getActiveCell()); + } } @Test void createFreezePane_XSSF() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - - sheet.createFreezePane(2, 4); - assertEquals(2.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0); - assertSame(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); - sheet.createFreezePane(3, 6, 10, 10); - assertEquals(3.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0); - // assertEquals(10, sheet.getTopRow()); - // assertEquals(10, sheet.getLeftCol()); - sheet.createSplitPane(4, 8, 12, 12, 1); - assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0); - assertSame(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); - - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CTWorksheet ctWorksheet = sheet.getCTWorksheet(); + + sheet.createFreezePane(2, 4); + assertEquals(2.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0); + assertSame(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); + sheet.createFreezePane(3, 6, 10, 10); + assertEquals(3.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0); + // assertEquals(10, sheet.getTopRow()); + // assertEquals(10, sheet.getLeftCol()); + sheet.createSplitPane(4, 8, 12, 12, 1); + assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0); + assertSame(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); + } } @Test void removeMergedRegion_lowlevel() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - CellRangeAddress region_1 = CellRangeAddress.valueOf("A1:B2"); - CellRangeAddress region_2 = CellRangeAddress.valueOf("C3:D4"); - CellRangeAddress region_3 = CellRangeAddress.valueOf("E5:F6"); - CellRangeAddress region_4 = CellRangeAddress.valueOf("G7:H8"); - assertEquals(0, sheet.addMergedRegion(region_1)); - assertEquals(1, sheet.addMergedRegion(region_2)); - assertEquals(2, sheet.addMergedRegion(region_3)); - assertEquals("C3:D4", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); - assertEquals(3, sheet.getNumMergedRegions()); - sheet.removeMergedRegion(1); - assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); - assertEquals(2, sheet.getNumMergedRegions()); - sheet.removeMergedRegion(1); - sheet.removeMergedRegion(0); - assertEquals(0, sheet.getNumMergedRegions()); - assertNull(sheet.getCTWorksheet().getMergeCells(), - "CTMergeCells should be deleted after removing the last merged region on the sheet."); - assertEquals(0, sheet.addMergedRegion(region_1)); - assertEquals(1, sheet.addMergedRegion(region_2)); - assertEquals(2, sheet.addMergedRegion(region_3)); - assertEquals(3, sheet.addMergedRegion(region_4)); - // test invalid indexes OOBE - Set<Integer> rmIdx = new HashSet<>(Arrays.asList(5, 6)); - sheet.removeMergedRegions(rmIdx); - rmIdx = new HashSet<>(Arrays.asList(1, 3)); - sheet.removeMergedRegions(rmIdx); - assertEquals("A1:B2", ctWorksheet.getMergeCells().getMergeCellArray(0).getRef()); - assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CTWorksheet ctWorksheet = sheet.getCTWorksheet(); + CellRangeAddress region_1 = CellRangeAddress.valueOf("A1:B2"); + CellRangeAddress region_2 = CellRangeAddress.valueOf("C3:D4"); + CellRangeAddress region_3 = CellRangeAddress.valueOf("E5:F6"); + CellRangeAddress region_4 = CellRangeAddress.valueOf("G7:H8"); + assertEquals(0, sheet.addMergedRegion(region_1)); + assertEquals(1, sheet.addMergedRegion(region_2)); + assertEquals(2, sheet.addMergedRegion(region_3)); + assertEquals("C3:D4", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); + assertEquals(3, sheet.getNumMergedRegions()); + sheet.removeMergedRegion(1); + assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); + assertEquals(2, sheet.getNumMergedRegions()); + sheet.removeMergedRegion(1); + sheet.removeMergedRegion(0); + assertEquals(0, sheet.getNumMergedRegions()); + assertNull(sheet.getCTWorksheet().getMergeCells(), + "CTMergeCells should be deleted after removing the last merged region on the sheet."); + assertEquals(0, sheet.addMergedRegion(region_1)); + assertEquals(1, sheet.addMergedRegion(region_2)); + assertEquals(2, sheet.addMergedRegion(region_3)); + assertEquals(3, sheet.addMergedRegion(region_4)); + // test invalid indexes OOBE + Set<Integer> rmIdx = new HashSet<>(Arrays.asList(5, 6)); + sheet.removeMergedRegions(rmIdx); + rmIdx = new HashSet<>(Arrays.asList(1, 3)); + sheet.removeMergedRegions(rmIdx); + assertEquals("A1:B2", ctWorksheet.getMergeCells().getMergeCellArray(0).getRef()); + assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); + } } @Test void setDefaultColumnStyle() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - StylesTable stylesTable = workbook.getStylesSource(); - XSSFFont font = new XSSFFont(); - font.setFontName("Cambria"); - stylesTable.putFont(font); - CTXf cellStyleXf = CTXf.Factory.newInstance(); - cellStyleXf.setFontId(1); - cellStyleXf.setFillId(0); - cellStyleXf.setBorderId(0); - cellStyleXf.setNumFmtId(0); - assertEquals(2, stylesTable.putCellStyleXf(cellStyleXf)); - CTXf cellXf = CTXf.Factory.newInstance(); - cellXf.setXfId(1); - stylesTable.putCellXf(cellXf); - XSSFCellStyle cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); - assertEquals(1, cellStyle.getFontIndex()); - - sheet.setDefaultColumnStyle(3, cellStyle); - assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle()); - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CTWorksheet ctWorksheet = sheet.getCTWorksheet(); + StylesTable stylesTable = workbook.getStylesSource(); + XSSFFont font = new XSSFFont(); + font.setFontName("Cambria"); + stylesTable.putFont(font); + CTXf cellStyleXf = CTXf.Factory.newInstance(); + cellStyleXf.setFontId(1); + cellStyleXf.setFillId(0); + cellStyleXf.setBorderId(0); + cellStyleXf.setNumFmtId(0); + assertEquals(2, stylesTable.putCellStyleXf(cellStyleXf)); + CTXf cellXf = CTXf.Factory.newInstance(); + cellXf.setXfId(1); + stylesTable.putCellXf(cellXf); + XSSFCellStyle cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); + assertEquals(1, cellStyle.getFontIndex()); + + sheet.setDefaultColumnStyle(3, cellStyle); + assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle()); + } } @Test void groupUngroupColumn() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - //one level - sheet.groupColumn(2, 7); - sheet.groupColumn(10, 11); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(2, cols.sizeOfColArray()); - CTCol[] colArray = cols.getColArray(); - assertNotNull(colArray); - assertEquals(2 + 1, colArray[0].getMin()); // 1 based - assertEquals(7 + 1, colArray[0].getMax()); // 1 based - assertEquals(1, colArray[0].getOutlineLevel()); - assertEquals(0, sheet.getColumnOutlineLevel(0)); - - //two level - sheet.groupColumn(1, 2); - cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(4, cols.sizeOfColArray()); - colArray = cols.getColArray(); - assertEquals(2, colArray[1].getOutlineLevel()); - - //three level - sheet.groupColumn(6, 8); - sheet.groupColumn(2, 3); - cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(7, cols.sizeOfColArray()); - colArray = cols.getColArray(); - assertEquals(3, colArray[1].getOutlineLevel()); - assertEquals(3, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); - - sheet.ungroupColumn(8, 10); - colArray = cols.getColArray(); - assertEquals(3, colArray[1].getOutlineLevel()); - - sheet.ungroupColumn(4, 6); - sheet.ungroupColumn(2, 2); - colArray = cols.getColArray(); - assertEquals(4, colArray.length); - assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); - - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + + //one level + sheet.groupColumn(2, 7); + sheet.groupColumn(10, 11); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + assertEquals(2, cols.sizeOfColArray()); + CTCol[] colArray = cols.getColArray(); + assertNotNull(colArray); + assertEquals(2 + 1, colArray[0].getMin()); // 1 based + assertEquals(7 + 1, colArray[0].getMax()); // 1 based + assertEquals(1, colArray[0].getOutlineLevel()); + assertEquals(0, sheet.getColumnOutlineLevel(0)); + + //two level + sheet.groupColumn(1, 2); + cols = sheet.getCTWorksheet().getColsArray(0); + assertEquals(4, cols.sizeOfColArray()); + colArray = cols.getColArray(); + assertEquals(2, colArray[1].getOutlineLevel()); + + //three level + sheet.groupColumn(6, 8); + sheet.groupColumn(2, 3); + cols = sheet.getCTWorksheet().getColsArray(0); + assertEquals(7, cols.sizeOfColArray()); + colArray = cols.getColArray(); + assertEquals(3, colArray[1].getOutlineLevel()); + assertEquals(3, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); + + sheet.ungroupColumn(8, 10); + colArray = cols.getColArray(); + assertEquals(3, colArray[1].getOutlineLevel()); + + sheet.ungroupColumn(4, 6); + sheet.ungroupColumn(2, 2); + colArray = cols.getColArray(); + assertEquals(4, colArray.length); + assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); + } } @Test void groupUngroupRow() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - //one level - sheet.groupRow(9, 10); - assertEquals(2, sheet.getPhysicalNumberOfRows()); - CTRow ctrow = sheet.getRow(9).getCTRow(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); - assertNotNull(ctrow); - assertEquals(10, ctrow.getR()); - assertEquals(1, ctrow.getOutlineLevel()); - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); + //one level + sheet.groupRow(9, 10); + assertEquals(2, sheet.getPhysicalNumberOfRows()); + CTRow ctrow = sheet.getRow(9).getCTRow(); - //two level - sheet.groupRow(10, 13); - assertEquals(5, sheet.getPhysicalNumberOfRows()); - ctrow = sheet.getRow(10).getCTRow(); - assertNotNull(ctrow); - assertEquals(11, ctrow.getR()); - assertEquals(2, ctrow.getOutlineLevel()); - assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); + assertNotNull(ctrow); + assertEquals(10, ctrow.getR()); + assertEquals(1, ctrow.getOutlineLevel()); + assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); + //two level + sheet.groupRow(10, 13); + assertEquals(5, sheet.getPhysicalNumberOfRows()); + ctrow = sheet.getRow(10).getCTRow(); + assertNotNull(ctrow); + assertEquals(11, ctrow.getR()); + assertEquals(2, ctrow.getOutlineLevel()); + assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - sheet.ungroupRow(8, 10); - assertEquals(4, sheet.getPhysicalNumberOfRows()); - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - sheet.ungroupRow(10, 10); - assertEquals(3, sheet.getPhysicalNumberOfRows()); + sheet.ungroupRow(8, 10); + assertEquals(4, sheet.getPhysicalNumberOfRows()); + assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); + sheet.ungroupRow(10, 10); + assertEquals(3, sheet.getPhysicalNumberOfRows()); - workbook.close(); + assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); + } } @Test @@ -450,11 +457,11 @@ public final class TestXSSFSheet extends BaseTestXSheet { XSSFSheet sheet1 = workBook.createSheet("new sheet"); sheet1.setZoom(75); // 75 percent magnification long zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 75); + assertEquals(75, zoom); sheet1.setZoom(200); zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 200); + assertEquals(200, zoom); // Valid scale values range from 10 to 400 assertThrows(IllegalArgumentException.class, () -> sheet1.setZoom(500)); @@ -654,79 +661,78 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void setRowGroupCollapsed() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet1 = wb1.createSheet(); - - sheet1.groupRow( 5, 14 ); - sheet1.groupRow( 7, 14 ); - sheet1.groupRow( 16, 19 ); - - assertEquals(14,sheet1.getPhysicalNumberOfRows()); - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - //collapsed - sheet1.setRowGroupCollapsed( 7, true ); - - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - //expanded - sheet1.setRowGroupCollapsed( 7, false ); - - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - wb2.close(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet1 = wb1.createSheet(); + + sheet1.groupRow(5, 14); + sheet1.groupRow(7, 14); + sheet1.groupRow(16, 19); + + assertEquals(14, sheet1.getPhysicalNumberOfRows()); + assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(7).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(9).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(14).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); + + //collapsed + sheet1.setRowGroupCollapsed(7, true); + + assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(7).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(9).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(14).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); + + //expanded + sheet1.setRowGroupCollapsed(7, false); + + assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(7).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(9).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(14).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); + + + // Save and re-load + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + sheet1 = wb2.getSheetAt(0); + + assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(7).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(9).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); + assertTrue(sheet1.getRow(14).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); + assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); + assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); + } + } } /** @@ -734,46 +740,45 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void columnWidth_lowlevel() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnWidth(1, 22 * 256); - assertEquals(22 * 256, sheet.getColumnWidth(1)); - - // Now check the low level stuff, and check that's all - // been set correctly - CTWorksheet cts = sheet.getCTWorksheet(); - - assertEquals(1, cts.sizeOfColsArray()); - CTCols cols = cts.getColsArray(0); - assertEquals(1, cols.sizeOfColArray()); - CTCol col = cols.getColArray(0); - - // XML is 1 based, POI is 0 based - assertEquals(2, col.getMin()); - assertEquals(2, col.getMax()); - assertEquals(22.0, col.getWidth(), 0.0); - assertTrue(col.getCustomWidth()); - - // Now set another - sheet.setColumnWidth(3, 33 * 256); - - assertEquals(1, cts.sizeOfColsArray()); - cols = cts.getColsArray(0); - assertEquals(2, cols.sizeOfColArray()); - - col = cols.getColArray(0); - assertEquals(2, col.getMin()); // POI 1 - assertEquals(2, col.getMax()); - assertEquals(22.0, col.getWidth(), 0.0); - assertTrue(col.getCustomWidth()); - - col = cols.getColArray(1); - assertEquals(4, col.getMin()); // POI 3 - assertEquals(4, col.getMax()); - assertEquals(33.0, col.getWidth(), 0.0); - assertTrue(col.getCustomWidth()); - - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet("Sheet 1"); + sheet.setColumnWidth(1, 22 * 256); + assertEquals(22 * 256, sheet.getColumnWidth(1)); + + // Now check the low level stuff, and check that's all + // been set correctly + CTWorksheet cts = sheet.getCTWorksheet(); + + assertEquals(1, cts.sizeOfColsArray()); + CTCols cols = cts.getColsArray(0); + assertEquals(1, cols.sizeOfColArray()); + CTCol col = cols.getColArray(0); + + // XML is 1 based, POI is 0 based + assertEquals(2, col.getMin()); + assertEquals(2, col.getMax()); + assertEquals(22.0, col.getWidth(), 0.0); + assertTrue(col.getCustomWidth()); + + // Now set another + sheet.setColumnWidth(3, 33 * 256); + + assertEquals(1, cts.sizeOfColsArray()); + cols = cts.getColsArray(0); + assertEquals(2, cols.sizeOfColArray()); + + col = cols.getColArray(0); + assertEquals(2, col.getMin()); // POI 1 + assertEquals(2, col.getMax()); + assertEquals(22.0, col.getWidth(), 0.0); + assertTrue(col.getCustomWidth()); + + col = cols.getColArray(1); + assertEquals(4, col.getMin()); // POI 3 + assertEquals(4, col.getMax()); + assertEquals(33.0, col.getWidth(), 0.0); + assertTrue(col.getCustomWidth()); + } } /** @@ -781,59 +786,58 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void bug47862() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47862.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - //<cols> - // <col min="1" max="5" width="15.77734375" customWidth="1"/> - //</cols> - - //a span of columns [1,5] - assertEquals(1, cols.sizeOfColArray()); - CTCol col = cols.getColArray(0); - assertEquals(1, col.getMin()); - assertEquals(5, col.getMax()); - double swidth = 15.77734375; //width of columns in the span - assertEquals(swidth, col.getWidth(), 0.0); - - for (int i = 0; i < 5; i++) { - assertEquals((int)(swidth*256), sheet.getColumnWidth(i)); - } + try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47862.xlsx")) { + XSSFSheet sheet = wb1.getSheetAt(0); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + //<cols> + // <col min="1" max="5" width="15.77734375" customWidth="1"/> + //</cols> + + //a span of columns [1,5] + assertEquals(1, cols.sizeOfColArray()); + CTCol col = cols.getColArray(0); + assertEquals(1, col.getMin()); + assertEquals(5, col.getMax()); + double swidth = 15.77734375; //width of columns in the span + assertEquals(swidth, col.getWidth(), 0.0); + + for (int i = 0; i < 5; i++) { + assertEquals((int) (swidth * 256), sheet.getColumnWidth(i)); + } - int[] cw = new int[]{10, 15, 20, 25, 30}; - for (int i = 0; i < 5; i++) { - sheet.setColumnWidth(i, cw[i]*256); - } + int[] cw = new int[]{10, 15, 20, 25, 30}; + for (int i = 0; i < 5; i++) { + sheet.setColumnWidth(i, cw[i] * 256); + } - //the check below failed prior to fix of Bug #47862 - ColumnHelper.sortColumns(cols); - //<cols> - // <col min="1" max="1" customWidth="true" width="10.0" /> - // <col min="2" max="2" customWidth="true" width="15.0" /> - // <col min="3" max="3" customWidth="true" width="20.0" /> - // <col min="4" max="4" customWidth="true" width="25.0" /> - // <col min="5" max="5" customWidth="true" width="30.0" /> - //</cols> - - //now the span is splitted into 5 individual columns - assertEquals(5, cols.sizeOfColArray()); - for (int i = 0; i < 5; i++) { - assertEquals(cw[i]*256L, sheet.getColumnWidth(i)); - assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); - } + //the check below failed prior to fix of Bug #47862 + ColumnHelper.sortColumns(cols); + //<cols> + // <col min="1" max="1" customWidth="true" width="10.0" /> + // <col min="2" max="2" customWidth="true" width="15.0" /> + // <col min="3" max="3" customWidth="true" width="20.0" /> + // <col min="4" max="4" customWidth="true" width="25.0" /> + // <col min="5" max="5" customWidth="true" width="30.0" /> + //</cols> + + //now the span is splitted into 5 individual columns + assertEquals(5, cols.sizeOfColArray()); + for (int i = 0; i < 5; i++) { + assertEquals(cw[i] * 256L, sheet.getColumnWidth(i)); + assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); + } - //serialize and check again - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(5, cols.sizeOfColArray()); - for (int i = 0; i < 5; i++) { - assertEquals(cw[i]*256L, sheet.getColumnWidth(i)); - assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); + //serialize and check again + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + cols = sheet.getCTWorksheet().getColsArray(0); + assertEquals(5, cols.sizeOfColArray()); + for (int i = 0; i < 5; i++) { + assertEquals(cw[i] * 256L, sheet.getColumnWidth(i)); + assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); + } + } } - - wb2.close(); } /** @@ -841,112 +845,110 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void bug47804() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47804.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(2, cols.sizeOfColArray()); - CTCol col; - //<cols> - // <col min="2" max="4" width="12" customWidth="1"/> - // <col min="7" max="7" width="10.85546875" customWidth="1"/> - //</cols> - - //a span of columns [2,4] - col = cols.getColArray(0); - assertEquals(2, col.getMin()); - assertEquals(4, col.getMax()); - //individual column - col = cols.getColArray(1); - assertEquals(7, col.getMin()); - assertEquals(7, col.getMax()); - - sheet.setColumnHidden(2, true); // Column C - sheet.setColumnHidden(6, true); // Column G - - assertTrue(sheet.isColumnHidden(2)); - assertTrue(sheet.isColumnHidden(6)); - - //other columns but C and G are not hidden - assertFalse(sheet.isColumnHidden(1)); - assertFalse(sheet.isColumnHidden(3)); - assertFalse(sheet.isColumnHidden(4)); - assertFalse(sheet.isColumnHidden(5)); - - //the check below failed prior to fix of Bug #47804 - ColumnHelper.sortColumns(cols); - //the span is now splitted into three parts - //<cols> - // <col min="2" max="2" customWidth="true" width="12.0" /> - // <col min="3" max="3" customWidth="true" width="12.0" hidden="true"/> - // <col min="4" max="4" customWidth="true" width="12.0"/> - // <col min="7" max="7" customWidth="true" width="10.85546875" hidden="true"/> - //</cols> - - assertEquals(4, cols.sizeOfColArray()); - col = cols.getColArray(0); - assertEquals(2, col.getMin()); - assertEquals(2, col.getMax()); - col = cols.getColArray(1); - assertEquals(3, col.getMin()); - assertEquals(3, col.getMax()); - col = cols.getColArray(2); - assertEquals(4, col.getMin()); - assertEquals(4, col.getMax()); - col = cols.getColArray(3); - assertEquals(7, col.getMin()); - assertEquals(7, col.getMax()); - - //serialize and check again - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - assertTrue(sheet.isColumnHidden(2)); - assertTrue(sheet.isColumnHidden(6)); - assertFalse(sheet.isColumnHidden(1)); - assertFalse(sheet.isColumnHidden(3)); - assertFalse(sheet.isColumnHidden(4)); - assertFalse(sheet.isColumnHidden(5)); - - wb2.close(); + try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47804.xlsx")) { + XSSFSheet sheet = wb1.getSheetAt(0); + CTCols cols = sheet.getCTWorksheet().getColsArray(0); + assertEquals(2, cols.sizeOfColArray()); + CTCol col; + //<cols> + // <col min="2" max="4" width="12" customWidth="1"/> + // <col min="7" max="7" width="10.85546875" customWidth="1"/> + //</cols> + + //a span of columns [2,4] + col = cols.getColArray(0); + assertEquals(2, col.getMin()); + assertEquals(4, col.getMax()); + //individual column + col = cols.getColArray(1); + assertEquals(7, col.getMin()); + assertEquals(7, col.getMax()); + + sheet.setColumnHidden(2, true); // Column C + sheet.setColumnHidden(6, true); // Column G + + assertTrue(sheet.isColumnHidden(2)); + assertTrue(sheet.isColumnHidden(6)); + + //other columns but C and G are not hidden + assertFalse(sheet.isColumnHidden(1)); + assertFalse(sheet.isColumnHidden(3)); + assertFalse(sheet.isColumnHidden(4)); + assertFalse(sheet.isColumnHidden(5)); + + //the check below failed prior to fix of Bug #47804 + ColumnHelper.sortColumns(cols); + //the span is now splitted into three parts + //<cols> + // <col min="2" max="2" customWidth="true" width="12.0" /> + // <col min="3" max="3" customWidth="true" width="12.0" hidden="true"/> + // <col min="4" max="4" customWidth="true" width="12.0"/> + // <col min="7" max="7" customWidth="true" width="10.85546875" hidden="true"/> + //</cols> + + assertEquals(4, cols.sizeOfColArray()); + col = cols.getColArray(0); + assertEquals(2, col.getMin()); + assertEquals(2, col.getMax()); + col = cols.getColArray(1); + assertEquals(3, col.getMin()); + assertEquals(3, col.getMax()); + col = cols.getColArray(2); + assertEquals(4, col.getMin()); + assertEquals(4, col.getMax()); + col = cols.getColArray(3); + assertEquals(7, col.getMin()); + assertEquals(7, col.getMax()); + + //serialize and check again + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + assertTrue(sheet.isColumnHidden(2)); + assertTrue(sheet.isColumnHidden(6)); + assertFalse(sheet.isColumnHidden(1)); + assertFalse(sheet.isColumnHidden(3)); + assertFalse(sheet.isColumnHidden(4)); + assertFalse(sheet.isColumnHidden(5)); + } + } } @Test void commentsTable() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet1 = wb1.createSheet(); - CommentsTable comment1 = sheet1.getCommentsTable(false); - assertNull(comment1); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet1 = wb1.createSheet(); + CommentsTable comment1 = sheet1.getCommentsTable(false); + assertNull(comment1); - comment1 = sheet1.getCommentsTable(true); - assertNotNull(comment1); - assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); + comment1 = sheet1.getCommentsTable(true); + assertNotNull(comment1); + assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); - assertSame(comment1, sheet1.getCommentsTable(true)); + assertSame(comment1, sheet1.getCommentsTable(true)); - //second sheet - XSSFSheet sheet2 = wb1.createSheet(); - CommentsTable comment2 = sheet2.getCommentsTable(false); - assertNull(comment2); + //second sheet + XSSFSheet sheet2 = wb1.createSheet(); + CommentsTable comment2 = sheet2.getCommentsTable(false); + assertNull(comment2); - comment2 = sheet2.getCommentsTable(true); - assertNotNull(comment2); + comment2 = sheet2.getCommentsTable(true); + assertNotNull(comment2); - assertSame(comment2, sheet2.getCommentsTable(true)); - assertEquals("/xl/comments2.xml", comment2.getPackagePart().getPartName().getName()); + assertSame(comment2, sheet2.getCommentsTable(true)); + assertEquals("/xl/comments2.xml", comment2.getPackagePart().getPartName().getName()); - //comment1 and comment2 are different objects - assertNotSame(comment1, comment2); - wb1.close(); + //comment1 and comment2 are different objects + assertNotSame(comment1, comment2); + } //now test against a workbook containing cell comments - XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - sheet1 = wb2.getSheetAt(0); - comment1 = sheet1.getCommentsTable(true); - assertNotNull(comment1); - assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); - assertSame(comment1, sheet1.getCommentsTable(true)); - - wb2.close(); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx")) { + XSSFSheet sheet1 = wb2.getSheetAt(0); + CommentsTable comment1 = sheet1.getCommentsTable(true); + assertNotNull(comment1); + assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); + assertSame(comment1, sheet1.getCommentsTable(true)); + } } /** @@ -956,187 +958,183 @@ public final class TestXSSFSheet extends BaseTestXSheet { @Override @Test protected void createRow() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - CTWorksheet wsh = sheet.getCTWorksheet(); - CTSheetData sheetData = wsh.getSheetData(); - assertEquals(0, sheetData.sizeOfRowArray()); - - XSSFRow row1 = sheet.createRow(2); - row1.createCell(2); - row1.createCell(1); - - XSSFRow row2 = sheet.createRow(1); - row2.createCell(2); - row2.createCell(1); - row2.createCell(0); - - XSSFRow row3 = sheet.createRow(0); - row3.createCell(3); - row3.createCell(0); - row3.createCell(2); - row3.createCell(5); - - - CTRow[] xrow = sheetData.getRowArray(); - assertEquals(3, xrow.length); - - //rows are sorted: {0, 1, 2} - assertEquals(4, xrow[0].sizeOfCArray()); - assertEquals(1, xrow[0].getR()); - assertEquals(xrow[0], row3.getCTRow()); - - assertEquals(3, xrow[1].sizeOfCArray()); - assertEquals(2, xrow[1].getR()); - assertEquals(xrow[1], row2.getCTRow()); - - assertEquals(2, xrow[2].sizeOfCArray()); - assertEquals(3, xrow[2].getR()); - assertEquals(xrow[2], row1.getCTRow()); - - CTCell[] xcell = xrow[0].getCArray(); - assertEquals("D1", xcell[0].getR()); - assertEquals("A1", xcell[1].getR()); - assertEquals("C1", xcell[2].getR()); - assertEquals("F1", xcell[3].getR()); - - //re-creating a row does NOT add extra data to the parent - row2 = sheet.createRow(1); - assertEquals(3, sheetData.sizeOfRowArray()); - //existing cells are invalidated - assertEquals(0, sheetData.getRowArray(1).sizeOfCArray()); - assertEquals(0, row2.getPhysicalNumberOfCells()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - wsh = sheet.getCTWorksheet(); - assertNotNull(wsh); - xrow = sheetData.getRowArray(); - assertEquals(3, xrow.length); - - //rows are sorted: {0, 1, 2} - assertEquals(4, xrow[0].sizeOfCArray()); - assertEquals(1, xrow[0].getR()); - //cells are now sorted - xcell = xrow[0].getCArray(); - assertEquals("A1", xcell[0].getR()); - assertEquals("C1", xcell[1].getR()); - assertEquals("D1", xcell[2].getR()); - assertEquals("F1", xcell[3].getR()); - - - assertEquals(0, xrow[1].sizeOfCArray()); - assertEquals(2, xrow[1].getR()); - - assertEquals(2, xrow[2].sizeOfCArray()); - assertEquals(3, xrow[2].getR()); - - wb2.close(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet(); + CTWorksheet wsh = sheet.getCTWorksheet(); + CTSheetData sheetData = wsh.getSheetData(); + assertEquals(0, sheetData.sizeOfRowArray()); + + XSSFRow row1 = sheet.createRow(2); + row1.createCell(2); + row1.createCell(1); + + XSSFRow row2 = sheet.createRow(1); + row2.createCell(2); + row2.createCell(1); + row2.createCell(0); + + XSSFRow row3 = sheet.createRow(0); + row3.createCell(3); + row3.createCell(0); + row3.createCell(2); + row3.createCell(5); + + + CTRow[] xrow = sheetData.getRowArray(); + assertEquals(3, xrow.length); + + //rows are sorted: {0, 1, 2} + assertEquals(4, xrow[0].sizeOfCArray()); + assertEquals(1, xrow[0].getR()); + assertEquals(xrow[0], row3.getCTRow()); + + assertEquals(3, xrow[1].sizeOfCArray()); + assertEquals(2, xrow[1].getR()); + assertEquals(xrow[1], row2.getCTRow()); + + assertEquals(2, xrow[2].sizeOfCArray()); + assertEquals(3, xrow[2].getR()); + assertEquals(xrow[2], row1.getCTRow()); + + CTCell[] xcell = xrow[0].getCArray(); + assertEquals("D1", xcell[0].getR()); + assertEquals("A1", xcell[1].getR()); + assertEquals("C1", xcell[2].getR()); + assertEquals("F1", xcell[3].getR()); + + //re-creating a row does NOT add extra data to the parent + row2 = sheet.createRow(1); + assertEquals(3, sheetData.sizeOfRowArray()); + //existing cells are invalidated + assertEquals(0, sheetData.getRowArray(1).sizeOfCArray()); + assertEquals(0, row2.getPhysicalNumberOfCells()); + + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheetAt(0); + wsh = sheet.getCTWorksheet(); + assertNotNull(wsh); + xrow = sheetData.getRowArray(); + assertEquals(3, xrow.length); + + //rows are sorted: {0, 1, 2} + assertEquals(4, xrow[0].sizeOfCArray()); + assertEquals(1, xrow[0].getR()); + //cells are now sorted + xcell = xrow[0].getCArray(); + assertEquals("A1", xcell[0].getR()); + assertEquals("C1", xcell[1].getR()); + assertEquals("D1", xcell[2].getR()); + assertEquals("F1", xcell[3].getR()); + + + assertEquals(0, xrow[1].sizeOfCArray()); + assertEquals(2, xrow[1].getR()); + + assertEquals(2, xrow[2].sizeOfCArray()); + assertEquals(3, xrow[2].getR()); + } + } } @Test void setAutoFilter() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("new sheet"); - sheet.setAutoFilter(CellRangeAddress.valueOf("A1:D100")); - - assertEquals("A1:D100", sheet.getCTWorksheet().getAutoFilter().getRef()); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet("new sheet"); + sheet.setAutoFilter(CellRangeAddress.valueOf("A1:D100")); - // auto-filter must be registered in workboook.xml, see Bugzilla 50315 - XSSFName nm = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(nm); + assertEquals("A1:D100", sheet.getCTWorksheet().getAutoFilter().getRef()); - assertEquals(0, nm.getCTName().getLocalSheetId()); - assertTrue(nm.getCTName().getHidden()); - assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName()); - assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue()); + // auto-filter must be registered in workboook.xml, see Bugzilla 50315 + XSSFName nm = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); + assertNotNull(nm); - wb.close(); + assertEquals(0, nm.getCTName().getLocalSheetId()); + assertTrue(nm.getCTName().getHidden()); + assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName()); + assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue()); + } } @Test void protectSheet_lowlevel() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); - assertNull(pr, "CTSheetProtection should be null by default"); - String password = "Test"; - sheet.protectSheet(password); - pr = sheet.getCTWorksheet().getSheetProtection(); - assertNotNull(pr, "CTSheetProtection should be not null"); - assertTrue(pr.isSetSheet(), "sheet protection should be on"); - assertTrue(pr.isSetObjects(), "object protection should be on"); - assertTrue(pr.isSetScenarios(), "scenario protection should be on"); - int hashVal = CryptoFunctions.createXorVerifier1(password); - int actualVal = Integer.parseInt(pr.xgetPassword().getStringValue(),16); - assertEquals(hashVal, actualVal, "well known value for top secret hash should match"); - - sheet.protectSheet(null); - assertNull(sheet.getCTWorksheet().getSheetProtection(), "protectSheet(null) should unset CTSheetProtection"); - - wb.close(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); + assertNull(pr, "CTSheetProtection should be null by default"); + String password = "Test"; + sheet.protectSheet(password); + pr = sheet.getCTWorksheet().getSheetProtection(); + assertNotNull(pr, "CTSheetProtection should be not null"); + assertTrue(pr.isSetSheet(), "sheet protection should be on"); + assertTrue(pr.isSetObjects(), "object protection should be on"); + assertTrue(pr.isSetScenarios(), "scenario protection should be on"); + int hashVal = CryptoFunctions.createXorVerifier1(password); + int actualVal = Integer.parseInt(pr.xgetPassword().getStringValue(), 16); + assertEquals(hashVal, actualVal, "well known value for top secret hash should match"); + + sheet.protectSheet(null); + assertNull(sheet.getCTWorksheet().getSheetProtection(), "protectSheet(null) should unset CTSheetProtection"); + } } @Test void protectSheet_emptyPassword() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); - assertNull(pr, "CTSheetProtection should be null by default"); - String password = ""; - sheet.protectSheet(password); - pr = sheet.getCTWorksheet().getSheetProtection(); - assertNotNull(pr, "CTSheetProtection should be not null"); - assertTrue(pr.isSetSheet(), "sheet protection should be on"); - assertTrue(pr.isSetObjects(), "object protection should be on"); - assertTrue(pr.isSetScenarios(), "scenario protection should be on"); - int hashVal = CryptoFunctions.createXorVerifier1(password); - STUnsignedShortHex xpassword = pr.xgetPassword(); - int actualVal = Integer.parseInt(xpassword.getStringValue(),16); - assertEquals(hashVal, actualVal, "well known value for top secret hash should match"); - - sheet.protectSheet(null); - assertNull(sheet.getCTWorksheet().getSheetProtection(), "protectSheet(null) should unset CTSheetProtection"); - - wb.close(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + XSSFSheet sheet = wb.createSheet(); + CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); + assertNull(pr, "CTSheetProtection should be null by default"); + String password = ""; + sheet.protectSheet(password); + pr = sheet.getCTWorksheet().getSheetProtection(); + assertNotNull(pr, "CTSheetProtection should be not null"); + assertTrue(pr.isSetSheet(), "sheet protection should be on"); + assertTrue(pr.isSetObjects(), "object protection should be on"); + assertTrue(pr.isSetScenarios(), "scenario protection should be on"); + int hashVal = CryptoFunctions.createXorVerifier1(password); + STUnsignedShortHex xpassword = pr.xgetPassword(); + int actualVal = Integer.parseInt(xpassword.getStringValue(), 16); + assertEquals(hashVal, actualVal, "well known value for top secret hash should match"); + + sheet.protectSheet(null); + assertNull(sheet.getCTWorksheet().getSheetProtection(), "protectSheet(null) should unset CTSheetProtection"); + } } @Test void protectSheet_lowlevel_2013() throws IOException { String password = "test"; - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet xs = wb1.createSheet(); - xs.setSheetPassword(password, HashAlgorithm.sha384); - XSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - assertTrue(wb2.getSheetAt(0).validateSheetPassword(password)); - wb2.close(); - - XSSFWorkbook wb3 = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx"); - assertTrue(wb3.getSheetAt(0).validateSheetPassword("pwd")); - wb3.close(); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet xs = wb1.createSheet(); + xs.setSheetPassword(password, HashAlgorithm.sha384); + try (XSSFWorkbook wb2 = writeOutAndReadBack(wb1)) { + assertTrue(wb2.getSheetAt(0).validateSheetPassword(password)); + } + } + + try (XSSFWorkbook wb3 = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx")) { + assertTrue(wb3.getSheetAt(0).validateSheetPassword("pwd")); + } } @Test void bug49966() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("49966.xlsx"); - CalculationChain calcChain = wb1.getCalculationChain(); - assertNotNull(wb1.getCalculationChain()); - assertEquals(3, calcChain.getCTCalcChain().sizeOfCArray()); - - XSSFSheet sheet = wb1.getSheetAt(0); - XSSFRow row = sheet.getRow(0); - - sheet.removeRow(row); - assertEquals(0, calcChain.getCTCalcChain().sizeOfCArray(), "XSSFSheet#removeRow did not clear calcChain entries"); - - //calcChain should be gone - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertNull(wb2.getCalculationChain()); - wb2.close(); + try (XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("49966.xlsx")) { + CalculationChain calcChain = wb1.getCalculationChain(); + assertNotNull(wb1.getCalculationChain()); + assertEquals(3, calcChain.getCTCalcChain().sizeOfCArray()); + + XSSFSheet sheet = wb1.getSheetAt(0); + XSSFRow row = sheet.getRow(0); + + sheet.removeRow(row); + assertEquals(0, calcChain.getCTCalcChain().sizeOfCArray(), "XSSFSheet#removeRow did not clear calcChain entries"); + + //calcChain should be gone + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + assertNull(wb2.getCalculationChain()); + } + } } /** @@ -1144,28 +1142,28 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void tables() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - - // Check the table sheet - XSSFSheet s1 = wb.getSheetAt(0); - assertEquals("a", s1.getRow(0).getCell(0).getRichStringCellValue().toString()); - assertEquals(1.0, s1.getRow(1).getCell(0).getNumericCellValue(), 0); - - List<XSSFTable> tables = s1.getTables(); - assertNotNull(tables); - assertEquals(1, tables.size()); - - XSSFTable table = tables.get(0); - assertEquals("Tabella1", table.getName()); - assertEquals("Tabella1", table.getDisplayName()); - - // And the others - XSSFSheet s2 = wb.getSheetAt(1); - assertEquals(0, s2.getTables().size()); - XSSFSheet s3 = wb.getSheetAt(2); - assertEquals(0, s3.getTables().size()); - wb.close(); + try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx")) { + assertEquals(3, wb.getNumberOfSheets()); + + // Check the table sheet + XSSFSheet s1 = wb.getSheetAt(0); + assertEquals("a", s1.getRow(0).getCell(0).getRichStringCellValue().toString()); + assertEquals(1.0, s1.getRow(1).getCell(0).getNumericCellValue(), 0); + + List<XSSFTable> tables = s1.getTables(); + assertNotNull(tables); + assertEquals(1, tables.size()); + + XSSFTable table = tables.get(0); + assertEquals("Tabella1", table.getName()); + assertEquals("Tabella1", table.getDisplayName()); + + // And the others + XSSFSheet s2 = wb.getSheetAt(1); + assertEquals(0, s2.getTables().size()); + XSSFSheet s3 = wb.getSheetAt(2); + assertEquals(0, s3.getTables().size()); + } } /** @@ -1173,97 +1171,71 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void setForceFormulaRecalculation() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("Sheet 1"); + try (XSSFWorkbook wb1 = new XSSFWorkbook()) { + XSSFSheet sheet = wb1.createSheet("Sheet 1"); - assertFalse(sheet.getForceFormulaRecalculation()); + assertFalse(sheet.getForceFormulaRecalculation()); - // Set - sheet.setForceFormulaRecalculation(true); - assertTrue(sheet.getForceFormulaRecalculation()); + // Set + sheet.setForceFormulaRecalculation(true); + assertTrue(sheet.getForceFormulaRecalculation()); - // calcMode="manual" is unset when forceFormulaRecalculation=true - CTCalcPr calcPr = wb1.getCTWorkbook().addNewCalcPr(); - calcPr.setCalcMode(STCalcMode.MANUAL); - sheet.setForceFormulaRecalculation(true); - assertSame(STCalcMode.AUTO, calcPr.getCalcMode()); + // calcMode="manual" is unset when forceFormulaRecalculation=true + CTCalcPr calcPr = wb1.getCTWorkbook().addNewCalcPr(); + calcPr.setCalcMode(STCalcMode.MANUAL); + sheet.setForceFormulaRecalculation(true); + assertSame(STCalcMode.AUTO, calcPr.getCalcMode()); - // Check - sheet.setForceFormulaRecalculation(false); - assertFalse(sheet.getForceFormulaRecalculation()); + // Check + sheet.setForceFormulaRecalculation(false); + assertFalse(sheet.getForceFormulaRecalculation()); - // Save, re-load, and re-check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheet("Sheet 1"); - assertFalse(sheet.getForceFormulaRecalculation()); - wb2.close(); + // Save, re-load, and re-check + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1)) { + sheet = wb2.getSheet("Sheet 1"); + assertFalse(sheet.getForceFormulaRecalculation()); + } + } } - @Test - void bug54607() throws IOException { + @ParameterizedTest + @CsvSource(value = { // run with the file provided in the Bug-Report - runGetTopRow("54607.xlsx", true, 1, 0, 0); - runGetLeftCol("54607.xlsx", true, 0, 0, 0); + "54607.xlsx, '1, 0, 0', '0, 0, 0'", // run with some other flie to see - runGetTopRow("54436.xlsx", true, 0); - runGetLeftCol("54436.xlsx", true, 0); - runGetTopRow("TwoSheetsNoneHidden.xlsx", true, 0, 0); - runGetLeftCol("TwoSheetsNoneHidden.xlsx", true, 0, 0); - runGetTopRow("TwoSheetsNoneHidden.xls", false, 0, 0); - runGetLeftCol("TwoSheetsNoneHidden.xls", false, 0, 0); - } - - private void runGetTopRow(String file, boolean isXSSF, int... topRows) throws IOException { - final Workbook wb = (isXSSF) - ? XSSFTestDataSamples.openSampleWorkbook(file) - : HSSFTestDataSamples.openSampleWorkbook(file); - - for (int si = 0; si < wb.getNumberOfSheets(); si++) { - Sheet sh = wb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals(topRows[si], sh.getTopRow(), "Did not match for sheet " + si); - } - - // for XSSF also test with SXSSF - if (isXSSF) { - Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb); - for (int si = 0; si < swb.getNumberOfSheets(); si++) { - Sheet sh = swb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals(topRows[si], sh.getTopRow(), "Did not match for sheet " + si); + "54436.xlsx, '0', '0'", + "TwoSheetsNoneHidden.xlsx, '0, 0', '0, 0'", + "TwoSheetsNoneHidden.xls, '0, 0', '0, 0'" + }) + void bug54607(String file, String topRows, String leftCols) throws IOException { + Consumer<Workbook> testFun = (wb) -> { + for (int i=0; i<2; i++) { + Function<Sheet, Short> sheetFun = (i==0) ? Sheet::getTopRow : Sheet::getLeftCol; + String exp = (i==0) ? topRows : leftCols; + + wb.forEach(sh -> assertNotNull(sh.getSheetName())); + + String act = StreamSupport.stream(Spliterators.spliterator(wb.iterator(), wb.getNumberOfSheets(), Spliterator.ORDERED), false). + map(sh -> sheetFun.apply(sh).toString()). + collect(Collectors.joining(", ")); + + assertEquals(exp, act); } - swb.close(); - } + }; - wb.close(); - } + try (InputStream is = HSSFTestDataSamples.openSampleFileStream(file); + Workbook wb = WorkbookFactory.create(is)) { + testFun.accept(wb); - private void runGetLeftCol(String file, boolean isXSSF, int... topRows) throws IOException { - final Workbook wb = (isXSSF) - ? XSSFTestDataSamples.openSampleWorkbook(file) - : HSSFTestDataSamples.openSampleWorkbook(file); - - for (int si = 0; si < wb.getNumberOfSheets(); si++) { - Sheet sh = wb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals(topRows[si], sh.getLeftCol(), "Did not match for sheet " + si); - } - - // for XSSF also test with SXSSF - if(isXSSF) { - Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb); - for (int si = 0; si < swb.getNumberOfSheets(); si++) { - Sheet sh = swb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals(topRows[si], sh.getLeftCol(), "Did not match for sheet " + si); + // for XSSF also test with SXSSF + if (wb instanceof XSSFWorkbook) { + try (Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb)) { + testFun.accept(swb); + } } - swb.close(); } - - wb.close(); } @Test @@ -1278,31 +1250,30 @@ public final class TestXSSFSheet extends BaseTestXSheet { @Test void bug55723b() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - // stored with a special name - assertNull(wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0)); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + Sheet sheet = wb.createSheet(); - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); + // stored with a special name + assertNull(wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0)); - // stored with a special name - XSSFName name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(name); - assertEquals("Sheet0!$A:$B", name.getRefersToFormula()); + CellRangeAddress range = CellRangeAddress.valueOf("A:B"); + AutoFilter filter = sheet.setAutoFilter(range); + assertNotNull(filter); - range = CellRangeAddress.valueOf("B:C"); - filter = sheet.setAutoFilter(range); - assertNotNull(filter); + // stored with a special name + XSSFName name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); + assertNotNull(name); + assertEquals("Sheet0!$A:$B", name.getRefersToFormula()); - // stored with a special name - name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(name); - assertEquals("Sheet0!$B:$C", name.getRefersToFormula()); + range = CellRangeAddress.valueOf("B:C"); + filter = sheet.setAutoFilter(range); + assertNotNull(filter); - wb.close(); + // stored with a special name + name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); + assertNotNull(name); + assertEquals("Sheet0!$B:$C", name.getRefersToFormula()); + } } @Timeout(value = 180, unit = SECONDS) @@ -1341,81 +1312,81 @@ public final class TestXSSFSheet extends BaseTestXSheet { @Test void testCreateTwoPivotTablesInOneSheet() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - - assertNotNull(wb); - assertNotNull(sheet); - XSSFPivotTable pivotTable = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), - new CellReference("H5")); - assertNotNull(pivotTable); - assertTrue(wb.getPivotTables().size() > 0); - XSSFPivotTable pivotTable2 = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), - new CellReference("L5"), sheet); - assertNotNull(pivotTable2); - assertTrue(wb.getPivotTables().size() > 1); - wb.close(); + try (XSSFWorkbook wb = setupSheet()) { + XSSFSheet sheet = wb.getSheetAt(0); + + assertNotNull(wb); + assertNotNull(sheet); + XSSFPivotTable pivotTable = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), + new CellReference("H5")); + assertNotNull(pivotTable); + assertTrue(wb.getPivotTables().size() > 0); + XSSFPivotTable pivotTable2 = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), + new CellReference("L5"), sheet); + assertNotNull(pivotTable2); + assertTrue(wb.getPivotTables().size() > 1); + } } @Test void testCreateTwoPivotTablesInTwoSheets() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - - assertNotNull(wb); - assertNotNull(sheet); - XSSFPivotTable pivotTable = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5")); - assertNotNull(pivotTable); - assertTrue(wb.getPivotTables().size() > 0); - assertNotNull(wb); - XSSFSheet sheet2 = wb.createSheet(); - XSSFPivotTable pivotTable2 = sheet2.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), - new CellReference("H5"), sheet); - assertNotNull(pivotTable2); - assertTrue(wb.getPivotTables().size() > 1); - wb.close(); + try (XSSFWorkbook wb = setupSheet()) { + XSSFSheet sheet = wb.getSheetAt(0); + + assertNotNull(wb); + assertNotNull(sheet); + XSSFPivotTable pivotTable = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5")); + assertNotNull(pivotTable); + assertTrue(wb.getPivotTables().size() > 0); + assertNotNull(wb); + XSSFSheet sheet2 = wb.createSheet(); + XSSFPivotTable pivotTable2 = sheet2.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), + new CellReference("H5"), sheet); + assertNotNull(pivotTable2); + assertTrue(wb.getPivotTables().size() > 1); + } } @Test void testCreatePivotTable() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - - assertNotNull(wb); - assertNotNull(sheet); - XSSFPivotTable pivotTable = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5")); - assertNotNull(pivotTable); - assertTrue(wb.getPivotTables().size() > 0); - wb.close(); + try (XSSFWorkbook wb = setupSheet()) { + XSSFSheet sheet = wb.getSheetAt(0); + + assertNotNull(wb); + assertNotNull(sheet); + XSSFPivotTable pivotTable = sheet.createPivotTable(wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5")); + assertNotNull(pivotTable); + assertTrue(wb.getPivotTables().size() > 0); + } } @Test void testCreatePivotTableInOtherSheetThanDataSheet() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet1 = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet(); - - XSSFPivotTable pivotTable = sheet2.createPivotTable - (wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5"), sheet1); - assertEquals(0, pivotTable.getRowLabelColumns().size()); - - assertEquals(1, wb.getPivotTables().size()); - assertEquals(0, sheet1.getPivotTables().size()); - assertEquals(1, sheet2.getPivotTables().size()); - wb.close(); + try (XSSFWorkbook wb = setupSheet()) { + XSSFSheet sheet1 = wb.getSheetAt(0); + XSSFSheet sheet2 = wb.createSheet(); + + XSSFPivotTable pivotTable = sheet2.createPivotTable + (wb.getCreationHelper().createAreaReference("A1:B2"), new CellReference("H5"), sheet1); + assertEquals(0, pivotTable.getRowLabelColumns().size()); + + assertEquals(1, wb.getPivotTables().size()); + assertEquals(0, sheet1.getPivotTables().size()); + assertEquals(1, sheet2.getPivotTables().size()); + } } @Test void testCreatePivotTableInOtherSheetThanDataSheetUsingAreaReference() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet("TEST"); - - XSSFPivotTable pivotTable = sheet2.createPivotTable( - wb.getCreationHelper().createAreaReference(sheet.getSheetName()+"!A$1:B$2"), - new CellReference("H5")); - assertEquals(0, pivotTable.getRowLabelColumns().size()); - wb.close(); + try (XSSFWorkbook wb = setupSheet()) { + XSSFSheet sheet = wb.getSheetAt(0); + XSSFSheet sheet2 = wb.createSheet("TEST"); + + XSSFPivotTable pivotTable = sheet2.createPivotTable( + wb.getCreationHelper().createAreaReference(sheet.getSheetName() + "!A$1:B$2"), + new CellReference("H5")); + assertEquals(0, pivotTable.getRowLabelColumns().size()); + } } @Test @@ -1448,12 +1419,12 @@ public final class TestXSSFSheet extends BaseTestXSheet { */ @Test void testCreateComment() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - ClientAnchor anchor = wb.getCreationHelper().createClientAnchor(); - XSSFSheet sheet = wb.createSheet(); - XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(anchor); - assertNotNull(comment); - wb.close(); + try (XSSFWorkbook wb = new XSSFWorkbook()) { + ClientAnchor anchor = wb.getCreationHelper().createClientAnchor(); + XSSFSheet sheet = wb.createSheet(); + XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(anchor); + assertNotNull(comment); + } } @Test @@ -1791,73 +1762,72 @@ public final class TestXSSFSheet extends BaseTestXSheet { @Test void testIgnoredErrors() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - sheet.addIgnoredErrors(region, IgnoredErrorType.NUMBER_STORED_AS_TEXT); - final CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertTrue(ignoredError.getNumberStoredAsText()); - - Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); - assertEquals(1, ignoredErrors.size()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).iterator().next().formatAsString()); - - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); + sheet.addIgnoredErrors(region, IgnoredErrorType.NUMBER_STORED_AS_TEXT); + final CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); + assertEquals(1, ignoredError.getSqref().size()); + assertEquals("B2:D4", ignoredError.getSqref().get(0)); + assertTrue(ignoredError.getNumberStoredAsText()); + + Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); + assertEquals(1, ignoredErrors.size()); + assertEquals(1, ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).size()); + assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).iterator().next().formatAsString()); + } } @Test void testIgnoredErrorsMultipleTypes() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA, IgnoredErrorType.EVALUATION_ERROR); - final CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertFalse(ignoredError.getNumberStoredAsText()); - assertTrue(ignoredError.getFormula()); - assertTrue(ignoredError.getEvalError()); - - Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); - assertEquals(2, ignoredErrors.size()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.FORMULA).iterator().next().formatAsString()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); + sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA, IgnoredErrorType.EVALUATION_ERROR); + final CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); + assertEquals(1, ignoredError.getSqref().size()); + assertEquals("B2:D4", ignoredError.getSqref().get(0)); + assertFalse(ignoredError.getNumberStoredAsText()); + assertTrue(ignoredError.getFormula()); + assertTrue(ignoredError.getEvalError()); + + Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); + assertEquals(2, ignoredErrors.size()); + assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); + assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.FORMULA).iterator().next().formatAsString()); + assertEquals(1, ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).size()); + assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); + } } @Test void testIgnoredErrorsMultipleCalls() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - // Two calls means two elements, no clever collapsing just yet. - sheet.addIgnoredErrors(region, IgnoredErrorType.EVALUATION_ERROR); - sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA); - - CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertFalse(ignoredError.getFormula()); - assertTrue(ignoredError.getEvalError()); - - ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(1); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertTrue(ignoredError.getFormula()); - assertFalse(ignoredError.getEvalError()); - - Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); - assertEquals(2, ignoredErrors.size()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.FORMULA).iterator().next().formatAsString()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); - workbook.close(); + try (XSSFWorkbook workbook = new XSSFWorkbook()) { + XSSFSheet sheet = workbook.createSheet(); + CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); + // Two calls means two elements, no clever collapsing just yet. + sheet.addIgnoredErrors(region, IgnoredErrorType.EVALUATION_ERROR); + sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA); + + CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); + assertEquals(1, ignoredError.getSqref().size()); + assertEquals("B2:D4", ignoredError.getSqref().get(0)); + assertFalse(ignoredError.getFormula()); + assertTrue(ignoredError.getEvalError()); + + ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(1); + assertEquals(1, ignoredError.getSqref().size()); + assertEquals("B2:D4", ignoredError.getSqref().get(0)); + assertTrue(ignoredError.getFormula()); + assertFalse(ignoredError.getEvalError()); + + Map<IgnoredErrorType, Set<CellRangeAddress>> ignoredErrors = sheet.getIgnoredErrors(); + assertEquals(2, ignoredErrors.size()); + assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); + assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.FORMULA).iterator().next().formatAsString()); + assertEquals(1, ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).size()); + assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); + } } @Test diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFTable.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFTable.java index 83763bec73..166149959f 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFTable.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFTable.java @@ -17,11 +17,24 @@ package org.apache.poi.xssf.usermodel; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.util.AreaReference; import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.IOUtils; import org.apache.poi.util.TempFile; import org.apache.poi.xssf.XSSFTestDataSamples; import org.apache.poi.xssf.streaming.SXSSFWorkbook; @@ -30,20 +43,6 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - public final class TestXSSFTable { @Test @@ -86,34 +85,33 @@ public final class TestXSSFTable { @Test void testCTTableStyleInfo() throws IOException { - XSSFWorkbook outputWorkbook = new XSSFWorkbook(); - XSSFSheet sheet = outputWorkbook.createSheet(); - - //Create - XSSFTable outputTable = sheet.createTable(null); - outputTable.setDisplayName("Test"); - CTTable outputCTTable = outputTable.getCTTable(); - - //Style configurations - CTTableStyleInfo outputStyleInfo = outputCTTable.addNewTableStyleInfo(); - outputStyleInfo.setName("TableStyleLight1"); - outputStyleInfo.setShowColumnStripes(false); - outputStyleInfo.setShowRowStripes(true); - - XSSFWorkbook inputWorkbook = XSSFTestDataSamples.writeOutAndReadBack(outputWorkbook); - List<XSSFTable> tables = inputWorkbook.getSheetAt(0).getTables(); - assertEquals(1, tables.size(), "Tables number"); - - XSSFTable inputTable = tables.get(0); - assertEquals(outputTable.getDisplayName(), inputTable.getDisplayName(), "Table display name"); - - CTTableStyleInfo inputStyleInfo = inputTable.getCTTable().getTableStyleInfo(); - assertEquals(outputStyleInfo.getName(), inputStyleInfo.getName(), "Style name"); - assertEquals(outputStyleInfo.getShowColumnStripes(), inputStyleInfo.getShowColumnStripes(), "Show column stripes"); - assertEquals(outputStyleInfo.getShowRowStripes(), inputStyleInfo.getShowRowStripes(), "Show row stripes"); - - inputWorkbook.close(); - outputWorkbook.close(); + try (XSSFWorkbook outputWorkbook = new XSSFWorkbook()) { + XSSFSheet sheet = outputWorkbook.createSheet(); + + //Create + XSSFTable outputTable = sheet.createTable(null); + outputTable.setDisplayName("Test"); + CTTable outputCTTable = outputTable.getCTTable(); + + //Style configurations + CTTableStyleInfo outputStyleInfo = outputCTTable.addNewTableStyleInfo(); + outputStyleInfo.setName("TableStyleLight1"); + outputStyleInfo.setShowColumnStripes(false); + outputStyleInfo.setShowRowStripes(true); + + try (XSSFWorkbook inputWorkbook = XSSFTestDataSamples.writeOutAndReadBack(outputWorkbook)) { + List<XSSFTable> tables = inputWorkbook.getSheetAt(0).getTables(); + assertEquals(1, tables.size(), "Tables number"); + + XSSFTable inputTable = tables.get(0); + assertEquals(outputTable.getDisplayName(), inputTable.getDisplayName(), "Table display name"); + + CTTableStyleInfo inputStyleInfo = inputTable.getCTTable().getTableStyleInfo(); + assertEquals(outputStyleInfo.getName(), inputStyleInfo.getName(), "Style name"); + assertEquals(outputStyleInfo.getShowColumnStripes(), inputStyleInfo.getShowColumnStripes(), "Show column stripes"); + assertEquals(outputStyleInfo.getShowRowStripes(), inputStyleInfo.getShowRowStripes(), "Show row stripes"); + } + } } @Test @@ -269,8 +267,6 @@ public final class TestXSSFTable { assertEquals(new CellReference("C1"), table.getStartCellReference()); assertEquals(new CellReference("M3"), table.getEndCellReference()); - - IOUtils.closeQuietly(wb); } } @@ -292,8 +288,6 @@ public final class TestXSSFTable { // update cell references to clear the cache table.updateReferences(); assertEquals(11, table.getRowCount()); - - IOUtils.closeQuietly(wb); } } @@ -311,8 +305,6 @@ public final class TestXSSFTable { assertEquals(6, table.getRowCount()); assertEquals(5, table.getDataRowCount()); - - IOUtils.closeQuietly(wb); } } @@ -340,8 +332,6 @@ public final class TestXSSFTable { assertEquals(0, table.getTotalsRowCount()); assertEquals("C10:C15", table.getArea().formatAsString()); - - IOUtils.closeQuietly(wb); } } @@ -441,10 +431,10 @@ public final class TestXSSFTable { assertTrue (cB.getId() < cD.getId(), "Column D ID"); assertTrue (cD.getId() < cC.getId(), "Column C ID"); // generated name - assertEquals(table.getColumns().get(0).getName(), "Column 1"); - assertEquals(table.getColumns().get(1).getName(), "Column B"); - assertEquals(table.getColumns().get(2).getName(), "Column C"); - assertEquals(table.getColumns().get(3).getName(), "Column D"); + assertEquals("Column 1", table.getColumns().get(0).getName()); + assertEquals("Column B", table.getColumns().get(1).getName()); + assertEquals("Column C", table.getColumns().get(2).getName()); + assertEquals("Column D", table.getColumns().get(3).getName()); } } @@ -528,23 +518,20 @@ public final class TestXSSFTable { )); // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - IOUtils.closeQuietly(wb); - s = wb2.getSheetAt(0); - - // Check - assertEquals(1, s.getTables().size()); - t = s.getTables().get(0); - assertEquals("A1", t.getStartCellReference().formatAsString()); - assertEquals("C2", t.getEndCellReference().formatAsString()); - - // TODO Nicer column fetching - assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName()); - assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName()); - assertEquals("ABCD", t.getCTTable().getTableColumns().getTableColumnArray(2).getName()); - - // Done - IOUtils.closeQuietly(wb2); + try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) { + s = wb2.getSheetAt(0); + + // Check + assertEquals(1, s.getTables().size()); + t = s.getTables().get(0); + assertEquals("A1", t.getStartCellReference().formatAsString()); + assertEquals("C2", t.getEndCellReference().formatAsString()); + + // TODO Nicer column fetching + assertEquals("12", t.getCTTable().getTableColumns().getTableColumnArray(0).getName()); + assertEquals("34.56", t.getCTTable().getTableColumns().getTableColumnArray(1).getName()); + assertEquals("ABCD", t.getCTTable().getTableColumns().getTableColumnArray(2).getName()); + } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java index 312bc8c57b..de24cb66bc 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java @@ -40,9 +40,9 @@ public final class TestXSSFCategoryAxis { XDDFCategoryAxis axis = chart.createCategoryAxis(AxisPosition.BOTTOM); axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); + assertEquals(AxisCrosses.AUTO_ZERO, axis.getCrosses()); - assertEquals(chart.getAxes().size(), 1); + assertEquals(1, chart.getAxes().size()); } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java index 0175cddae2..e64a88c26b 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFDateAxis.java @@ -41,9 +41,9 @@ public final class TestXSSFDateAxis { XDDFDateAxis axis = chart.createDateAxis(AxisPosition.BOTTOM); axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); + assertEquals(AxisCrosses.AUTO_ZERO, axis.getCrosses()); - assertEquals(chart.getAxes().size(), 1); + assertEquals(1, chart.getAxes().size()); } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java index d87057526d..73d4dcd97a 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java @@ -42,12 +42,12 @@ public final class TestXSSFValueAxis { XDDFValueAxis axis = chart.createValueAxis(AxisPosition.BOTTOM); axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY); + assertEquals(AxisCrossBetween.MIDPOINT_CATEGORY, axis.getCrossBetween()); axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); + assertEquals(AxisCrosses.AUTO_ZERO, axis.getCrosses()); - assertEquals(chart.getAxes().size(), 1); + assertEquals(1, chart.getAxes().size()); } } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java index 735b0d5413..2626d0f8ea 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java @@ -18,6 +18,7 @@ package org.apache.poi.xssf.usermodel.extensions; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -89,19 +90,13 @@ class TestXSSFCellFill { XSSFCell cellWithThemeColor = wb.getSheetAt(0).getRow(10).getCell(0); //color RGB will be extracted from theme XSSFColor foregroundColor = cellWithThemeColor.getCellStyle().getFillForegroundXSSFColor(); - byte[] rgb = foregroundColor.getRGB(); - byte[] rgbWithTint = foregroundColor.getRGBWithTint(); // Dk2 - assertEquals(rgb[0], 31); - assertEquals(rgb[1], 73); - assertEquals(rgb[2], 125); + assertArrayEquals(new byte[]{31, 73, 125}, foregroundColor.getRGB()); // Dk2, lighter 40% (tint is about 0.39998) // 31 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 120.59552 => 120 (byte) // 73 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 145.79636 => -111 (byte) // 125 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 176.99740 => -80 (byte) - assertEquals(rgbWithTint[0], 120); - assertEquals(rgbWithTint[1], -111); - assertEquals(rgbWithTint[2], -80); + assertArrayEquals(new byte[]{120, -111, -80}, foregroundColor.getRGBWithTint()); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java index 10c8fca9e7..ba2070eeae 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java @@ -53,12 +53,12 @@ class TestXWPFBugs { run.setFontFamily("Times New Roman"); run.setFontSize(20); - assertEquals(run.getFontFamily(), "Times New Roman"); - assertEquals(run.getFontFamily(FontCharRange.cs), "Times New Roman"); - assertEquals(run.getFontFamily(FontCharRange.eastAsia), "Times New Roman"); - assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Times New Roman"); + assertEquals("Times New Roman", run.getFontFamily()); + assertEquals("Times New Roman", run.getFontFamily(FontCharRange.cs)); + assertEquals("Times New Roman", run.getFontFamily(FontCharRange.eastAsia)); + assertEquals("Times New Roman", run.getFontFamily(FontCharRange.hAnsi)); run.setFontFamily("Arial", FontCharRange.hAnsi); - assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial"); + assertEquals("Arial", run.getFontFamily(FontCharRange.hAnsi)); } } diff --git a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java index 887f53dbd7..3f8e910b52 100644 --- a/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ b/poi-ooxml/src/test/java/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java @@ -45,29 +45,19 @@ import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.xmlbeans.XmlCursor; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; public final class TestXWPFDocument { @Test void testContainsMainContentType() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - OPCPackage pack = doc.getPackage(); - - boolean found = false; - for (PackagePart part : pack.getParts()) { - if (part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) { - found = true; - } -// if (false) { -// // successful tests should be silent -// System.out.println(part); -// } + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); + OPCPackage pack = doc.getPackage()) { + String ct = XWPFRelation.DOCUMENT.getContentType(); + boolean found = pack.getParts().stream().anyMatch(p -> ct.equals(p.getContentType())); + assertTrue(found); } - assertTrue(found); - - pack.close(); - doc.close(); } @Test @@ -105,90 +95,92 @@ public final class TestXWPFDocument { @Test void testMetadataComplex() throws IOException { - XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx"); - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - assertEquals("Microsoft Office Outlook", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(5184, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - - assertEquals(" ", xml.getProperties().getCoreProperties().getTitle()); - Optional<String> subjectProperty = xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty(); - assertTrue(subjectProperty.isPresent()); - assertEquals(" ", subjectProperty.get()); - xml.close(); + try (XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx")) { + assertNotNull(xml.getProperties().getCoreProperties()); + assertNotNull(xml.getProperties().getExtendedProperties()); + + CTProperties up = xml.getProperties().getExtendedProperties().getUnderlyingProperties(); + assertEquals("Microsoft Office Outlook", up.getApplication()); + assertEquals(5184, up.getCharacters()); + assertEquals(0, up.getLines()); + + POIXMLProperties.CoreProperties cp = xml.getProperties().getCoreProperties(); + assertEquals(" ", cp.getTitle()); + Optional<String> subjectProperty = cp.getUnderlyingProperties().getSubjectProperty(); + assertTrue(subjectProperty.isPresent()); + assertEquals(" ", subjectProperty.get()); + } } @Test void testWorkbookProperties() throws Exception { - XWPFDocument doc = new XWPFDocument(); - POIXMLProperties props = doc.getProperties(); - assertNotNull(props); - assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); - doc.close(); + try (XWPFDocument doc = new XWPFDocument()) { + POIXMLProperties props = doc.getProperties(); + assertNotNull(props); + assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); + } } @Test void testAddParagraph() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - assertEquals(3, doc.getParagraphs().size()); - - XWPFParagraph p = doc.createParagraph(); - assertEquals(p, doc.getParagraphs().get(3)); - assertEquals(4, doc.getParagraphs().size()); - - assertEquals(3, doc.getParagraphPos(3)); - assertEquals(3, doc.getPosOfParagraph(p)); - - CTP ctp = p.getCTP(); - XWPFParagraph newP = doc.getParagraph(ctp); - assertSame(p, newP); - XmlCursor cursor = doc.getDocument().getBody().getPArray(0).newCursor(); - XWPFParagraph cP = doc.insertNewParagraph(cursor); - assertSame(cP, doc.getParagraphs().get(0)); - assertEquals(5, doc.getParagraphs().size()); - doc.close(); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { + assertEquals(3, doc.getParagraphs().size()); + + XWPFParagraph p = doc.createParagraph(); + assertEquals(p, doc.getParagraphs().get(3)); + assertEquals(4, doc.getParagraphs().size()); + + assertEquals(3, doc.getParagraphPos(3)); + assertEquals(3, doc.getPosOfParagraph(p)); + + CTP ctp = p.getCTP(); + XWPFParagraph newP = doc.getParagraph(ctp); + assertSame(p, newP); + XmlCursor cursor = doc.getDocument().getBody().getPArray(0).newCursor(); + XWPFParagraph cP = doc.insertNewParagraph(cursor); + assertSame(cP, doc.getParagraphs().get(0)); + assertEquals(5, doc.getParagraphs().size()); + } } @Test void testAddPicture() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg"); - String relationId = doc.addPictureData(jpeg, Document.PICTURE_TYPE_JPEG); - - 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]); + try (XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx")) { + byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg"); + String relationId = doc.addPictureData(jpeg, Document.PICTURE_TYPE_JPEG); + + 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]); + } } - doc.close(); } @Test void testAllPictureFormats() throws IOException, InvalidFormatException { - XWPFDocument doc = new XWPFDocument(); - - doc.addPictureData(new byte[10], Document.PICTURE_TYPE_EMF); - doc.addPictureData(new byte[11], Document.PICTURE_TYPE_WMF); - doc.addPictureData(new byte[12], Document.PICTURE_TYPE_PICT); - doc.addPictureData(new byte[13], Document.PICTURE_TYPE_JPEG); - doc.addPictureData(new byte[14], Document.PICTURE_TYPE_PNG); - doc.addPictureData(new byte[15], Document.PICTURE_TYPE_DIB); - doc.addPictureData(new byte[16], Document.PICTURE_TYPE_GIF); - doc.addPictureData(new byte[17], Document.PICTURE_TYPE_TIFF); - doc.addPictureData(new byte[18], Document.PICTURE_TYPE_EPS); - doc.addPictureData(new byte[19], Document.PICTURE_TYPE_BMP); - doc.addPictureData(new byte[20], Document.PICTURE_TYPE_WPG); - - assertEquals(11, doc.getAllPictures().size()); - - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(11, doc2.getAllPictures().size()); - doc2.close(); - doc.close(); + try (XWPFDocument doc = new XWPFDocument()) { + + doc.addPictureData(new byte[10], Document.PICTURE_TYPE_EMF); + doc.addPictureData(new byte[11], Document.PICTURE_TYPE_WMF); + doc.addPictureData(new byte[12], Document.PICTURE_TYPE_PICT); + doc.addPictureData(new byte[13], Document.PICTURE_TYPE_JPEG); + doc.addPictureData(new byte[14], Document.PICTURE_TYPE_PNG); + doc.addPictureData(new byte[15], Document.PICTURE_TYPE_DIB); + doc.addPictureData(new byte[16], Document.PICTURE_TYPE_GIF); + doc.addPictureData(new byte[17], Document.PICTURE_TYPE_TIFF); + doc.addPictureData(new byte[18], Document.PICTURE_TYPE_EPS); + doc.addPictureData(new byte[19], Document.PICTURE_TYPE_BMP); + doc.addPictureData(new byte[20], Document.PICTURE_TYPE_WPG); + + assertEquals(11, doc.getAllPictures().size()); + + try (XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc)) { + assertEquals(11, doc2.getAllPictures().size()); + } + } } @Test @@ -201,8 +193,8 @@ public final class TestXWPFDocument { assertEquals("rId7", h.getHyperlinkId()); assertEquals("https://poi.apache.org/", h.getHyperlink(doc).getURL()); - assertEquals(p.getRuns().size(), 1); - assertEquals(p.getRuns().get(0), h); + assertEquals(1, p.getRuns().size()); + assertEquals(h, p.getRuns().get(0)); h = p.createHyperlinkRun("https://poi.apache.org/"); h.setText("Apache POI"); @@ -426,32 +418,27 @@ public final class TestXWPFDocument { settings.setMirrorMargins(true); assertTrue(settings.getMirrorMargins()); - XWPFDocument doc = new XWPFDocument(); - assertEquals(100, doc.getZoomPercent()); - - doc.setZoomPercent(50); - assertEquals(50, doc.getZoomPercent()); + try (XWPFDocument doc = new XWPFDocument()) { + assertEquals(100, doc.getZoomPercent()); - doc.setZoomPercent(200); - assertEquals(200, doc.getZoomPercent()); + doc.setZoomPercent(50); + assertEquals(50, doc.getZoomPercent()); - assertFalse(doc.getEvenAndOddHeadings()); - doc.setEvenAndOddHeadings(true); - assertTrue(doc.getEvenAndOddHeadings()); + doc.setZoomPercent(200); + assertEquals(200, doc.getZoomPercent()); - assertFalse(doc.getMirrorMargins()); - doc.setMirrorMargins(true); - assertTrue(doc.getMirrorMargins()); + assertFalse(doc.getEvenAndOddHeadings()); + doc.setEvenAndOddHeadings(true); + assertTrue(doc.getEvenAndOddHeadings()); - XWPFDocument back = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(200, back.getZoomPercent()); - back.close(); + assertFalse(doc.getMirrorMargins()); + doc.setMirrorMargins(true); + assertTrue(doc.getMirrorMargins()); -// OutputStream out = new FileOutputStream("/tmp/testZoom.docx"); -// doc.write(out); -// out.close(); - - doc.close(); + try (XWPFDocument back = XWPFTestDataSamples.writeOutAndReadBack(doc)) { + assertEquals(200, back.getZoomPercent()); + } + } } @Test @@ -464,20 +451,19 @@ public final class TestXWPFDocument { @Test @Disabled("XWPF should be able to write to a new Stream when opened Read-Only") void testWriteFromReadOnlyOPC() throws Exception { - OPCPackage opc = OPCPackage.open( + try (OPCPackage opc = OPCPackage.open( POIDataSamples.getDocumentInstance().getFile("SampleDoc.docx"), PackageAccess.READ - ); - XWPFDocument doc = new XWPFDocument(opc); - - 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()); + ); + XWPFDocument doc = new XWPFDocument(opc); + XWPFWordExtractor ext = new XWPFWordExtractor(doc) + ) { + final String origText = ext.getText(); + + try (XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc); + XWPFWordExtractor ext2 = new XWPFWordExtractor(doc2)) { + assertEquals(origText, ext2.getText()); + } } } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java index 5525cdf808..f13991370c 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/extractor/TestExtractor.java @@ -165,7 +165,7 @@ public final class TestExtractor { assertNotNull(nText); // Notes record were corrupt, so don't expect any - assertEquals(nText.length(), 0); + assertEquals(0, nText.length()); // Slide records were fine assertContains(text, "Using Disease Surveillance and Response"); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java index 84af931507..2b7cbb240b 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/model/TestShapes.java @@ -116,7 +116,7 @@ public final class TestShapes { String text = txtbox.getText(); assertNotNull(text); - assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1); + assertEquals(1, txtbox.getTextParagraphs().get(0).getTextRuns().size()); HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); switch (text) { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java index 2b1cfa3bda..fc8c353e33 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExControl.java @@ -80,9 +80,9 @@ public final class TestExControl { ExOleObjAtom oleObj = record.getExOleObjAtom(); assertNotNull(oleObj); - assertEquals(oleObj.getDrawAspect(), ExOleObjAtom.DRAW_ASPECT_VISIBLE); - assertEquals(oleObj.getType(), ExOleObjAtom.TYPE_CONTROL); - assertEquals(oleObj.getSubType(), ExOleObjAtom.SUBTYPE_DEFAULT); + assertEquals(ExOleObjAtom.DRAW_ASPECT_VISIBLE, oleObj.getDrawAspect()); + assertEquals(ExOleObjAtom.TYPE_CONTROL, oleObj.getType()); + assertEquals(ExOleObjAtom.SUBTYPE_DEFAULT, oleObj.getSubType()); assertEquals("Shockwave Flash Object", record.getMenuName()); assertEquals("ShockwaveFlash.ShockwaveFlash.9", record.getProgId()); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java index 01d72f3265..337f6f5307 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestExOleObjAtom.java @@ -38,12 +38,13 @@ public final class TestExOleObjAtom { ExOleObjAtom record = new ExOleObjAtom(data, 0, data.length); assertEquals(RecordTypes.ExOleObjAtom.typeID, record.getRecordType()); - assertEquals(record.getDrawAspect(), ExOleObjAtom.DRAW_ASPECT_VISIBLE); - assertEquals(record.getType(), ExOleObjAtom.TYPE_CONTROL); - assertEquals(record.getObjID(), 1); - assertEquals(record.getSubType(), ExOleObjAtom.SUBTYPE_DEFAULT); - assertEquals(record.getObjStgDataRef(), 2); - assertEquals(record.getOptions(), 1283584); //ther meaning is unknown + assertEquals(ExOleObjAtom.DRAW_ASPECT_VISIBLE, record.getDrawAspect()); + assertEquals(ExOleObjAtom.TYPE_CONTROL, record.getType()); + assertEquals(1, record.getObjID()); + assertEquals(ExOleObjAtom.SUBTYPE_DEFAULT, record.getSubType()); + assertEquals(2, record.getObjStgDataRef()); + // the meaning is unknown + assertEquals(1283584, record.getOptions()); } @Test diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java index 3592100af6..a15fa80016 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestFontCollection.java @@ -55,28 +55,28 @@ public final class TestFontCollection { void testFonts() { FontCollection fonts = new FontCollection(data, 0, data.length); Record[] child = fonts.getChildRecords(); - assertEquals(child.length, 1); + assertEquals(1, child.length); FontEntityAtom fnt = (FontEntityAtom)child[0]; - assertEquals(fnt.getFontName(), "Times New Roman"); + assertEquals("Times New Roman", fnt.getFontName()); } @Test void testAddFont() { FontCollection fonts = new FontCollection(data, 0, data.length); HSLFFontInfo fi = fonts.addFont(HSLFFontInfoPredefined.TIMES_NEW_ROMAN); - assertEquals((int)fi.getIndex(), 0); + assertEquals(0, (int)fi.getIndex()); fi = fonts.addFont(new HSLFFontInfo("Helvetica")); - assertEquals((int)fi.getIndex(), 1); + assertEquals(1, (int)fi.getIndex()); fi = fonts.addFont(HSLFFontInfoPredefined.ARIAL); - assertEquals((int)fi.getIndex(), 2); + assertEquals(2, (int)fi.getIndex()); //the font being added twice fi = fonts.addFont(HSLFFontInfoPredefined.ARIAL); - assertEquals((int)fi.getIndex(), 2); + assertEquals(2, (int)fi.getIndex()); // Font collection should contain 3 fonts Record[] child = fonts.getChildRecords(); - assertEquals(child.length, 3); + assertEquals(3, child.length); // Check we get the right font name for the indicies fi = fonts.getFontInfo(0); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java index 2a64d4fc21..e1a08b6e09 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hslf/record/TestTextRulerAtom.java @@ -45,8 +45,8 @@ public final class TestTextRulerAtom { @Test void testReadRuler() { TextRulerAtom ruler = new TextRulerAtom(data_1, 0, data_1.length); - assertEquals(ruler.getNumberOfLevels(), 0); - assertEquals(ruler.getDefaultTabSize(), 0); + assertEquals(0, ruler.getNumberOfLevels()); + assertEquals(0, ruler.getDefaultTabSize()); List<HSLFTabStop> tabStops = ruler.getTabStops(); assertNotNull(tabStops); diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java index a11ba12c90..c5395232dc 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hsmf/TestExtractEmbeddedMSG.java @@ -102,7 +102,7 @@ public class TestExtractEmbeddedMSG { expectedMessageDate.set(Calendar.MILLISECOND, 0); assertEquals(expectedMessageDate.getTimeInMillis(), messageDate.getTimeInMillis()); // test variable length property - assertEquals(msg.getSubject(), "Test Attachment"); + assertEquals("Test Attachment", msg.getSubject()); } private POIFSFileSystem rebuildFromAttached(MAPIMessage attachedMsg) throws IOException { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestPlexOfCps.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestPlexOfCps.java index 23a4c28777..ef467516e0 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestPlexOfCps.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/model/TestPlexOfCps.java @@ -26,53 +26,51 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public final class TestPlexOfCps { - private PlexOfCps _plexOfCps; - private HWPFDocFixture _hWPFDocFixture; + private PlexOfCps _plexOfCps; + private HWPFDocFixture _hWPFDocFixture; - @Test - void testWriteRead() { - _plexOfCps = new PlexOfCps(4); + @Test + void testWriteRead() { + _plexOfCps = new PlexOfCps(4); - int last = 0; - for (int x = 0; x < 110; x++) - { - byte[] intHolder = new byte[4]; - int span = (int)(110.0f * Math.random()); - LittleEndian.putInt(intHolder, 0, span); - _plexOfCps.addProperty(new GenericPropertyNode(last, last + span, intHolder)); - last += span; - } + int last = 0; + for (int x = 0; x < 110; x++) { + byte[] intHolder = new byte[4]; + int span = (int) (110.0f * Math.random()); + LittleEndian.putInt(intHolder, 0, span); + _plexOfCps.addProperty(new GenericPropertyNode(last, last + span, intHolder)); + last += span; + } - byte[] output = _plexOfCps.toByteArray(); - _plexOfCps = new PlexOfCps(output, 0, output.length, 4); - int len = _plexOfCps.length(); - assertEquals(len, 110); + byte[] output = _plexOfCps.toByteArray(); + _plexOfCps = new PlexOfCps(output, 0, output.length, 4); + int len = _plexOfCps.length(); + assertEquals(110, len); - last = 0; - for (int x = 0; x < len; x++) - { - GenericPropertyNode node = _plexOfCps.getProperty(x); - assertEquals(node.getStart(), last); - last = node.getEnd(); - int span = LittleEndian.getInt(node.getBytes()); - assertEquals(node.getEnd()-node.getStart(), span); + last = 0; + for (int x = 0; x < len; x++) { + GenericPropertyNode node = _plexOfCps.getProperty(x); + assertEquals(node.getStart(), last); + last = node.getEnd(); + int span = LittleEndian.getInt(node.getBytes()); + assertEquals(node.getEnd() - node.getStart(), span); + } } - } - @BeforeEach - void setUp() throws Exception { - /**@todo verify the constructors*/ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); + @BeforeEach + void setUp() throws Exception { + /* @todo verify the constructors*/ + _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - _hWPFDocFixture.setUp(); - } + _hWPFDocFixture.setUp(); + } - @AfterEach - void tearDown() throws Exception { - _plexOfCps = null; - _hWPFDocFixture.tearDown(); + @AfterEach + void tearDown() { + _plexOfCps = null; + _hWPFDocFixture.tearDown(); - _hWPFDocFixture = null; - } + _hWPFDocFixture = null; + } } diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestPictures.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestPictures.java index 61e4ced097..b792289282 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestPictures.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestPictures.java @@ -52,9 +52,8 @@ public final class TestPictures { List<Picture> pics = doc.getPicturesTable().getAllPictures(); assertNotNull(pics); - assertEquals(pics.size(), 2); - for (int i = 0; i < pics.size(); i++) { - Picture pic = pics.get(i); + assertEquals(2, pics.size()); + for (Picture pic : pics) { assertNotNull(pic.suggestFileExtension()); assertNotNull(pic.suggestFullFileName()); } @@ -289,7 +288,6 @@ public final class TestPictures { assertEquals(0, plain8s); } - @SuppressWarnings("deprecation") @Test void testCroppedPictures() { HWPFDocument doc = openSampleFile("testCroppedPictures.doc"); @@ -334,40 +332,40 @@ public final class TestPictures { } @Test - void testPictureWithAlternativeText() { - HWPFDocument document = openSampleFile("Picture_Alternative_Text.doc"); - PicturesTable pictureTable = document.getPicturesTable(); - Picture picture = pictureTable.getAllPictures().get(0); + void testPictureWithAlternativeText() throws IOException { + try (HWPFDocument document = openSampleFile("Picture_Alternative_Text.doc")) { + PicturesTable pictureTable = document.getPicturesTable(); + Picture picture = pictureTable.getAllPictures().get(0); - assertEquals("This is the alternative text for the picture.", picture.getDescription()); + assertEquals("This is the alternative text for the picture.", picture.getDescription()); + } } @Disabled("This bug is not fixed yet") @Test void test58804_1() throws Exception { - HWPFDocument docA = openSampleFile("58804_1.doc"); - - expectImages(docA, 1); - - HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); + try (HWPFDocument docA = openSampleFile("58804_1.doc")) { + expectImages(docA, 1); - try (OutputStream out = new FileOutputStream("/tmp/58804_1_out.doc")) { - docB.write(out); + try (HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); + OutputStream out = new FileOutputStream("/tmp/58804_1_out.doc")) { + docB.write(out); + expectImages(docB, 1); + } } - - expectImages(docB, 1); } @Disabled("This bug is not fixed yet") @Test - void test58804() throws Exception { - HWPFDocument docA = openSampleFile("58804.doc"); - - expectImages(docA, 7); + void test58804() throws IOException { + try (HWPFDocument docA = openSampleFile("58804.doc")) { + expectImages(docA, 7); - HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); + try (HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA)) { + expectImages(docB, 7); + } + } - expectImages(docB, 7); } private void expectImages(HWPFDocument docA, int expectedCount) { diff --git a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestRange.java b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestRange.java index 7d6c72fc6e..4965fc44b0 100644 --- a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestRange.java +++ b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/usermodel/TestRange.java @@ -64,33 +64,31 @@ public final class TestRange { @Test void testBug46817() throws IOException { - InputStream is = SAMPLES.openResourceAsStream( "Bug46817.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( is ); - is.close(); + try (InputStream is = SAMPLES.openResourceAsStream("Bug46817.doc"); + HWPFDocument hwpfDocument = new HWPFDocument(is)) { - final List<SEPX> sections = hwpfDocument.getSectionTable() - .getSections(); - assertEquals( sections.size(), 1 ); + final List<SEPX> sections = hwpfDocument.getSectionTable().getSections(); + assertEquals( 1, sections.size() ); - // whole document, including additional text from shape - SEPX sepx = sections.get( 0 ); - assertEquals( sepx.getStart(), 0 ); - assertEquals( sepx.getEnd(), 1428 ); + // whole document, including additional text from shape + SEPX sepx = sections.get( 0 ); + assertEquals( 0, sepx.getStart() ); + assertEquals( 1428, sepx.getEnd() ); - // only main range - Range range = hwpfDocument.getRange(); - assertEquals( range.getStartOffset(), 0 ); - assertEquals( range.getEndOffset(), 766 ); + // only main range + Range range = hwpfDocument.getRange(); + assertEquals( 0, range.getStartOffset() ); + assertEquals( 766, range.getEndOffset() ); - Paragraph lastInMainRange = range.getParagraph( range.numParagraphs() - 1); - assertTrue( lastInMainRange.getEndOffset() <= 766 ); + Paragraph lastInMainRange = range.getParagraph( range.numParagraphs() - 1); + assertTrue( lastInMainRange.getEndOffset() <= 766 ); - Section section = range.getSection( 0 ); - assertTrue( section.getEndOffset() <= 766 ); + Section section = range.getSection( 0 ); + assertTrue( section.getEndOffset() <= 766 ); - Paragraph lastInMainSection = section.getParagraph( section + Paragraph lastInMainSection = section.getParagraph( section .numParagraphs() - 1); - assertTrue( lastInMainSection.getEndOffset() <= 766 ); - hwpfDocument.close(); + assertTrue( lastInMainSection.getEndOffset() <= 766 ); + } } } diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java index cc75abc874..e2ce00ceb1 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestBasic.java @@ -168,7 +168,7 @@ final class TestBasic { final SummaryInformation si = (SummaryInformation)PropertySetFactory.create(is); final List<Section> sections = si.getSections(); final Section s = sections.get(0); - assertEquals(s.getFormatID(), SummaryInformation.FORMAT_ID); + assertEquals(SummaryInformation.FORMAT_ID, s.getFormatID()); assertNotNull(s.getProperties()); assertEquals(17, s.getPropertyCount()); assertEquals("Titel", s.getProperty(PropertyIDMap.PID_TITLE)); diff --git a/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java b/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java index 0fdb48eea0..2cb8086c0c 100644 --- a/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java +++ b/poi/src/test/java/org/apache/poi/hpsf/basic/TestEmptyProperties.java @@ -141,13 +141,13 @@ final class TestEmptyProperties { assertNotNull(s.getTemplate()); assertNotNull(s.getLastAuthor()); assertNotNull(s.getRevNumber()); - assertEquals(s.getEditTime(), 0); + assertEquals(0, s.getEditTime()); assertNull(s.getLastPrinted()); assertNull(s.getCreateDateTime()); assertNull(s.getLastSaveDateTime()); - assertEquals(s.getPageCount(), 0); - assertEquals(s.getWordCount(), 0); - assertEquals(s.getCharCount(), 0); + assertEquals(0, s.getPageCount()); + assertEquals(0, s.getWordCount()); + assertEquals(0, s.getCharCount()); assertNull(s.getThumbnail()); assertNull(s.getApplicationName()); } diff --git a/poi/src/test/java9/module-info.class b/poi/src/test/java9/module-info.class Binary files differindex 028b943d0a..438e778ab5 100644 --- a/poi/src/test/java9/module-info.class +++ b/poi/src/test/java9/module-info.class |